问:
How to generate multiple lines in PDF using Apache pdfbox
I am using Pdfbox to generate PDF files using Java. The problem is that when i add long text contents in the document, it is not displayed properly. Only a part of it is displayed. That too in a single line.

I want text to be in multiple lines.

My code is given below:

```<code>PDPageContentStream pdfContent=new PDPageContentStream(pdfDocument, pdfPage, true, true);

pdfContent.beginText();
pdfContent.setFont(pdfFont, 11);
pdfContent.moveTextPositionByAmount(30,750);
pdfContent.drawString("I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox");
pdfContent.endText();
</code>```

My output:

答:
```<code>///// FOR PDBOX 2.0.X
//  FOR ADDING DYNAMIC PAGE ACCORDING THE LENGTH OF THE CONTENT

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class Document_Creation {

   public static void main (String args[]) throws IOException {

       PDDocument doc = null;
       try
       {
           doc = new PDDocument();
           PDPage page = new PDPage();
           doc.addPage(page);
           PDPageContentStream contentStream = new PDPageContentStream(doc, page);

           PDFont pdfFont = PDType1Font.HELVETICA;
           float fontSize = 25;
           float leading = 1.5f * fontSize;

           PDRectangle mediabox = page.getMediaBox();
           float margin = 72;
           float width = mediabox.getWidth() - 2*margin;
           float startX = mediabox.getLowerLeftX() + margin;
           float startY = mediabox.getUpperRightY() - margin;

           String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox.An essay is, generally, a piece of writing that gives the author's own argument — but the definition is vague, overlapping with those of an article, a pamphlet, and a short story. Essays have traditionally been sub-classified as formal and informal. Formal essays are characterized by serious purpose, dignity, logical organization, length,whereas the informal essay is characterized by the personal element (self-revelation, individual tastes and experiences, confidential manner), humor, graceful style, rambling structure, unconventionality or novelty of theme.Lastly, one of the most attractive features of cats as housepets is their ease of care. Cats do not have to be walked. They get plenty of exercise in the house as they play, and they do their business in the litter box. Cleaning a litter box is a quick, painless procedure. Cats also take care of their own grooming. Bathing a cat is almost never necessary because under ordinary circumstances cats clean themselves. Cats are more particular about personal cleanliness than people are. In addition, cats can be left home alone for a few hours without fear. Unlike some pets, most cats will not destroy the furnishings when left alone. They are content to go about their usual activities until their owners return.";
           List<String> lines = new ArrayList<String>();
           int lastSpace = -1;
           while (text.length() > 0)
           {
               int spaceIndex = text.indexOf(' ', lastSpace + 1);
               if (spaceIndex < 0)
                   spaceIndex = text.length();
               String subString = text.substring(0, spaceIndex);
               float size = fontSize * pdfFont.getStringWidth(subString) / 1000;
               System.out.printf("'%s' - %f of %f\n", subString, size, width);
               if (size > width)
               {
                   if (lastSpace < 0)
                       lastSpace = spaceIndex;
                   subString = text.substring(0, lastSpace);
                   lines.add(subString);
                   text = text.substring(lastSpace).trim();
                   System.out.printf("'%s' is line\n", subString);
                   lastSpace = -1;
               }
               else if (spaceIndex == text.length())
               {
                   lines.add(text);
                   System.out.printf("'%s' is line\n", text);
                   text = "";
               }
               else
               {
                   lastSpace = spaceIndex;
               }
           }

           contentStream.beginText();
           contentStream.setFont(pdfFont, fontSize);
           contentStream.newLineAtOffset(startX, startY);
           float currentY=startY;
           for (String line: lines)
           {
               currentY -=leading;

               if(currentY<=margin)
               {

                   contentStream.endText();
                   contentStream.close();
                   PDPage new_Page = new PDPage();
                   doc.addPage(new_Page);
                   contentStream = new PDPageContentStream(doc, new_Page);
                   contentStream.beginText();
                   contentStream.setFont(pdfFont, fontSize);
                   contentStream.newLineAtOffset(startX, startY);
                   currentY=startY;
               }
               contentStream.showText(line);
               contentStream.newLineAtOffset(0, -leading);
           }
           contentStream.endText();
           contentStream.close();

           doc.save("C:/Users/VINAYAK/Desktop/docccc/break-long-string.pdf");
       }
       finally
       {
           if (doc != null)
           {
               doc.close();
           }
       }

   }
}
</code>```

Body:
I am using Pdfbox to generate PDF files using Java. The problem is that when i add long text contents in the document, it is not displayed properly. Only a part of it is displayed. That too in a single line.

I want text to be in multiple lines.

My code is given below:

PDPageContentStream pdfContent=new PDPageContentStream(pdfDocument, pdfPage, true, true);

pdfContent.beginText();
pdfContent.setFont(pdfFont, 11);
pdfContent.moveTextPositionByAmount(30,750);
pdfContent.drawString("I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox");
pdfContent.endText();

My output:


来源: stackexchange

问:
ERROR: Cannot find outputs of project output group 'Content Files from Web (Active)'
I just tried to implement automate build of our project on server, I use devenv to build vdproj project on jenkins. Everything is fine when I use devenv command line in local vm.
Project is using VS2017 to build and also using 2017 to develop.

But things get weird when I use same command line on server

devenv c:\jenkins\workspace\ABC\ABC.sln /Rebuild Release /Project WebInstaller\WebInstaller.vdproj /ProjectConfig Release

When I run it on server, it failed when validate vdproj project, error message shows:

------ Starting pre-build validation for project 'WebInstaller' ------

WARNING: All custom dialogs must precede the 'Installation Folder'
  dialog.

ERROR: Cannot find outputs of project output group 'Content Files from
  Web (Active)'.  Either the group, its configuration, or
  its project may have been removed from the solution.

ERROR: Cannot find outputs of project output group 'Primary output
  from Web (Active)'.  Either the group, its configuration,
  or its project may have been removed from the solution.

------ Pre-build validation for project 'WebInstaller' completed ------

Just don't know why this happen, I download same workspace from jenkins and build local, it works fine.

There's may be a clue that I find Web project always cannot build when build solution.

devenv /Rebuild Release /Project Web\Web.csproj c:\jenkins\workspace\ABC\ABC.sln

The message shows nothing is build after run this on server:

Microsoft Visual Studio 2017 Version 15.0.27004.2002.

Copyright (C) Microsoft Corp. All rights reserved.

========== Rebuild All: 0 succeeded, 0 failed, 0 skipped ==========

It builds nothing for Web Project.

Does anyone encounter same issue or has any thoughts on this?

答:
Our project suffered the same issue, in Visual Studio 2015.

Build Server:  Windows 10 Pro, build 1607.
CI Agent:  CruiseControl.NET.
VS:  Visual Studio Pro, Update 3 with VS Installer Projects Extension.
IIS: Not installed.

The problem manifested in solution files that contained Assembly project(s), WinForms project(s), Web project(s), and Setup project(s) when built using the  task in CC.NET.  The project builds without fail when from within the IDE on the CI server (and all developer machines).

Examination of 'Diagnostic' build logs provided no information as to why this one project was being skipped.

