问:
Can you avoid unboxing in a memoizing generic method?
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

```<code>public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}
</code>```

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

答:
Consider using Lazy<T> for this.

So if you have some kind of collection of properties.

```<code>public class MyClass
{
...
}

Public class MyClass<T> : MyClass
{
  T val;
  bool valSet;
  public T GetValue<T> () {
        if (!valSet)
        {
            val = (T)Convert.ChangeType(DatabaseValue, typeof(T))};
            valSet = true;
        }
        return val;
    }
}
</code>```

Presumably you then have a generic method in your parent class

```<code>class SomePropertyBag{

private Dictionary<string, MyClass> dict;

T GetValue<T>(string name, T default)
{
  MyClass res;
  if(!dict.TryGetValue(out res))
  {
     res = new MyClass<T>(name);
     dict.Add(name, res);
  }
  return ((MyClass<T>)res).GetValue();
}
</code>```

Body:
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

Body:
Consider using Lazy<T> for this.

So if you have some kind of collection of properties.

public class MyClass
{
...
}

Public class MyClass<T> : MyClass
{
  T val;
  bool valSet;
  public T GetValue<T> () {
        if (!valSet)
        {
            val = (T)Convert.ChangeType(DatabaseValue, typeof(T))};
            valSet = true;
        }
        return val;
    }
}

Presumably you then have a generic method in your parent class

class SomePropertyBag{

private Dictionary<string, MyClass> dict;

T GetValue<T>(string name, T default)
{
  MyClass res;
  if(!dict.TryGetValue(out res))
  {
     res = new MyClass<T>(name);
     dict.Add(name, res);
  }
  return ((MyClass<T>)res).GetValue();
}


来源: stackexchange

问:
How to get X and Y position of Image inside a ListView in Xamarin.Forms?
I need to show a tooltip popup when the images inside a listview is tapped. For that i'm creating a absolute layout page and adding the listview and the popup layout inside the absolute layout. I'm then trying to use the Position of the Image inside a listview to place the popup layout just below the image.

But the image X position is returning some value but the Y value returns 0 always.

答: We could achieve this by following the code in this link Getting X and Y coordinates but again its not giving the screens X & Y position.</p>

ContentLicense: CC BY-SA 3.0


问:
Find a way in the java logging frameworks scene
Java has a lot of frameworks / APIs that help you do logging in your application:

The Java API has java.util.logging package.

Apache's Log4j.

Apache's Commons Logging.

SLF4J (logging Facade).

jLo.
and many many more...

I've always used the log4j library, i found it sufficient most of the time, and extensible when i needed more control.

Anyone who had experience with more than one framework can share his experience? when is it better to use one framework over the other and from application architecture point of view? Why would i prefer one over other?

Thanks

答:
This question seems identical to 354837.

The simple answer is that you'd go for Commons Logging if you're writing a library that may be dropped into applications where you have no control over the logging, one of the other choices if not. I personally use CL in all cases, simply because it's common -- I don't need to remember the differences between frameworks.

OwnerDisplayName: Alon

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: kdgregory


问:
When generating barcodes, is there a limit on the number of characters?
I have to develop a system that generates barcodes that will be printed and was wondering if there's a limit to the number of characters of a barcode? I intend to make this using PHP, also would it be better in some way to use QR codes?

EDIT

I want to do this barcodes for a system that will stor different types of shoes but since there are lots of variations to the shoes I require some more characters, but I think I can use hexadecimal numbers to create the barcodes (not sure if this is possible I'm looking into it)

答:
Of course there's a limit on the number of characters. Normal barcodes can usually encode somewhere around 12 digits or a handful of bits of data. Two dimensional codes can typically store a few thousand bytes of data. This all depends on the type of barcode/matrix code you choose. And this most likely depends on who will read these codes.

Here's an overview: http://en.wikipedia.org/wiki/Barcode#Types_of_barcodes


问:
How to detect scrolling to an end of an horizontal UICollectionView
do you know a way in order to detect when a user has scrolled to the end (or the beginning) of an UICollectionView (in order to load new content). Since the UICollectionView scrolls horizontally and not vertically, I am not interested to the scrolling to top/bottom but to leftmost/rightmost.

The only way I found so far is to subclass the UICollectionView and then register the view controller as a delegate that is informed of when the collection view willLayoutSubviews and perform calculations accordingly.

But let's say I don't want to subclass UICollectionView, is there a way to detect the scrolling to the end/beginning of UICollectionView?

EDIT:
since UICollectionView inherits from UIScrollView, I can use its delegate methods. How does it work with with horizontal scrolling?

Thank you

答:
```<code>- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isKindOfClass:[UICollectionView class]] == YES) {
        CGFloat threshold = 100.0 ;
        CGFloat contentOffset = scrollView.contentOffset.x;
        CGFloat maximumOffset = scrollView.contentSize.width - scrollView.frame.size.width;
        if ((maximumOffset - contentOffset <= threshold) && (maximumOffset - contentOffset != -5.0) ){
            //Your code
        }
    }
}
</code>```


问:
Convert a data read in by fread function to data.frame
Assume that I have a sample csv file which has 3 rows and 4 columns. Say it looks like the following:

```<code>name1 name2  name3 name4
11    12     13    14
21    22     23    24
31    32     33    34
</code>```

I read it in using fread() (I am using the small sample for illustration purpose):

```<code>data <- fread(sample.csv, stringsAsFactors=FALSE)
</code>```

then I do

```<code>class(data)
</code>```

it will return

```<code>[1] "data.table" "data.frame"
</code>```

I want to see the first element of the fourth column, I tried

```<code>data[1,4]
</code>```

But it returns 4 (which I guess is the index of the column).

Interestingly, when I call the following

```<code>data[1,]
</code>```

or

```<code>data[1]
</code>```

it returns the first row.

So I did

```<code>data <- data.frame(data)
</code>```

to convert data to a data frame.

My questions:

1. Since the initial data has two classes, is there a way for me to choose one class and 'drop' the other? In my case, I just want to use the data as data frame.

2. In general, if data has more than one class, may we choose one class to keep? For instance, as.POSIXct() will return an object with two classes ("POSIXct" "POSIXt"). What if we just want to keep one of the classes? Any function works for this purpose in a generic way?

答:
if you want to use fread and want to get data as data frame just set the property of data.table to FALSE. By default it is true.

A data.table by default. A data.frame when argument data.table=FALSE;

E.g.

```<code>options(datatable.fread.datatable=FALSE).
</code>```

See the documentation of R fread for reference.
https://www.rdocumentation.org/packages/data.table/versions/1.10.4-2/topics/fread

Body:
Assume that I have a sample csv file which has 3 rows and 4 columns. Say it looks like the following:

name1 name2  name3 name4
11    12     13    14
21    22     23    24
31    32     33    34

I read it in using fread() (I am using the small sample for illustration purpose):

data <- fread(sample.csv, stringsAsFactors=FALSE)

then I do

class(data)

it will return

[1] "data.table" "data.frame"

I want to see the first element of the fourth column, I tried

data[1,4]

But it returns 4 (which I guess is the index of the column).

Interestingly, when I call the following

data[1,]

or

data[1]

it returns the first row.

So I did

data <- data.frame(data)

to convert data to a data frame.

My questions:

1. Since the initial data has two classes, is there a way for me to choose one class and 'drop' the other? In my case, I just want to use the data as data frame.

2. In general, if data has more than one class, may we choose one class to keep? For instance, as.POSIXct() will return an object with two classes ("POSIXct" "POSIXt"). What if we just want to keep one of the classes? Any function works for this purpose in a generic way?

Body:
if you want to use fread and want to get data as data frame just set the property of data.table to FALSE. By default it is true.

A data.table by default. A data.frame when argument data.table=FALSE;

E.g.

options(datatable.fread.datatable=FALSE).

See the documentation of R fread for reference.
https://www.rdocumentation.org/packages/data.table/versions/1.10.4-2/topics/fread


问:
'Address already in use' when running tests using Spring LDAP embedded server
I am trying to use Spring LDAP in one of my Spring Boot projects but I am getting an 'Address already in use' error when running multiple tests.

I have cloned locally the sample project here:
https://spring.io/guides/gs/authenticating-ldap/

...and just added the boilerplate test normally created by Spring Boot to verify that the Application Context loads correctly:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {
    @Test
    public void contextLoads() {
    }
}
</code>```

If run alone, this test passes. As soon as LdapAuthenticationTests and MyApplicationTests are run together, I get the error above for the latter.

After debugging a bit, I've found out that this happens because the system tries to spawn a second instance of the embedded server.

I am sure I am missing something very stupid in the configuration.
How can I fix this problem?

答:
Okay, I think I found a solution by adding a @DirtiesContext annotation to my test classes:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

Body:
I am trying to use Spring LDAP in one of my Spring Boot projects but I am getting an 'Address already in use' error when running multiple tests.

I have cloned locally the sample project here:
https://spring.io/guides/gs/authenticating-ldap/

...and just added the boilerplate test normally created by Spring Boot to verify that the Application Context loads correctly:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {
    @Test
    public void contextLoads() {
    }
}

If run alone, this test passes. As soon as LdapAuthenticationTests and MyApplicationTests are run together, I get the error above for the latter.

After debugging a bit, I've found out that this happens because the system tries to spawn a second instance of the embedded server.

I am sure I am missing something very stupid in the configuration.
How can I fix this problem?


问:
How to upload a file using Selenium in Python
It's a button tag and I'm trying with below code:</p>

```<code>element = self.driver.find_element_by_xpath("//*[text()='Browse']")
element.send_keys('//Users//test//Desktop//Auto//AutomationDownloads//IonicSamlAssertion.xml')
</code>```

答:
You are sending keys to a button, that will not work. If you have an input field with type 'file' you can send the keys to that input field and submit the form, for example:

```<code>element = self.driver.find_element_by_id("inputFile");
element.send_keys('//Users//test//Desktop//Auto//AutomationDownloads//IonicSamlAssertion.xml');
</code>```

After that, you can submit the form

Body:
It's a button tag and I'm trying with below code:

element = self.driver.find_element_by_xpath("//*[text()='Browse']")
element.send_keys('//Users//test//Desktop//Auto//AutomationDownloads//IonicSamlAssertion.xml')

Body:
You are sending keys to a button, that will not work. If you have an input field with type 'file' you can send the keys to that input field and submit the form, for example:

element = self.driver.find_element_by_id("inputFile");
element.send_keys('//Users//test//Desktop//Auto//AutomationDownloads//IonicSamlAssertion.xml');

After that, you can submit the form


问:
Get values from an array of objects
I am looping through my array to get the corresponding field value:

```<code>var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)
</code>```

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.

答:
You can use array.prototype.find:

var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];
var someFun = (nm) => {
    var found = names.find(el => el.name === nm);
    return found && found.age || null;
}
console.log(someFun('tom'));```

Title: Get values from an array of objects

Body:
I am looping through my array to get the corresponding field value:

var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.


问:
twain scanner not acquiring the image from scanner
i implemented one applet to acquire the image from scanner for that i have used twain implementation.it is working fine while i am running the application as java applet but the problem is it is not able to acquire the image from scan device while i run from one html file .it is not giving any error and i am not able to debug the application.
can any body tell me how can i resolve the issue.

this is my html

```<code><html>
<head><title>Scann</title></head>
<body>
<center>
    <applet id="TwainApplet"
            code = "com.nic.applet.TwainExample.class"
            archive="TwainApplet.jar"
            width="200"
            height="60">
    </applet>
</center>
</body>
</html>
</code>```

below is my Twain class..

```<code>public class TwainExample extends Applet implements ScannerListener{

  static TwainExample app;

  Scanner scanner;

  public TwainExample(String[] argv)throws ScannerIOException{
    scanner=Scanner.getDevice();
    scanner.addListener(this);
    scanner.acquire();
  }

  public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata){
    if(type.equals(ScannerIOMetadata.ACQUIRED)){
      BufferedImage image=metadata.getImage();
      System.out.println("Have an image now!");
      try{
        ImageIO.write(image, "png", new File("mmsc_image.png"));
      }catch(Exception e){
        e.printStackTrace();
      }
    }else if(type.equals(ScannerIOMetadata.NEGOTIATE)){
      ScannerDevice device=metadata.getDevice();
      try{
//        device.setShowUserInterface(true);
//        device.setShowProgressBar(true);
//        device.setResolution(100);
      }catch(Exception e){
        e.printStackTrace();
      }
    }else if(type.equals(ScannerIOMetadata.STATECHANGE)){
      System.err.println(metadata.getStateStr());
      if(metadata.isFinished()){
        System.exit(0);
      }
    }else if(type.equals(ScannerIOMetadata.EXCEPTION)){
      metadata.getException().printStackTrace();
    }
  }

  public static void main(String[] argv){
    try{
      app=new TwainExample(argv);
    }catch(Exception e){
      e.printStackTrace();
    }
 }
}
</code>```

答:
try this</p>

```<code>public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata){
if(type.equals(ScannerIOMetadata.ACQUIRED)){
  BufferedImage image=metadata.getImage();
  System.out.println("Have an image now!");
  System.out.println("Have"+identy);
  try{

      File home = new File("C:\\Directory1");//المجلد الاساسي حق الموظفين
      File dir  = new File(home,identy);//مجلد الموظف عشان نحفظ فيه ملفات الموظف لوحده
      if(!dir.exists()){ dir = home;}//اذا مجلد الموظف غير موجود احفظ في المجلد الاساسي
      File file = new File(dir,"we.jpg");//file.delete();
      ImageIO.write(image, "JPG", file);
//        ImageIO.write(image, "png", new File("C:\\Directory1//we.png"));
         System.out.println(file.getCanonicalPath());
         convertTOpdf();
      }catch(Exception e){
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e.getMessage());
      }
    }else if(type.equals(ScannerIOMetadata.NEGOTIATE)){
      ScannerDevice device=metadata.getDevice();
      try{
        device.setShowUserInterface(true);
        device.setShowProgressBar(true);
        device.setResolution(100);
      }catch(Exception e){
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e.getMessage());
      }
    }else if(type.equals(ScannerIOMetadata.STATECHANGE)){
      System.err.println(metadata.getStateStr());
      if(metadata.isFinished()){
        //System.exit(0);
      }
    }else if(type.equals(ScannerIOMetadata.EXCEPTION)){
      metadata.getException().printStackTrace();
    }
  }
</code>```

Body:
i implemented one applet to acquire the image from scanner for that i have used twain implementation.it is working fine while i am running the application as java applet but the problem is it is not able to acquire the image from scan device while i run from one html file .it is not giving any error and i am not able to debug the application.
can any body tell me how can i resolve the issue.

this is my html

<title>Scann</title>

