问:
Xcode 8 generates broken NSManagedObject subclasses for iOS 10
I updated my iOS app project recently to iOS 10. Now I'm trying to change the Core Data Model of my app but the new NSManagedObject subclasses which Xcode generates are broken. I also tried to fix the subclasses manual but this doesn't work.

The minimum tools version for the Core Data Model is set to Xcode 7.0 and code generation language is set to Swift.

This is the code which Xcode generates:

```<code>import Foundation
import CoreData
import

extension Group {

    @nonobjc public class func fetchRequest() -> NSFetchRequest {
        return NSFetchRequest(entityName: "Group");
    }

    @NSManaged public var name: String?
    @NSManaged public var platform: NSNumber?
    @NSManaged public var profiles: NSOrderedSet?

}

// MARK: Generated accessors for profiles
extension Group {

    @objc(insertObject:inProfilesAtIndex:)
    @NSManaged public func insertIntoProfiles(_ value: SavedProfile, at idx: Int)

    @objc(removeObjectFromProfilesAtIndex:)
    @NSManaged public func removeFromProfiles(at idx: Int)

    @objc(insertProfiles:atIndexes:)
    @NSManaged public func insertIntoProfiles(_ values: [SavedProfile], at indexes: NSIndexSet)

    @objc(removeProfilesAtIndexes:)
    @NSManaged public func removeFromProfiles(at indexes: NSIndexSet)

    @objc(replaceObjectInProfilesAtIndex:withObject:)
    @NSManaged public func replaceProfiles(at idx: Int, with value: SavedProfile)

    @objc(replaceProfilesAtIndexes:withProfiles:)
    @NSManaged public func replaceProfiles(at indexes: NSIndexSet, with values: [SavedProfile])

    @objc(addProfilesObject:)
    @NSManaged public func addToProfiles(_ value: SavedProfile)

    @objc(removeProfilesObject:)
    @NSManaged public func removeFromProfiles(_ value: SavedProfile)

    @objc(addProfiles:)
    @NSManaged public func addToProfiles(_ values: NSOrderedSet)

    @objc(removeProfiles:)
    @NSManaged public func removeFromProfiles(_ values: NSOrderedSet)

}</code>```

Edit: These are the specific errors which Xcode gives:

```<code>1. Group+CoreDataProperties.swift:13:1: Expected identifier in import declaration (the empty import)
2. Group+CoreDataProperties.swift:13:11: 'Group' is ambiguous for type lookup in this context
3. Group+CoreDataProperties.swift:15:16: Cannot specialize non-generic type 'NSFetchRequest'
4. Group+CoreDataProperties.swift:26:11: 'Group' is ambiguous for type lookup in this context
4. Group+CoreDataProperties.swift:43:82: 'SavedProfile' is ambiguous for type lookup in this context
</code>```

答:
I solved it like an example given below

Create CurrentcyPair.xcdatamodeld

select CurrentcyPair.xcdatamodeld and select Default -> Entity (CurrencyPair) , rename the class as (.ManagedCurrencyPair)

Select Entity and open Inspector. Set code gen at data model as Manual/None

Body:
I updated my iOS app project recently to iOS 10. Now I'm trying to change the Core Data Model of my app but the new NSManagedObject subclasses which Xcode generates are broken. I also tried to fix the subclasses manual but this doesn't work.

The minimum tools version for the Core Data Model is set to Xcode 7.0 and code generation language is set to Swift.

This is the code which Xcode generates:

import Foundation
import CoreData
import

extension Group {

    @nonobjc public class func fetchRequest() -> NSFetchRequest {
        return NSFetchRequest(entityName: "Group");
    }

    @NSManaged public var name: String?
    @NSManaged public var platform: NSNumber?
    @NSManaged public var profiles: NSOrderedSet?

}

// MARK: Generated accessors for profiles
extension Group {

    @objc(insertObject:inProfilesAtIndex:)
    @NSManaged public func insertIntoProfiles(_ value: SavedProfile, at idx: Int)

    @objc(removeObjectFromProfilesAtIndex:)
    @NSManaged public func removeFromProfiles(at idx: Int)

    @objc(insertProfiles:atIndexes:)
    @NSManaged public func insertIntoProfiles(_ values: [SavedProfile], at indexes: NSIndexSet)

    @objc(removeProfilesAtIndexes:)
    @NSManaged public func removeFromProfiles(at indexes: NSIndexSet)

    @objc(replaceObjectInProfilesAtIndex:withObject:)
    @NSManaged public func replaceProfiles(at idx: Int, with value: SavedProfile)

    @objc(replaceProfilesAtIndexes:withProfiles:)
    @NSManaged public func replaceProfiles(at indexes: NSIndexSet, with values: [SavedProfile])

    @objc(addProfilesObject:)
    @NSManaged public func addToProfiles(_ value: SavedProfile)

    @objc(removeProfilesObject:)
    @NSManaged public func removeFromProfiles(_ value: SavedProfile)

    @objc(addProfiles:)
    @NSManaged public func addToProfiles(_ values: NSOrderedSet)

    @objc(removeProfiles:)
    @NSManaged public func removeFromProfiles(_ values: NSOrderedSet)

}

Edit: These are the specific errors which Xcode gives:

1. Group+CoreDataProperties.swift:13:1: Expected identifier in import declaration (the empty import)
2. Group+CoreDataProperties.swift:13:11: 'Group' is ambiguous for type lookup in this context
3. Group+CoreDataProperties.swift:15:16: Cannot specialize non-generic type 'NSFetchRequest'
4. Group+CoreDataProperties.swift:26:11: 'Group' is ambiguous for type lookup in this context
4. Group+CoreDataProperties.swift:43:82: 'SavedProfile' is ambiguous for type lookup in this context


来源: stackexchange

问:
How to remove duplicate words from a text file using java
I have a input file like

names.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

</code>```

I want to output like. Removing duplicates words from the name

output.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

</code>```

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}
```

答:
You are going to want to make use of a Set or HashSet in order to track duplicate names, and an ArrayList in order to store your ultimate lines to be written to your output file.

Since we are making changes on a line-by-line basis, we need to 1) read the file line-by-line, 2) split the line up to process the individual names, 3) edit the line or create a new resulting line as required, and 4) then store the edited line to be output at the end:

```<code>import java.util.*;
import java.io.*;

public class Duplicate {
    public static void main(String[] args) throws IOException {
        HashSet<String> uniqueNames = new HashSet<String>();
        ArrayList<String> outputLines = new ArrayList<String>();

        Scanner input = new Scanner(new File("input.txt"));
        while (input.hasNextLine()) {

            // Split a line into an array of names.
            String[] names = input.nextLine().split(" ");
            String edited = "";
            for (int i = 0; i < names.length; i++) {

                // If the name is already in the set, remove it.
                if (uniqueNames.add(names[i])) {
                    edited += names[i] + " ";
                }
            }

            edited = edited.strip();  // remove excess whitespace

            // Add the final line to our output array.
            if (!edited.equals("")) {
                outputLines.add(edited);
            }
        }

        // Write the output array to a file.
        String outputFn = "output.txt";
        BufferedWriter output = new BufferedWriter(new FileWriter(outputFn));
        output.write(String.join("\n", outputLines));
        output.close();
        System.out.println("File '" + outputFn + "' created!");
    }
}
</code>```

I leave it as an exercise if you want to add other features, like counting total words or unique words, since the question seemed to be mostly about the removing duplicates behavior.

ContentLicense: CC BY-SA 4.0

Body:
I have a input file like

names.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

I want to output like. Removing duplicates words from the name

output.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}

Body:
You are going to want to make use of a Set or HashSet in order to track duplicate names, and an ArrayList in order to store your ultimate lines to be written to your output file.

Since we are making changes on a line-by-line basis, we need to 1) read the file line-by-line, 2) split the line up to process the individual names, 3) edit the line or create a new resulting line as required, and 4) then store the edited line to be output at the end:

import java.util.*;
import java.io.*;

public class Duplicate {
    public static void main(String[] args) throws IOException {
        HashSet<String> uniqueNames = new HashSet<String>();
        ArrayList<String> outputLines = new ArrayList<String>();

        Scanner input = new Scanner(new File("input.txt"));
        while (input.hasNextLine()) {

            // Split a line into an array of names.
            String[] names = input.nextLine().split(" ");
            String edited = "";
            for (int i = 0; i < names.length; i++) {

                // If the name is already in the set, remove it.
                if (uniqueNames.add(names[i])) {
                    edited += names[i] + " ";
                }
            }

            edited = edited.strip();  // remove excess whitespace

            // Add the final line to our output array.
            if (!edited.equals("")) {
                outputLines.add(edited);
            }
        }

        // Write the output array to a file.
        String outputFn = "output.txt";
        BufferedWriter output = new BufferedWriter(new FileWriter(outputFn));
        output.write(String.join("\n", outputLines));
        output.close();
        System.out.println("File '" + outputFn + "' created!");
    }
}

I leave it as an exercise if you want to add other features, like counting total words or unique words, since the question seemed to be mostly about the removing duplicates behavior.


问:
how do we deal with not knowing the prefix/namespace?
How do I iterate through a specific xpath against an XmlDocument that has no prefix/namespace ?

I'm parsing XML like so :

```<code>        var doc = new XmlDocument();
        doc.LoadXml(input);
        var nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace(nsPrefix, ns);
        var nodes = doc.SelectNodes(xpath, nsmgr);
</code>```

This works totally fine when the nsPrefix as well as the ns are passed in and non-empty.

However, when the namespace/prefix are empty for example in this scenario:

Then I am unable to correctly parse the XML.

The full function is:

```<code>public static class XPathWalker
    {
        public static IEnumerable<string> GetListOfAttachments(string input, string xpath, string nsPrefix, string ns)
        {
            var doc = new XmlDocument();
            doc.LoadXml(input);
            var nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace(nsPrefix, ns);
            var nodes = doc.SelectNodes(xpath, nsmgr);
            foreach (XmlNode node in nodes)
            {
                if (string.IsNullOrWhiteSpace(node.InnerText))
                {
                    continue;
                }
                yield return node.InnerText;
            }
        }
    }