[Devenv (rather than MSBuild) is required to build the setup project(s).  We don't have mixed solutions without setup projects, so it is not clear if this issue would manifest using MSBuild tasks.]

After much frustration over this and establishing that a test solution made with freshly created, empty projects of the various types would build correctly, we compared the solution and project files.

Long, painful story short, setting the <UseIIS> tag to 'True' in the web project(s) seems to fix the issue for our environment.

```<code>  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>True</UseIIS>
</code>```

It is unclear why this worked for us.

Of course, our files are checked into source control with this tag as 'False' (developers typically use IISExpress, and no, setting the <UseIISExpress> tag to 'True' did not help), so automating a change to this element became another step for the CI server.

ContentLicense: CC BY-SA 3.0

Body:
Our project suffered the same issue, in Visual Studio 2015.

Build Server:  Windows 10 Pro, build 1607.
CI Agent:  CruiseControl.NET.
VS:  Visual Studio Pro, Update 3 with VS Installer Projects Extension.
IIS: Not installed.

The problem manifested in solution files that contained Assembly project(s), WinForms project(s), Web project(s), and Setup project(s) when built using the  task in CC.NET.  The project builds without fail when from within the IDE on the CI server (and all developer machines).

Examination of 'Diagnostic' build logs provided no information as to why this one project was being skipped.

[Devenv (rather than MSBuild) is required to build the setup project(s).  We don't have mixed solutions without setup projects, so it is not clear if this issue would manifest using MSBuild tasks.]

After much frustration over this and establishing that a test solution made with freshly created, empty projects of the various types would build correctly, we compared the solution and project files.

Long, painful story short, setting the <UseIIS> tag to 'True' in the web project(s) seems to fix the issue for our environment.

  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>True</UseIIS>

It is unclear why this worked for us.

Of course, our files are checked into source control with this tag as 'False' (developers typically use IISExpress, and no, setting the <UseIISExpress> tag to 'True' did not help), so automating a change to this element became another step for the CI server.


问:
Multiple scrollviews inside each other
I have a vertical paged scrollview inside a horizontal scrollview.
The horizontal scrollview works but the vertical one does not.

I used scrollView.contentSize=CGSize(500,2000) on vertical scrollview but it is still not working.

Now what is the problem?

I should say, the vertical one added to view, programmatically using xib.

this is my Main.swift (i have no storyboard):

```<code>class test: UIViewController {

@IBOutlet weak var scroll: UIScrollView!
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewDidLayoutSubviews() {

    let myView3:TourDetailsDescription = TourDetailsDescription(frame: CGRect(x: 0, y: 0, width: scroll.frame.width, height: scroll.frame.height))
    myView3.getView().frame.origin.x = CGFloat(2*scroll.frame.width)
    scroll.addSubview(myView3)

    let img1:UIImageView = UIImageView(image: UIImage(named: "kavir"))
    img1.frame = CGRect(x: 0, y: 0, width: 300, height: 600)
    myView3.mainScroll.addSubview(img1)
    myView3.mainScroll.contentSize = CGSize(width: 300, height: 600)

    self.scroll.contentSize = CGSize(width:UIScreen.main.bounds.width * CGFloat(2), height:self.scroll.frame.height)
}
}
</code>```

and my TourDetailsDescription.swift :

class TourDetailsDescription: UIView {

```<code>@IBOutlet weak var mainScroll: UIScrollView!
var parent:UIView!
@IBOutlet var contentView: UIView!

override init(frame: CGRect) {
    super.init(frame: frame)
    commitInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commitInit()
}
private func commitInit(){
    Bundle.main.loadNibNamed("TourDetailsDescription", owner: self, options: nil)
    addSubview(contentView)
    contentView.frame = self.bounds
    contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}

func getView()->UIView{
    return contentView
}
}
</code>```

答:
May be this help you :), this is working on playground</p>

```<code>class ScrollingViewController : UIViewController {

override func loadView() {

    let contentView = UIView(frame: CGRect(x: 0, y: 20, width: 2000, height: 200))
    contentView.backgroundColor = .green

    let scrollView = UIScrollView()
    scrollView.contentSize = contentView.frame.size
    scrollView.addSubview(contentView)
    scrollView.flashScrollIndicators()
    scrollView.backgroundColor = .white

    let verticalContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    verticalContainerView.backgroundColor = .blue

    let verticalContentView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 2000))
    verticalContentView.backgroundColor = .red

    let verticalScrollView = UIScrollView(frame: verticalContainerView.frame)
    verticalScrollView.contentSize = verticalContentView.frame.size
    verticalScrollView.addSubview(verticalContentView)
    scrollView.flashScrollIndicators()
    verticalScrollView.backgroundColor = .white

    verticalContainerView.addSubview(verticalScrollView)

    contentView.addSubview(verticalContainerView)

    self.view = scrollView
}

}

PlaygroundPage.current.liveView = ScrollingViewController()
</code>```

Title: Multiple scrollviews inside each other

Body:
I have a vertical paged scrollview inside a horizontal scrollview.
The horizontal scrollview works but the vertical one does not.

I used scrollView.contentSize=CGSize(500,2000) on vertical scrollview but it is still not working.

Now what is the problem?

I should say, the vertical one added to view, programmatically using xib.

this is my Main.swift (i have no storyboard):

class test: UIViewController {

@IBOutlet weak var scroll: UIScrollView!
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewDidLayoutSubviews() {

    let myView3:TourDetailsDescription = TourDetailsDescription(frame: CGRect(x: 0, y: 0, width: scroll.frame.width, height: scroll.frame.height))
    myView3.getView().frame.origin.x = CGFloat(2*scroll.frame.width)
    scroll.addSubview(myView3)

    let img1:UIImageView = UIImageView(image: UIImage(named: "kavir"))
    img1.frame = CGRect(x: 0, y: 0, width: 300, height: 600)
    myView3.mainScroll.addSubview(img1)
    myView3.mainScroll.contentSize = CGSize(width: 300, height: 600)

    self.scroll.contentSize = CGSize(width:UIScreen.main.bounds.width * CGFloat(2), height:self.scroll.frame.height)
}
}

and my TourDetailsDescription.swift :

class TourDetailsDescription: UIView {

@IBOutlet weak var mainScroll: UIScrollView!
var parent:UIView!
@IBOutlet var contentView: UIView!

override init(frame: CGRect) {
    super.init(frame: frame)
    commitInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commitInit()
}
private func commitInit(){
    Bundle.main.loadNibNamed("TourDetailsDescription", owner: self, options: nil)
    addSubview(contentView)
    contentView.frame = self.bounds
    contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}

func getView()->UIView{
    return contentView
}
}

Body:
May be this help you :), this is working on playground

class ScrollingViewController : UIViewController {

override func loadView() {

    let contentView = UIView(frame: CGRect(x: 0, y: 20, width: 2000, height: 200))
    contentView.backgroundColor = .green

    let scrollView = UIScrollView()
    scrollView.contentSize = contentView.frame.size
    scrollView.addSubview(contentView)
    scrollView.flashScrollIndicators()
    scrollView.backgroundColor = .white

    let verticalContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    verticalContainerView.backgroundColor = .blue

    let verticalContentView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 2000))
    verticalContentView.backgroundColor = .red

    let verticalScrollView = UIScrollView(frame: verticalContainerView.frame)
    verticalScrollView.contentSize = verticalContentView.frame.size
    verticalScrollView.addSubview(verticalContentView)
    scrollView.flashScrollIndicators()
    verticalScrollView.backgroundColor = .white

    verticalContainerView.addSubview(verticalScrollView)

    contentView.addSubview(verticalContainerView)

    self.view = scrollView
}

}

PlaygroundPage.current.liveView = ScrollingViewController()


问:
Create a cert with multiple subject alt names with Ansible
I'm using a block like below

```<code>- name: Ensure that the existing certificate has a certain domain in its subjectAltName
  openssl_certificate:
    path: /etc/ssl/crt/example.com.crt
    provider: selfsigned
    subject_alt_name:
      - www.example.com
      - test.example.com
</code>```

To generate a selfsigned cert with Ansible, I'd like to use the ips in my inventory file as subject_alt_names something like

```<code>- name: Generate cert
  openssl_certificate:
    path: ssl/mongo-test.crt
    privatekey_path: ssl/mongo-test.pem
    csr_path: ssl/mongo-test.csr
    provider: selfsigned
    subject_alt_name:
      - IP:{{hostvars[item].ansible_host}}
</code>```

So that I end up with

```<code>- name: Generate cert
  openssl_certificate:
    path: ssl/mongo-test.crt
    privatekey_path: ssl/mongo-test.pem
    csr_path: ssl/mongo-test.csr
    provider: selfsigned
    subject_alt_name:
      - IP:10.136.31.37
      - IP:10.136.29.52
      - IP:10.136.30.53
</code>```

How do I get all my inventory ips to come under the subject_alt_name list?

I've tried using with_items but that creates a new cert per ip address and each iteration overwrites the last.

答:
I know that I am not answering to your question directly but I had the same problem and I chose another approach, hopping it could apply to you too.

I created an openssl.conf file that is templated with Jinja:

```<code>[ req ]
prompt = no
distinguished_name = req_distinguished_name
{% if letsencrypt_sans_domains[item] is defined and letsencrypt_sans_domains[item] | length > 0 %}
req_extensions     = req_ext
{% endif %}

string_mask = utf8only
default_md = sha256

[ req_distinguished_name ]
O=Organization
L=Boston
ST=Massachusetts
C=US
CN={{ item }}

{% if letsencrypt_sans_domains[item] is defined and letsencrypt_sans_domains[item] | length > 0 %}
[ req_ext ]
subjectAltName          = @alt_names

[alt_names]
DNS.1 = {{ item }}
{% set i = 2 %}
{% for domain in letsencrypt_sans_domains[item] %}
DNS.{{ i }} = {{ domain }}
{% set i = i + 1 %}
{% endfor %}
{% endif %}
</code>```

Then I deploy the file using template module and call:

```<code>- name: "Generate CSR"
  command: "openssl req -config openssl_req_{{ item }}.conf -nodes -new -newkey rsa:4096 -out {{ item }}.csr -keyout {{ item }}.key"
  with_items: "{{ letsencrypt_domains | default([]) }}"
</code>```

The variables letsencrypt_sans_domains and letsencrypt_domains point to:

```<code>letsencrypt_domains: [
  "a.b.com"
],
letsencrypt_sans_domains: {
  "a.b.com": [ "b.b.com", "c.b.com", "d.b.com" ]
}
</code>```

}

Of course if letsencrypt is your use case, you'll need to answer the challenge for all SANs domain

Body:
I'm using a block like below

- name: Ensure that the existing certificate has a certain domain in its subjectAltName
  openssl_certificate:
    path: /etc/ssl/crt/example.com.crt
    provider: selfsigned
    subject_alt_name:
      - www.example.com
      - test.example.com

To generate a selfsigned cert with Ansible, I'd like to use the ips in my inventory file as subject_alt_names something like

- name: Generate cert
  openssl_certificate:
    path: ssl/mongo-test.crt
    privatekey_path: ssl/mongo-test.pem
    csr_path: ssl/mongo-test.csr
    provider: selfsigned
    subject_alt_name:
      - IP:{{hostvars[item].ansible_host}}

So that I end up with

- name: Generate cert
  openssl_certificate:
    path: ssl/mongo-test.crt
    privatekey_path: ssl/mongo-test.pem
    csr_path: ssl/mongo-test.csr
    provider: selfsigned
    subject_alt_name:
      - IP:10.136.31.37
      - IP:10.136.29.52
      - IP:10.136.30.53

How do I get all my inventory ips to come under the subject_alt_name list?

I've tried using with_items but that creates a new cert per ip address and each iteration overwrites the last.

Body:
I know that I am not answering to your question directly but I had the same problem and I chose another approach, hopping it could apply to you too.

I created an openssl.conf file that is templated with Jinja:

[ req ]
prompt = no
distinguished_name = req_distinguished_name
{% if letsencrypt_sans_domains[item] is defined and letsencrypt_sans_domains[item] | length > 0 %}
req_extensions     = req_ext
{% endif %}

string_mask = utf8only
default_md = sha256

[ req_distinguished_name ]
O=Organization
L=Boston
ST=Massachusetts
C=US
CN={{ item }}

{% if letsencrypt_sans_domains[item] is defined and letsencrypt_sans_domains[item] | length > 0 %}
[ req_ext ]
subjectAltName          = @alt_names

[alt_names]
DNS.1 = {{ item }}
{% set i = 2 %}
{% for domain in letsencrypt_sans_domains[item] %}
DNS.{{ i }} = {{ domain }}
{% set i = i + 1 %}
{% endfor %}
{% endif %}

Then I deploy the file using template module and call:

- name: "Generate CSR"
  command: "openssl req -config openssl_req_{{ item }}.conf -nodes -new -newkey rsa:4096 -out {{ item }}.csr -keyout {{ item }}.key"
  with_items: "{{ letsencrypt_domains | default([]) }}"

The variables letsencrypt_sans_domains and letsencrypt_domains point to:

letsencrypt_domains: [
  "a.b.com"
],
letsencrypt_sans_domains: {
  "a.b.com": [ "b.b.com", "c.b.com", "d.b.com" ]
}

}

Of course if letsencrypt is your use case, you'll need to answer the challenge for all SANs domain


问:
Altering a View to add a column as bit not null
I'm trying to add a column to a view using ALTER VIEW but it keeps saying 'The column is invalid'. I need the column to be BIT NOT NULL. How would I go about doing this?  Thank you all!