    <applet id="TwainApplet"
            code = "com.nic.applet.TwainExample.class"
            archive="TwainApplet.jar"
            width="200"
            height="60">
    </applet>

below is my Twain class..

public class TwainExample extends Applet implements ScannerListener{

  static TwainExample app;

  Scanner scanner;

  public TwainExample(String[] argv)throws ScannerIOException{
    scanner=Scanner.getDevice();
    scanner.addListener(this);
    scanner.acquire();
  }

  public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata){
    if(type.equals(ScannerIOMetadata.ACQUIRED)){
      BufferedImage image=metadata.getImage();
      System.out.println("Have an image now!");
      try{
        ImageIO.write(image, "png", new File("mmsc_image.png"));
      }catch(Exception e){
        e.printStackTrace();
      }
    }else if(type.equals(ScannerIOMetadata.NEGOTIATE)){
      ScannerDevice device=metadata.getDevice();
      try{
//        device.setShowUserInterface(true);
//        device.setShowProgressBar(true);
//        device.setResolution(100);
      }catch(Exception e){
        e.printStackTrace();
      }
    }else if(type.equals(ScannerIOMetadata.STATECHANGE)){
      System.err.println(metadata.getStateStr());
      if(metadata.isFinished()){
        System.exit(0);
      }
    }else if(type.equals(ScannerIOMetadata.EXCEPTION)){
      metadata.getException().printStackTrace();
    }
  }

  public static void main(String[] argv){
    try{
      app=new TwainExample(argv);
    }catch(Exception e){
      e.printStackTrace();
    }
 }
}

Body:
try this

public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata){
if(type.equals(ScannerIOMetadata.ACQUIRED)){
  BufferedImage image=metadata.getImage();
  System.out.println("Have an image now!");
  System.out.println("Have"+identy);
  try{

      File home = new File("C:\\Directory1");//المجلد الاساسي حق الموظفين
      File dir  = new File(home,identy);//مجلد الموظف عشان نحفظ فيه ملفات الموظف لوحده
      if(!dir.exists()){ dir = home;}//اذا مجلد الموظف غير موجود احفظ في المجلد الاساسي
      File file = new File(dir,"we.jpg");//file.delete();
      ImageIO.write(image, "JPG", file);
//        ImageIO.write(image, "png", new File("C:\\Directory1//we.png"));
         System.out.println(file.getCanonicalPath());
         convertTOpdf();
      }catch(Exception e){
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e.getMessage());
      }
    }else if(type.equals(ScannerIOMetadata.NEGOTIATE)){
      ScannerDevice device=metadata.getDevice();
      try{
        device.setShowUserInterface(true);
        device.setShowProgressBar(true);
        device.setResolution(100);
      }catch(Exception e){
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e.getMessage());
      }
    }else if(type.equals(ScannerIOMetadata.STATECHANGE)){
      System.err.println(metadata.getStateStr());
      if(metadata.isFinished()){
        //System.exit(0);
      }
    }else if(type.equals(ScannerIOMetadata.EXCEPTION)){
      metadata.getException().printStackTrace();
    }
  }


问:
Open report link URL in new blank window
I have dynamic links in my report and when the link is clicked I want it to open in target="_blank".

I have tried the following, but I must be missing a single or double quote somewhere because I am having no luck. The parameters may be throwing me off. For example, I tried these:

="javascript:void(window.open('http://server/folder/filename.aspx?ds='& Parameters!UserName.Value & '&bu=' & Fields!Business_Unit.Value & '&in=' & Fields!Item_No.Value,'_blank'))"
```

<p>And:</p>

<pre class="lang-vb prettyprint-override"><code>="http://server/folder/filename.aspx?ds="& Parameters!UserName.Value & "&bu="& Fields!Business_Unit.Value & "&in=" & Fields!Item_No.Value &rc:LinkTarget=_blank
</code>```

Any suggestions?

答:
```<code>="javascript:void window.open(" &"'" & Globals!ReportServerUrl & "/Pages/ReportViewer.aspx?" & Globals!ReportFolder & "/SubReportWithMemberInfoUsedByWaiverFinance&rc:Parameters=False&RepParameterSet=50,>64,E," & Fields!YYYYMM.Value & "','_blank')"
</code>```