</code>```

How do I iterate through a specific xpath against an XmlDocument that has no prefix/namespace ?

答:
There was indeed a way to do this with XmlDocument. Firstly, I had to convert the input string to a stream:

```<code>// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);
</code>```

Once I had my stream, I was able to feed it into XmlDocument. Here's the full code:

```<code>        string input = @"<?xml version="1.0" encoding="UTF-8"?>etc..";
        byte[] byteArray = Encoding.UTF8.GetBytes(input);
        var stream = new MemoryStream(byteArray);
        var doc = new XmlDocument();
        var nodes = doc.SelectNodes(xpath);
        using (var tr = new XmlTextReader(stream))
        {
            tr.Namespaces = false;
            doc.Load(tr);
        }
</code>```

Body:
How do I iterate through a specific xpath against an XmlDocument that has no prefix/namespace ?

I'm parsing XML like so :

        var doc = new XmlDocument();
        doc.LoadXml(input);
        var nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace(nsPrefix, ns);
        var nodes = doc.SelectNodes(xpath, nsmgr);

This works totally fine when the nsPrefix as well as the ns are passed in and non-empty.

However, when the namespace/prefix are empty for example in this scenario:

Then I am unable to correctly parse the XML.

The full function is:

public static class XPathWalker
    {
        public static IEnumerable<string> GetListOfAttachments(string input, string xpath, string nsPrefix, string ns)
        {
            var doc = new XmlDocument();
            doc.LoadXml(input);
            var nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace(nsPrefix, ns);
            var nodes = doc.SelectNodes(xpath, nsmgr);
            foreach (XmlNode node in nodes)
            {
                if (string.IsNullOrWhiteSpace(node.InnerText))
                {
                    continue;
                }
                yield return node.InnerText;
            }
        }
    }

How do I iterate through a specific xpath against an XmlDocument that has no prefix/namespace ?

Body:
There was indeed a way to do this with XmlDocument. Firstly, I had to convert the input string to a stream:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);

Once I had my stream, I was able to feed it into XmlDocument. Here's the full code:

        string input = @"<?xml version="1.0" encoding="UTF-8"?>etc..";
        byte[] byteArray = Encoding.UTF8.GetBytes(input);
        var stream = new MemoryStream(byteArray);
        var doc = new XmlDocument();
        var nodes = doc.SelectNodes(xpath);
        using (var tr = new XmlTextReader(stream))
        {
            tr.Namespaces = false;
            doc.Load(tr);
        }


问:
Xamarin: Error trying to show WebView using OpenLayers maps with html and javascript
I'm trying to show a map in xamarin using a WebView component,
try passing this code to an html file and it works fine.  The WebView is from Xamarin.Forms

The line alert('test');
and the word App in the body of the html is shown without problems, but the map doesn't show.

The devise for test was running android 9

```<code>    var browser = new WebView();
    browser.HeightRequest = 600;
    browser.WidthRequest = 600;

    var htmlSource = new HtmlWebViewSource();
    htmlSource.Html = @"<html>
                           <head>
                              <script src='http://www.openlayers.org/api/OpenLayers.js'></script>
                            </head>
                            <body>
                                 App
                                  <div id='mapdiv'></div>
                                  <script>
                                       alert('test');
                                       map = new OpenLayers.Map('mapdiv');
                                       map.addLayer(new OpenLayers.Layer.OSM());

                                       var lonLat = new OpenLayers.LonLat(-0.1279688, 51.5077286)
                                      .transform(
                                       new OpenLayers.Projection('EPSG:4326'),
                                       map.getProjectionObject()
                                    );

                                      var zoom = 16;

                                      var markers = new
                                      OpenLayers.Layer.Markers('Markers');
                                      map.addLayer(markers);

                                      markers.addMarker(new OpenLayers.Marker(lonLat));

                                      map.setCenter(lonLat, zoom);
                                </script>
                      </body></html>";

                    browser.Source = htmlSource;
                    Children.Add(browser);
</code>```

答:
1st: Change your script link use https (vs. http)

2nd: The OpenLayers.js script itself uses a lot of non-secure links and that is a problem on iOS and new Android API levels from Google as by default all links should be secure (https).

If you review the application output you will see log messages such as:

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

iOS:

So on iOS, you will have to add an exception to your app's Info.plist such as:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</code>```

re: https://stackoverflow.com/a/40299837/4984832

Android:

Starting with Android 9 (API level 28), cleartext support is disabled by default.

On Android 9+ you will have add a security exception to your app (cleartextTrafficPermitted)

re: https://stackoverflow.com/a/55997456/4984832

Note: My Xamarin-based answer is linked, or edit the manifest directly via the other answers to that question.

BTW: The ultimate answer would be to file a bug with OpenLayers to use secure endpoints in all their scripts so application security exceptions do not have to be applied for...

Body:
I'm trying to show a map in xamarin using a WebView component,
try passing this code to an html file and it works fine.  The WebView is from Xamarin.Forms

The line alert('test');
and the word App in the body of the html is shown without problems, but the map doesn't show.

The devise for test was running android 9

    var browser = new WebView();
    browser.HeightRequest = 600;
    browser.WidthRequest = 600;

    var htmlSource = new HtmlWebViewSource();
    htmlSource.Html = @"

                                 App

                      ";

                    browser.Source = htmlSource;
                    Children.Add(browser);

Body:
1st: Change your script link use https (vs. http)

2nd: The OpenLayers.js script itself uses a lot of non-secure links and that is a problem on iOS and new Android API levels from Google as by default all links should be secure (https).

If you review the application output you will see log messages such as:

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

iOS:

So on iOS, you will have to add an exception to your app's Info.plist such as:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

re: https://stackoverflow.com/a/40299837/4984832

Android:

Starting with Android 9 (API level 28), cleartext support is disabled by default.

On Android 9+ you will have add a security exception to your app (cleartextTrafficPermitted)

re: https://stackoverflow.com/a/55997456/4984832

Note: My Xamarin-based answer is linked, or edit the manifest directly via the other answers to that question.

BTW: The ultimate answer would be to file a bug with OpenLayers to use secure endpoints in all their scripts so application security exceptions do not have to be applied for...


问:
Find a row and its index then delete this row using index
I would looking for a way to basically delete, step by step, a specific row.

```<code>      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design
</code>```

After deleting some row because of NaN, id's are different than index.
So, I used :

```<code>app.loc[app['prix']=='Everyone',:]
</code>```

To learn more about which row contains "Everyone" in the column "prix".

Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)

I tried :

```<code>app.index[app['prix'] == 'Everyone'].tolist()
</code>```

But the result give me [28].
Then I tried

```<code>app.loc[app.index==28]
</code>```

Same result.
app.index[28] will told me :

```<code>IndexError: index 28 is out of bounds for axis 0 with size 5
</code>```

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?

Thanks

EDIT :
There are the solutions I was looking for :

♣ Reset the Index

```<code>app = app.reset_index()
</code>```

♣ Find the rows (and the index)

```<code>app.loc[app['prix']=='Everyone',:]
</code>```

♣ Delete this row using the index

```<code>app = app.drop(4795)
</code>```

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.

答:
The 28 is the row identifier of the dataframe. It was originally (before you removed NA) the 28th row (29th I suppose because of the zero-based indexing). You can drop the row based on that id.</p>

```<code>app.drop([28])
</code>```

Body:
I would looking for a way to basically delete, step by step, a specific row.

      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design

After deleting some row because of NaN, id's are different than index.
So, I used :

app.loc[app['prix']=='Everyone',:]

To learn more about which row contains "Everyone" in the column "prix".

Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)

I tried :

app.index[app['prix'] == 'Everyone'].tolist()

But the result give me [28].
Then I tried

app.loc[app.index==28]

Same result.
app.index[28] will told me :

IndexError: index 28 is out of bounds for axis 0 with size 5

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?

Thanks

EDIT :
There are the solutions I was looking for :

♣ Reset the Index

app = app.reset_index()

♣ Find the rows (and the index)

app.loc[app['prix']=='Everyone',:]

♣ Delete this row using the index

app = app.drop(4795)

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.

Body:
The 28 is the row identifier of the dataframe. It was originally (before you removed NA) the 28th row (29th I suppose because of the zero-based indexing). You can drop the row based on that id.

app.drop([28])


问:
How 'append' works?
I want to read a file line by line, and each line may have lots of characters.

This version readline works well

```<code>func readLine(r *bufio.Reader) ([]byte, error) {
    var (
        isPrefix = true
        err      error
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }
    return ln, err
}
</code>```

but another doesn't work

```<code>func readLine(r *bufio.Reader) ([]byte, error) {
    line, isprefix, err := r.ReadLine()
    for isprefix && err == nil {
        var bs []byte
        bs, isprefix, err = r.ReadLine()

        line = append(line, bs...)
    }
    return line, err
}
</code>```

And I know the problem is caused by append, but I doesn't the reason, who can help me? Thanks.

The line data like this s=
e411dbebd2f7d64dafeef9b14b5c59ec60c36779d43f850e5e347abee1e1a455,1,[encoded data, 8052 characters],1000000,

This is the sample code, and the the second version of readLine didn't return the entire data what it reads.

```<code>func main() {
    reader := bufio.NewReader(strings.NewReader(s))
    fmt.Println(readLine(reader))
}
</code>```

答:
The issue is that you are reusing a slice returned by a function call. You don't know how that slice will be accessed/modified by bufio package.

Take a look at the doc here: https://golang.org/pkg/bufio/#Reader.ReadLine. It says:

The returned buffer is only valid until the next call to ReadLine.

This means that you should not reuse it for your buffering. It is always better to create your own.

Title: How 'append' works?

Body:
I want to read a file line by line, and each line may have lots of characters.

This version readline works well