```<code>SELECT dbo.tbl_skins.skinName, dbo.tbl_prefs.PersonID, dbo.tbl_prefs[columnName] etc...
FROM dbo.tbl_prefs
INNER JOIN dbo.tbl_skins
   ON dbo.tbl_prefs.skinId = dbo.tbl_skins.skinId
</code>```

I didn't add the rest of the columns because the rest are all from dbo.tbl_prefs. The only one that is different is that first one that reads dbo.tbl_skins.skinName.

Upon opening the table I see,

```<code>SELECT TOP (1000) [column1],[column2], etc... FROM [table_name].
</code>```

All I'm trying to do is add a new column of type BIT, NOT NULL to the table (dbo.tbl_prefs) and the same to the view (dbo.qry_prefs).

答:
try this----

create table #temp (
  col_1   varchar(15) not null,
  col_2   varchar(15) not null
);

create view tq84_v as select col_1, col_2 from

Body:
I'm trying to add a column to a view using ALTER VIEW but it keeps saying 'The column is invalid'. I need the column to be BIT NOT NULL. How would I go about doing this?  Thank you all!

SELECT dbo.tbl_skins.skinName, dbo.tbl_prefs.PersonID, dbo.tbl_prefs[columnName] etc...
FROM dbo.tbl_prefs
INNER JOIN dbo.tbl_skins
   ON dbo.tbl_prefs.skinId = dbo.tbl_skins.skinId

I didn't add the rest of the columns because the rest are all from dbo.tbl_prefs. The only one that is different is that first one that reads dbo.tbl_skins.skinName.

Upon opening the table I see,

SELECT TOP (1000) [column1],[column2], etc... FROM [table_name].

All I'm trying to do is add a new column of type BIT, NOT NULL to the table (dbo.tbl_prefs) and the same to the view (dbo.qry_prefs).


问:
hiding text on mobile and hiding on sizes above mobile
I'm hiding some text with the following code

```<code>/* Smartphones in portrait mode (0-401px) */
@media only screen and ( max-width: 401px ) {
    .dontdisplayonmobile    {
    display: none !important;
}
}
</code>```

It stops it displaying on mobile. but the spacing it creates is still there so it's making the text go but not completely going as if there's nothing there.

I tried adding , but it didn't work

```<code>margin: 0 !important;
padding: 0 !important;
</code>```

Any ideas.?

EDIT

Does anyone know the best way to media query when you want to hide something on anything above 401 px for example.

Do you just put 100000000 or similar so it never shows ?

答:
you only should need html like this

```<code><span class="dontdisplayonmobile">Free Quotes. </span><span class="calltodayword">Call today.</span> <a href="tel:01216631202"><i class="fa fa-phone icon-phone"></i> 0121-663-1202</a>

@media only screen and ( max-width: 401px ) {
  .dontdisplayonmobile    {
    display: none;
  }
}
</code>```

so you are only hiding the part with "Free Quotes"

Body:
I'm hiding some text with the following code

/* Smartphones in portrait mode (0-401px) */
@media only screen and ( max-width: 401px ) {
    .dontdisplayonmobile    {
    display: none !important;
}
}

It stops it displaying on mobile. but the spacing it creates is still there so it's making the text go but not completely going as if there's nothing there.

I tried adding , but it didn't work

margin: 0 !important;
padding: 0 !important;

Any ideas.?

EDIT

Does anyone know the best way to media query when you want to hide something on anything above 401 px for example.

Do you just put 100000000 or similar so it never shows ?

Body:
you only should need html like this

<span class="dontdisplayonmobile">Free Quotes. </span><span class="calltodayword">Call today.</span> <a href="tel:01216631202"><i class="fa fa-phone icon-phone"></i> 0121-663-1202</a>

@media only screen and ( max-width: 401px ) {
  .dontdisplayonmobile    {
    display: none;
  }
}

so you are only hiding the part with "Free Quotes"


问:
Angular 2 Stop *NgFor if certain value is funded
I have a JSon like this:

```<code>[
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country2", etc...}
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country1", etc...}
]
</code>```

...and code:

```<code><ng-container *ngFor="let contact of contacts">
  <ng-container *ngIf="contact.country == 'country1'">
  <div>COUNTRY1</div>
</ng-container></ng-container>
</code>```

This code create the COUNTRY1 every time it find "country1"
i'd like to print the country value once. is it possible?

答:
You have to create a pipe that filters the array with unique items:

```<code>@Pipe({
  name: 'filterUnique',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    // Remove the duplicate elements
    let uniqueArray = value.filter(function (el, index, array) {
      return array.indexOf (el) == index;
    });

    return uniqueArray;
  }
}
</code>```

Then you can apply your pipe:

```<code><ng-container *ngFor="let contact of contacts | filterUnique">
  <ng-container ...>
  <div>COUNTRY1</div>
</ng-container></ng-container>
</code>```

Working example: https://plnkr.co/edit/yxvoKVD3Nvgz0T3AB7w3?p=preview

OR

If you don't want to use pipes then you can use a set of all the values:

```<code>myList = [
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country2", etc...}
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country1", etc...}
];

myNewSet =  Array.from(new Set(myList ));
</code>```

Then use this set in the template.

Body:
I have a JSon like this:

[
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country2", etc...}
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country1", etc...}
]

...and code:

<ng-container *ngFor="let contact of contacts">
  <ng-container *ngIf="contact.country == 'country1'">

COUNTRY1

</ng-container></ng-container>

This code create the COUNTRY1 every time it find "country1"
i'd like to print the country value once. is it possible?

Body:
You have to create a pipe that filters the array with unique items:

@Pipe({
  name: 'filterUnique',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    // Remove the duplicate elements
    let uniqueArray = value.filter(function (el, index, array) {
      return array.indexOf (el) == index;
    });

    return uniqueArray;
  }
}

Then you can apply your pipe:

<ng-container *ngFor="let contact of contacts | filterUnique">
  <ng-container ...>
  <div>COUNTRY1</div>
</ng-container></ng-container>

Working example: https://plnkr.co/edit/yxvoKVD3Nvgz0T3AB7w3?p=preview

OR

If you don't want to use pipes then you can use a set of all the values:

myList = [
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country2", etc...}
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country1", etc...}
];

myNewSet =  Array.from(new Set(myList ));

Then use this set in the template.


问:
Removing "NUL" characters
I have got characters like that in my notepad++

When i am trying to copy whole line, i am actually copying everything until "NUL":

```<code>File:1
</code>```

What i want to do, is replace those null, to be nothing, so i can copy my whole line.
Maybe there is any keyword that will tell notepad++(or any other program that might help) to replace those characters?
When i am selecting it, use Right Click and then "clear", its gone - but i dont want to do it one by one.

I don't care about removing the cause of this problem, just the effect(NULs)

答:
I was having same problem. The above put me on the right track but was not quite correct in my case. What did work was closely related:

Open your file in Notepad++

Type Control-A (select all)

Type Control-H (replace)

In 'Find What' type \x00

In 'Replace With' leave BLANK

In 'Search Mode' Selected 'Extended'

Then Click on 'Replace All'

Title: Removing "NUL" characters

Body:
I have got characters like that in my notepad++

When i am trying to copy whole line, i am actually copying everything until "NUL":

File:1

What i want to do, is replace those null, to be nothing, so i can copy my whole line.
Maybe there is any keyword that will tell notepad++(or any other program that might help) to replace those characters?
When i am selecting it, use Right Click and then "clear", its gone - but i dont want to do it one by one.

I don't care about removing the cause of this problem, just the effect(NULs)

ContentLicense: CC BY-SA 4.0


问:
Linux sed command
Can anyone help me understand what the following command does in Linux.</p>

```<code>sed -i file.c -e "s/  __attribute__ ((__unused__))$$/# ifndef __cplusplus\n  __attribute__ ((__unused__));\n# endif/"
</code>```

答: It adds # ifndef __cplusplus and # endif around __attribute__ ((__unused__)); in file.c

ContentLicense: CC BY-SA 2.5

Title: Linux sed command

Body:
Can anyone help me understand what the following command does in Linux.

sed -i file.c -e "s/  __attribute__ ((__unused__))$$/# ifndef __cplusplus\n  __attribute__ ((__unused__));\n# endif/"


问:
Appcelerator app crash after taking picture
My app crashes after taking a picture with the camera.
This has never happened before Using titanium SDK 6.3.0 on iOS 11.
Does anyone have a solution?
thanks </p>

```<code>Titanium.Media.showCamera({
                        success: function(event) {
                            lObjPhoto = event.media;
                            parameters.callbackApply(lObjPhoto);
                        },
                        cancel: function() {
                            lObjPhoto = null;
                            lObjThumb = null;
                            parameters.callbackApply(lObjPhoto);
                        },
                        error: function(error) {
                                lObjPhoto = null;
                                var a = Titanium.UI.createAlertDialog({title:'Camera', ok: 'Ok'});
                                if (error.code == Titanium.Media.NO_CAMERA) a.setMessage('Device does not have camera');
                                else a.setMessage('Unexpected error: ' + error.code);
                                a.show();
                                parameters.callbackApply(lObjPhoto);
                        },
                        allowImageEditing: false,
                        saveToPhotoGallery: false,
                    })
</code>```

答:
Also use the below code for Marshmallow and above to accept permission

```<code>var permissions = ['android.permission.CAMERA', 'android.permission.READ_EXTERNAL_STORAGE'];
Ti.Android.requestPermissions(permissions, function(e) {
if (e.success) {
   //Action
   Ti.API.info("Success");

  });
} else {
    Ti.API.info("ERROR: " + e.error);
}
</code>```

});

Body:
My app crashes after taking a picture with the camera.
This has never happened before Using titanium SDK 6.3.0 on iOS 11.
Does anyone have a solution?
thanks

Titanium.Media.showCamera({
                        success: function(event) {
                            lObjPhoto = event.media;
                            parameters.callbackApply(lObjPhoto);
                        },
                        cancel: function() {
                            lObjPhoto = null;
                            lObjThumb = null;
                            parameters.callbackApply(lObjPhoto);
                        },
                        error: function(error) {
                                lObjPhoto = null;
                                var a = Titanium.UI.createAlertDialog({title:'Camera', ok: 'Ok'});
                                if (error.code == Titanium.Media.NO_CAMERA) a.setMessage('Device does not have camera');
                                else a.setMessage('Unexpected error: ' + error.code);
                                a.show();
                                parameters.callbackApply(lObjPhoto);
                        },
                        allowImageEditing: false,
                        saveToPhotoGallery: false,
                    })