Works well I tested in SSRS 2014  ( That extra parenthesis between VOID and WINDOW is not needed.

Body:
I have dynamic links in my report and when the link is clicked I want it to open in target="_blank".

I have tried the following, but I must be missing a single or double quote somewhere because I am having no luck. The parameters may be throwing me off. For example, I tried these:

="javascript:void(window.open('http://server/folder/filename.aspx?ds='& Parameters!UserName.Value & '&bu=' & Fields!Business_Unit.Value & '&in=' & Fields!Item_No.Value,'_blank'))"

And:

="http://server/folder/filename.aspx?ds="& Parameters!UserName.Value & "&bu="& Fields!Business_Unit.Value & "&in=" & Fields!Item_No.Value &rc:LinkTarget=_blank

Any suggestions?

Body:
="javascript:void window.open(" &"'" & Globals!ReportServerUrl & "/Pages/ReportViewer.aspx?" & Globals!ReportFolder & "/SubReportWithMemberInfoUsedByWaiverFinance&rc:Parameters=False&RepParameterSet=50,>64,E," & Fields!YYYYMM.Value & "','_blank')"

Works well I tested in SSRS 2014  ( That extra parenthesis between VOID and WINDOW is not needed.


问:
All text in HTML webpage has turned to a link pointing to a specific element id in the page. How to fix?
Sorry if this is a stupid question; this is the first coding project I have ever tried to do.

I tried to put a few links at the top of my page that would each point to and scroll down to a specific element/section on the page, but when I did that, 90% of the entire page has turned into a link that points to one specific section ("Favorite Memories" section) on the page. When I say the whole page is a "link", I mean that the mouse pointer is a pointer-finger wherever I go on the page, and it all points to the same section (I can click anywhere on the page, even clicking play on my video, and it will jump down to the "Favorite Memories" section). I can't figure out why this happened or to change it so the whole page isn't acting as a "link".

Any advice would be greatly appreciated!!

Here is the code (I erased all of the actual text so that it isn't so long):

```<code><html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,400i,700,700i" rel="stylesheet">
</head>

<body>
    <div class="intro-container">
        <ul>
            <li><a href="#video" class="nav-link">Birthday Video</li>
            <li><a href="#reasons" class="nav-link">50 Things I Love About You</li>
            <li><a href="#memories" class="nav-link">Favorite Memories</li>
        </ul>
        <div class="intro-div">
          <h1>Te amo.</h1>
          <hr class="style15">
          <p class="tagline">
            </p>
        </div>
    </div>

    <div class="video-div">
        <h2 class="video_title" id="video">Feliz Cumpleaños, Hermosa Mía!</h2>
        <video width="500" height="400" controls>
            <source src="video.mp4" type="video/mp4">
            Your browser does not support the video tag.
        </video>
    </div>

    <div class="reasons-div">
        <h2 class="reasons-title" id="reasons">50 Things I Love About You</h2>
        <p class="reasons-text">
        </p>
    </div>

    <div class="memories-div">
        <h2 class="memories-title" id="memories">My Top 10 Favorite Memories Together</h2>

        <div class="box-text">
            <p class="memories-text">
            </p>
        </div>

        <div class="box-pics">
        </div>
        <br class="clear" />
    </div>

    <div class="end_div">
        <p class="end_text">
        </p>
        <hr class="style15">
    </div>
</body>
</html>
</code>```

答:
You haven't closed your link tags:

```<code><li><a href="#video" class="nav-link">Birthday Video</li>
<li><a href="#reasons" class="nav-link">50 Things I Love About You</li>
<li><a href="#memories" class="nav-link">Favorite Memories</li>
</code>```

Should be:

```<code><li><a href="#video" class="nav-link">Birthday Video</a></li>
<li><a href="#reasons" class="nav-link">50 Things I Love About You</a></li>
<li><a href="#memories" class="nav-link">Favorite Memories</a></li>
</code>```

Body:
Sorry if this is a stupid question; this is the first coding project I have ever tried to do.

I tried to put a few links at the top of my page that would each point to and scroll down to a specific element/section on the page, but when I did that, 90% of the entire page has turned into a link that points to one specific section ("Favorite Memories" section) on the page. When I say the whole page is a "link", I mean that the mouse pointer is a pointer-finger wherever I go on the page, and it all points to the same section (I can click anywhere on the page, even clicking play on my video, and it will jump down to the "Favorite Memories" section). I can't figure out why this happened or to change it so the whole page isn't acting as a "link".

Any advice would be greatly appreciated!!

Here is the code (I erased all of the actual text so that it isn't so long):

    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,400i,700,700i" rel="stylesheet">

Birthday Video

50 Things I Love About You

Favorite Memories

Te amo.

Feliz Cumpleaños, Hermosa Mía!

        <video width="500" height="400" controls>
            <source src="video.mp4" type="video/mp4">
            Your browser does not support the video tag.
        </video>

50 Things I Love About You

My Top 10 Favorite Memories Together

Body:
You haven't closed your link tags:

<li><a href="#video" class="nav-link">Birthday Video</li>
<li><a href="#reasons" class="nav-link">50 Things I Love About You</li>
<li><a href="#memories" class="nav-link">Favorite Memories</li>

Should be:

<li><a href="#video" class="nav-link">Birthday Video</a></li>
<li><a href="#reasons" class="nav-link">50 Things I Love About You</a></li>
<li><a href="#memories" class="nav-link">Favorite Memories</a></li>


问:
How to write aria hidden correctly?
I have very strange question. How correct write aria-hidden value: arIa or arEa?
Because on some website i see and first, and second type to writing this attribute.

答:
aria-hidden is the correct variant.

https://www.w3.org/TR/wai-aria-1.1/#aria-hidden

Title: How to write aria hidden correctly?


问:
Possible to start up Jenkins again via ..war file even though the machine where Jenkins is deployed restarts?
Is it possible to start up Jenkins again via .war even though the machine where Jenkins is deployed restarts?

I have jenkins deployed on a Virtual machine using a .war file with the following command: java -jar jenkins.war

If the machine gets restarted, the command prompt which is using the above command closes and therefore stops my instance of Jenkins from running.

Is there a way to automatically start up Jenkins again even if the machine gets restarted?

VM is using windows 2008 server.

Thanks

答:
Msconfig in Run > startup programs > add your command.
It will be executed on start of OS.</p>


问:
Default SQL Server for Entity Framework
I have two instances of SQL Server - SQLEXPRESS and MSSQLServer 2017. My Entity Framework test application creates database in SQLEXPRESS. Where is it defined which instance of SQL Server Entity Framework should use?

Test application:

```<code>    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class PeopleContext : DbContext
    {
        public IDbSet<Person> People { get; set; }
    }

    static void Main(string[] args) // using DB
    {
        try
        {
            using (PeopleContext ctx = new PeopleContext())
            {
                ctx.People.Add(new Person() { Id = 1, Name = "John Doe" });
                ctx.SaveChanges();
            }

            using (PeopleContext ctx = new PeopleContext())
            {
                Person person = ctx.People.SingleOrDefault(p => p.Id == 1);
                Console.WriteLine(person.Name);
            }

        }
        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }

        Console.WriteLine("finish");
        Console.ReadLine();
    }
</code>```

UPD:
I have several connection strings in my app.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="LearnCSharpConn_server" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=LearnCSharp;Integrated Security=True" />
    <add name="LearnCSharpConn" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LearnCSharp.mdf;Integrated Security=True" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
</code>```

How EF decides which one to use?

答:
To discover the server, username, password and default database you should seek to find the connection string being used by Entity Framework.

You do not specify which version of Entity framework you use, however most versions store the connection string in either web.config or app.config.

Alternatively, you may step into the PeopleContext constructor via Visual Studio's debug mode to view a connection string, or in .Net Core the connection string can be found by stepping through the OnConfigure method in PeopleContext.cs.

Failing that you may Ctrl + f to search connectionString over entire solution.

Title: Default SQL Server for Entity Framework

Body:
I have two instances of SQL Server - SQLEXPRESS and MSSQLServer 2017. My Entity Framework test application creates database in SQLEXPRESS. Where is it defined which instance of SQL Server Entity Framework should use?

Test application:

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class PeopleContext : DbContext
    {
        public IDbSet<Person> People { get; set; }
    }

    static void Main(string[] args) // using DB
    {
        try
        {
            using (PeopleContext ctx = new PeopleContext())
            {
                ctx.People.Add(new Person() { Id = 1, Name = "John Doe" });
                ctx.SaveChanges();
            }

            using (PeopleContext ctx = new PeopleContext())
            {
                Person person = ctx.People.SingleOrDefault(p => p.Id == 1);
                Console.WriteLine(person.Name);
            }

        }
        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }

        Console.WriteLine("finish");
        Console.ReadLine();
    }

UPD:
I have several connection strings in my app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="LearnCSharpConn_server" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=LearnCSharp;Integrated Security=True" />
    <add name="LearnCSharpConn" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LearnCSharp.mdf;Integrated Security=True" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

How EF decides which one to use?


问:
Replicate photo booth screen flash in cocoa
I am trying to replicate a screen flash effect in a mac cocoa application similar to that of the Photo Booth.

A white layer is overlayed on the screen and the brightness of the screen fades really bright and then down again.

Can anyone give me some advice on how this can be replicated in Cocoa?

Thanks

答: You could take a look at this tutorial for creating a full screen window. Just make it white and the use Core Animation to fade it in and out. For example: [[MyFullScreenWindow animator] setAlphaValue:0.0]; will fade it out.


问:
swift 4 json array struct
How will the struct look when you have this data? Must you add the the Success, Code and message in the struct?

"{"Entries":[{"Utility":"Electricity","ConsumptionDateTime":"2017-11-06","Consumption":0.6268,"Amount":0.94999999999999984},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-07","Consumption":55.1076,"Amount":100.88000000000001},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-08","Consumption":54.2914,"Amount":99.659999999999982},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-09","Consumption":54.3062,"Amount":99.809999999999974},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-10","Consumption":54.3584,"Amount":99.330000000000013},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-11","Consumption":53.6868,"Amount":98.570000000000022},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-12","Consumption":38.5152,"Amount":66.65}],"Success":true,"Code":0,"Message":""}"

```<code>struct consumptionResponse: Decodable {
    let Entries: String?
    let consumption: [consumptionEntrys]
    let Success: String?
    let Code: Int?
    let message: String?
}

struct consumptionEntrys: Decodable {

    // MARK: - Properties
    var consumptionUtility: String?
    var consumptionDateTime: String?
    let consumptionReading: Double?
    let consumptionAmount: Double?
 }
</code>```

答:
As luk2302 said you could get the Pretty Print JSON and then form your structures from there.

An edited version of the Pretty Printed JSON yields the following:

```<code>{
"Entries": [
{
"Utility": "Electricity",
"ConsumptionDateTime": "2017-11-06",
"Consumption": 0.6268,
"Amount": 0.95
},
{
"Utility": "Electricity",
"ConsumptionDateTime": "2017-11-07",
"Consumption": 55.1076,
"Amount": 100.88
],
"Success": true,
"Code": 0,
"Message": ""
}
</code>```

As such a viable model should be:

```<code>struct Response: Decodable{

let Entries: [Entries]?
let Success: Bool?
let Code: Int?
let Message: String?

}

struct Entries: Decodable{

let Utility: String?
let ConsumptionDateTime: String?
let Consumption: Double?
let Amount: Double?

}
</code>```

You will of course need to check whether the variables are correct e.g. is the key: ConsumptionDateTime a String?

Anyway hopefully this will help you get started.

Title: swift 4 json array struct

Body:
How will the struct look when you have this data? Must you add the the Success, Code and message in the struct?

"{"Entries":[{"Utility":"Electricity","ConsumptionDateTime":"2017-11-06","Consumption":0.6268,"Amount":0.94999999999999984},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-07","Consumption":55.1076,"Amount":100.88000000000001},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-08","Consumption":54.2914,"Amount":99.659999999999982},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-09","Consumption":54.3062,"Amount":99.809999999999974},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-10","Consumption":54.3584,"Amount":99.330000000000013},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-11","Consumption":53.6868,"Amount":98.570000000000022},{"Utility":"Electricity","ConsumptionDateTime":"2017-11-12","Consumption":38.5152,"Amount":66.65}],"Success":true,"Code":0,"Message":""}"

struct consumptionResponse: Decodable {
    let Entries: String?
    let consumption: [consumptionEntrys]
    let Success: String?
    let Code: Int?
    let message: String?
}

struct consumptionEntrys: Decodable {

    // MARK: - Properties
    var consumptionUtility: String?
    var consumptionDateTime: String?
    let consumptionReading: Double?
    let consumptionAmount: Double?
 }

Body:
As luk2302 said you could get the Pretty Print JSON and then form your structures from there.

An edited version of the Pretty Printed JSON yields the following:

{
"Entries": [
{
"Utility": "Electricity",
"ConsumptionDateTime": "2017-11-06",
"Consumption": 0.6268,
"Amount": 0.95
},
{
"Utility": "Electricity",
"ConsumptionDateTime": "2017-11-07",
"Consumption": 55.1076,
"Amount": 100.88
],
"Success": true,
"Code": 0,
"Message": ""
}

As such a viable model should be:

struct Response: Decodable{

let Entries: [Entries]?
let Success: Bool?
let Code: Int?
let Message: String?

}

struct Entries: Decodable{

let Utility: String?
let ConsumptionDateTime: String?
let Consumption: Double?
let Amount: Double?

}

You will of course need to check whether the variables are correct e.g. is the key: ConsumptionDateTime a String?

Anyway hopefully this will help you get started.


问:
How to add number before a word inside a text file?
I have this menu inside a text file:

#Menu 1 file
Jelly Fish Yee Sang with Pear
Dried Seafood with Fish Soup
Steamed Sea Water Grouper
```

<p>and I have this code:</p>

```menuList = input('enter number:')
def printPackage(menuList):
    if menuList == '1':
        with open('menu/Menu1.txt')as f:
            data = f.read()
            print(data)
printPackage(menuList)
```

<p>What should I add to my code so that I have my text file to print like this?</p>

<pre class="lang-none prettyprint-override"><code>---------
Menu List
---------
1. Jelly Fish Yee Sang with Pear
2. Dried Seafood with Fish Soup
3. Steamed Sea Water Grouper
</code>```

Help please.

答:
Try This Pythonic WAY ( MUCH FASTER ):

```<code>get_input = input('Enter Number: ')
if not get_input == "1":
    exit()
write_save = open("menu/result.txt", "a")
read_lines = [write_save.write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('menu/Menu1.txt'), 1)]
write_save.close()
</code>```

Or Even Shorter :

```<code>get_input = input('Enter Number: ')
if not get_input == "1":
    exit()
read_lines = [open("result.txt", "a").write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('Menu1.txt'), 1)]
</code>```

JUST ONE LINE ( LOOL ) :

```<code>if input("Enter Number: ") == "1" : [open("result.txt", "a").write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('Menu1.txt'), 1)]
</code>```

Body:
I have this menu inside a text file:

#Menu 1 file
Jelly Fish Yee Sang with Pear
Dried Seafood with Fish Soup
Steamed Sea Water Grouper

and I have this code:

menuList = input('enter number:')
def printPackage(menuList):
    if menuList == '1':
        with open('menu/Menu1.txt')as f:
            data = f.read()
            print(data)
printPackage(menuList)

What should I add to my code so that I have my text file to print like this?

---------
Menu List
---------
1. Jelly Fish Yee Sang with Pear
2. Dried Seafood with Fish Soup
3. Steamed Sea Water Grouper

Help please.

Body:
Try This Pythonic WAY ( MUCH FASTER ):

get_input = input('Enter Number: ')
if not get_input == "1":
    exit()
write_save = open("menu/result.txt", "a")
read_lines = [write_save.write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('menu/Menu1.txt'), 1)]
write_save.close()

Or Even Shorter :

get_input = input('Enter Number: ')
if not get_input == "1":
    exit()
read_lines = [open("result.txt", "a").write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('Menu1.txt'), 1)]

JUST ONE LINE ( LOOL ) :

if input("Enter Number: ") == "1" : [open("result.txt", "a").write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('Menu1.txt'), 1)]


问:
Error #1064 adding MySql datetime default value with fractional seconds
I have table:

```<code>CREATE TABLE t1 (
    id INT(3)
  , datetime DATETIME(6)
);
</code>```

I want to add default value to datetime column with fractional seconds:

```<code>ALTER TABLE 't1'
CHANGE 'datetime' 'datetime'
DATETIME DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
</code>```

I get error message #1064:

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near ''t1' CHANGE 'dt' 'dt' DATETIME DEFAULT CURRENT_TIMESTAMP(6) ON
  UPDATE CURRENT_TI' at line 1

答:
You need to use.

Without the qoutes around the table name and column name.

I've used backticks around datetime because datetime is a keyword in MySQL.

And you have forgotten that DATETIME needs to have that fractional seconds defined like DATETIME(6)

```<code>ALTER TABLE t1
CHANGE `datetime` `datetime`
DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
</code>```

Body:
I have table:

CREATE TABLE t1 (
    id INT(3)
  , datetime DATETIME(6)
);

I want to add default value to datetime column with fractional seconds:

ALTER TABLE 't1'
CHANGE 'datetime' 'datetime'
DATETIME DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)

I get error message #1064:

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near ''t1' CHANGE 'dt' 'dt' DATETIME DEFAULT CURRENT_TIMESTAMP(6) ON
  UPDATE CURRENT_TI' at line 1

Body:
You need to use.

Without the qoutes around the table name and column name.

I've used backticks around datetime because datetime is a keyword in MySQL.

And you have forgotten that DATETIME needs to have that fractional seconds defined like DATETIME(6)

ALTER TABLE t1
CHANGE `datetime` `datetime`
DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)


问:
Filling EditText with existing data from SharedPreferences
I'm sure this is something really basic that I'm overlooking but compared with all the articles I've researched, I seem to be doing it right.

I have a DialogPreference that has edittexts for both username and password and a button to save the data to preferences. Upon creation, I'd like to query the preferences and fill the edittext boxes with previously saved data to be edited, otherwise leave the boxes blank. Currently, if no previous data exists, I'm having no issues, but if data does exist, my app crashes when trying to open the DialogPreference.

My DialogPreference code:

```<code>public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener {

    private EditText mUserbox, mPassbox;
    CharSequence mPassboxdata, mUserboxdata;
    private Context mContext;

    private int mWhichButtonClicked;

    public AccDialog(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;

    }

    @Override
    protected View onCreateDialogView() {

        // Access default SharedPreferences
        @SuppressWarnings("unused")
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);

        // Register listener
        final OnCheckedChangeListener mShowchar_listener;

        // Run the following methods onCreate
        existingData();

        @SuppressWarnings("unused")
        LinearLayout.LayoutParams params;
        LinearLayout layout = new LinearLayout(mContext);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setPadding(10, 10, 10, 10);
            layout.setBackgroundColor(0xFF000000);

            mUserbox = new EditText(mContext);
                mUserbox.setSingleLine(true);
                mUserbox.setSelectAllOnFocus(true);

            mPassbox = new EditText(mContext);
                mPassbox.setSingleLine(true);
                mPassbox.setSelectAllOnFocus(true);

            layout.addView(mUserbox);
            layout.addView(mPassbox);

        return layout;
    }

    private void existingData() {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
        String Unamedata = pref.getString("usernamekey", "");
        String Pworddata = pref.getString("passwordkey", "");

        if((Unamedata.length() != 0) && (Pworddata.length() != 0)) {
            mUserbox.setText(Unamedata);
            mPassbox.setText(Pworddata);
        }
    }

}
</code>```

答:
It's because you get a NullPointerException. You are calling existingData() before the edittexs are created. It should work this way:

```<code>    // initialize them first!!!!
    mUserbox = new EditText(mContext);
    mPassbox = new EditText(mContext);
    // Run the following methods onCreate
    existingData();

    @SuppressWarnings("unused")
    LinearLayout.LayoutParams params;
    LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(10, 10, 10, 10);
        layout.setBackgroundColor(0xFF000000);

            mUserbox.setSingleLine(true);
            mUserbox.setSelectAllOnFocus(true);

            mPassbox.setSingleLine(true);
            mPassbox.setSelectAllOnFocus(true);

        layout.addView(mUserbox);
        layout.addView(mPassbox);
</code>```

Just a last advice: learn how to use the logcat tool. It will show you why, when and where your app crashes.

Body:
I'm sure this is something really basic that I'm overlooking but compared with all the articles I've researched, I seem to be doing it right.

I have a DialogPreference that has edittexts for both username and password and a button to save the data to preferences. Upon creation, I'd like to query the preferences and fill the edittext boxes with previously saved data to be edited, otherwise leave the boxes blank. Currently, if no previous data exists, I'm having no issues, but if data does exist, my app crashes when trying to open the DialogPreference.

My DialogPreference code:

public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener {

    private EditText mUserbox, mPassbox;
    CharSequence mPassboxdata, mUserboxdata;
    private Context mContext;

    private int mWhichButtonClicked;

    public AccDialog(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;

    }

    @Override
    protected View onCreateDialogView() {

        // Access default SharedPreferences
        @SuppressWarnings("unused")
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);

        // Register listener
        final OnCheckedChangeListener mShowchar_listener;

        // Run the following methods onCreate
        existingData();

        @SuppressWarnings("unused")
        LinearLayout.LayoutParams params;
        LinearLayout layout = new LinearLayout(mContext);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setPadding(10, 10, 10, 10);
            layout.setBackgroundColor(0xFF000000);

            mUserbox = new EditText(mContext);
                mUserbox.setSingleLine(true);
                mUserbox.setSelectAllOnFocus(true);

            mPassbox = new EditText(mContext);
                mPassbox.setSingleLine(true);
                mPassbox.setSelectAllOnFocus(true);

            layout.addView(mUserbox);
            layout.addView(mPassbox);

        return layout;
    }

    private void existingData() {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
        String Unamedata = pref.getString("usernamekey", "");
        String Pworddata = pref.getString("passwordkey", "");

        if((Unamedata.length() != 0) && (Pworddata.length() != 0)) {
            mUserbox.setText(Unamedata);
            mPassbox.setText(Pworddata);
        }
    }

}

Body:
It's because you get a NullPointerException. You are calling existingData() before the edittexs are created. It should work this way:

    // initialize them first!!!!
    mUserbox = new EditText(mContext);
    mPassbox = new EditText(mContext);
    // Run the following methods onCreate
    existingData();

    @SuppressWarnings("unused")
    LinearLayout.LayoutParams params;
    LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(10, 10, 10, 10);
        layout.setBackgroundColor(0xFF000000);

            mUserbox.setSingleLine(true);
            mUserbox.setSelectAllOnFocus(true);

            mPassbox.setSingleLine(true);
            mPassbox.setSelectAllOnFocus(true);

        layout.addView(mUserbox);
        layout.addView(mPassbox);

Just a last advice: learn how to use the logcat tool. It will show you why, when and where your app crashes.


问:
How to query the File Name of the Filestream Filegroup in a database?
In sys.filegroups i see all the filegroups (main and filestram9 of my database, in  particular this query gives me the name of the filegroup:

```<code>select  name from sys.filegroups where type = 'FD'
</code>```

I would like to get the Filename of that filegroup, for a filestream filegroup the filename is the physical path on disc in  which filestream  data is stored and it is visible from management studio by selecting the database properties and then navigating to the File section.

答:
The follolwing query should give you the value you are looking for</p>

```<code>DECLARE @full_path VARCHAR(1000)
SET @full_path =
(SELECT physical_name
 FROM sys.master_files
 WHERE name =
 (SELECT  name
  FROM sys.filegroups
  WHERE type = 'FD'))

SELECT LEFT(@full_path,LEN(@full_path) -
charindex('\',reverse(@full_path),1) + 1) [FileStreamPath]
</code>```

Body:
In sys.filegroups i see all the filegroups (main and filestram9 of my database, in  particular this query gives me the name of the filegroup:

select  name from sys.filegroups where type = 'FD'

I would like to get the Filename of that filegroup, for a filestream filegroup the filename is the physical path on disc in  which filestream  data is stored and it is visible from management studio by selecting the database properties and then navigating to the File section.

Body:
The follolwing query should give you the value you are looking for

DECLARE @full_path VARCHAR(1000)
SET @full_path =
(SELECT physical_name
 FROM sys.master_files
 WHERE name =
 (SELECT  name
  FROM sys.filegroups
  WHERE type = 'FD'))

SELECT LEFT(@full_path,LEN(@full_path) -
charindex('\',reverse(@full_path),1) + 1) [FileStreamPath]


问:
Regular Expression to match Arabic or English Name
I wanted a regular expression that would match Arabic OR English Names that would allow only characters(alphabets) and spaces, I found a JavaScript RegEx that does the job

```<code>var regex = /^(?:[a-zA-Z\s\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDCF\uFDF0-\uFDFF\uFE70-\uFEFF]|(?:\uD802[\uDE60-\uDE9F]|\uD83B[\uDE00-\uDEFF])){0,30}$/;
</code>```

I converted it to PCRE compliant as

```<code>/^(?:[a-zA-Z\s\x{600}-\x{6FF}\x{750}-\x{77F}\x{8A0}-\x{8FF}\x{FB50}-\x{FDCF}\x{FDF0}-\x{FDFF}\x{FE70}-\x{FEFF}]|(?:\x{D802}[\x{DE60}-\x{DE9F}]|\x{D83B}[\x{DE00}-\x{DEFF}])){0,70}$/u
</code>```

however when I try

```<code>var_dump(preg_match('/^(?:[a-zA-Z\s\x{0600}-\x{06FF}\x{0750}-\x{077F}\x{08A0}-\x{08FF}\x{FB50}-\x{FDCF}\x{FDF0}-\x{FDFF}\x{FE70}-\x{FEFF}]|(?:\x{D802}[\x{DE60}-\x{DE9F}]|\x{D83B}[\x{DE00}-\x{DEFF}])){0,70}$/u', 'Foo Bar'));
</code>```

OR

```<code>var_dump(preg_match('/^(?:[a-zA-Z\s\x{600}-\x{6FF}\x{750}-\x{77F}\x{8A0}-\x{8FF}\x{FB50}-\x{FDCF}\x{FDF0}-\x{FDFF}\x{FE70}-\x{FEFF}]|(?:\x{D802}[\x{DE60}-\x{DE9F}]|\x{D83B}[\x{DE00}-\x{DEFF}])){0,70}$/u', 'Foo Bar'));
</code>```

it returns

PHP Warning:  preg_match(): Compilation failed: disallowed Unicode code point (>= 0xd800 && <= 0xdfff) at offset 127 in php shell code on line 1
  bool(false)

Please help to resolve this warning!

Any help appreciated!
Thank You!

答:
If by letters you mean language main 28 characters you don't even have to construct a code-point based character class (you can build it by typing letters manually!).

But if you mean Arabic (0600–06FF, 255 characters) then again that long character class doesn't provide what you desire.

Anyhow you can go with this:

```<code>/^(?!.*\d)[a-z\p{Arabic}\s]+$/iu
</code>```

Note: you may want to check for different blocks in Arabic script here.

Body:
I wanted a regular expression that would match Arabic OR English Names that would allow only characters(alphabets) and spaces, I found a JavaScript RegEx that does the job

var regex = /^(?:[a-zA-Z\s\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDCF\uFDF0-\uFDFF\uFE70-\uFEFF]|(?:\uD802[\uDE60-\uDE9F]|\uD83B[\uDE00-\uDEFF])){0,30}$/;

I converted it to PCRE compliant as

/^(?:[a-zA-Z\s\x{600}-\x{6FF}\x{750}-\x{77F}\x{8A0}-\x{8FF}\x{FB50}-\x{FDCF}\x{FDF0}-\x{FDFF}\x{FE70}-\x{FEFF}]|(?:\x{D802}[\x{DE60}-\x{DE9F}]|\x{D83B}[\x{DE00}-\x{DEFF}])){0,70}$/u

however when I try

var_dump(preg_match('/^(?:[a-zA-Z\s\x{0600}-\x{06FF}\x{0750}-\x{077F}\x{08A0}-\x{08FF}\x{FB50}-\x{FDCF}\x{FDF0}-\x{FDFF}\x{FE70}-\x{FEFF}]|(?:\x{D802}[\x{DE60}-\x{DE9F}]|\x{D83B}[\x{DE00}-\x{DEFF}])){0,70}$/u', 'Foo Bar'));

OR

var_dump(preg_match('/^(?:[a-zA-Z\s\x{600}-\x{6FF}\x{750}-\x{77F}\x{8A0}-\x{8FF}\x{FB50}-\x{FDCF}\x{FDF0}-\x{FDFF}\x{FE70}-\x{FEFF}]|(?:\x{D802}[\x{DE60}-\x{DE9F}]|\x{D83B}[\x{DE00}-\x{DEFF}])){0,70}$/u', 'Foo Bar'));

it returns

PHP Warning:  preg_match(): Compilation failed: disallowed Unicode code point (>= 0xd800 && <= 0xdfff) at offset 127 in php shell code on line 1
  bool(false)

Please help to resolve this warning!

Any help appreciated!
Thank You!

Body:
If by letters you mean language main 28 characters you don't even have to construct a code-point based character class (you can build it by typing letters manually!).

But if you mean Arabic (0600–06FF, 255 characters) then again that long character class doesn't provide what you desire.

Anyhow you can go with this:

/^(?!.*\d)[a-z\p{Arabic}\s]+$/iu

Note: you may want to check for different blocks in Arabic script here.


问:
I want to know is it okay if i will use following method of memory allocation?
I want to know is it okay if i will use following method? There is no syntax errors and any warnings but i want to know is there any memory problems?</p>

```<code>#include <iostream>
using namespace std;

class test {
    int* x;
public:
    test(int *n) { this->x = new int(*n); }
    inline int get() { return *x; }
    ~test() { delete x; }
};

int main(void) {
while(1){
    test a(new int(3));
    cout << a.get() << endl;
}
    return 0;
}
</code>```

答:
You are violating the rule of 3 (5 since c++11). It means that since you defined the destructor you should define the copy/move constructor/operation.

With your implementation, the copy/move constructor/operation are wrong. When you copy your object, it will do a shallow copy of your pointer and will delete it therefore you will have a double delete. When you move it, you will delete a pointer you didn't allocated.

Bonus point: your inline is useless

Body:
I want to know is it okay if i will use following method? There is no syntax errors and any warnings but i want to know is there any memory problems?

#include <iostream>
using namespace std;

class test {
    int* x;
public:
    test(int *n) { this->x = new int(*n); }
    inline int get() { return *x; }
    ~test() { delete x; }
};

int main(void) {
while(1){
    test a(new int(3));
    cout << a.get() << endl;
}
    return 0;
}


问:
Magical Record delete all records Swift
I'm trying to clear all rows from a table in Magical Record in Swift. I tried:

```<code>DeviceLog.mr_truncateAll()
</code>```

but this seems to have no effect. Does someone know how to do it properly?

Thanks in advance.

答:
Looks like I wasn't awake, it worked when I do it in save. </p>

```<code>MagicalRecord.save({ (context) in
            DeviceLog.mr_truncateAll(in: context)
        }, completion: { (changed, error) in
            if let _ = error {
                print("Error truncating DeviceLog: \(String(describing: error?.localizedDescription))")
            } else {
                print("Truncate DeviceLog successful: \(changed)")
                print(DeviceLog.mr_countOfEntities())
            }
        })
</code>```

Title: Magical Record delete all records Swift

Body:
I'm trying to clear all rows from a table in Magical Record in Swift. I tried:

DeviceLog.mr_truncateAll()

but this seems to have no effect. Does someone know how to do it properly?

Thanks in advance.

Body:
Looks like I wasn't awake, it worked when I do it in save.

MagicalRecord.save({ (context) in
            DeviceLog.mr_truncateAll(in: context)
        }, completion: { (changed, error) in
            if let _ = error {
                print("Error truncating DeviceLog: \(String(describing: error?.localizedDescription))")
            } else {
                print("Truncate DeviceLog successful: \(changed)")
                print(DeviceLog.mr_countOfEntities())
            }
        })


问:
Ionic cordova social sharing plugin always returning true
Cordova social  sharing plugin(Facebook) is always returning true in .then(function(res)). Before posting its showing true.If we cancel the share posting then its also returning true. .then(function()) returning true before posting.Please anybody help for that.Its very urgent.Need code help.</p>

```<code>$scope.share_fb = function(message, logo, url){
$cordovaSocialSharing.shareViaFacebook(message, '', url)
    .then(function (result) {
    var link=site_url+"share_point?id="+user_id;
                                        $http.post(link).success(function(res){
                                        $scope.load_profile();
                                        });
                                    $ionicLoading.hide().then(function(){});
    }, function(error) {
                         alert("Cannot share on Facebook");
                     })
}
$cordovaSocialSharing.canShareVia("facebook", message, logo, url).then(function(result) {
        $scope.share_fb(message, logo, url);

                }, function(error) {
                    alert("Cannot share on Facebook");
                });
</code>```

答:
As seen here: similar question + answer on the Ionic forums

```<code>var isIOS = ionic.Platform.isIOS();
var isAndroid = ionic.Platform.isAndroid();

if(isIOS) {
    $cordovaSocialSharing.canShareVia("instagram").then(function(result) {
        $scope.canShareInstagram  = true;
    }, function() {
        $scope.canShareInstagram  = false;
    });
} else {
   if(isAndroid) {
    $cordovaAppAvailability.check('com.instagram.android')
        .then(function() {
            $scope.canShareInstagram  = true;
        }, function () {
            $scope.canShareInstagram  = false;
        });
   }
}
</code>```

It's a workaround that should prove just as satisfactory.

Body:
Cordova social  sharing plugin(Facebook) is always returning true in .then(function(res)). Before posting its showing true.If we cancel the share posting then its also returning true. .then(function()) returning true before posting.Please anybody help for that.Its very urgent.Need code help.

$scope.share_fb = function(message, logo, url){
$cordovaSocialSharing.shareViaFacebook(message, '', url)
    .then(function (result) {
    var link=site_url+"share_point?id="+user_id;
                                        $http.post(link).success(function(res){
                                        $scope.load_profile();
                                        });
                                    $ionicLoading.hide().then(function(){});
    }, function(error) {
                         alert("Cannot share on Facebook");
                     })
}
$cordovaSocialSharing.canShareVia("facebook", message, logo, url).then(function(result) {
        $scope.share_fb(message, logo, url);

                }, function(error) {
                    alert("Cannot share on Facebook");
                });

Body:
As seen here: similar question + answer on the Ionic forums

var isIOS = ionic.Platform.isIOS();
var isAndroid = ionic.Platform.isAndroid();

if(isIOS) {
    $cordovaSocialSharing.canShareVia("instagram").then(function(result) {
        $scope.canShareInstagram  = true;
    }, function() {
        $scope.canShareInstagram  = false;
    });
} else {
   if(isAndroid) {
    $cordovaAppAvailability.check('com.instagram.android')
        .then(function() {
            $scope.canShareInstagram  = true;
        }, function () {
            $scope.canShareInstagram  = false;
        });
   }
}

It's a workaround that should prove just as satisfactory.


问:
Http get response blank page
I am trying to create  light Angularjs app. I am running api server through irb cli and it is running on port 4567. When i run bundle exec ruby.rb I can confirm that there is data on the address: http://localhost:4567/api/v1/companies:

```<code>[
  {"id": "1",
   "name": "A"
  },
  {
    "id": "2",
    "name": "B",
  }
]
</code>```

I have tried with this code (hello.js):

```<code>var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
        $scope.company=[];
      $http.get("http://localhost:4567/api/v1/companies")
      /*$http.get("http://localhost/fake.json")*/
    .then(function(response) {
        $scope.company = response.data;

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

HTML:

```<code><html>
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

        <body>
            <div ng-app="myApp" ng-controller="customersCtrl">
            <ul>
                    <li ng-repeat="x in company">
                        {{ 'name: ' + x.name + ',  id:' + x.id }}
                    </li>
            </ul>
            </div>
        </body>
    </html>
</code>```

The thing is, if I change the url to the "http://localhost/fake.json" as commented I see the data response clear. But if I use the local web server I can not see anything. Is there some kind of permissions problem or something else.

答:
use success callback instead of then see this document

```<code>$scope.company=[];
      $http.get("http://localhost:4567/api/v1/companies")
      /*$http.get("http://localhost/fake.json")*/
    .success(function(response) {
        $scope.company = response.data;// response or response.data is depend your service response
    }).error(function(errorStatus)
    {
      //code
    });
</code>```

Title: Http get response blank page

Body:
I am trying to create  light Angularjs app. I am running api server through irb cli and it is running on port 4567. When i run bundle exec ruby.rb I can confirm that there is data on the address: http://localhost:4567/api/v1/companies:

[
  {"id": "1",
   "name": "A"
  },
  {
    "id": "2",
    "name": "B",
  }
]

I have tried with this code (hello.js):

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
        $scope.company=[];
      $http.get("http://localhost:4567/api/v1/companies")
      /*$http.get("http://localhost/fake.json")*/
    .then(function(response) {
        $scope.company = response.data;

    });
});

HTML:

        <title>Hello AngularJS</title>

                        {{ 'name: ' + x.name + ',  id:' + x.id }}

The thing is, if I change the url to the "http://localhost/fake.json" as commented I see the data response clear. But if I use the local web server I can not see anything. Is there some kind of permissions problem or something else.

Body:
use success callback instead of then see this document

$scope.company=[];
      $http.get("http://localhost:4567/api/v1/companies")
      /*$http.get("http://localhost/fake.json")*/
    .success(function(response) {
        $scope.company = response.data;// response or response.data is depend your service response
    }).error(function(errorStatus)
    {
      //code
    });


问:
Sort a dictionary by a custom order
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

```<code>public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}
</code>```

the data:

```<code>private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user
</code>```

and a list of possible locations

```<code>        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };
</code>```

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

```<code>    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }
</code>```

答:
You can try to order by your "custom location order" like this:

```<code>string[] locations =
{
    "europe",
    "america",
    "asia",
    "africa"
};

Dictionary<string, UserInfo> sortedUsers = new Dictionary<string, UserInfo>();

foreach (var item in locations)
{
    sortedUsers = sortedUsers.Concat(users.Where(u => u.Value.Location == item)
                             .ToDictionary(d => d.Key, d => d.Value))
                             .ToDictionary(d => d.Key, d => d.Value);
}
</code>```

Title: Sort a dictionary by a custom order

Body:
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}

the data:

private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user

and a list of possible locations

        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }

Body:
You can try to order by your "custom location order" like this:

string[] locations =
{
    "europe",
    "america",
    "asia",
    "africa"
};

Dictionary<string, UserInfo> sortedUsers = new Dictionary<string, UserInfo>();

foreach (var item in locations)
{
    sortedUsers = sortedUsers.Concat(users.Where(u => u.Value.Location == item)
                             .ToDictionary(d => d.Key, d => d.Value))
                             .ToDictionary(d => d.Key, d => d.Value);
}


问:
Default inheritance access specifier
If I have for example two classes A and B, such that class B inherits A as follows:

class B: public A

In this case, I'm doing public inheritance.

If I write the previous code as follows:

class B: A

What type of inheritance will I be doing here (i.e; public)? In other words, what is the default access specifier?

Just a side question here. Do I call the previous line of codes statements? Especially that I remember I read in the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart book that statements are that that end with ;. What do you think about that?

Thanks.

答:
The "type" of inheritance depends on how the class is defined. There are default access specifiers applied to inheritance. From the C++ standard:

[class.access.base]/2

In the absence of an access-specifier for a base class, public is
  assumed when the derived class is defined with the class-key struct
  and private is assumed when the class is defined with the class-key
  class. [ Example:

```<code>class B { /* ... */ };
class D1 : private B { /* ... */ };
class D2 : public B { /* ... */ };
class D3 : B { /* ... */ };             // B private by default
struct D4 : public B { /* ... */ };
struct D5 : private B { /* ... */ };
struct D6 : B { /* ... */ };            // B public by default
class D7 : protected B { /* ... */ };
struct D8 : protected B { /* ... */ };
</code>```

Here B is a public base of D2, D4, and D6, a private base of D1, D3,
  and D5, and a protected base of D7 and D8.  — end example ]

Title: Default inheritance access specifier

Body:
The "type" of inheritance depends on how the class is defined. There are default access specifiers applied to inheritance. From the C++ standard:

[class.access.base]/2

In the absence of an access-specifier for a base class, public is
  assumed when the derived class is defined with the class-key struct
  and private is assumed when the class is defined with the class-key
  class. [ Example:

class B { /* ... */ };
class D1 : private B { /* ... */ };
class D2 : public B { /* ... */ };
class D3 : B { /* ... */ };             // B private by default
struct D4 : public B { /* ... */ };
struct D5 : private B { /* ... */ };
struct D6 : B { /* ... */ };            // B public by default
class D7 : protected B { /* ... */ };
struct D8 : protected B { /* ... */ };

Here B is a public base of D2, D4, and D6, a private base of D1, D3,
  and D5, and a protected base of D7 and D8.  — end example ]


问:
Run commands on host on 'docker-compose up'
I'm trying to run specifics commands that would be automatically fired on docker-compose up

I want to avoid all those steps : https://github.com/FLKone/Dodee/tree/php_mysql_slim

(downloading a zip containing the docker-compose.yml + some required default file)

In that example I need a default config file for Nginx.

So now the solution is to download the zip containing both the yml and the config file. But it would be better if the config file was downloaded  when the user run docker-compose up (or created by it, to limit network access)

(Maybe the best practice here is to create an installion script to download both the yml and the config file ?)

Thanks

答:
I'm trying to run specifics commands that would be automatically fired on docker-compose up

Use entrypoint in your docker-compose.yml. You can do this per service, so the web container can download/configure nginx conf, the php container can run composer, etc.


问:
Trouble connecting phone to arduino using droidScript
I am trying to connect my sony xperia sp running on android 7.1 ( Lineage OS ) to my arduino uno using an OTG cable and the droidScript app. It worked perfectly the first time, it asked permission to open droidScript : I clicked on "OK" and checked "Use by default for this USB device".

But now I can't get it to work. When I reconnect my phone to the Uno nothing happen on my phone, droidScrip does not seem to recognize the device either and now when I try to connect my phone to my computer it does not work either ( but it's charging ).