func readLine(r *bufio.Reader) ([]byte, error) {
    var (
        isPrefix = true
        err      error
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }
    return ln, err
}

but another doesn't work

func readLine(r *bufio.Reader) ([]byte, error) {
    line, isprefix, err := r.ReadLine()
    for isprefix && err == nil {
        var bs []byte
        bs, isprefix, err = r.ReadLine()

        line = append(line, bs...)
    }
    return line, err
}

And I know the problem is caused by append, but I doesn't the reason, who can help me? Thanks.

The line data like this s=
e411dbebd2f7d64dafeef9b14b5c59ec60c36779d43f850e5e347abee1e1a455,1,[encoded data, 8052 characters],1000000,

This is the sample code, and the the second version of readLine didn't return the entire data what it reads.

func main() {
    reader := bufio.NewReader(strings.NewReader(s))
    fmt.Println(readLine(reader))
}


问:
Secure, portable encrypted config values -- possible?
I'm just curious if anyone has any great ideas on this.

We have a lot of C# windows services.  Each app is installed on multiple machines (anywhere from 2-80, depending on the app.)

Due to the security setup of the network, we cannot (consistently) use Windows authentication to the SQL servers, so our connection strings and credentials have actual usernames and passwords.

Our infrastructure folks want to be able to do the following when deploying the software:
1) Edit the configuration once -- set the appropriate server, user, and passwords for various database connections.
2) Have the connection strings (at least) encrypted or otherwise unreadable to the naked eye
3) Copy that configuration file to all installations of a particular piece of software.  This means that the encryption cannot be tied to a specific machine.

Can DPAPI do this?  Can one set of keys be installed on all targets to allow the decryption of a common config file?  How is the configuration edited in this case?  How do you keep other users from viewing the encrypted configuration in the same manner?

答:
I can comment on at least one aspect of your question, as we have a service configured this way where I work.

When editing/creating the configuration, we put a special token as the first character:

```<code><value>:secret_password</value>
</code>```

The colon is the special token.  When the service starts and reads the configuration, it finds all the unencrypted values by looking for the token, encrypts them, and then overwrites the plain-text with the encrypted value.

So this allows the file to be edited, while keeping the secrets secret.

OwnerDisplayName: Joe

ContentLicense: CC BY-SA 2.5

Body:
I can comment on at least one aspect of your question, as we have a service configured this way where I work.

When editing/creating the configuration, we put a special token as the first character:

<value>:secret_password</value>

The colon is the special token.  When the service starts and reads the configuration, it finds all the unencrypted values by looking for the token, encrypts them, and then overwrites the plain-text with the encrypted value.

So this allows the file to be edited, while keeping the secrets secret.

OwnerDisplayName: magnifico


问:
Hyperledger Explorer not starting on 8080 (discover issue)
Running hlf 1.4 and latest explorer in kubernetes. Explorer hangs in the start phase where it tries to reach peers. It doesn't reach the code were it starts web interface.

Peer has chaincode installed, connected to channel, no issues.

I have disabled TLS to make investigation easier and put logs in Channel.js, Peer.js in explorer dependencies to better investigate it.

I have added log to Channel.js in
/blockchain-explorer/node_modules/fabric-client/lib/Channel.js
to print connect to target and I can see that it shows grpc://localhost:undefined. I believe it tries to send request to invalid address and silently dies. Entire file https://gist.github.com/gad0lin/51384bfea1c207ccf016a0cad8e413b6#file-channel-js-L3474.

```<code>[{"_options":"1","_url":"2","_endpoint":"3","_name":"4","_request_timeout":45000,"_grpc_wait_for_ready_timeout":3000,
"_endorserClient":"5","_discoveryClient":"6"},{"name":"4","grpc.ssl_target_name_override":"4","grpc.default_authority":"4","grpc.max_receive_message_length":-1,"grpc.max_send_message_length":-1},"grpc://localhost:undefined",{"addr":"7","creds":"8"},"peer1-hlf-peer.peers.svc.cluster.local",
{"$interceptors":"9","$interceptor_providers":"10","$channel":"11"},{"$interceptors":"12","$interceptor_providers":"13","$channel":"14"},"localhost",{},[],[],{},[],[],{}]
</code>```

Here is hlf config:

```<code>{
  "network-configs": {
    "network-1": {
      "version": "1.0",
      "clients": {
            "cli": {
              "tlsEnable": false,
              "organization": "Org1MSP",
              "channel": "mychannel",
              "credentialStore": {
                  "path": "./tmp/credentialStore_Org1/credential",
                  "cryptoStore": {
                    "path": "./tmp/credentialStore_Org1/crypto"
                }
              }
            }
      },
      "channels": {
          "mychannel": {
              "peers": {
                "peer1-hlf-peer.peers.svc.cluster.local": {}
              },
              "connection": {
               "timeout": {
                 "peer": {
                    "endorser": "30",
                    "eventHub": "30",
                    "eventReg": "30"
                }
              }
            }
          }
      },
      "organizations": {
        "Org1MSP": {
          "certificateAuthorities": ["fabric-ca"],
          "mspid": "Org1MSP",
          "fullpath": true,
          "adminPrivateKey": {
            "path": "/var/hyperledger/msp/admincerts/key.pem"
          },
          "signedCert": {
            "path": "/var/hyperledger/msp/admincerts/cert.pem"
          }
        }
      },
      "peers": {
        "peer1-hlf-peer.peers.svc.cluster.local": {
          "url": "grpc://peer1-hlf-peer.peers.svc.cluster.local:7051",
           "eventUrl": "grpc://peer1-hlf-peer.peers.svc.cluster.local:7053",
           "grpcOptions": {
              "ssl-target-name-override": "peer1-hlf-peer.peers.svc.cluster.local"
            }
          }
      },
      "orderers": {
        "ord1-hlf-ord.orderers.svc.cluster.local" : {
                "url":"grpc://ord1-hlf-ord.orderers.svc.cluster.local:7050"
              }
      },
      "certificateAuthorities": {
        "fabric-ca": {
          "url": "http://ca-hlf-ca.cas.svc.cluster.local:7054",
          "httpOptions":{
            "verify": false
          },
          "registrar": {
            "enrollId": "admin",
            "enrollSecret": "adminpw"
          },
          "caName": "ca"
        }
      }
    }
  }
}{
  "persistence": "postgreSQL",
  "platforms": ["fabric"],
  "postgreSQL": {
    "host": "explorer-db.x.svc.cluster.local",
    "port": "5432",
    "database": "fabricexplorer",
    "username": "hppoc",
    "passwd": "password"
  },
  "sync": {
    "type": "local",
    "platform": "fabric",
    "blocksSyncTime": "3"
  }
}
</code>```

答:
I found the culprit. There were two issues.

I didn't set environment variable DISCOVERY_AS_LOCALHOST to false in explorer config. That was the reason I saw: localhost.

In peer I had set variable CORE_PEER_GOSSIP_EXTERNALENDPOINT, but without port. That was the reason I saw undefined as port.

Body:
Running hlf 1.4 and latest explorer in kubernetes. Explorer hangs in the start phase where it tries to reach peers. It doesn't reach the code were it starts web interface.

Peer has chaincode installed, connected to channel, no issues.

I have disabled TLS to make investigation easier and put logs in Channel.js, Peer.js in explorer dependencies to better investigate it.

I have added log to Channel.js in
/blockchain-explorer/node_modules/fabric-client/lib/Channel.js
to print connect to target and I can see that it shows grpc://localhost:undefined. I believe it tries to send request to invalid address and silently dies. Entire file https://gist.github.com/gad0lin/51384bfea1c207ccf016a0cad8e413b6#file-channel-js-L3474.

[{"_options":"1","_url":"2","_endpoint":"3","_name":"4","_request_timeout":45000,"_grpc_wait_for_ready_timeout":3000,
"_endorserClient":"5","_discoveryClient":"6"},{"name":"4","grpc.ssl_target_name_override":"4","grpc.default_authority":"4","grpc.max_receive_message_length":-1,"grpc.max_send_message_length":-1},"grpc://localhost:undefined",{"addr":"7","creds":"8"},"peer1-hlf-peer.peers.svc.cluster.local",
{"$interceptors":"9","$interceptor_providers":"10","$channel":"11"},{"$interceptors":"12","$interceptor_providers":"13","$channel":"14"},"localhost",{},[],[],{},[],[],{}]

Here is hlf config:

{
  "network-configs": {
    "network-1": {
      "version": "1.0",
      "clients": {
            "cli": {
              "tlsEnable": false,
              "organization": "Org1MSP",
              "channel": "mychannel",
              "credentialStore": {
                  "path": "./tmp/credentialStore_Org1/credential",
                  "cryptoStore": {
                    "path": "./tmp/credentialStore_Org1/crypto"
                }
              }
            }
      },
      "channels": {
          "mychannel": {
              "peers": {
                "peer1-hlf-peer.peers.svc.cluster.local": {}
              },
              "connection": {
               "timeout": {
                 "peer": {
                    "endorser": "30",
                    "eventHub": "30",
                    "eventReg": "30"
                }
              }
            }
          }
      },
      "organizations": {
        "Org1MSP": {
          "certificateAuthorities": ["fabric-ca"],
          "mspid": "Org1MSP",
          "fullpath": true,
          "adminPrivateKey": {
            "path": "/var/hyperledger/msp/admincerts/key.pem"
          },
          "signedCert": {
            "path": "/var/hyperledger/msp/admincerts/cert.pem"
          }
        }
      },
      "peers": {
        "peer1-hlf-peer.peers.svc.cluster.local": {
          "url": "grpc://peer1-hlf-peer.peers.svc.cluster.local:7051",
           "eventUrl": "grpc://peer1-hlf-peer.peers.svc.cluster.local:7053",
           "grpcOptions": {
              "ssl-target-name-override": "peer1-hlf-peer.peers.svc.cluster.local"
            }
          }
      },
      "orderers": {
        "ord1-hlf-ord.orderers.svc.cluster.local" : {
                "url":"grpc://ord1-hlf-ord.orderers.svc.cluster.local:7050"
              }
      },
      "certificateAuthorities": {
        "fabric-ca": {
          "url": "http://ca-hlf-ca.cas.svc.cluster.local:7054",
          "httpOptions":{
            "verify": false
          },
          "registrar": {
            "enrollId": "admin",
            "enrollSecret": "adminpw"
          },
          "caName": "ca"
        }
      }
    }
  }
}{
  "persistence": "postgreSQL",
  "platforms": ["fabric"],
  "postgreSQL": {
    "host": "explorer-db.x.svc.cluster.local",
    "port": "5432",
    "database": "fabricexplorer",
    "username": "hppoc",
    "passwd": "password"
  },
  "sync": {
    "type": "local",
    "platform": "fabric",
    "blocksSyncTime": "3"
  }
}