Body:
Also use the below code for Marshmallow and above to accept permission

var permissions = ['android.permission.CAMERA', 'android.permission.READ_EXTERNAL_STORAGE'];
Ti.Android.requestPermissions(permissions, function(e) {
if (e.success) {
   //Action
   Ti.API.info("Success");

  });
} else {
    Ti.API.info("ERROR: " + e.error);
}

});


问:
vuejs namespace getters undefined error
I am having difficulties testing namespaced getters although it works I am not able to test it successfully.</p>

```<code>getContextMenuListSelectedState: function (menu) {
  return this.$store.getters['appContext/getContextMenuListSelectedState'](menu)
}

<view-switcher @switchView="setCurrentView" />

setCurrentView: function (obj) {
...
let maintSelected = this.getContextMenuListSelectedState('docsmaint').label === 'maint'
...
}

is throwing an error in test:
'[Vue warn]: Error in event handler for "switchView": "TypeError: this.$store.getters**.appContext/getContextMenuListSelectedState** is not a function"
</code>```

答:
The error was quite misleading. I finally was able to stub it with a fake. After refactoring it as provided above.</p>

```<code> function fakeGetter (menu) {
      return store.state.appContext.contextMenusLists[menu].filter((item) => {
        return item.selected
      })
    }

getContextMenuListSelectedStateSpy = sinon.stub(omsLayout.methods, 'getContextMenuListSelectedState').callsFake(fakeGetter)
</code>```

Title: vuejs namespace getters undefined error

Body:
I am having difficulties testing namespaced getters although it works I am not able to test it successfully.

getContextMenuListSelectedState: function (menu) {
  return this.$store.getters['appContext/getContextMenuListSelectedState'](menu)
}

<view-switcher @switchView="setCurrentView" />

setCurrentView: function (obj) {
...
let maintSelected = this.getContextMenuListSelectedState('docsmaint').label === 'maint'
...
}

is throwing an error in test:
'[Vue warn]: Error in event handler for "switchView": "TypeError: this.$store.getters**.appContext/getContextMenuListSelectedState** is not a function"

Body:
The error was quite misleading. I finally was able to stub it with a fake. After refactoring it as provided above.

 function fakeGetter (menu) {
      return store.state.appContext.contextMenusLists[menu].filter((item) => {
        return item.selected
      })
    }

getContextMenuListSelectedStateSpy = sinon.stub(omsLayout.methods, 'getContextMenuListSelectedState').callsFake(fakeGetter)


问:
MouseMotionListener on MouseDragged Only Returns The Component The Drag Started On
I have been trying to make a lock screen program which is a JFrame that contains multiple JPanels inside. I have added a MouseMotionListener in each panel (Cell) class. I would like it so that the user can drag the mouse and be able to drag into multiple cells. The problem is that MouseEvent.GetSource (casted to a cell) is only returning the cell that the drag started from. Here's my code.</p>

```<code>public class Cell extends JPanel {

    public String name;

    public Cell(String name, Color color) {
        this.name = name;
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                onMouseOver(e);
            }
        });
        setBackground(color);
        setVisible(true);
        repaint();
    }

    private void onMouseOver(MouseEvent e) {
        System.out.println(name);
    }
}
</code>```

答:
The problem is that MouseEvent.GetSource (casted to a cell) is only returning the cell that the drag started from

That is correct. All events will be relative to the cell that you clicked on when dragging started.

If you want to know what cell you are currently over then you need to do the calculation yourself.

So you can use getPoint() method from the MouseEvent and then calculate the component you are over.

So for example you could convert the point to the parent container using the SwingUtilities.convertPoint(...) method.

Then once you have the Point relative to the parent container you can find the current component on the container using the Container.findComponentAt(...) method.

You will need to keep track of every component you find. Maybe add the component to a Set.

Or, instead of adding the listener to every cell. You could just add the listener to the parent panel. Then all the points will be relative to the panel so you won't need to convert point, just do the findComponentAt(...) logic.

Body:
I have been trying to make a lock screen program which is a JFrame that contains multiple JPanels inside. I have added a MouseMotionListener in each panel (Cell) class. I would like it so that the user can drag the mouse and be able to drag into multiple cells. The problem is that MouseEvent.GetSource (casted to a cell) is only returning the cell that the drag started from. Here's my code.

public class Cell extends JPanel {

    public String name;

    public Cell(String name, Color color) {
        this.name = name;
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                onMouseOver(e);
            }
        });
        setBackground(color);
        setVisible(true);
        repaint();
    }

    private void onMouseOver(MouseEvent e) {
        System.out.println(name);
    }
}


问:
How to Name your Tables after the Sheet Names
I want to name my tables I'm creating in VBA according to the worksheet name they're on.

```<code>   With myTable
                .Name = Application.Caller.Worksheet.Name
                .TableStyle = "TableStyleLight1"
            End With
</code>```

I get a run time error '424' which says "Object Required"

How do I have the tables I'm creating via previous code name the tables the same as the worksheet names?

答:
Use the Parent property to get the name of the worksheet (the parent object of a table).

```<code>With myTable
    .Name = .Parent.Name
End With
</code>```

Body:
I want to name my tables I'm creating in VBA according to the worksheet name they're on.

   With myTable
                .Name = Application.Caller.Worksheet.Name
                .TableStyle = "TableStyleLight1"
            End With

I get a run time error '424' which says "Object Required"

How do I have the tables I'm creating via previous code name the tables the same as the worksheet names?

Body:
Use the Parent property to get the name of the worksheet (the parent object of a table).

With myTable
    .Name = .Parent.Name
End With


问:
What does Tokens do and why they need to be created in C++ programming?
I am reading a book (Programming Principles and Practice by Bjarne Stroustrup).

In which he introduce Tokens:

“A token is a sequence of characters that represents something we consider a unit, such as a number or an operator. That’s the way a C++ compiler deals with its source. Actually, “tokenizing” in some form or another is the way most analysis of text starts.”

```<code>class Token {
public:
    char kind;
    double value;
};
</code>```

I do get what they are but he never explains this in detail and its quite confusing to me.

答:
As mentioned by others Bjrane is referring to Lexical analysis.

In general terms tokenizing || creating tokens, is a process of processing input streams and dividing them into blocks, without worrying about whitespaces etc. best described earlier by @StoryTeller.
 "or as bjrane said: is a sequence of characters that represent something we consider a unit".

The token itself is an example of a C++ user-defined type'UDT' like int or char, so token can be used to define variables and hold values.

UDT can have member functions as well as data members. In your code you define two member functions which is very basic.

1)Kind, 2)Value

```<code>class Token {
public:
   char kind;
   double value;
};
</code>```

Based on it we can initialize or construct its objects.

```<code>Token token_kind_one{'+'};
</code>```

Initializing token_kind_one with its kind(operator) '+'.

```<code>Token token_kind_two{'8',3.14};
</code>```

and token_kind_two with its kind(integer/number) '8' and with a value of 3.14.

Lets assume we have an expression of ten characters 1+2*3(5/4), which translates to ten tokens.

Tokens:

```<code>        |----------------------|---------------------|
Kind    |'8' |'+' |'8' |'*'|'8'|'('|'8' |'/'|'8' |')'|
        |----------------------|---------------------|
Value   | 1  |    | 2  |   | 3 |   | 5  |   | 4  |   |
        |----------------------|---------------------|
</code>```

C++ compiler transfer file data to a token sequence skipping all whitespaces. To make it understandable to itself.

Body:
I am reading a book (Programming Principles and Practice by Bjarne Stroustrup).

In which he introduce Tokens:

“A token is a sequence of characters that represents something we consider a unit, such as a number or an operator. That’s the way a C++ compiler deals with its source. Actually, “tokenizing” in some form or another is the way most analysis of text starts.”

class Token {
public:
    char kind;
    double value;
};

I do get what they are but he never explains this in detail and its quite confusing to me.

Body:
As mentioned by others Bjrane is referring to Lexical analysis.

In general terms tokenizing || creating tokens, is a process of processing input streams and dividing them into blocks, without worrying about whitespaces etc. best described earlier by @StoryTeller.
 "or as bjrane said: is a sequence of characters that represent something we consider a unit".

The token itself is an example of a C++ user-defined type'UDT' like int or char, so token can be used to define variables and hold values.

UDT can have member functions as well as data members. In your code you define two member functions which is very basic.

1)Kind, 2)Value

class Token {
public:
   char kind;
   double value;
};

Based on it we can initialize or construct its objects.

Token token_kind_one{'+'};

Initializing token_kind_one with its kind(operator) '+'.

Token token_kind_two{'8',3.14};

and token_kind_two with its kind(integer/number) '8' and with a value of 3.14.

Lets assume we have an expression of ten characters 1+2*3(5/4), which translates to ten tokens.

Tokens:

        |----------------------|---------------------|
Kind    |'8' |'+' |'8' |'*'|'8'|'('|'8' |'/'|'8' |')'|
        |----------------------|---------------------|
Value   | 1  |    | 2  |   | 3 |   | 5  |   | 4  |   |
        |----------------------|---------------------|

C++ compiler transfer file data to a token sequence skipping all whitespaces. To make it understandable to itself.


问:
When Is The Object Eligible For Garbage Collection?
In the code below, given that amethod has been called. At what point/line is the Object originally referenced by myObject, eligible for Garbage Collection?

```<code>class Test {
  private Object classObject;

  public void amethod() {
    Object myObject = new Object();
    classObject = myObject;
    myObject = null;
  }
}
</code>```

And if classObject or amethod had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected?

My first thought is that the Object is eligible for Garbage Collection when the Test object is eligible for Garbage Collection.

But then again. The optimizer may know that the classObject is never read from in which case classObject = myObject; would be optimized out and myObject = null; is the point it is eligible for Garbage Collection.

答:
This is actually addressed precisely by the Java Language Specification, §12.6.1,  Implementing Finalization :

Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.

Another example of this occurs if the values in an object's fields are stored in registers. The program may then access the registers instead of the object, and never access the object again. This would imply that the object is garbage. …

But

… Note that this sort of optimization is only allowed if references are on the stack, not stored in the heap.

For example, consider the Finalizer Guardian pattern:

```<code>   class Foo {
       private final Object finalizerGuardian = new Object() {
           protected void finalize() throws Throwable {
               /* finalize outer Foo object */
           }
       }
   }
</code>```

The finalizer guardian forces super.finalize to be called if a subclass overrides finalize and does not explicitly call super.finalize.