I have tested all my cables and connected the arduino the same way using a different phone several times and it worked ( but didn't allow "Use by default for this USB device" as I suspect it comes from here ). Manually enable MTP through dev options does not work.

How can I remove that "Use by default for this USB device" option, and get the asking permission box back when I connect to my Uno ?

答:
Try unistalling DroidScript and any other apps that might have talked to that USB device and then re-install DroidScript but don't start it up.

Plugin the OTG cable to the device (make sure you get it the right way round so that the OTG cable goes into the phone end) and then you should see the popup box for permissions.


问:
How to generate non-prefix autocomplete suggestions?
I  would like to add autocomplete to my tagging functionality.

A couple of questions:

How do I generate a list of autocomplete suggestions that includes matches in both the prefix and the middle of string? For example, if the user type "auto", the autocomplete suggestions should include terms such as "autocomplete" and  "build automation".

I would like to allow multi-word tags and use comma (",") as a separator for tags. So when the use  hits the space bar, he is still typing out the same tag, but when he hits the comma key, he's starting a new tag. How do I do that?

I am using Django, jQuery, MySQL, and Solr. What is the best way to achieve to implement the above 2 features?

答:
I've implemented exactly what you're asking about and it works really well.  There's two issues to be aware of:

Highlighting in the results list summaries doesn't work, and the suggested workaround also doesn't work in this particular case.

If your documents have long titles and truncate them when displayed, there's a chance you'll be matching on the prefix of a word that's not being displayed.  Several ways to handle this of course.

And in a future version, I'd like to give words towards the start of the title a bit more weight then words at the end.  This would be one way to mitigate the previous item.

Like the previous answer, I'd start with the same article linked above, but you DO want the Edge NGram analyzer.  The thing you'll add is to ALSO do whitespace tokenization.

And then you'd make these changes to your schema.xml file.  This example assumes you already have a field called "title" defined, and it's what you'd like to display as well.  I create a second field, which is ONLY used for autocomplete prefix matching.

Step 1: Define Edge NGram Text field type

```<code><types>
  <!-- ... other types ... -->

  <!-- Assuming you already have this -->
  <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    ... normal text definition ...
  </fieldType>

  <!-- Adding this -->
  <fieldType name="prefix_edge_text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <!-- not using enablePositionIncrements="true" for now -->
      <filter class="solr.StopFilterFactory" words="stopwords.txt" />
      <filter class="solr.EdgeNGramFilterFactory" minGramSize="1" maxGramSize="25" />
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <!-- No need to create Edges here -->
      <!-- Don't want stopwords here -->
    </analyzer>
  </fieldType>

</types>
</code>```

Step 2: Define the New Field

```<code><fields>
  <!-- ... other fields ... -->

  <!-- Assuming you already have this -->
  <field name="title" type="text" indexed="true" stored="true" multiValued="true"/>

  <!-- Adding this -->
  <field name="prefix_title" type="prefix_edge_text" indexed="true" stored="true" multiValued="true" />

</fields>
</code>```

Step 3: Copy the Title's content over to the prefix field during indexing

```<code><!-- Adding this -->
<copyField source="title" dest="prefix_title" />
</code>```

That's pretty much it for the schema.  Just remember:

When you do a regular search, you still search against the regular title field.

When you're doing an autocomplete search, search against the prefix_title.

Body:
I've implemented exactly what you're asking about and it works really well.  There's two issues to be aware of:

Highlighting in the results list summaries doesn't work, and the suggested workaround also doesn't work in this particular case.

If your documents have long titles and truncate them when displayed, there's a chance you'll be matching on the prefix of a word that's not being displayed.  Several ways to handle this of course.

And in a future version, I'd like to give words towards the start of the title a bit more weight then words at the end.  This would be one way to mitigate the previous item.

Like the previous answer, I'd start with the same article linked above, but you DO want the Edge NGram analyzer.  The thing you'll add is to ALSO do whitespace tokenization.

And then you'd make these changes to your schema.xml file.  This example assumes you already have a field called "title" defined, and it's what you'd like to display as well.  I create a second field, which is ONLY used for autocomplete prefix matching.

Step 1: Define Edge NGram Text field type

<types>
  <!-- ... other types ... -->

  <!-- Assuming you already have this -->
  <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    ... normal text definition ...
  </fieldType>

  <!-- Adding this -->
  <fieldType name="prefix_edge_text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <!-- not using enablePositionIncrements="true" for now -->
      <filter class="solr.StopFilterFactory" words="stopwords.txt" />
      <filter class="solr.EdgeNGramFilterFactory" minGramSize="1" maxGramSize="25" />
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <!-- No need to create Edges here -->
      <!-- Don't want stopwords here -->
    </analyzer>
  </fieldType>

</types>

Step 2: Define the New Field

<fields>
  <!-- ... other fields ... -->

  <!-- Assuming you already have this -->
  <field name="title" type="text" indexed="true" stored="true" multiValued="true"/>

  <!-- Adding this -->
  <field name="prefix_title" type="prefix_edge_text" indexed="true" stored="true" multiValued="true" />

</fields>

Step 3: Copy the Title's content over to the prefix field during indexing

<!-- Adding this -->
<copyField source="title" dest="prefix_title" />

That's pretty much it for the schema.  Just remember:

When you do a regular search, you still search against the regular title field.

When you're doing an autocomplete search, search against the prefix_title.


问:
How to open a file with running instance of netbeans?
When I run the following command it opens a new instance everytime. Is it possible to open file in the running instance of netbeans ?

I'm using NetbeansPortable 8.2

```<code>E:/Netbeans/NetBeansPHPPortable.exe --open "c:\\test.php"
</code>```

答:
If there is an instance of the IDE already running, the file will
  simply open in this instance and the command will exit. You may need
  to pass the --userdir option to match the user directory of the
  running IDE.

Source: http://wiki.netbeans.org/FaqCliOpen

Body:
When I run the following command it opens a new instance everytime. Is it possible to open file in the running instance of netbeans ?

I'm using NetbeansPortable 8.2

E:/Netbeans/NetBeansPHPPortable.exe --open "c:\\test.php"


问:
Csv file writing the extra rows while downloading
When I try to export the csv file from servlet code it displayed the correct records but at the end it display extra rows.

Example: It need 1000 rows but it display 1041 rows long with 1000 records.

Below is my code and the excel sheet.

```<code>// for downloading csv
public void getDownloaded(String filepath, HttpServletResponse response) {
    try {
        File file = new File(filepath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] outputByte = new byte[4096];
        // copy binary content to output stream
        while (in.read(outputByte, 0, 4096) != -1) {
            out.write(outputByte, 0, 4096);
        }
        in.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

答:
Actually there is a subtle bug in the getDownloaded method. This code here reads eventually an writes an incorrect number of bytes in case less than 4096 bytes are read, thus writing potentially garbage to the out stream:

```<code>//copy binary content to output stream
while(in.read(outputByte, 0, 4096) != -1){
    out.write(outputByte, 0, 4096);
}
</code>```

It should actually use the exact number of read bytes in the write statement:

```<code>int length;
while ((length = in.read(outputByte, 0, 4096)) != -1) {
    out.write(outputByte, 0, length);
}
</code>```

Body:
When I try to export the csv file from servlet code it displayed the correct records but at the end it display extra rows.

Example: It need 1000 rows but it display 1041 rows long with 1000 records.

Below is my code and the excel sheet.

// for downloading csv
public void getDownloaded(String filepath, HttpServletResponse response) {
    try {
        File file = new File(filepath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] outputByte = new byte[4096];
        // copy binary content to output stream
        while (in.read(outputByte, 0, 4096) != -1) {
            out.write(outputByte, 0, 4096);
        }
        in.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Body:
Actually there is a subtle bug in the getDownloaded method. This code here reads eventually an writes an incorrect number of bytes in case less than 4096 bytes are read, thus writing potentially garbage to the out stream:

//copy binary content to output stream
while(in.read(outputByte, 0, 4096) != -1){
    out.write(outputByte, 0, 4096);
}

It should actually use the exact number of read bytes in the write statement:

int length;
while ((length = in.read(outputByte, 0, 4096)) != -1) {
    out.write(outputByte, 0, length);
}


问:
Numpy: an efficient way to implement sum of pairwise mins operation
It's easy to do sum of products between two matrices, i.e.:

```<code>A = np.random.randn(100, 64)
B = np.random.randn(64, 100)
G = np.dot(A, B)
</code>```

Is there a similar approach to do sum of pairwise mins between vectors ?

An inefficient approach is to do:

```<code># For each row, col vector i,j in A and B respectively
for i in range(A.shape[0]):
    for j in range(B.shape[1]):
        G[i, j] = np.minimum(A[i], B[:,j]).sum()
</code>```

So I am looking for something like:

G = np.dot(A, B, operation=np.minimum)

The goal is to avoid the slow for loops and to take advantage of numpy's BLAS implementation.

One major use case is the intersection of histograms kernel. An example is described in this great blog post:
http://blog.datadive.net/histogram-intersection-for-change-detection/

答:
One straight-forward way would be to extend A to 3D and leverage broadcasting -

```<code>np.minimum(A[...,None], B).sum(1)
</code>```

Body:
It's easy to do sum of products between two matrices, i.e.:

A = np.random.randn(100, 64)
B = np.random.randn(64, 100)
G = np.dot(A, B)

Is there a similar approach to do sum of pairwise mins between vectors ?

An inefficient approach is to do:

# For each row, col vector i,j in A and B respectively
for i in range(A.shape[0]):
    for j in range(B.shape[1]):
        G[i, j] = np.minimum(A[i], B[:,j]).sum()

So I am looking for something like:

G = np.dot(A, B, operation=np.minimum)

The goal is to avoid the slow for loops and to take advantage of numpy's BLAS implementation.

One major use case is the intersection of histograms kernel. An example is described in this great blog post:
http://blog.datadive.net/histogram-intersection-for-change-detection/

Body:
One straight-forward way would be to extend A to 3D and leverage broadcasting -

np.minimum(A[...,None], B).sum(1)


问:
When generating barcodes, is there a limit on the number of characters?
I have to develop a system that generates barcodes that will be printed and was wondering if there's a limit to the number of characters of a barcode? I intend to make this using PHP, also would it be better in some way to use QR codes?

EDIT

I want to do this barcodes for a system that will stor different types of shoes but since there are lots of variations to the shoes I require some more characters, but I think I can use hexadecimal numbers to create the barcodes (not sure if this is possible I'm looking into it)

答:
All barcodes have some limit on the number of characters (or, most commonly, digits) they can represent - you wouldn't expect any kind of barcode to hold an infinite amount of data, would you? ;)

There are many kinds of barcodes, some even have variable lengths.

Emitting barcodes is not as simple as you may think, you'd probably have to:

use a checksum algorithm

follow the predifined "namespaces" (ISBN comes to mind)

register your own namespace with GS1 or a similar regulating body

QR Codes and Semacodes are two-dimensional, this makes it harder to scramble the data they hold and I'm almost sure they are not regulated, but they are also a bit harder to generate.

Some more information about what (and why) you want to do would be helpful, otherwise you probably won't get any decent answers.

Some food for thought:

will these barcodes be used internally? if not, how will you make sure your barcode isn't misinterpreted by another product which happens to share the same code?

I might be wrong, but you can only use digits (and maybe X for the check digit) with the GTIN family of barcodes - more importantly, why would you need more than the 0-9 charset? even a 8-digit barcode provides 7^10 (282.475.249) different codes... Do you really have that many shoes?

have you considered generating Semacodes instead? They allow direct URL routing and can be read by most cellphones nowadays - wouldn't such a system be enough for your needs?


答:
You have 2 issues in your code:

your class violates rule of three/five/zero

you are leaking memory when create a

In this code:

```<code>test a(new int(3));
</code>```

you dynamically allocate int with value 3 and pass to a ctor which uses value and creates it's own dynamically allocated int. After that this memory is leaked. If you want to pass dynamically allocated data to a class use a smart  pointer:

```<code>class test {
    std::unique_ptr<int> x;
public:
    test(std::unique_ptr<int> n) : x( std::move( n ) ) {  }
    int get() const { return *x; }
};

int main()
{
    x a( std::make_unique<int>( 3 ) ); // since c++14
    x a( std::unique_ptr<int>( new int(3) ) ); // before c++14
    ...
}
</code>```

and you do not need to implement dtor explicitly, you do not violate the rule and it is safe to pass dynamically allocated data to ctor.

Note: I assumed you used int as example and you would understand that dynamically allocate one int is useless, you should just store it by value.

Title: I want to know is it okay if i will use following method of memory allocation?

Body:
You have 2 issues in your code:

your class violates rule of three/five/zero

you are leaking memory when create a

In this code:

test a(new int(3));

you dynamically allocate int with value 3 and pass to a ctor which uses value and creates it's own dynamically allocated int. After that this memory is leaked. If you want to pass dynamically allocated data to a class use a smart  pointer:

class test {
    std::unique_ptr<int> x;
public:
    test(std::unique_ptr<int> n) : x( std::move( n ) ) {  }
    int get() const { return *x; }
};

int main()
{
    x a( std::make_unique<int>( 3 ) ); // since c++14
    x a( std::unique_ptr<int>( new int(3) ) ); // before c++14
    ...
}

and you do not need to implement dtor explicitly, you do not violate the rule and it is safe to pass dynamically allocated data to ctor.

Note: I assumed you used int as example and you would understand that dynamically allocate one int is useless, you should just store it by value.


问:
Connection Only on merged Power Queries
I have two queries in my workbook that rely on each other.  One is set to a connection only, the other is set to load to a table after performing some merging and expanding operations.  I noticed that when refreshing, the query set to "Connection only" does not have a visual indication of refreshing.

When I refresh the secondary query that relies on information from the connection only one, does it actually refresh both of them?  I am having a hard time finding clear documentation on this.  A link to where the information is would also be appreciated.

Further information on the queries themselves:

Both link to SQL tables.

One pulls the latest data available in the table.

The other pulls recent information from a different table.

The second one merges the two tables together (by the key).

The second one then only grabs information from the first when there is missing information in the second.

I am specifically asking; When the second table calls a refresh, does the first table also refresh even though it is a connection only?

答: I also had a tough time finding information about this. There is a post by Ken Puls in PowerPivotPro.com that helps drive some (good) conclusions about this. Net-net, the "connection only" queries ARE refreshed before the merge query, you just don't see it (which, btw, I think should be implemented in Excel). Hope this helps.</p>

Title: Connection Only on merged Power Queries


问:
adding indexes for spring data neo4j doesn't work
Hi all I am trying to add indexes for neo4j Database through the code.
I have my configuration class setup like this.:

```<code>@Configuration
public class CreateIndex {

@Bean
public org.neo4j.ogm.config.Configuration configuration() {
   org.neo4j.ogm.config.Configuration configuration = new
              org.neo4j.ogm.config.Configuration();

 configuration.autoIndexConfiguration()
 .setAutoIndex(AutoIndexMode.ASSERT.getName());

 configuration.driverConfiguration().setDriverClassName
 ("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");

 return configuration;
 }

  @Bean
  public SessionFactory sessionFactory() {
    return new SessionFactory(configuration(), "com.domain");
  }
}
</code>```

and I have my domain class where I added the @Index annotation .

```<code>    @NodeEntity
    @Getter
    @NoArgsConstructor
    @Component
    public class Movie {
      @GraphId
      private Long id;

      @Index(unique = true)
      private String movieId;
    }
</code>```

and I have my dependencies as

```<code>    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-neo4j</artifactId>
         <version>1.4.0.RELEASE</version>
     </dependency>
</code>```

In my logs I see that my Index query is being executed

```<code>n.o.d.e.request.EmbeddedRequest        : Request: CALL db.constraints() with params {}
2017-11-02 16:30:11.780  INFO 40073 --- [           main] o.n.o.d.e.request.EmbeddedRequest        : Request: CALL db.indexes() with params {}
2017-11-02 16:30:11.789  INFO 40073 --- [           main] o.n.o.d.e.request.EmbeddedRequest        : Request: CREATE INDEX ON :MOVIE(movieId ) with params {}
</code>```

But when I try to see if the indexes exists or not by using :schema
that doesn't return anything.

I was trying to execute the query using NEO4JTemplate but it is been deprecated you know how can I execute the queries on startup.

For example I want to add the index query by code during start of the application

```<code>CREATE INDEX ON :MOVIE(movieId)
</code>```

This works if I add manually, but how to add to the configuration class.

Thanks in advance

答:
Your configuration is mostly correct.

You don't say where you run the :schema command, but my guess is that it is a different database than one used in your app, because following configuration:

```<code>org.neo4j.ogm.config.Configuration configuration = new
          org.neo4j.ogm.config.Configuration();
configuration.autoIndexConfiguration()
    .setAutoIndex(AutoIndexMode.ASSERT.getName());
configuration.driverConfiguration()
    .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
</code>```

will create impermanent database in temp directory, which gets deleted after application shutdown. The reason is that no URI is specified.

Specify database URI and check the schema in that database:

```<code>configuration.driverConfiguration()
    .setURI("....");
</code>```

Body:
Hi all I am trying to add indexes for neo4j Database through the code.
I have my configuration class setup like this.:

@Configuration
public class CreateIndex {

@Bean
public org.neo4j.ogm.config.Configuration configuration() {
   org.neo4j.ogm.config.Configuration configuration = new
              org.neo4j.ogm.config.Configuration();

 configuration.autoIndexConfiguration()
 .setAutoIndex(AutoIndexMode.ASSERT.getName());

 configuration.driverConfiguration().setDriverClassName
 ("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");

 return configuration;
 }

  @Bean
  public SessionFactory sessionFactory() {
    return new SessionFactory(configuration(), "com.domain");
  }
}

and I have my domain class where I added the @Index annotation .

    @NodeEntity
    @Getter
    @NoArgsConstructor
    @Component
    public class Movie {
      @GraphId
      private Long id;

      @Index(unique = true)
      private String movieId;
    }

and I have my dependencies as

    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-neo4j</artifactId>
         <version>1.4.0.RELEASE</version>
     </dependency>

In my logs I see that my Index query is being executed

n.o.d.e.request.EmbeddedRequest        : Request: CALL db.constraints() with params {}
2017-11-02 16:30:11.780  INFO 40073 --- [           main] o.n.o.d.e.request.EmbeddedRequest        : Request: CALL db.indexes() with params {}
2017-11-02 16:30:11.789  INFO 40073 --- [           main] o.n.o.d.e.request.EmbeddedRequest        : Request: CREATE INDEX ON :MOVIE(movieId ) with params {}

But when I try to see if the indexes exists or not by using :schema
that doesn't return anything.

I was trying to execute the query using NEO4JTemplate but it is been deprecated you know how can I execute the queries on startup.

For example I want to add the index query by code during start of the application

CREATE INDEX ON :MOVIE(movieId)

This works if I add manually, but how to add to the configuration class.

Thanks in advance

Body:
Your configuration is mostly correct.

You don't say where you run the :schema command, but my guess is that it is a different database than one used in your app, because following configuration:

org.neo4j.ogm.config.Configuration configuration = new
          org.neo4j.ogm.config.Configuration();
configuration.autoIndexConfiguration()
    .setAutoIndex(AutoIndexMode.ASSERT.getName());
configuration.driverConfiguration()
    .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");

will create impermanent database in temp directory, which gets deleted after application shutdown. The reason is that no URI is specified.

Specify database URI and check the schema in that database:

configuration.driverConfiguration()
    .setURI("....");