问:
Can (endless) CSS keyframe animations be stopped at certain time point or a defined keyframe?
I am trying to find out if CSS today offers enough tools to have animations run until an event tells them to stop?

Yes this is possible see snippet, however:

This animation will jump to the end if stopped in between. I was wondering if it can be stopped at any certain point of the computed keyframes. So basically like a wheel of fortune keep spinning the DIV until it's stopped and when stopped while upside down remain upside down until maybe restarted?

snippet:

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: 0;
  animation-timing-function: linear;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='wrap'>
  <div id='left-eye'>

  </div>
  <div id='right-eye'>

  </div>
  <div id='mouth'>

  </div>
</div>
<input type='button' value='start' onClick="document.getElementById('wrap').style.animationIterationCount = 'infinite';">
<input type='button' value='stop' onClick="document.getElementById('wrap').style.animationIterationCount = '0';"></code>```

答:
This was very useful so far, yet the remaining question related to these answers:

I added window.getComputedStyle(wrap, null).getPropertyValue("transform") and write it to an output field. This returns the matrix state of the animation. How should the matrix be interpreted to know at what rotation degree or what keyframe it was paused? I found 4 float values in the matrix. Some values seem to be always the same as, or the negative value of one other value. So I guess I can calculate back to milliseconds with these values?

Or maybe there is a different property to read from with getComputedStyle() that makes this a bit simpler?

I have moved the snipped to a new more detailed question at: How can an animation keyframe or time offset be calculated from a CSS transform matrix?

Body:
I am trying to find out if CSS today offers enough tools to have animations run until an event tells them to stop?

Yes this is possible see snippet, however:

This animation will jump to the end if stopped in between. I was wondering if it can be stopped at any certain point of the computed keyframes. So basically like a wheel of fortune keep spinning the DIV until it's stopped and when stopped while upside down remain upside down until maybe restarted?

snippet:

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: 0;
  animation-timing-function: linear;
}

<input type='button' value='start' onClick="document.getElementById('wrap').style.animationIterationCount = 'infinite';">
<input type='button' value='stop' onClick="document.getElementById('wrap').style.animationIterationCount = '0';">


问:
why wil R NOT detects the duplicate character？
I'm trying to delete duplicate id data in my data frame

```<code>buying<-buy_nobuy[duplicated(buy_nobuy[,1])==F,]
</code>```

after this, it tells me that there is no duplicated data left

```<code>length(buying[duplicated(buying[,1])==TRUE,1])

[1] 0
</code>```

but when I check manually in the global environment, I found that
actually, there are still duplicate data exist (like the pic show)

And I check if I test the rows, which has the same id, what will happen：

```<code>> buying[9,1]==buying[71,1]
[1] FALSE
</code>```

Seems ridiculous. I guess this may be some data type problem？

anyone knows how to solve this？

by the way, I read the data frame in the type of character since ID can not be read as numeric or it will be presented in an exponential way and lose real ID

```<code>buy_nobuy <- read.csv('community_achievement_buying.csv',colClasses= c(Id="character"))
</code>```

I FOUND that there is extra space here in row71 as you said.

```<code>> print(buying[9,1])
[1] 76561198321932950\t
73039 Levels: 76561197960272112\t ...
> print(buying[71,1])
[1] 76561198321932950\t\t
73039 Levels: 76561197960272112\t
</code>```

答:
```<code>data <- data.frame(
  id = c("123456789", "123456789 "),
  buy = c(1,1)
)
</code>```

Like already mentioned, characters vectors often have trailing white space => You will not see this in the R Studio Data viewer. There is an easy way to detect if these values are really the same: Try charToRaw to see if both IDs are the same.

```<code>apply(data[1], 1, charToRaw)
[[1]]
[1] 31 32 33 34 35 36 37 38 39

[[2]]
 [1] 31 32 33 34 35 36 37 38 39 20

data$id <- trimws(data$id) # Thanks @ Mako212

apply(data[1], 1, charToRaw)

      [,1] [,2]
 [1,]   31   31
 [2,]   32   32
 [3,]   33   33
 [4,]   34   34
 [5,]   35   35
 [6,]   36   36
 [7,]   37   37
 [8,]   38   38
 [9,]   39   39
</code>```

Body:
I'm trying to delete duplicate id data in my data frame

buying<-buy_nobuy[duplicated(buy_nobuy[,1])==F,]

after this, it tells me that there is no duplicated data left

length(buying[duplicated(buying[,1])==TRUE,1])

[1] 0

but when I check manually in the global environment, I found that
actually, there are still duplicate data exist (like the pic show)

And I check if I test the rows, which has the same id, what will happen：

> buying[9,1]==buying[71,1]
[1] FALSE

Seems ridiculous. I guess this may be some data type problem？

anyone knows how to solve this？

by the way, I read the data frame in the type of character since ID can not be read as numeric or it will be presented in an exponential way and lose real ID

buy_nobuy <- read.csv('community_achievement_buying.csv',colClasses= c(Id="character"))

I FOUND that there is extra space here in row71 as you said.

> print(buying[9,1])
[1] 76561198321932950\t
73039 Levels: 76561197960272112\t ...
> print(buying[71,1])
[1] 76561198321932950\t\t
73039 Levels: 76561197960272112\t

Body:
data <- data.frame(
  id = c("123456789", "123456789 "),
  buy = c(1,1)
)

Like already mentioned, characters vectors often have trailing white space => You will not see this in the R Studio Data viewer. There is an easy way to detect if these values are really the same: Try charToRaw to see if both IDs are the same.

apply(data[1], 1, charToRaw)
[[1]]
[1] 31 32 33 34 35 36 37 38 39

[[2]]
 [1] 31 32 33 34 35 36 37 38 39 20

data$id <- trimws(data$id) # Thanks @ Mako212

apply(data[1], 1, charToRaw)

      [,1] [,2]
 [1,]   31   31
 [2,]   32   32
 [3,]   33   33
 [4,]   34   34
 [5,]   35   35
 [6,]   36   36
 [7,]   37   37
 [8,]   38   38
 [9,]   39   39


问:
Should I exit my gradient descent loop as soon as the cost increases?
I'm trying to learn machine learning so I'm taking a course and currently studying gradient descent for linear regression. I just learned that if the learning rate is small enough, the value returned by the cost function should continuously decrease until convergence. When I imagine this being done in a loop of code, it seems like I could just keep track of what the cost was in the previous iteration and exit the loop if the new cost is greater than the previous, since this tells us the learning rate is too large. I'd like to hear opinions since I'm new to this, but in an effort to not make this question primarily opinion-based my main question is this: Would there be anything wrong with this method of detecting a learning rate that needs to be decreased? I'd appreciate an example of when this method would fail, if possible.</p>

答:
In this example below, we will vary the learning rate eta = 10^k with k={-6,-5,-4,...0}

```<code>def f(x):
  return 100 * (x[ 0] *x[0] - x[ 1]) **2 + (x[ 0] -1) **2

def df(x):
  a = x[ 0] *x[0] - x[ 1]
  ret = np.zeros(2)
  ret[ 0] = 400 * a * x[0] + 2 * (x[0] - 1)
  ret[ 1] = -200 * a
  return ret

for k in range(-6, 0):
  eta = math.pow(10.0, k)
  print("eta: " + str(eta))
  x = -np.ones(2)
  for iter in range(1000000):
    fx = f(x)
    if fx < 1e-10:
      print(" solved after " + str(iter) + " iterations; f(x) = " + str(f(x)))
      break
    if fx > 1e10:
      print(" divergence detected after " + str(iter) + " iterations; f(x) = " +
        str(f(x)))
      break
  g = df(x)
  x -= eta * g
  if iter == 999999:
    print(" not solved; f(x) = " + str(f(x)))

</code>```

For too small learning rates, the optimization is very slow and the problem is not solved within the iteration budget.
For too large learning rates, the optimization process becomes unstable and diverges very quickly. The learning rate must be "just right" for the optimization process to work well.

Body:
In this example below, we will vary the learning rate eta = 10^k with k={-6,-5,-4,...0}

def f(x):
  return 100 * (x[ 0] *x[0] - x[ 1]) **2 + (x[ 0] -1) **2

def df(x):
  a = x[ 0] *x[0] - x[ 1]
  ret = np.zeros(2)
  ret[ 0] = 400 * a * x[0] + 2 * (x[0] - 1)
  ret[ 1] = -200 * a
  return ret

for k in range(-6, 0):
  eta = math.pow(10.0, k)
  print("eta: " + str(eta))
  x = -np.ones(2)
  for iter in range(1000000):
    fx = f(x)
    if fx < 1e-10:
      print(" solved after " + str(iter) + " iterations; f(x) = " + str(f(x)))
      break
    if fx > 1e10:
      print(" divergence detected after " + str(iter) + " iterations; f(x) = " +
        str(f(x)))
      break
  g = df(x)
  x -= eta * g
  if iter == 999999:
    print(" not solved; f(x) = " + str(f(x)))

For too small learning rates, the optimization is very slow and the problem is not solved within the iteration budget.
For too large learning rates, the optimization process becomes unstable and diverges very quickly. The learning rate must be "just right" for the optimization process to work well.


问:
Oracle SQL query question
I'm trying to complete this Oracle SQL query with no luck.

"List the department that has the least average cost. (Hint: SELECT  MIN(AVG(cost)) is valid as long as no other column is combined in the SELECT statement. You can combine the above as a subquery with another query)"

I'm able to get it to display the Depts with their average cost, but when I try to work in MIN it breaks. This is what I have so far.

```<code>SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;
</code>```

That will give me the depts and their AVG, but when I change AVG(projcost) to be MIN(AVG(projcost) it breaks. The hint is to make it a subquery but I can't figure out how to do that yet. Any help would be much appreciated.

答:
```<code>SELECT
  MIN(q1.AvgProjCost)