If these optimizations are allowed for references that are stored on the heap, then a Java compiler can detect that the finalizerGuardian field is never read, null it out, collect the object immediately, and call the finalizer early. This runs counter to the intent: the programmer probably wanted to call the Foo finalizer when the Foo instance became unreachable. This sort of transformation is therefore not legal: the inner class object should be reachable for as long as the outer class object is reachable.

This example can be applied 1:1 to your example, as long as the object is referenced by the instance field classObject, it can not get garbage collected earlier than the Test instance containing the reference.

Note, however, that the aggressive optimizations mentioned in the specification are still allowed, when being applied to the code using the Test instance. The earlier-than-expected collection may happen, as long as both, the Test instance and the referenced object are collected together. In this case, the following aspect specified in §12.6 applies:

The Java programming language imposes no ordering on finalize method calls. Finalizers may be called in any order, or even concurrently.

So it’s perfectly possible that the Test instance is collected earlier than the object referenced by classObject whereas the “inner” object’s finalizer is invoked earlier. The only thing that is guaranteed, is, that when the inner object’s finalizer runs, the outer object is unreachable (or has a pending or concurrent finalization). Since in your example, neither has a non-trivial finalizer, that doesn’t matter anyway…

Body:
In the code below, given that amethod has been called. At what point/line is the Object originally referenced by myObject, eligible for Garbage Collection?

class Test {
  private Object classObject;

  public void amethod() {
    Object myObject = new Object();
    classObject = myObject;
    myObject = null;
  }
}

And if classObject or amethod had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected?

My first thought is that the Object is eligible for Garbage Collection when the Test object is eligible for Garbage Collection.

But then again. The optimizer may know that the classObject is never read from in which case classObject = myObject; would be optimized out and myObject = null; is the point it is eligible for Garbage Collection.

Body:
This is actually addressed precisely by the Java Language Specification, §12.6.1,  Implementing Finalization :

Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.

Another example of this occurs if the values in an object's fields are stored in registers. The program may then access the registers instead of the object, and never access the object again. This would imply that the object is garbage. …

But

… Note that this sort of optimization is only allowed if references are on the stack, not stored in the heap.

For example, consider the Finalizer Guardian pattern:

   class Foo {
       private final Object finalizerGuardian = new Object() {
           protected void finalize() throws Throwable {
               /* finalize outer Foo object */
           }
       }
   }

The finalizer guardian forces super.finalize to be called if a subclass overrides finalize and does not explicitly call super.finalize.

If these optimizations are allowed for references that are stored on the heap, then a Java compiler can detect that the finalizerGuardian field is never read, null it out, collect the object immediately, and call the finalizer early. This runs counter to the intent: the programmer probably wanted to call the Foo finalizer when the Foo instance became unreachable. This sort of transformation is therefore not legal: the inner class object should be reachable for as long as the outer class object is reachable.

This example can be applied 1:1 to your example, as long as the object is referenced by the instance field classObject, it can not get garbage collected earlier than the Test instance containing the reference.

Note, however, that the aggressive optimizations mentioned in the specification are still allowed, when being applied to the code using the Test instance. The earlier-than-expected collection may happen, as long as both, the Test instance and the referenced object are collected together. In this case, the following aspect specified in §12.6 applies:

The Java programming language imposes no ordering on finalize method calls. Finalizers may be called in any order, or even concurrently.

So it’s perfectly possible that the Test instance is collected earlier than the object referenced by classObject whereas the “inner” object’s finalizer is invoked earlier. The only thing that is guaranteed, is, that when the inner object’s finalizer runs, the outer object is unreachable (or has a pending or concurrent finalization). Since in your example, neither has a non-trivial finalizer, that doesn’t matter anyway…


问:
Cannot assign through subscript: 'dict' is a 'let' constant
I have a very simple problem with Swift.
I created this function:

```<code>var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
     for (name, age) in dict {
          guard age >= 0 else {
          dict[name] = 0
          continue
          }
     }
}
correctAges(dict:dictAges)
</code>```

But I don't understand the error:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

How can I solve it?

答:
Your expectation that you can mutate a dictionary passed into a function is wrong, for the simple reason that a dictionary in Swift is a value type. And the types inside the dictionary, String and Int, are values too. This means that, in effect, the parameter dict is a copy of the original dictAges. Nothing that you do to dict can have any effect on dictAges.

This is a sign that you should rethink your entire architecture. If it was wrong to enter a negative number as an age, you should have caught that up front, as it was being entered. In effect, your entire use of a dictionary of Ints as the model here is probably incorrect. You should have used a dictionary of Person, where Person is a struct with an age and a setter that prevents an age from being negative in the first place.

If you must have a function that runs through an arbitrary dictionary and fixes the values to be nonnegative, make that a feature of dictionaries themselves:

```<code>var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

extension Dictionary where Value : SignedInteger {
    mutating func fixAges() {
        for (k,v) in self {
            if v < 0 {
                self[k] = 0
            }
        }
    }
}

dictAges.fixAges()
</code>```

Body:
I have a very simple problem with Swift.
I created this function:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
     for (name, age) in dict {
          guard age >= 0 else {
          dict[name] = 0
          continue
          }
     }
}
correctAges(dict:dictAges)

But I don't understand the error:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

How can I solve it?

Body:
Your expectation that you can mutate a dictionary passed into a function is wrong, for the simple reason that a dictionary in Swift is a value type. And the types inside the dictionary, String and Int, are values too. This means that, in effect, the parameter dict is a copy of the original dictAges. Nothing that you do to dict can have any effect on dictAges.

This is a sign that you should rethink your entire architecture. If it was wrong to enter a negative number as an age, you should have caught that up front, as it was being entered. In effect, your entire use of a dictionary of Ints as the model here is probably incorrect. You should have used a dictionary of Person, where Person is a struct with an age and a setter that prevents an age from being negative in the first place.

If you must have a function that runs through an arbitrary dictionary and fixes the values to be nonnegative, make that a feature of dictionaries themselves:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

extension Dictionary where Value : SignedInteger {
    mutating func fixAges() {
        for (k,v) in self {
            if v < 0 {
                self[k] = 0
            }
        }
    }
}

dictAges.fixAges()


问:
How to add a list using (api sendgrid) cakephp
I'm trying to make requests in external Web Services with Cake HttpSocket, I'm trying to create a new list I'm getting an error from api sendgrid

[body] => {"errors":[{"message":"request body is invalid"}]}

```<code>public function addemail() {
    $HttpSocket = new HttpSocket();
    $lista = array('name' => 'Teste');
    $retorno = $HttpSocket->post('https://api.sendgrid.com/v3/contactdb/lists', $lista,
    array(
        'header' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer SG.XXXXXXXXX'
        )
    ));
    if ($retorno->isOk()) {
        debug($retorno->body());

    }
}
</code>```

what is wrong? in the sendgrid documentation says that the body should be this way

{
"name": "listname"
}

答:
You need to json encode the array like so:</p>

```<code>$lista = json_encode(array('name' => 'Teste'));
</code>```

Body:
I'm trying to make requests in external Web Services with Cake HttpSocket, I'm trying to create a new list I'm getting an error from api sendgrid

[body] => {"errors":[{"message":"request body is invalid"}]}

public function addemail() {
    $HttpSocket = new HttpSocket();
    $lista = array('name' => 'Teste');
    $retorno = $HttpSocket->post('https://api.sendgrid.com/v3/contactdb/lists', $lista,
    array(
        'header' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer SG.XXXXXXXXX'
        )
    ));
    if ($retorno->isOk()) {
        debug($retorno->body());

    }
}

what is wrong? in the sendgrid documentation says that the body should be this way

{
"name": "listname"
}

Body:
You need to json encode the array like so:

$lista = json_encode(array('name' => 'Teste'));


问:
Rank function inconsistency with the expected output in R
As I read about rank function, it has Ties.method to specify what happens when ties occur.

In this vector: c(2,3,4,4,5,6), As Matt Krause suggested:

average assigns each tied element the "average" rank. The ranks would therefore be 1, 2, 3.5, 3.5, 5, 6

first lets the "earlier" entry "win", so the ranks are in numerical order (1,2,3,4,5,6)

min assigns every tied element to the lowest rank, so you get 1,2,3,3,5,6

max does the opposite: tied elements get the highest rank (1,2,4,4,5,6)

random breaks ties randomly, so you'd get either (1,2,3,4,5,6) or (1,2,4,3,5,6).

BUT, I need this output: (1,2,3,3,4,5). What can I do for that?

I want to use the output to fill in another matrix (X) which has 5 columns. The final output for this instance should be : (1,1,2,1,1), which means that we have 2 of the third-ranked item and one of the rest.

Now, if we have (2,3,4,4,5,6) as instance 1 and (2,3,3,3,4,2) as instance 2, in matrix (X), they will be converted to:

(1,1,2,1,1)

(2,3,1,0,0)

(the number of the columns of matrix (X) equals to the number of unique values in all instances; considering that all numbers are between 2 to 6 which means we have 5 different values in total) ...

I think rank does not work in this situation correctly.

答:
There's probably a more efficient/shorter way to compute the unique values of the union of all instances, but otherwise this is pretty much as @whuber suggested in the comments:

Test case:

```<code>instances <- list(c(2,3,4,4,5,6),c(2,3,3,3,4,2))
</code>```

The only tricky part is making sure we have the full range of levels so that zeros get counted properly:

```<code>ulevs <- sort(unique(Reduce(union,instances)))
f <- function(x) {
   table(factor(x,levels=ulevs))
}
</code>```

Apply and convert to a matrix:

```<code>t(sapply(instances,f))
##      2 3 4 5 6
## [1,] 1 1 2 1 1
## [2,] 2 3 1 0 0
</code>```

OwnerDisplayName: Hadij

Body:
There's probably a more efficient/shorter way to compute the unique values of the union of all instances, but otherwise this is pretty much as @whuber suggested in the comments:

Test case:

instances <- list(c(2,3,4,4,5,6),c(2,3,3,3,4,2))

The only tricky part is making sure we have the full range of levels so that zeros get counted properly:

ulevs <- sort(unique(Reduce(union,instances)))
f <- function(x) {
   table(factor(x,levels=ulevs))
}

Apply and convert to a matrix:

t(sapply(instances,f))
##      2 3 4 5 6
## [1,] 1 1 2 1 1
## [2,] 2 3 1 0 0


问:
PCA() got an unexpected keyword argument 'k'
I am trying t perform pca from a spark application using PySpark API on a python script. I doing This way:

pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
PCAmodel = pca.fit(data)
```

when I run those two code line in the pyspark shell it work and return good results, but in an application script, I am getting the type of error:

PCA() got an unexpected keyword argument 'k'

PS: In both case I am using Spark 2.2.0

where is the problem? why it does work in the PySpark shell and not for the application?

答:
You probably imported from ml in one case:

```<code>from pyspark.ml.feature import PCA
</code>```

and mllib in the other:

```<code>from pyspark.mllib.feature import PCA
</code>```

Body:
I am trying t perform pca from a spark application using PySpark API on a python script. I doing This way:

pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
PCAmodel = pca.fit(data)

when I run those two code line in the pyspark shell it work and return good results, but in an application script, I am getting the type of error:

PCA() got an unexpected keyword argument 'k'

PS: In both case I am using Spark 2.2.0

where is the problem? why it does work in the PySpark shell and not for the application?

Body:
You probably imported from ml in one case:

from pyspark.ml.feature import PCA

and mllib in the other:

from pyspark.mllib.feature import PCA


答:
It's doing an inplace search-and-replace on file.c, looking for

```<code> __attribute__ (__unused__)
</code>```

at the end of a line, and replacing any occurences with

```<code># ifndef __cplusplus\n  __attribute__ (__unused__);\nendif
</code>```

which works out to:

```<code># ifndef __cplusplus
    __attribute__ (__unused__)
# endif
</code>```

THe doubled brackets and $ signs are to "escape" those characters in the shell.

Title: Linux sed command

Body:
Can anyone help me understand what the following command does in Linux.

sed -i file.c -e "s/  __attribute__ ((__unused__))$$/# ifndef __cplusplus\n  __attribute__ ((__unused__));\n# endif/"

Body:
It's doing an inplace search-and-replace on file.c, looking for

 __attribute__ (__unused__)

at the end of a line, and replacing any occurences with

# ifndef __cplusplus\n  __attribute__ (__unused__);\nendif

which works out to:

# ifndef __cplusplus
    __attribute__ (__unused__)
# endif

THe doubled brackets and $ signs are to "escape" those characters in the shell.


问:
No matching function on heap
I've created a mix method which is taking two lists by reference. Than I've created mixed list(3) to which I'm assigning elements form list 1 and 2, than I return a list 3.

When I try to implement it it works in stack, but not heap.
What can be a possible problem?

(sth3 = sth3->mix(sth1,sth2);) - I have no matching function problem.

Not working:

```<code>    Sequence<int,string> *sth1 = new Sequence<int,string>();
    sth1->AddNode(1,"n1");
    sth1->AddNode(2,"n2");

    Sequence<int,string> *sth2 = new Sequence<int,string>();
    sth2->AddNode(10,"n1");

    Sequence<int,string> *sth3 = new Sequence<int,string>();
    sth3 = sth3->mix(sth1,sth2);
    sth3->Print();
</code>```

Working one:

```<code>    Sequence<int,string> st1;
    st1.AddNode(1,"n1");

    Sequence<int,string> st2;
    st2.AddNode(10,"n1");

    Sequence<int,string> st3;
    st3 = st3.mix(st1,st2);
    st3.Print();
</code>```

Simplified function mix(..)

```<code>template<typename key,typename info>
Sequence<key, info> Sequence<key, info>::mix(const Sequence<key, info> &s1, const Sequence<key,info> &s2)
{
            Sequence<key,info> s;
            Node<key, info> *curr1 = s1.head;
            Node<key, info> *curr2 = s2.head;

            while (s.count < 10)
            {
                s.AddNode(curr1->GetId(), curr1->GetData())
                curr1 = curr1->GetNext();
                s.AddNode(curr2->GetId(), curr2->GetData())
                curr2 = curr2->GetNext();

                if (curr1 == NULL && curr2 == NULL)
                    break;

            }

    return s;
}
</code>```

答: In the heap one, you are giving pointer to a function that expects reference, you have to derefence them.</p>

Title: No matching function on heap

Body:
I've created a mix method which is taking two lists by reference. Than I've created mixed list(3) to which I'm assigning elements form list 1 and 2, than I return a list 3.

When I try to implement it it works in stack, but not heap.
What can be a possible problem?

(sth3 = sth3->mix(sth1,sth2);) - I have no matching function problem.

Not working:

    Sequence<int,string> *sth1 = new Sequence<int,string>();
    sth1->AddNode(1,"n1");
    sth1->AddNode(2,"n2");

    Sequence<int,string> *sth2 = new Sequence<int,string>();
    sth2->AddNode(10,"n1");

    Sequence<int,string> *sth3 = new Sequence<int,string>();
    sth3 = sth3->mix(sth1,sth2);
    sth3->Print();

Working one:

    Sequence<int,string> st1;
    st1.AddNode(1,"n1");

    Sequence<int,string> st2;
    st2.AddNode(10,"n1");

    Sequence<int,string> st3;
    st3 = st3.mix(st1,st2);
    st3.Print();

Simplified function mix(..)

template<typename key,typename info>
Sequence<key, info> Sequence<key, info>::mix(const Sequence<key, info> &s1, const Sequence<key,info> &s2)
{
            Sequence<key,info> s;
            Node<key, info> *curr1 = s1.head;
            Node<key, info> *curr2 = s2.head;

            while (s.count < 10)
            {
                s.AddNode(curr1->GetId(), curr1->GetData())
                curr1 = curr1->GetNext();
                s.AddNode(curr2->GetId(), curr2->GetData())
                curr2 = curr2->GetNext();

                if (curr1 == NULL && curr2 == NULL)
                    break;

            }

    return s;
}


问:
Interface a function to have an optional argument instead of a required one
Suppose I use a function (coming from a third-party API, in another namespace) having arguments filled by the function with some information:

```<code>double foo::f(double x, double& info);
</code>```

When I call it, I have to create a local variable, even if I don't care about the filled value:

```<code>const double x = 3.14159;
double info = 0.0;
const double y = foo::f(x, info);
// Nothing to do with info
</code>```

Then, I want to interface this function to have an optional argument instead of a reference. Is there an usual/better/easiest/more-readable way than the following to do that ?

```<code>double ff(double x, double* info = 0)
{
  double unused_info = 0.0;
  double& info_ = ((bool)info ? *info : unused_info);
  return foo::f(x, info_);
}
</code>```

This works, but it looks a little bit clumsy for the need.

Note: I don't use C++11 for compatibility reasons. But I'm interested by C++11 solutions even if it doesn't answer the question.

答:
Rather than change the current implementation you can just add an overloaded function with one argument:</p>

```<code>double f(double x)
{
    double info;
    return f(x, info);
}
</code>```

Body:
Suppose I use a function (coming from a third-party API, in another namespace) having arguments filled by the function with some information:

double foo::f(double x, double& info);

When I call it, I have to create a local variable, even if I don't care about the filled value:

const double x = 3.14159;
double info = 0.0;
const double y = foo::f(x, info);
// Nothing to do with info

Then, I want to interface this function to have an optional argument instead of a reference. Is there an usual/better/easiest/more-readable way than the following to do that ?

double ff(double x, double* info = 0)
{
  double unused_info = 0.0;
  double& info_ = ((bool)info ? *info : unused_info);
  return foo::f(x, info_);
}

This works, but it looks a little bit clumsy for the need.

Note: I don't use C++11 for compatibility reasons. But I'm interested by C++11 solutions even if it doesn't answer the question.

Body:
Rather than change the current implementation you can just add an overloaded function with one argument:

double f(double x)
{
    double info;
    return f(x, info);
}


问:
Why do these links exceed the width?
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
</div></code>```

What is the usual good practice to not be trapped in such corner cases?

答:
Set a{display:inline-block;} for inline elements a

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }
a{
display:inline-block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

Title: Why do these links exceed the width?

Body:
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo

What is the usual good practice to not be trapped in such corner cases?

Body:
Set a{display:inline-block;} for inline elements a

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }
a{
display:inline-block;}

<div class="small">
<a class="date" href="blah">2 January 2017</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a>
</div>


问:
Write a const pattern to a file of specific size
I need to write C++ code that will open a binary file and will write 5 MB of '1' in to it.

Currently my code is:

```<code>#define BYTES_BUFFER_SIZE_5MB (1024*1024*5)

static char buffer[BYTES_BUFFER_SIZE_5MB];
memset(buffer, 0xff, BYTES_BUFFER_SIZE_5MB);
ofstream myFile ("data.bin", ios::out | ios::binary);
myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);
</code>```

Is there a memset-like method for writing to a file, so I can avoid having a buffer?

答:
It's not simpler, but you can use memory-mapped files. They give you exactly what you asked for - you can write the file as if you're writing to memory.

Each (popular) operating system have different API for them, but there are a few libraries that provide portable support.

Body:
I need to write C++ code that will open a binary file and will write 5 MB of '1' in to it.

Currently my code is:

#define BYTES_BUFFER_SIZE_5MB (1024*1024*5)

static char buffer[BYTES_BUFFER_SIZE_5MB];
memset(buffer, 0xff, BYTES_BUFFER_SIZE_5MB);
ofstream myFile ("data.bin", ios::out | ios::binary);
myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);

Is there a memset-like method for writing to a file, so I can avoid having a buffer?


问:
How can I set the size of logos the same via CSS?
The images are all of the same sizes.
I use Image GIF and the size of the images on the hard disk is 415x72.

The images are placed in a table I want to make all images the same via css.

Images details on the hard disk:

view.jsp:

```<code><%
logo ="<img src='/path/images/vendor/"+vendor.toLowerCase()+".gif' style='max-width:120px'/>";
%>

<liferay-ui:search-container-column-text name='vendor'
         cssClass="width-10" value="<%=logo%>" />
</code>```

Image details:

I've looked into this link, but doesn't work for me. I couldn't get any solution to work to my requirement.

I tried this code below but the picture becomes blurry.

```<code>.img {
    position: relative;
    float: left;
    width:  100px;
    height: 100px;
    background-position: 50% 50%;
    background-repeat:   no-repeat;
    background-size:     cover;
}
</code>```

view.jsp:

```<code><%
logo ="<img class='img' src='/path/images/vendor/"+vendor.toLowerCase()+".gif' style='max-width:120px'/>";
%>
</code>```

Images details after adding the code:

Is there a solution with the css or I have to use a software for image?

The requested result image of same size and clear:

requested result

Update:

1- I tried to change the width and set the height to auto but I did not get what I want.

2- I tried this line but did not work.

```<code><%
logo = "<div class='img' style='background-image:url(\""+logoUrl+"\");' style='max-width:220px;'> </div>";
%>
</code>```

3- I tried to resize with html tag  and to cut with background-image.
I followed this link: CSS Display an Image Resized and Cropped I did not got a good result.

```<code><%
logo = "<div class='crop'><img class='img' src='"+logoUrl+"' style='max-width:120px;' alt='"+vendor.toLowerCase()+"'/></div>";
%>
</code>```

css:

```<code>.crop {
    width: 160px;
    height: 120px;
    overflow: hidden;
}

.crop img {
    width: 565px;
    height: auto;
    margin: -75px 0 0 -100px;
}
</code>```

Details images:

Images with 128x128 size

From the outside the images are the same size but from the inside they are not the same size. I want images with the same height and width without modifying the aspect ratio of the images. How can I do that?

答:
Css :

```<code>.image-container {
    width:300px;
    height:150px;
    text-align:center;
}

.image-container img {
    height:100%;
}
</code>```

Html:

```<code><div class="image-container">
    <img src="path"/>
</div>
</code>```

Body:
The images are all of the same sizes.
I use Image GIF and the size of the images on the hard disk is 415x72.

The images are placed in a table I want to make all images the same via css.

Images details on the hard disk:

view.jsp:

<%
logo ="";
%>

<liferay-ui:search-container-column-text name='vendor'
         cssClass="width-10" value="<%=logo%>" />

Image details:

I've looked into this link, but doesn't work for me. I couldn't get any solution to work to my requirement.

I tried this code below but the picture becomes blurry.

.img {
    position: relative;
    float: left;
    width:  100px;
    height: 100px;
    background-position: 50% 50%;
    background-repeat:   no-repeat;
    background-size:     cover;
}

view.jsp:

<%
logo ="";
%>

Images details after adding the code:

Is there a solution with the css or I have to use a software for image?

The requested result image of same size and clear:

requested result

Update:

1- I tried to change the width and set the height to auto but I did not get what I want.

2- I tried this line but did not work.

<%
logo = "

";
%>

3- I tried to resize with html tag  and to cut with background-image.
I followed this link: CSS Display an Image Resized and Cropped I did not got a good result.

<%
logo = "

";
%>

css:

.crop {
    width: 160px;
    height: 120px;
    overflow: hidden;
}

.crop img {
    width: 565px;
    height: auto;
    margin: -75px 0 0 -100px;
}

Details images:

Images with 128x128 size

From the outside the images are the same size but from the inside they are not the same size. I want images with the same height and width without modifying the aspect ratio of the images. How can I do that?

Body:
Css :

.image-container {
    width:300px;
    height:150px;
    text-align:center;
}

.image-container img {
    height:100%;
}

Html:

<div class="image-container">
    <img src="path"/>
</div>


问:
Sidebar hide and show with Bootstrap and Jquery?
Guys I want to create a sidebar hiding and showing using bootstrap, but my code isn't working..

Please help me...

My code HTML is:

```<code><nav role="nav" class="navbar">
    <a href="" class="menu">button</a>
</nav>

<nav role="nav" class="sidebar">
    sidebar menu
</nav>

<main role="main" class="main-page">
    main content
</main>
</code>```

This is my CSS code:

```<code>.menu {
    display: block !important;
}

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
}

.main-page {
    color: #000;
    margin-left: 240px;
    position :relative;
}
</code>```

And this is my jquery code:

```<code><script>
    $(function () {
        $('.menu').on('click', function () {
            if ($('.sidebar').is(':visible')) {
                $('.sidebar').animate({'width': '0px'}, 'slow', function () {
                    $('.sidebar').hide();
                });
                $('.main-page').animate({'padding-left': '0px'}, 'slow');
            } else {
                $('.sidebar').show();
                $('.sidebar').animate({'width': '240px'}, 'slow');
                $('.main-page').animate({'padding-left': '240px'}, 'slow');
            }
        });
    });
</script>
</code>```

I'm using bootstrp CDN: jquery-3.2.1.slim.min.js / popper.min.js / bootstrap.min.js

答:
Try not to use jquery.slim. It goes well with min.js

```<code>https://code.jquery.com/jquery-3.2.1.min.js
</code>```

Check the jsfiddle

Body:
Guys I want to create a sidebar hiding and showing using bootstrap, but my code isn't working..

Please help me...

My code HTML is:

    button

    sidebar menu

    main content

This is my CSS code:

.menu {
    display: block !important;
}

.sidebar {
    color: #fff;
    width: 240px;
    height: 100%;
    position: fixed;
    background: #2a3542;
}

.main-page {
    color: #000;
    margin-left: 240px;
    position :relative;
}

And this is my jquery code:

I'm using bootstrp CDN: jquery-3.2.1.slim.min.js / popper.min.js / bootstrap.min.js

Body:
Try not to use jquery.slim. It goes well with min.js

https://code.jquery.com/jquery-3.2.1.min.js

Check the jsfiddle


问:
What is the work around for XAML validation not updating the CLR property if validation fails
My xaml code:

```<code><StackPanel>
 <TextBox>
   <TextBox.Text>
       <Binding Path="ContactNumber"
                UpdateSourceTrigger="PropertyChanged">
                   <Binding.ValidationRules>
                       <validators:ContactValidation ValidatesOnTargetUpdated = "True"  />
                   </Binding.ValidationRules>
       </Binding>
    </TextBox.Text>
 </TextBox>
 <Button Command="{Binding SaveContact}"/>
</code>```

My View Model(Already implements Inotify Fody Weaver, Standard Relay Command Implementation for ICommand)

```<code> public class DemoVM{
public string ContactNumber{get;set;}
public ICommand SaveContact=new RelayCommand(()=> //Simulate Db save of (ContactNumber));

}
</code>```

My validation class

```<code>  public class ContactValidation : ValidationRule
{

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
if (//some regex match)
 return ValidationResult.ValidResult;
else
 return new ValidationResult(false,"Error message")
  }
}
</code>```

Everytime the validation rule returns a valid result, the ContactNumber Property is updated. When the validation rule returns invalid result, the ContactNumber property is its last validated value.
How do i proceed to validate all the values in the xaml(Show error message and such) side of code as well as in my viewmodel(Prevent submit if error showing or enable button only if all fields validated)?

The official databinding document by MSDN covers bothe validation part separately bu there is nothing if we want to make use of the same Validation Rules to validate from both UI and code behind perspective.

答:
You should get rid of the ValidationRules in the view and implement the validation logic in your view model.

This is done by implementing the INotifyDataErrorInfo interface. Validate your data in the setter of your properies as suggested in the following TechNet article.

WPF 4.5: Validating Data in Using the INotifyDataErrorInfo Interface: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx

This is the MVVM way of implementing data validation. Using a ValidationRule is not.

Body:
My xaml code:

<StackPanel>
 <TextBox>
   <TextBox.Text>
       <Binding Path="ContactNumber"
                UpdateSourceTrigger="PropertyChanged">
                   <Binding.ValidationRules>
                       <validators:ContactValidation ValidatesOnTargetUpdated = "True"  />
                   </Binding.ValidationRules>
       </Binding>
    </TextBox.Text>
 </TextBox>
 <Button Command="{Binding SaveContact}"/>