FROM (SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo) q1
</code>```

EDITED
Suppose I Have the following department project costs

```<code>Department ProjectCost
1          15
1          15
1          15
2          16
2          16
3          17
3          17
4          18
</code>```

These project Costs would render the following averages

```<code>Department Average
1          15
2          16
3          17
4          18
</code>```

The minimum average for each department is still the same result set.

EDITED AGAIN

If you really must have Minimum Average for each department then this will work

```<code>SELECT
  q1.Dept,
  MIN(q1.AvgProjCost)
FROM (SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo) q1
GROUP BY q1.Dept
</code>```

However you will soon realize that this result set is and will always be the same as

```<code>      SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo
</code>```

EDITED Once More

To obtain the department with the smallest average project cost

```<code>SELECT
  q1.Dept,
  q1.AvgProjCost
FROM (SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo) q1
WHERE rownum = 1
ORDER BY AvgProjCost DESC
</code>```

ContentLicense: CC BY-SA 3.0

Title: Oracle SQL query question

Body:
I'm trying to complete this Oracle SQL query with no luck.

"List the department that has the least average cost. (Hint: SELECT  MIN(AVG(cost)) is valid as long as no other column is combined in the SELECT statement. You can combine the above as a subquery with another query)"

I'm able to get it to display the Depts with their average cost, but when I try to work in MIN it breaks. This is what I have so far.

SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;

That will give me the depts and their AVG, but when I change AVG(projcost) to be MIN(AVG(projcost) it breaks. The hint is to make it a subquery but I can't figure out how to do that yet. Any help would be much appreciated.

Body:
SELECT
  MIN(q1.AvgProjCost)
FROM (SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo) q1

EDITED
Suppose I Have the following department project costs

Department ProjectCost
1          15
1          15
1          15
2          16
2          16
3          17
3          17
4          18

These project Costs would render the following averages

Department Average
1          15
2          16
3          17
4          18

The minimum average for each department is still the same result set.

EDITED AGAIN

If you really must have Minimum Average for each department then this will work

SELECT
  q1.Dept,
  MIN(q1.AvgProjCost)
FROM (SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo) q1
GROUP BY q1.Dept

However you will soon realize that this result set is and will always be the same as

      SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo

EDITED Once More

To obtain the department with the smallest average project cost

SELECT
  q1.Dept,
  q1.AvgProjCost
FROM (SELECT
        DeptNo,
        AVG(projcost) as AvgProjCost
      FROM projects, clinicians
      WHERE clinicians.Clinicianno = projects.Clinicianno
      GROUP BY DeptNo) q1
WHERE rownum = 1
ORDER BY AvgProjCost DESC


问:
Algorithm to return all combinations of k elements from n
I want to write a function that takes an array of letters as an argument and a number of those letters to select.

Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:

```<code>8! / ((8 - 3)! * 3!) = 56
</code>```

Arrays (or words) in return consisting of 3 letters each.

答:
JavaScript, generator-based, recursive approach:

function *nCk(n,k){
  for(var i=n-1;i>=k-1;--i)
    if(k===1)
      yield [i];
    else
      for(var temp of nCk(i,k-1)){
        temp.unshift(i);
        yield temp;
      }
}

function test(){
  try{
    var n=parseInt(ninp.value);
    var k=parseInt(kinp.value);
    log.innerText="";
    var stop=Date.now()+1000;
    if(k>=1)
      for(var res of nCk(n,k))
        if(Date.now()<stop)
          log.innerText+=JSON.stringify(res)+" ";
        else{
          log.innerText+="1 second passed, stopping here.";
          break;
        }
  }catch(ex){}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>n:<input id="ninp" oninput="test()">
>= k:<input id="kinp" oninput="test()"> >= 1
<div id="log"></div></code>```

This way (decreasing i and unshift()) it produces combinations and elements inside combinations in decreasing order, somewhat pleasing the eye.

Test stops after 1 second, so entering weird numbers is relatively safe.

OwnerDisplayName: IQue

Body:
I want to write a function that takes an array of letters as an argument and a number of those letters to select.

Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:

8! / ((8 - 3)! * 3!) = 56

Arrays (or words) in return consisting of 3 letters each.

Body:
JavaScript, generator-based, recursive approach:

function *nCk(n,k){
  for(var i=n-1;i>=k-1;--i)
    if(k===1)
      yield [i];
    else
      for(var temp of nCk(i,k-1)){
        temp.unshift(i);
        yield temp;
      }
}

function test(){
  try{
    var n=parseInt(ninp.value);
    var k=parseInt(kinp.value);
    log.innerText="";
    var stop=Date.now()+1000;
    if(k>=1)
      for(var res of nCk(n,k))
        if(Date.now()<stop)
          log.innerText+=JSON.stringify(res)+" ";
        else{
          log.innerText+="1 second passed, stopping here.";
          break;
        }
  }catch(ex){}
}

n:<input id="ninp" oninput="test()">
&gt;= k:<input id="kinp" oninput="test()"> &gt;= 1
<div id="log"></div>

This way (decreasing i and unshift()) it produces combinations and elements inside combinations in decreasing order, somewhat pleasing the eye.

Test stops after 1 second, so entering weird numbers is relatively safe.


问:
Create tree view with horizontal and vertical lines showing the connectivity using css
I'm having the requirement where we need to show the nested elements to have horizontal and vertical line for folders and subfolder. i searched but unable to find anything relevant.
See below picture for reference.

Sample Image

Can someone help me in this issue.

答:
The first it's know how make it using .css. I find this beauty Minimalist Tree View In Pure CSS

Well, with this idea we can use Angular to generate a "recursive component". but first we must take account that we need use "attribute selector" to not generate the tag of the component. Don't worry, it's only use as selector some like

```<code>selector: '[recursive]'
</code>```

So, instead of write some like

```<code><recursive></recursive>
</code>```

we can use some like

```<code><ul recursive></ul>
</code>```

Well, the component is like

```<code><li *ngFor="let item of children">
    {{item.label}}
    <ul recursive *ngIf="item.children"
        [children]="item.children"
        [parent]="self"
        [level]="level!=undefined?level+1:0">
    </ul>
</li>

@Component({
  selector: '[recursive]', //<--the the "selector"
  templateUrl:'./hello.component.html'
})
export class HelloComponent  {
  @Input() level: number;
  @Input() label: string;
  @Input() children: any;
  @Input() parent: any;

  self=this;

}
</code>```

Well, I add the properties "level" and "parent" that I don't use in the code but can be interesting if our component make "some-more" that show the tree.

And our app.component.html is some like

```<code><ul class="tree" recursive [children]="data"></ul>
</code>```

Be carefull. I need use ViewEncapsulation.None in the app.component to transport the .css

See that we give [children] the own data

where, e.g.

```<code>data = [{label: "Parent1", children: [
      { label: "Parent 1's only child"  }
  ]},
    {label:"Parent2"},
    {label:"Parent3", children: [
      { label: "1st Child of 3" ,children:[
         {label:"1st grandchild"},
         {label:"2nd grandchild"}
      ]},
      { label: "2nd Child of 3" },
      { label: "3rd Child of 3" }
      ]
   },
   {
    label: "Parent 4", children: [
      { label: "Parent 4's only child"  }
  ]}]
</code>```

You can see in this stackblitz

Updated If we want add open/close capacity, it's easy adding a span and using [ngClass] for the three cases: doc, open and close, so our recursive.html becomes

```<code><li *ngFor="let item of children">
    <span [ngClass]="!item.children?
         'doc':item.isOpen?'open':'close'"
         (click)="item.isOpen=!item.isOpen"></span>
    {{item.label}}
    <ul recursive *ngIf="item.children && item.isOpen"
        [children]="item.children"
        [parent]="self"
        [level]="level!=undefined?level+1:0">
    </ul>
</li>
</code>```

I used a .css like

```<code>.doc,.open,.close
{
  display:inline-block;
  width:1rem;
  height:1rem;
  background-size: 1rem 1rem;
}
.doc
{
  background-image:url('...');
}
.open
{
  background-image:url('...');
}
.close
{
  background-image:url('...');
}
</code>```

The updated stackblitz

Updated 2 I don't like so much use ViewEncapsulation.None, so we can make a work-around and our recursive component becomes like

```<code><ul class="tree" *ngIf="level==undefined">
  <ng-container *ngTemplateOutlet="tree;context:{children:children}">
  </ng-container>
</ul>
<ng-container *ngIf="level!=undefined">
  <ng-container *ngTemplateOutlet="tree;context:{children:children}">
  </ng-container>
</ng-container>

<ng-template #tree let-children="children">
<li *ngFor="let item of children">
    <span [ngClass]="!item.children?'doc':item.isOpen?'open':'close'" (click)="item.isOpen=!item.isOpen"></span>{{item.label}}
    <ul recursive *ngIf="item.children && item.isOpen"
        [children]="item.children"
        [parent]="self"
        [level]="level!=undefined?level+1:0">
            </ul>
</li>
</ng-template>
</code>```

That's. The first use a
...
, the others not add the

Again, the final stackblitz

Body:
The first it's know how make it using .css. I find this beauty Minimalist Tree View In Pure CSS

Well, with this idea we can use Angular to generate a "recursive component". but first we must take account that we need use "attribute selector" to not generate the tag of the component. Don't worry, it's only use as selector some like

selector: '[recursive]'

So, instead of write some like

<recursive></recursive>

we can use some like

<ul recursive></ul>

Well, the component is like

<li *ngFor="let item of children">
    {{item.label}}
    <ul recursive *ngIf="item.children"
        [children]="item.children"
        [parent]="self"
        [level]="level!=undefined?level+1:0">
    </ul>
</li>

@Component({
  selector: '[recursive]', //<--the the "selector"
  templateUrl:'./hello.component.html'
})
export class HelloComponent  {
  @Input() level: number;
  @Input() label: string;
  @Input() children: any;
  @Input() parent: any;

  self=this;

}

Well, I add the properties "level" and "parent" that I don't use in the code but can be interesting if our component make "some-more" that show the tree.

And our app.component.html is some like

<ul class="tree" recursive [children]="data"></ul>

Be carefull. I need use ViewEncapsulation.None in the app.component to transport the .css

See that we give [children] the own data

where, e.g.

data = [{label: "Parent1", children: [
      { label: "Parent 1's only child"  }
  ]},
    {label:"Parent2"},
    {label:"Parent3", children: [
      { label: "1st Child of 3" ,children:[
         {label:"1st grandchild"},
         {label:"2nd grandchild"}
      ]},
      { label: "2nd Child of 3" },
      { label: "3rd Child of 3" }
      ]
   },
   {
    label: "Parent 4", children: [
      { label: "Parent 4's only child"  }
  ]}]

You can see in this stackblitz

Updated If we want add open/close capacity, it's easy adding a span and using [ngClass] for the three cases: doc, open and close, so our recursive.html becomes

<li *ngFor="let item of children">
    <span [ngClass]="!item.children?
         'doc':item.isOpen?'open':'close'"
         (click)="item.isOpen=!item.isOpen"></span>
    {{item.label}}
    <ul recursive *ngIf="item.children && item.isOpen"
        [children]="item.children"
        [parent]="self"
        [level]="level!=undefined?level+1:0">
    </ul>
</li>

I used a .css like

.doc,.open,.close
{
  display:inline-block;
  width:1rem;
  height:1rem;
  background-size: 1rem 1rem;
}
.doc
{
  background-image:url('...');
}
.open
{
  background-image:url('...');
}
.close
{
  background-image:url('...');
}

The updated stackblitz

Updated 2 I don't like so much use ViewEncapsulation.None, so we can make a work-around and our recursive component becomes like

<ul class="tree" *ngIf="level==undefined">
  <ng-container *ngTemplateOutlet="tree;context:{children:children}">
  </ng-container>
</ul>
<ng-container *ngIf="level!=undefined">
  <ng-container *ngTemplateOutlet="tree;context:{children:children}">
  </ng-container>
</ng-container>

<ng-template #tree let-children="children">
<li *ngFor="let item of children">
    <span [ngClass]="!item.children?'doc':item.isOpen?'open':'close'" (click)="item.isOpen=!item.isOpen"></span>{{item.label}}
    <ul recursive *ngIf="item.children && item.isOpen"
        [children]="item.children"
        [parent]="self"
        [level]="level!=undefined?level+1:0">
            </ul>
</li>
</ng-template>

That's. The first use a <ul class="tree">...</ul>, the others not add the <ul>

Again, the final stackblitz


问:
How can I combine numeric values of similar strings?
I have a list of licenses and associated license counts, for example:

```<code>1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
20 Station
</code>```

The lists are never in the same order and I simply need to add the totals for each license type so in the example I would want the return:

```<code>3 Third Party SIP Device Seat
29 Station
</code>```

The data is being entered into unsaved notepad and later moved into a database. Using excel isn't applicable as it's spaces between the numbers and names, not tabs.

What would be the easiest way to accomplish this task?

答:
You want a groupby. Fortunately itertools has one</p>

```<code>from itertools import groupby

text = """1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
0 Station"""

# clean stuff up and split on first space
lines = [line.strip().split(" ", 1) for line in text.split("\n")]

# groupby
result = []
for k, g in groupby(lines, lambda x: x[1]):
    total = 0
    for i in g:
        total += int(i[0])
    result.append([k, total])
print(result)
</code>```

Body:
I have a list of licenses and associated license counts, for example:

1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
20 Station

The lists are never in the same order and I simply need to add the totals for each license type so in the example I would want the return:

3 Third Party SIP Device Seat
29 Station

The data is being entered into unsaved notepad and later moved into a database. Using excel isn't applicable as it's spaces between the numbers and names, not tabs.

What would be the easiest way to accomplish this task?

Body:
You want a groupby. Fortunately itertools has one

from itertools import groupby

text = """1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
0 Station"""

# clean stuff up and split on first space
lines = [line.strip().split(" ", 1) for line in text.split("\n")]

# groupby
result = []
for k, g in groupby(lines, lambda x: x[1]):
    total = 0
    for i in g:
        total += int(i[0])
    result.append([k, total])
print(result)


问:
Check the details of columns which have attributes applied to them
In the splayed tables we can find the details/order of columns in the .d file.

I was searching if there is any file which maintains the attributes information of the columns in a table.
How can we find the details of the attributes in the file system?

```<code>t:([] a:1 2 3; b:4 5 6; c:`a`b`c)
`:/home/st set .Q.en[`:/home/st;t]
get `:/home/st/.d / Output - `a`b`c
@[`:/home/st/;`a;`s#] / Is there any place in file system where we can find the attribute applied to a column
meta get `:/home/st/ / Show that attribute s is applied on column a
</code>```

答:
You can actually read the attributes from columns on disk, it's just not recommended (and potentially subject to change):</p>

```<code>q){(0x0001020304!``s`u`p`g)first read1(x;3;1)}`:st/a
`s
q){(0x0001020304!``s`u`p`g)first read1(x;3;1)}`:st/b
`
</code>```

Body:
In the splayed tables we can find the details/order of columns in the .d file.

I was searching if there is any file which maintains the attributes information of the columns in a table.
How can we find the details of the attributes in the file system?

t:([] a:1 2 3; b:4 5 6; c:`a`b`c)
`:/home/st set .Q.en[`:/home/st;t]
get `:/home/st/.d / Output - `a`b`c
@[`:/home/st/;`a;`s#] / Is there any place in file system where we can find the attribute applied to a column
meta get `:/home/st/ / Show that attribute s is applied on column a

Body:
You can actually read the attributes from columns on disk, it's just not recommended (and potentially subject to change):

q){(0x0001020304!``s`u`p`g)first read1(x;3;1)}`:st/a
`s
q){(0x0001020304!``s`u`p`g)first read1(x;3;1)}`:st/b
`


问:
Wordpress messing with my db calls on the wordpress pages?
Hey, hows it going everyone? I am having database conflicts I was wanting some help with.

Basically, I have a header that pulls in a random database field. Nothing special. It is in my header in my template and works just fine on non WordPress pages.

```<code>$sql = "SELECT * FROM headerslogans ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql);
    while ($myrow = mysql_fetch_array($result)) {
    echo $myrow['slogan'];
};
</code>```

I am using the same database, same user name, same password, etc. However, I get this error where the echo should be....

```<code>Warning: mysql_query() [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) in <dir name>
</code>```

So obviously the wordpress connection is "overwriting" the other (wordpress works flawlessly). BUT, I was also confused as to why it doesn't work, although it is connecting to the same database with same username and password.

Can anybody help me out on this?

UPDATE: Posted connection code

$x = mysql_connect($server,$dbuser,$dbpass,true) or die(mysql_error());
mysql_select_db($dbname,$x);

答:
@NarfFlarf: You could just use WordPress queries to get your data --

```<code>$sql = "SELECT * FROM headerslogans ORDER BY RAND() LIMIT 1";
$result = $wpdb->get_results($sql);
foreach ($myrow as $result) {
    echo $myrow->slogan;
}
</code>```

See this WordPress Codex entry for further reference.

Update

Something else you can perhaps try then is to have  and within slogan.php:

```<code><?php
/* Instantiate own, non-WP MySQL connection */
/* Run query and retrieve image */

header("Content-type: image/jpeg");
echo file_get_contents('path/to/image/' . $image); // 'dynamic' image!
?>
</code>```

Body:
Hey, hows it going everyone? I am having database conflicts I was wanting some help with.

Basically, I have a header that pulls in a random database field. Nothing special. It is in my header in my template and works just fine on non WordPress pages.

$sql = "SELECT * FROM headerslogans ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql);
    while ($myrow = mysql_fetch_array($result)) {
    echo $myrow['slogan'];
};

I am using the same database, same user name, same password, etc. However, I get this error where the echo should be....

Warning: mysql_query() [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) in <dir name>

So obviously the wordpress connection is "overwriting" the other (wordpress works flawlessly). BUT, I was also confused as to why it doesn't work, although it is connecting to the same database with same username and password.

Can anybody help me out on this?

UPDATE: Posted connection code

$x = mysql_connect($server,$dbuser,$dbpass,true) or die(mysql_error());
mysql_select_db($dbname,$x);

Body:
@NarfFlarf: You could just use WordPress queries to get your data --

$sql = "SELECT * FROM headerslogans ORDER BY RAND() LIMIT 1";
$result = $wpdb->get_results($sql);
foreach ($myrow as $result) {
    echo $myrow->slogan;
}

See this WordPress Codex entry for further reference.

Update

Something else you can perhaps try then is to have <img src="slogan.php" alt=""> and within slogan.php:

<?php
/* Instantiate own, non-WP MySQL connection */
/* Run query and retrieve image */

header("Content-type: image/jpeg");
echo file_get_contents('path/to/image/' . $image); // 'dynamic' image!
?>


问:
SQL: count last equal values
I need to solve this problem in pure SQL:
I have to count all the records with a specific value:
In my table there is a column flag with values 0 or 1. I need to count all the 1 after last 0 and sum the amount column values of those records.

Example:

```<code>Flag | Amount

0    | 5
1    | 8
0    | 10
1    | 20
1    | 30
</code>```