My View Model(Already implements Inotify Fody Weaver, Standard Relay Command Implementation for ICommand)

 public class DemoVM{
public string ContactNumber{get;set;}
public ICommand SaveContact=new RelayCommand(()=> //Simulate Db save of (ContactNumber));

}

My validation class

  public class ContactValidation : ValidationRule
{

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
if (//some regex match)
 return ValidationResult.ValidResult;
else
 return new ValidationResult(false,"Error message")
  }
}

Everytime the validation rule returns a valid result, the ContactNumber Property is updated. When the validation rule returns invalid result, the ContactNumber property is its last validated value.
How do i proceed to validate all the values in the xaml(Show error message and such) side of code as well as in my viewmodel(Prevent submit if error showing or enable button only if all fields validated)?

The official databinding document by MSDN covers bothe validation part separately bu there is nothing if we want to make use of the same Validation Rules to validate from both UI and code behind perspective.


问:
CSS Div Positions
I'm a beginner in html and im clueless, i apologize if i seem ignorant.

In this picture example am I supposed to use absolute position or relative for the containers

and how many total containers do I need to make

This is the code i currently have:

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

```

In addition ,the 2nd division container is not included in the first one with its border, what could be causing it

答:
Try this </p>

```<code><div style="border-style: solid;border-color:blue;">
    <div> <img id="logo" src="insta.jpg"> <img id="logo" src="twitter.png"> <img id="logo" src="facebook.png">

        <br>
        <br> <img style="float:left;" src="u1.png">
        <p> <strong> Ali Omar <br> November 13,2017 </strong> </p>
        <br>
        <p> The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that. As such, they can be more than "flexible" choice. </p>
    </div>
    <div style="position:absolute; right :0px; left: 0px; border-style: solid;border-color:orange;">
        <br>
        <img style="float:left;" src="u2.png">
        <p> <strong> Guest <br> November 13,2017 <br> Hi Ali,,, </strong> </p> <br>
        <p> When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me </p>
    </div>
</div>
</code>```

Title: CSS Div Positions

Body:
I'm a beginner in html and im clueless, i apologize if i seem ignorant.

In this picture example am I supposed to use absolute position or relative for the containers

and how many total containers do I need to make

This is the code i currently have:

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

In addition ,the 2nd division container is not included in the first one with its border, what could be causing it

Body:
Try this

<div style="border-style: solid;border-color:blue;">
    <div> <img id="logo" src="insta.jpg"> <img id="logo" src="twitter.png"> <img id="logo" src="facebook.png">

        <br>
        <br> <img style="float:left;" src="u1.png">
        <p> <strong> Ali Omar <br> November 13,2017 </strong> </p>
        <br>
        <p> The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that. As such, they can be more than "flexible" choice. </p>
    </div>
    <div style="position:absolute; right :0px; left: 0px; border-style: solid;border-color:orange;">
        <br>
        <img style="float:left;" src="u2.png">
        <p> <strong> Guest <br> November 13,2017 <br> Hi Ali,,, </strong> </p> <br>
        <p> When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me </p>
    </div>
</div>


问:
Working on dynamic responses from a data source in klipfolio
Basically, In our data source, I have used facebook graph api to get the list of all posts including likes, shares and comments for each post.
I receive a json response in which we are getting "shares" keys presence is inconsistent which means inside json array which consists facebook post json object that in some cases have shares key value and in some cases its absent.
So, while using this data source in our klip, "shares" key value are not mapped correctly with the other post details.
It is because, when we use data source like this : @/data/shares/count , it will provide the value of shares for each post but in some cases where "shares" key is not present or absent for that data, then it replaces the value by the next found "shares" key value but it needs to be 0 so that data in the klip should be mapped exactly.

DATA SOURCE

KLIP

答:
Due to Facebook not returning a JSON record if there is no data for that record, you will need to manipulate the data with xpath axes. If you want to "pad" 0 where there is no record, you will also need to use LOOKUP(). For example:

Shares = @/data/shares/count

66 records

IDs where there are shares= @/data/id[preceding-sibling::count]

66 records

```<code>LOOKUP(@/data/id,
        @/data/id[preceding-sibling::count],
          @/data/shares/count)
</code>```

LOOKUP will return 100 records and pad where there is no share count value.

Body:
Due to Facebook not returning a JSON record if there is no data for that record, you will need to manipulate the data with xpath axes. If you want to "pad" 0 where there is no record, you will also need to use LOOKUP(). For example:

Shares = @/data/shares/count

66 records

IDs where there are shares= @/data/id[preceding-sibling::count]

66 records

LOOKUP(@/data/id,
        @/data/id[preceding-sibling::count],
          @/data/shares/count)

LOOKUP will return 100 records and pad where there is no share count value.


问:
Pointer code smell C++
I'm using the gsl library in C++. I have declared a gsl_vector pointer mesh as a private member of the class.

```<code>private:
    gsl_vector * mesh;
</code>```

I also have a method, MeshBuilder, that declares a gsl_vector, pointer mesh (over-riding the original mesh variable) and returns mesh.

```<code>gsl_vector * ThinFilm::LinearMesh(...){
    gsl_vector * mesh = gsl_vector_alloc(numberofcells);
    ...
    return mesh;
}
</code>```

I then assign the result of the method to the variable mesh as:

```<code>mesh = MeshBuilder(...);
</code>```

It compiles and runs just fine (no warnings either, with -Wall). Stepping through the program I noticed that the variable mesh is assigned an address, and then the MeshBuilder overwrites that. Which is exactly what I programmed to do.

But is it good practice? After all, shouldn't I not assign a value to the pointer address?

Shouldn't I instead not declare a the mesh pointer in the MeshBuilder method and therefore directly use the pointer declared in the private section of the class?

I'm guessing the only reason this works is because the address value I'm assigning to mesh is in fact valid having been declared.

答:
The mesh variable in the method shadows the private's variable.
If you use the private variable directly, then you avoid declaring a temporary, but in practice, it does not change much.

However, if the interface of the class is to be used in multithreaded contexts, then changing the private variable directly will make it visible to any other thread at the allocation time, so if the ... section in the code above does some sort of setup of the vector, it means other thread might see or use an invalid (not constructed) variable.
In that case, you should use a temporary (like in your initial code) and protect the assignment mesh = MeshBuilder(...) with either a mutex or an atomic operation (like CAS, or pointer exchange).

Also, in all cases, if you want to write safe code, you should also consider what is going to happen is an exception is thrown in the ... part of the code.
Setting the private variable directly, you might have a chance to clean the allocation (in the destructor of your class), else you'll get a memory leak since a pointer does not clean the allocation by itself.

If you want a really safe code that's working in all possible conditions, you should use a smart pointer in place of the temporary (for exception safe code), a mutex to protect private variable access (for multithread safe code).

Title: Pointer code smell C++

Body:
I'm using the gsl library in C++. I have declared a gsl_vector pointer mesh as a private member of the class.

private:
    gsl_vector * mesh;

I also have a method, MeshBuilder, that declares a gsl_vector, pointer mesh (over-riding the original mesh variable) and returns mesh.

gsl_vector * ThinFilm::LinearMesh(...){
    gsl_vector * mesh = gsl_vector_alloc(numberofcells);
    ...
    return mesh;
}

I then assign the result of the method to the variable mesh as:

mesh = MeshBuilder(...);

It compiles and runs just fine (no warnings either, with -Wall). Stepping through the program I noticed that the variable mesh is assigned an address, and then the MeshBuilder overwrites that. Which is exactly what I programmed to do.

But is it good practice? After all, shouldn't I not assign a value to the pointer address?

Shouldn't I instead not declare a the mesh pointer in the MeshBuilder method and therefore directly use the pointer declared in the private section of the class?

I'm guessing the only reason this works is because the address value I'm assigning to mesh is in fact valid having been declared.


问:
Binding radio button content to a dataset
I have a listView. What i need is to display a list of radio buttons on this list. For each distinct Name in exercises (which is basically a collection of entries from a database table), there should be a radio button with its content being Name.

```<code>private void GetChartData()
{
    ExercicesList.ItemsSource = exercises.Select(n => n.Name).Distinct();
}
</code>```

So far it displays the radio buttons, however not their content.

```<code><ListView Name="ExercicesList" HorizontalAlignment="Stretch"  VerticalAlignment="Center" Margin="0 100 0 0">
       <ListView.ItemTemplate>
             <DataTemplate>
                  <Grid>
                     <RadioButton Name="ExerciceCheck" GroupName="onlyOne" Content="{Binding Name, Mode=OneWay}" Grid.Column="0" IsChecked="False" Checked="ExerciceCheck_Checked"></RadioButton>
                  </Grid>
             </DataTemplate>
       </ListView.ItemTemplate>
</ListView>
</code>```

答:
```<code>ExercicesList.ItemsSource = exercises.Select(n => n.Name).Distinct();
</code>```

this code extract only the Name (IEnumerable<string>), not the exercise object (IEnumerable<exercise>). the RadioButton.Content binding try access a Name property, And there is not exsist in string. You can do a Binding to element itself - without a property:

```<code>Content="{Binding}"
</code>```

it work, but you lose access to other properties later in the logic.

instead, Leave the XAML as it is, just write this way when putting the list:

```<code>ExercicesList.ItemsSource = exercises.GroupBy(n => n.Name).Select(g => g.First());
</code>```

Because there is no DistinctBy in linq, use GropyBy & Select first from each group, for the same effect.

Body:
I have a listView. What i need is to display a list of radio buttons on this list. For each distinct Name in exercises (which is basically a collection of entries from a database table), there should be a radio button with its content being Name.

private void GetChartData()
{
    ExercicesList.ItemsSource = exercises.Select(n => n.Name).Distinct();
}

So far it displays the radio buttons, however not their content.

<ListView Name="ExercicesList" HorizontalAlignment="Stretch"  VerticalAlignment="Center" Margin="0 100 0 0">
       <ListView.ItemTemplate>
             <DataTemplate>
                  <Grid>
                     <RadioButton Name="ExerciceCheck" GroupName="onlyOne" Content="{Binding Name, Mode=OneWay}" Grid.Column="0" IsChecked="False" Checked="ExerciceCheck_Checked"></RadioButton>
                  </Grid>
             </DataTemplate>
       </ListView.ItemTemplate>
</ListView>

Body:
ExercicesList.ItemsSource = exercises.Select(n => n.Name).Distinct();

this code extract only the Name (IEnumerable<string>), not the exercise object (IEnumerable<exercise>). the RadioButton.Content binding try access a Name property, And there is not exsist in string. You can do a Binding to element itself - without a property:

Content="{Binding}"

it work, but you lose access to other properties later in the logic.

instead, Leave the XAML as it is, just write this way when putting the list:

ExercicesList.ItemsSource = exercises.GroupBy(n => n.Name).Select(g => g.First());

Because there is no DistinctBy in linq, use GropyBy & Select first from each group, for the same effect.


问:
Separating development and production dependencies with virtualenv
I have a simple flask app, where I use virtualenv for managing my dependencies. However, I would like to separate my dependencies. For testing I use Flask-Testing, but this is a dependency I wouldn't want to include in my production environment.

How can separate my dependencies, so that I have separate dependencies for development and for production?

答:
You can have multiple requirements.txt files for different environments. eg. requirements_dev.txt, requirements_prod.txt...

These files would have different pinned (having versions as well) packages. They can be generated by manually pip installing packages and then piping the output of pip freeze to a file.


问:
Failed to generate or install certificate
I am using  Zappa to deploy to my Django code to AWS Lambda. In that process I have to renew my Domain SSL certificate as it has expired. I tried to create new by doing
So I tried to create a new SSL key by doing

```<code> $ openssl genrsa 2048 > account.key;
</code>```

And Added my Domain name and Path to zappa_settings.json file.
I tried to run

```<code> $ zappa certify production
</code>```

This is what the Error I am getting

```<code> $ zappa certify production
 Calling certify for stage production..
 Are you sure you want to certify? [y/n] y
 Certifying domain xxxx.domain.com ..
 Error registering: 400 {
 "type": "urn:acme:error:malformed",
 "detail": "Provided agreement URL
 [https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf] does not match current agreement URL [https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf]",
"status": 400
 }
 Failed to generate or install certificate! :(
 ==============
</code>```

I find the link https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf has nothing but "404 Not Found" Error. what is the problem ?
And also do we have to run
     $ zappa certify everytime we need to
renew the certificate ?

答:
Its a temporary error which is being caused due to some changes on the subscribe agreement. Update zappa again tomorrow and try again.

https://community.letsencrypt.org/t/subscriber-agreement-update-november-15-2017/45607

Body:
I am using  Zappa to deploy to my Django code to AWS Lambda. In that process I have to renew my Domain SSL certificate as it has expired. I tried to create new by doing
So I tried to create a new SSL key by doing

 $ openssl genrsa 2048 > account.key;

And Added my Domain name and Path to zappa_settings.json file.
I tried to run

 $ zappa certify production

This is what the Error I am getting

 $ zappa certify production
 Calling certify for stage production..
 Are you sure you want to certify? [y/n] y
 Certifying domain xxxx.domain.com ..
 Error registering: 400 {
 "type": "urn:acme:error:malformed",
 "detail": "Provided agreement URL
 [https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf] does not match current agreement URL [https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf]",
"status": 400
 }
 Failed to generate or install certificate! :(
 ==============

I find the link https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf has nothing but "404 Not Found" Error. what is the problem ?
And also do we have to run
     $ zappa certify everytime we need to
renew the certificate ?