Output:

```<code>2    | 50
</code>```

If last value is 0 I don't need to do anything.
I hasten that I need to perform a fast query (possibly accessing just one time).

答:
I assumed that your example table is logically ordered by Amount. Then you can do this:

```<code>select
     count(*) as cnt
    ,sum(Amount) as Amount
from yourTable
where Amount > (select max(Amount) from yourTable where Flag = 0)
</code>```

If the biggest value is from a row where Flag = 0 then nothing will be returned.

Title: SQL: count last equal values

Body:
I need to solve this problem in pure SQL:
I have to count all the records with a specific value:
In my table there is a column flag with values 0 or 1. I need to count all the 1 after last 0 and sum the amount column values of those records.

Example:

Flag | Amount

0    | 5
1    | 8
0    | 10
1    | 20
1    | 30

Output:

2    | 50

If last value is 0 I don't need to do anything.
I hasten that I need to perform a fast query (possibly accessing just one time).

Body:
I assumed that your example table is logically ordered by Amount. Then you can do this:

select
     count(*) as cnt
    ,sum(Amount) as Amount
from yourTable
where Amount > (select max(Amount) from yourTable where Flag = 0)

If the biggest value is from a row where Flag = 0 then nothing will be returned.


问:
Convert a string made from array toString() back to Array
I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?

The string which I have produced and need to convert back to an array is:

```<code>{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}
</code>```

I tried to use the JSON Parser JSON.parse(text)

答:
You just need to format your string as an array in JSON format. You can do that like so:</p>

```<code>JSON.parse('[' + text + ']')
</code>```

Body:
I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?

The string which I have produced and need to convert back to an array is:

{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}

I tried to use the JSON Parser JSON.parse(text)

Body:
You just need to format your string as an array in JSON format. You can do that like so:

JSON.parse('[' + text + ']')


问:
How I can extract ordered questions and answers from a block of plain text
Questions are also available for plain text. I want to be able to use PHP, Regex. However, because my Regex information is not enough, I tried to do this with the PHP function.

Example plain text: (starting 12th question -> 15. question, here total 4 questions)

12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma
  sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are
  destroyed by 2/3 and restored with?llings. Occlusion is orthognathic.
  What denture construction would be optimal for this patient,
  considering his occupation as a lecturer? A.Porcelain-fused-to-metal
  dental bridge B.Plastic dental bridge C.Clasp-retained (bugel)
  removable partial denture with attachments D.Removable partial laminar
  denture for the upper jaw E.Swaged-soldered metal dental bridge with
  faceted intermediate part 13.A 7-year-old boy is diagnosed with epi-
  demic parotitis (mumps). Name the most li- kely complication of this
  disease: A.Orchitis B.Colitis C.Dermatitis D.Pneumonia
  E.Cholecystitis14.During preventive examination a 40-year- old man
  presents with the following changes: marginal gingiva is enlarged,
  torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental
  probe; there is no pain. Staining the gums with Lugol’s iodine
  solution results in light-brown coloring of mucosa. Make the
  diagnosis: A.Chronic catarrhal gingivitis B.Acute catarrhal gingivitis
  C.Exacerbation of chronic catarrhal gingivitis D.Chronic hypertrophic
  gingivitis E.Generalized periodontitis 15.A 4-year-old boy has been
  diagnosed wi- th acute purulent periostitis of the upper jaw
  originating from the 64 tooth. Choose the optimal treatment tactics:
  A.The 64 tooth extraction, periosteotomy, pharmacotherapy B.The 64
  tooth extraction, anti-in?ammatory pharmacotherapy C.Endodontological
  treatment of the 64 tooth, anti-in?ammatory pharmacotherapy
  D.Endodontological treatment of the 64 tooth, periosteotomy
  E.Periosteotomy, anti-in?ammatory pharmacotherapy

There's a question number at the beginning of each question.

Questions usually have 5 or 4 options

What I did?

```<code> function gettingQuestionAndOptions($string, $start, $end)
    {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;

        return substr($string, $ini, $len);
    }
</code>```

How do I use it?

```<code>if (gettingQuestionAndOptions($text, '?', "A. ")) {

    $parsedQuestion = gettingQuestionAndOptions($text, '', "?");
    $parsedA = gettingQuestionAndOptions($text, 'A. ', "B. ");
    $parsedB = gettingQuestionAndOptions($text, 'B. ', "C. ");
    $parsedC = gettingQuestionAndOptions($text, 'C. ', "D. ");
    $endQuestion = "?";

} else if (gettingQuestionAndOptions($text, ':', "A. ")) {

    $parsedQuestion = gettingQuestionAndOptions($text, '', ":");
    $parsedA = gettingQuestionAndOptions($text, 'A. ', "B. ");
    $parsedB = gettingQuestionAndOptions($text, 'B. ', "C. ");
    $parsedC = gettingQuestionAndOptions($text, 'C. ', "D. ");
    $endQuestion = ":";

} else {
}
</code>```

Result:

I tried min. 4 hours but still I'm getting an irregular result. If there are numbers or A, B in the problem, I get an even worse result.

How can I do this better? Or where's my fault?

Can I get more correct data with Regex?

答:
Assuming your text always starts with a number, grouping them should be a simple matter of just keeping track of the current question you're on, and then searching for the next one. This will help reduce false positives.

```<code><?php
$data = "12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are destroyed by 2/3 and restored with?llings. Occlusion is orthognathic. What denture construction would be optimal for this patient, considering his occupation as a lecturer? A.Porcelain-fused-to-metal dental bridge B.Plastic dental bridge C.Clasp-retained (bugel) removable partial denture with attachments D.Removable partial laminar denture for the upper jaw E.Swaged-soldered metal dental bridge with faceted intermediate part 13.A 7-year-old boy is diagnosed with epi- demic parotitis (mumps). Name the most li- kely complication of this disease: A.Orchitis B.Colitis C.Dermatitis D.Pneumonia E.Cholecystitis14.During preventive examination a 40-year- old man presents with the following changes: marginal gingiva is enlarged, torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental probe; there is no pain. Staining the gums with Lugol’s iodine solution results in light-brown coloring of mucosa. Make the diagnosis: A.Chronic catarrhal gingivitis B.Acute catarrhal gingivitis C.Exacerbation of chronic catarrhal gingivitis D.Chronic hypertrophic gingivitis E.Generalized periodontitis 15.A 4-year-old boy has been diagnosed wi- th acute purulent periostitis of the upper jaw originating from the 64 tooth. Choose the optimal treatment tactics: A.The 64 tooth extraction, periosteotomy, pharmacotherapy B.The 64 tooth extraction, anti-in?ammatory pharmacotherapy C.Endodontological treatment of the 64 tooth, anti-in?ammatory pharmacotherapy D.Endodontological treatment of the 64 tooth, periosteotomy E.Periosteotomy, anti-in?ammatory pharmacotherapy";
$questions = [];
$question_num = 12;
$previous_question_start = 0;
while (true) {
    $question_start = strpos($data, "$question_num.", $previous_question_start);
    $question_end = strpos($data, (++$question_num) . ".", $question_start);
    if ($question_end === false) {
        // no more matches, this is the last question
        $questions[] = substr($data, $question_start);
        break;
    }
    $questions[] = substr($data, $question_start, $question_end - $question_start);
    $previous_question_start = $question_start;
}
</code>```

At this point you have each question in an array element, so search for your answers in each one, using the same technique. We'll save our results into a new array.

```<code>$questions_answers = [];
$answer_choices = ["A", "B", "C", "D", "E"];
foreach ($questions as $q) {
    $qa = [];
    $qa["question"] = substr($q, 0, strpos($q, "$answer_choices[0]."));
    $previous_answer_start = 0;
    foreach ($answer_choices as $i=>$a) {
        $answer_start = strpos($q, $answer_choices[$i]. ".", $previous_answer_start);
        if (empty($answer_choices[$i + 1])) {
            // end of the array, this is the last answer
            $qa["answers"][] = substr($q, $answer_start);
            break;
        }
        $answer_end = strpos($q, $answer_choices[$i + 1] . ".", $answer_start);
        $qa["answers"][] = substr($q, $answer_start, $answer_end - $answer_start);
        $previous_answer_start = $answer_start;
    }
    $questions_answers[] = $qa;
}

print_r($questions_answers);
</code>```

Output:

```<code>Array
(
    [0] => Array
        (
            [question] => 12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are destroyed by 2/3 and restored with?llings. Occlusion is orthognathic. What denture construction would be optimal for this patient, considering his occupation as a lecturer?
            [answers] => Array
                (
                    [0] => A.Porcelain-fused-to-metal dental bridge
                    [1] => B.Plastic dental bridge
                    [2] => C.Clasp-retained (bugel) removable partial denture with attachments
                    [3] => D.Removable partial laminar denture for the upper jaw
                    [4] => E.Swaged-soldered metal dental bridge with faceted intermediate part
                )

        )

    [1] => Array
        (
            [question] => 13.A 7-year-old boy is diagnosed with epi- demic parotitis (mumps). Name the most li- kely complication of this disease:
            [answers] => Array
                (
                    [0] => A.Orchitis
                    [1] => B.Colitis
                    [2] => C.Dermatitis
                    [3] => D.Pneumonia
                    [4] => E.Cholecystitis
                )

        )

    [2] => Array
        (
            [question] => 14.During preventive examination a 40-year- old man presents with the following changes: marginal gingiva is enlarged, torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental probe; there is no pain. Staining the gums with Lugol’s iodine solution results in light-brown coloring of mucosa. Make the diagnosis:
            [answers] => Array
                (
                    [0] => A.Chronic catarrhal gingivitis
                    [1] => B.Acute catarrhal gingivitis
                    [2] => C.Exacerbation of chronic catarrhal gingivitis
                    [3] => D.Chronic hypertrophic gingivitis
                    [4] => E.Generalized periodontitis
                )

        )

    [3] => Array
        (
            [question] => 15.A 4-year-old boy has been diagnosed wi- th acute purulent periostitis of the upper jaw originating from the 64 tooth. Choose the optimal treatment tactics:
            [answers] => Array
                (
                    [0] => A.The 64 tooth extraction, periosteotomy, pharmacotherapy
                    [1] => B.The 64 tooth extraction, anti-in?ammatory pharmacotherapy
                    [2] => C.Endodontological treatment of the 64 tooth, anti-in?ammatory pharmacotherapy
                    [3] => D.Endodontological treatment of the 64 tooth, periosteotomy
                    [4] => E.Periosteotomy, anti-in?ammatory pharmacotherapy
                )

        )

)
</code>```

I kept this code pretty unoptimized so it would be easy to understand, but simple string manipulation is a very low-cost computation so it should be fine for everyday use.

As a side note, I notice you're losing characters like "ﬂ" (f/l ligature) and "ﬁ" (f/i ligature.) If you're pulling this information from a database or web page, make sure you're properly dealing with UTF-8 characters.

Body:
Questions are also available for plain text. I want to be able to use PHP, Regex. However, because my Regex information is not enough, I tried to do this with the PHP function.

Example plain text: (starting 12th question -> 15. question, here total 4 questions)

12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma
  sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are
  destroyed by 2/3 and restored with?llings. Occlusion is orthognathic.
  What denture construction would be optimal for this patient,
  considering his occupation as a lecturer? A.Porcelain-fused-to-metal
  dental bridge B.Plastic dental bridge C.Clasp-retained (bugel)
  removable partial denture with attachments D.Removable partial laminar
  denture for the upper jaw E.Swaged-soldered metal dental bridge with
  faceted intermediate part 13.A 7-year-old boy is diagnosed with epi-
  demic parotitis (mumps). Name the most li- kely complication of this
  disease: A.Orchitis B.Colitis C.Dermatitis D.Pneumonia
  E.Cholecystitis14.During preventive examination a 40-year- old man
  presents with the following changes: marginal gingiva is enlarged,
  torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental
  probe; there is no pain. Staining the gums with Lugol’s iodine
  solution results in light-brown coloring of mucosa. Make the
  diagnosis: A.Chronic catarrhal gingivitis B.Acute catarrhal gingivitis
  C.Exacerbation of chronic catarrhal gingivitis D.Chronic hypertrophic
  gingivitis E.Generalized periodontitis 15.A 4-year-old boy has been
  diagnosed wi- th acute purulent periostitis of the upper jaw
  originating from the 64 tooth. Choose the optimal treatment tactics:
  A.The 64 tooth extraction, periosteotomy, pharmacotherapy B.The 64
  tooth extraction, anti-in?ammatory pharmacotherapy C.Endodontological
  treatment of the 64 tooth, anti-in?ammatory pharmacotherapy
  D.Endodontological treatment of the 64 tooth, periosteotomy
  E.Periosteotomy, anti-in?ammatory pharmacotherapy

There's a question number at the beginning of each question.

Questions usually have 5 or 4 options

What I did?

 function gettingQuestionAndOptions($string, $start, $end)
    {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;

        return substr($string, $ini, $len);
    }

How do I use it?

if (gettingQuestionAndOptions($text, '?', "A. ")) {

    $parsedQuestion = gettingQuestionAndOptions($text, '', "?");
    $parsedA = gettingQuestionAndOptions($text, 'A. ', "B. ");
    $parsedB = gettingQuestionAndOptions($text, 'B. ', "C. ");
    $parsedC = gettingQuestionAndOptions($text, 'C. ', "D. ");
    $endQuestion = "?";

} else if (gettingQuestionAndOptions($text, ':', "A. ")) {

    $parsedQuestion = gettingQuestionAndOptions($text, '', ":");
    $parsedA = gettingQuestionAndOptions($text, 'A. ', "B. ");
    $parsedB = gettingQuestionAndOptions($text, 'B. ', "C. ");
    $parsedC = gettingQuestionAndOptions($text, 'C. ', "D. ");
    $endQuestion = ":";

} else {
}

Result:

I tried min. 4 hours but still I'm getting an irregular result. If there are numbers or A, B in the problem, I get an even worse result.

How can I do this better? Or where's my fault?

Can I get more correct data with Regex?

Body:
Assuming your text always starts with a number, grouping them should be a simple matter of just keeping track of the current question you're on, and then searching for the next one. This will help reduce false positives.

<?php
$data = "12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are destroyed by 2/3 and restored with?llings. Occlusion is orthognathic. What denture construction would be optimal for this patient, considering his occupation as a lecturer? A.Porcelain-fused-to-metal dental bridge B.Plastic dental bridge C.Clasp-retained (bugel) removable partial denture with attachments D.Removable partial laminar denture for the upper jaw E.Swaged-soldered metal dental bridge with faceted intermediate part 13.A 7-year-old boy is diagnosed with epi- demic parotitis (mumps). Name the most li- kely complication of this disease: A.Orchitis B.Colitis C.Dermatitis D.Pneumonia E.Cholecystitis14.During preventive examination a 40-year- old man presents with the following changes: marginal gingiva is enlarged, torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental probe; there is no pain. Staining the gums with Lugol’s iodine solution results in light-brown coloring of mucosa. Make the diagnosis: A.Chronic catarrhal gingivitis B.Acute catarrhal gingivitis C.Exacerbation of chronic catarrhal gingivitis D.Chronic hypertrophic gingivitis E.Generalized periodontitis 15.A 4-year-old boy has been diagnosed wi- th acute purulent periostitis of the upper jaw originating from the 64 tooth. Choose the optimal treatment tactics: A.The 64 tooth extraction, periosteotomy, pharmacotherapy B.The 64 tooth extraction, anti-in?ammatory pharmacotherapy C.Endodontological treatment of the 64 tooth, anti-in?ammatory pharmacotherapy D.Endodontological treatment of the 64 tooth, periosteotomy E.Periosteotomy, anti-in?ammatory pharmacotherapy";
$questions = [];
$question_num = 12;
$previous_question_start = 0;
while (true) {
    $question_start = strpos($data, "$question_num.", $previous_question_start);
    $question_end = strpos($data, (++$question_num) . ".", $question_start);
    if ($question_end === false) {
        // no more matches, this is the last question
        $questions[] = substr($data, $question_start);
        break;
    }
    $questions[] = substr($data, $question_start, $question_end - $question_start);
    $previous_question_start = $question_start;
}

At this point you have each question in an array element, so search for your answers in each one, using the same technique. We'll save our results into a new array.

$questions_answers = [];
$answer_choices = ["A", "B", "C", "D", "E"];
foreach ($questions as $q) {
    $qa = [];
    $qa["question"] = substr($q, 0, strpos($q, "$answer_choices[0]."));
    $previous_answer_start = 0;
    foreach ($answer_choices as $i=>$a) {
        $answer_start = strpos($q, $answer_choices[$i]. ".", $previous_answer_start);
        if (empty($answer_choices[$i + 1])) {
            // end of the array, this is the last answer
            $qa["answers"][] = substr($q, $answer_start);
            break;
        }
        $answer_end = strpos($q, $answer_choices[$i + 1] . ".", $answer_start);
        $qa["answers"][] = substr($q, $answer_start, $answer_end - $answer_start);
        $previous_answer_start = $answer_start;
    }
    $questions_answers[] = $qa;
}

print_r($questions_answers);

Output:

Array
(
    [0] => Array
        (
            [question] => 12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are destroyed by 2/3 and restored with?llings. Occlusion is orthognathic. What denture construction would be optimal for this patient, considering his occupation as a lecturer?
            [answers] => Array
                (
                    [0] => A.Porcelain-fused-to-metal dental bridge
                    [1] => B.Plastic dental bridge
                    [2] => C.Clasp-retained (bugel) removable partial denture with attachments
                    [3] => D.Removable partial laminar denture for the upper jaw
                    [4] => E.Swaged-soldered metal dental bridge with faceted intermediate part
                )

        )

    [1] => Array
        (
            [question] => 13.A 7-year-old boy is diagnosed with epi- demic parotitis (mumps). Name the most li- kely complication of this disease:
            [answers] => Array
                (
                    [0] => A.Orchitis
                    [1] => B.Colitis
                    [2] => C.Dermatitis
                    [3] => D.Pneumonia
                    [4] => E.Cholecystitis
                )

        )

    [2] => Array
        (
            [question] => 14.During preventive examination a 40-year- old man presents with the following changes: marginal gingiva is enlarged, torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental probe; there is no pain. Staining the gums with Lugol’s iodine solution results in light-brown coloring of mucosa. Make the diagnosis:
            [answers] => Array
                (
                    [0] => A.Chronic catarrhal gingivitis
                    [1] => B.Acute catarrhal gingivitis
                    [2] => C.Exacerbation of chronic catarrhal gingivitis
                    [3] => D.Chronic hypertrophic gingivitis
                    [4] => E.Generalized periodontitis
                )

        )

    [3] => Array
        (
            [question] => 15.A 4-year-old boy has been diagnosed wi- th acute purulent periostitis of the upper jaw originating from the 64 tooth. Choose the optimal treatment tactics:
            [answers] => Array
                (
                    [0] => A.The 64 tooth extraction, periosteotomy, pharmacotherapy
                    [1] => B.The 64 tooth extraction, anti-in?ammatory pharmacotherapy
                    [2] => C.Endodontological treatment of the 64 tooth, anti-in?ammatory pharmacotherapy
                    [3] => D.Endodontological treatment of the 64 tooth, periosteotomy
                    [4] => E.Periosteotomy, anti-in?ammatory pharmacotherapy
                )

        )

)

I kept this code pretty unoptimized so it would be easy to understand, but simple string manipulation is a very low-cost computation so it should be fine for everyday use.

As a side note, I notice you're losing characters like "ﬂ" (f/l ligature) and "ﬁ" (f/i ligature.) If you're pulling this information from a database or web page, make sure you're properly dealing with UTF-8 characters.