问:
How to search data in multiple fields / columns?
I tried a code like this, it works quite well:

View:

```<code>@model IEnumerable<InternProject.Models.Course>
....
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("Index", "Course", FormMethod.Get))
{
    <p>
        @Html.TextBox("searching")
        <input type="submit"  value="search" />

    </p>
}
<table class="table table-striped">
    <thead>
        <tr>
            <th>Course ID</th>
            <th>Course Name</th>
            <th>Major</th>
            <th>Specialization</th>
            <th></th>
        </tr>
    </thead>

@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.crs_ID)</td>
        <td>@Html.DisplayFor(modelItem => item.crs_Course)</td>
        <td>@Html.DisplayFor(modelItem => item.crs_Major)</td>
        <td>@Html.DisplayFor(modelItem => item.crs_Specialization)</td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.crs_ID }) |
            @Html.ActionLink("Details", "Details", new {id = item.crs_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.crs_ID })
        </td>
    </tr>
}

</table>
</code>```

Controller:

```<code>public class CourseController : Controller
{
    private DbCourse db = new DbCourse();
    public ActionResult Index(string submit, string searching)
    {
        var course = from x in db.Course select x;
        if (!String.IsNullOrWhiteSpace(searching))
        {
            return View(db.Course.Where(x => x.crs_Course.Contains(searching.Trim()) ||
                         x.crs_Major.Contains(searching.Trim()) ||
                         x.crs_Specialization.Contains(searching.Trim())).ToList());
        }
        else if (searching == null)
        {
            return View(db.Course.Where(x => x.crs_Course == searching || searching.Trim() == null).ToList());
        }
        else
        {
            return View(db.Course.ToList());
        }
    }
}
</code>```

But the id cannot be included because it is an integer. I want to have a solution wherein I can search also in the id of my database depending on the input in the search box.

Also, is there a better code than this for a simple search functionality like this? I've noticed it's so long and it obviously violates the DRY principle.

Here is what my simple application looks like:

I'm taking my baby steps in ASP.NET MVC as a beginner.

I hope to improve my knowledge using applied coding and not just relying on tutorial videos.

Thank you very much in advance! =)

答:
The simplest solution would be to convert the ID to a string. Your code then become the following.

```<code>return View(db.Course.Where(x => x.crs_Course.Contains(searching.Trim()) ||
                     x.crs_Major.Contains(searching.Trim()) ||
                     x.crs_Specialization.Contains(searching.Trim()) ||
                     x.crs_crs_ID.ToString().Contains(searching.Trim())).ToList())
</code>```

This doesn't go against the DRY principle since you're using Contains() on different variables; however, what is going against the DRY principle is the repetitive searching.Trim(). I suggest you trim the string once at the top of your code.

```<code>var match = searching.Trim();
</code>```

Then you can use match instead of searching.Trim() in the code below.

Body:
I tried a code like this, it works quite well:

View:

@model IEnumerable<InternProject.Models.Course>
....
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("Index", "Course", FormMethod.Get))
{

        @Html.TextBox("searching")
        <input type="submit"  value="search" />

}

            Course ID
            Course Name
            Major
            Specialization

@foreach (var item in Model) {

        @Html.DisplayFor(modelItem => item.crs_ID)
        @Html.DisplayFor(modelItem => item.crs_Course)
        @Html.DisplayFor(modelItem => item.crs_Major)
        @Html.DisplayFor(modelItem => item.crs_Specialization)

            @Html.ActionLink("Edit", "Edit", new { id = item.crs_ID }) |
            @Html.ActionLink("Details", "Details", new {id = item.crs_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.crs_ID })

}

Controller:

public class CourseController : Controller
{
    private DbCourse db = new DbCourse();
    public ActionResult Index(string submit, string searching)
    {
        var course = from x in db.Course select x;
        if (!String.IsNullOrWhiteSpace(searching))
        {
            return View(db.Course.Where(x => x.crs_Course.Contains(searching.Trim()) ||
                         x.crs_Major.Contains(searching.Trim()) ||
                         x.crs_Specialization.Contains(searching.Trim())).ToList());
        }
        else if (searching == null)
        {
            return View(db.Course.Where(x => x.crs_Course == searching || searching.Trim() == null).ToList());
        }
        else
        {
            return View(db.Course.ToList());
        }
    }
}

But the id cannot be included because it is an integer. I want to have a solution wherein I can search also in the id of my database depending on the input in the search box.

Also, is there a better code than this for a simple search functionality like this? I've noticed it's so long and it obviously violates the DRY principle.

Here is what my simple application looks like:

I'm taking my baby steps in ASP.NET MVC as a beginner.

I hope to improve my knowledge using applied coding and not just relying on tutorial videos.

Thank you very much in advance! =)

Body:
The simplest solution would be to convert the ID to a string. Your code then become the following.

return View(db.Course.Where(x => x.crs_Course.Contains(searching.Trim()) ||
                     x.crs_Major.Contains(searching.Trim()) ||
                     x.crs_Specialization.Contains(searching.Trim()) ||
                     x.crs_crs_ID.ToString().Contains(searching.Trim())).ToList())

This doesn't go against the DRY principle since you're using Contains() on different variables; however, what is going against the DRY principle is the repetitive searching.Trim(). I suggest you trim the string once at the top of your code.

var match = searching.Trim();

Then you can use match instead of searching.Trim() in the code below.


来源: stackexchange

问:
cannot resolve method sort using a comparator from apache common io
I'm using apache Commons IO to compare and sort an array of File[] type.

```<code>import org.apache.commons.io.comparator.*;
public abstract class Order {

static final String ABS = "abs", TYPE = "type", SIZE = "size";

    public static void runOrder(File[] filteredFiles, String[] command) {
    String currentOrder = command[0];
    File[] sortedFiles = null;
    if (command.length == 1) { //according to original order
        if (currentOrder.equals(ABS))
            sortedFiles = NameFileComparator.NAME_COMPARATOR.sort(filteredFiles);
        if (currentOrder.equals(TYPE))
            sortedFiles = ExtensionFileComparator.EXTENSION_COMPARATOR.sort(filteredFiles);
        if (currentOrder.equals(SIZE))
            sortedFiles = SizeFileComparator.SIZE_COMPARATOR.sort(filteredFiles);
</code>```

However while the Name\Extension\SizeFileComparator use works, the sort is marked in red in Intellij giving me a message of: Cannot resolve method sort(java.io.File[]). I don't understand why.

答:
You must instantiate the class NameFileComparator.</p>

```<code>NameFileComparator comparator = new NameFileComparator();
comparator.sort(...)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using apache Commons IO to compare and sort an array of File[] type.

import org.apache.commons.io.comparator.*;
public abstract class Order {

static final String ABS = "abs", TYPE = "type", SIZE = "size";

    public static void runOrder(File[] filteredFiles, String[] command) {
    String currentOrder = command[0];
    File[] sortedFiles = null;
    if (command.length == 1) { //according to original order
        if (currentOrder.equals(ABS))
            sortedFiles = NameFileComparator.NAME_COMPARATOR.sort(filteredFiles);
        if (currentOrder.equals(TYPE))
            sortedFiles = ExtensionFileComparator.EXTENSION_COMPARATOR.sort(filteredFiles);
        if (currentOrder.equals(SIZE))
            sortedFiles = SizeFileComparator.SIZE_COMPARATOR.sort(filteredFiles);

However while the Name\Extension\SizeFileComparator use works, the sort is marked in red in Intellij giving me a message of: Cannot resolve method sort(java.io.File[]). I don't understand why.

Body:
You must instantiate the class NameFileComparator.

NameFileComparator comparator = new NameFileComparator();
comparator.sort(...)


问:
Build an apk in runtime
i want to create a Windows application where you will be able to make some configurations and create own apk for downloading.

I'm using Unity 5.6 personal edition for this case.

So, my question is: is it even possible to make with Unity?

Can i create an apk in runtime?

Thx.

答:
Okay so after the discussion in the comments, I believe this is an approach you could take.

In case for each configuration you need a new android project, then you need to write a script that would create the android project with all its directories for you. (For this you could have a "template application" and your script could simply copy the whole directory to the desired path and undergo the modifications on the project there.)

After having the your android project modified, you can build the apk at runtime, on windows this is how you do it: Go to the app directory and run the following: gradlew.bat buildName where buildName could be something like assembleDebug or assembleRelease. For more information on the building process, please check here

Title: Build an apk in runtime


问:
Can single orderer handle mutliple channels?
Can single orderer handle multiple channels?

This is .yaml configuration of orderer:

```<code>orderer_example_com:
  container_name: orderer.example.com
  image: hyperledger/fabric-orderer
  environment:
    - ORDERER_GENERAL_LOGLEVEL=debug
    - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
    - ORDERER_GENERAL_GENESISMETHOD=file
    - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis1.block
    - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
    - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/crypto/orderer/msp
    - ORDERER_GENERAL_TLS_ENABLED=true
    - ORDERER_GENERAL_TLS_PRIVATEKEY=/etc/hyperledger/crypto/orderer/tls/server.key
    - ORDERER_GENERAL_TLS_CERTIFICATE=/etc/hyperledger/crypto/orderer/tls/server.crt
   - ORDERER_GENERAL_TLS_ROOTCAS=[/etc/hyperledger/crypto/orderer/tls/ca.crt, /etc/hyperledger/crypto/peerOrg1/tls/ca.crt, /etc/hyperledger/crypto/peerOrg2/tls/ca.crt, /etc/hyperledger/crypto/peerOrg3/tls/ca.crt]
  working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderers
  command: orderer
  ports:
    - 7050:7050
  volumes:
    - ./channel:/etc/hyperledger/configtx
    - ./channel/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/:/etc/hyperledger/crypto/orderer
    - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/crypto/peerOrg1
    - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/crypto/peerOrg2
    - ./channel/crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/:/etc/hyperledger/crypto/peerOrg3
  networks:
    chfn:
      aliases:
       - orderer.example.com
</code>```

I have 1 genesis file for each channel and property ORDERER_GENERAL_GENESISFILE is set to just one of them. Should I define orderers for each channel?

答:
The TL;DR: of @Artem's response is yes, an ordering service in Hyperledger Fabric can handle multiple channels.

The orderer service may have multiple nodes, to provide resilience of the service implemented by some fault tolerant protocol such as PAXOS, RAFT, *BFT, etc. For the Kafka orderer, we currently support crash fault tolerance.

Fabric also supports a topology model that has multiple distinct orderer services, each supporting a non-overlapping set of channels.

Peer nodes can participate in multiple channels, and those channels may each be supported by different orderer services.

Body:
Can single orderer handle multiple channels?

This is .yaml configuration of orderer:

orderer_example_com:
  container_name: orderer.example.com
  image: hyperledger/fabric-orderer
  environment:
    - ORDERER_GENERAL_LOGLEVEL=debug
    - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
    - ORDERER_GENERAL_GENESISMETHOD=file
    - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis1.block
    - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
    - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/crypto/orderer/msp
    - ORDERER_GENERAL_TLS_ENABLED=true
    - ORDERER_GENERAL_TLS_PRIVATEKEY=/etc/hyperledger/crypto/orderer/tls/server.key
    - ORDERER_GENERAL_TLS_CERTIFICATE=/etc/hyperledger/crypto/orderer/tls/server.crt
   - ORDERER_GENERAL_TLS_ROOTCAS=[/etc/hyperledger/crypto/orderer/tls/ca.crt, /etc/hyperledger/crypto/peerOrg1/tls/ca.crt, /etc/hyperledger/crypto/peerOrg2/tls/ca.crt, /etc/hyperledger/crypto/peerOrg3/tls/ca.crt]
  working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderers
  command: orderer
  ports:
    - 7050:7050
  volumes:
    - ./channel:/etc/hyperledger/configtx
    - ./channel/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/:/etc/hyperledger/crypto/orderer
    - ./channel/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/crypto/peerOrg1
    - ./channel/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/crypto/peerOrg2
    - ./channel/crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/:/etc/hyperledger/crypto/peerOrg3
  networks:
    chfn:
      aliases:
       - orderer.example.com

I have 1 genesis file for each channel and property ORDERER_GENERAL_GENESISFILE is set to just one of them. Should I define orderers for each channel?


问:
Naming conventions in C# compared to Java
The standard naming convention in the Java world is to name packages, classes and methods  according to:

```<code>com.domainname.productname (package)
com.domainname.productname.ClassName (class)
com.domainname.productname.ClassName.isUpperCase(String str) (method)
</code>```

What is the C#/.NET standard naming convention for the above cases?

答:
AKU's answer should help you out:

.NET namespaces

He links to Microsoft's guidelines:

http://msdn.microsoft.com/en-us/library/893ke618(VS.71).aspx

You should consider reading the the rest of the guidelines starting here:

http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx

The remainder of the post is also very informative:

.NET namespaces

In your case you would go with:

```<code>CompanyName.ProductName
CompanyName.ProductName.ClassName
CompanyName.ClassName.IsUpperCase(string str)
</code>```

The .NET guidelines don't follow the Java style of using reversed FQ domain names to specify namespaces, and I've yet to see a commercial component such as Telerik or Infragistics for example follow anything other the guidelines than the MS ones.

ContentLicense: CC BY-SA 2.5

Body:
The standard naming convention in the Java world is to name packages, classes and methods  according to:

com.domainname.productname (package)
com.domainname.productname.ClassName (class)
com.domainname.productname.ClassName.isUpperCase(String str) (method)

What is the C#/.NET standard naming convention for the above cases?

Body:
AKU's answer should help you out:

.NET namespaces

He links to Microsoft's guidelines:

http://msdn.microsoft.com/en-us/library/893ke618(VS.71).aspx

You should consider reading the the rest of the guidelines starting here:

http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx

The remainder of the post is also very informative:

.NET namespaces

In your case you would go with:

CompanyName.ProductName
CompanyName.ProductName.ClassName
CompanyName.ClassName.IsUpperCase(string str)

The .NET guidelines don't follow the Java style of using reversed FQ domain names to specify namespaces, and I've yet to see a commercial component such as Telerik or Infragistics for example follow anything other the guidelines than the MS ones.

OwnerDisplayName: Kev

LastEditorDisplayName: Kev


问:
Is it appropriate to use BackgroundWorker to do work that raises an event that I listen for
I'm new to Threading but I've read threads here on BackgroundWorker (BW) and mostly understand the material.  I suspect BW is not the correct solution but let me ask.
I have an object (GPS Emulator) that does its work in a loop mostly waiting (Thread.Sleep()) but occasionally raising an event that the UI listens for.  I want the UI to be responsive of course so it would be nice to put the work of the object in the background (as in gps.Start()).  On the UI I want to have the ability to Pause, Resume, and Stop the GPS.  I figured I could do this by setting appropriate flags in the GPS object that would break the loop running in the background.  What I don't understand is what happens to the events that are raised by the GPS.  The Thread that the event is raised on is not the Thread that is listening and so it seems, the UI can't respond correctly (as in painting the new GPS point on the UI).
Am I missing something wrt BW or is there a better (but still simple) way of doing this?</p>

答:
I think you can use the ProgressChanged event of the BackgroundWorker to monitor the the event on your own thread.

Update

If you want to pass custom information like GeoCordinates to the Main UI thread you can do so by Using the Overloaded Method of ReportProgress(Int32 progresschanged, object userstate) method.

Example:

This is just an example modify it according to your requirement

Create a class to hold cordinates postion:

```<code>public class Position
{
    public int Lat{get;set;}
    public int Long {get;set;}
}
</code>```

In your DoWork method do somthing like this:

```<code>private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //Perform what ever is your task and when you get somthing like a GeoPosition cordinate
    Position pos = new Position();
    pos.Lat = 100;
    pos.Long = 200; // just some position data
    //pass it on to progress changed event
    //any integer between 0 to 100 that tells how much you have done or just pass 0
    backgroundWorker1.ReportProgress( 0, pos);
}
</code>```

in your progress changed event handler :

```<code>private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
        //retrieve position from userstate
        Position pos = e.UserState as Position;
        some_counter_or_progressbar.Value = e.ProgressPercentage;
        textboxLatitude.Text = pos.Lat.ToString();
        textboxLongitude.Text = pos.Long.ToString();
}
</code>```

I'm sure you got the Idea...

Body:
I think you can use the ProgressChanged event of the BackgroundWorker to monitor the the event on your own thread.

Update

If you want to pass custom information like GeoCordinates to the Main UI thread you can do so by Using the Overloaded Method of ReportProgress(Int32 progresschanged, object userstate) method.

Example:

This is just an example modify it according to your requirement

Create a class to hold cordinates postion:

public class Position
{
    public int Lat{get;set;}
    public int Long {get;set;}
}

In your DoWork method do somthing like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //Perform what ever is your task and when you get somthing like a GeoPosition cordinate
    Position pos = new Position();
    pos.Lat = 100;
    pos.Long = 200; // just some position data
    //pass it on to progress changed event
    //any integer between 0 to 100 that tells how much you have done or just pass 0
    backgroundWorker1.ReportProgress( 0, pos);
}

in your progress changed event handler :

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
        //retrieve position from userstate
        Position pos = e.UserState as Position;
        some_counter_or_progressbar.Value = e.ProgressPercentage;
        textboxLatitude.Text = pos.Lat.ToString();
        textboxLongitude.Text = pos.Long.ToString();
}

I'm sure you got the Idea...


问:
How can i set @media only screen less then 320px for indetificator?
I have this piece of code. I'm  beginner :/

https://ibb.co/ccrFFG
Id like to add some responsibility by
@media only screen and (max-width: 320px) {}
but it doesnt works with IDs. How would you change the code pls? :)

Thanks

答:
css media-querys only work if you use the viewport meta-tag, make sure that you use it on your site.

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
</code>```

You can ready more about it here:
https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag

ContentLicense: CC BY-SA 4.0

Body:
css media-querys only work if you use the viewport meta-tag, make sure that you use it on your site.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

You can ready more about it here:
https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag


问:
Many XSDs sharing elements & types - Any way to generate classes? (c#)
I've been given around 160 XSDs and want to be able to generate c# classes, I'm not allowed to change the XSDs and they may add more schemas that follow the format that they gave to me.

Each schema declares the root element of the same name with many matching types e.g.:

Document 1:

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Root-XML" type="Root-XMLType1"/>
  <xs:complexType name="Root-XMLType1">
    <xs:sequence>
    <xs:element name="Header" type="HeaderStruct"/>
    <xs:element name="Delivery" type="DeliveryType1Struct"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="DeliveryType1Struct">
  <xs:complexContent>
  <xs:restriction base="DeliveryType1Abstract">
    <xs:all>
      <xs:element name="GMTOffset" type="GMTOffsetType"/>
      <xs:element name="UserName" type="UserNameType"/>
    </xs:all>
  </xs:restriction>
  </xs:complexContent>
</xs:complexType>
..... 9000 more lines of types .....
</xs:schema>
</code>```

Document 2:

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Root-XML" type="Root-XMLType2"/>
  <xs:complexType name="Root-XMLType2">
    <xs:sequence>
    <xs:element name="Header" type="HeaderStruct"/>
    <xs:element name="Delivery" type="DeliveryType2Struct"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="DeliveryType2Struct">
  <xs:complexContent>
  <xs:restriction base="DeliveryType2Abstract">
    <xs:all>
      <xs:element name="GMTOffset" type="GMTOffsetType"/>
      <xs:element name="UserName" type="UserNameType"/>
    </xs:all>
  </xs:restriction>
  </xs:complexContent>
</xs:complexType>
..... 9000 more lines of types .....
</xs:schema>
</code>```

Most of these schemas are the same except for a few added elements here and there.

I tried to use XSD.exe but there were 'this type was already declared' warnings and many missing elements; it seemed like it just picked the last XSD passed to it in the parameters file.

答:
You could use xsd.exe to generate a set of classes for each schema, and have them each one go into its own .net namespace.

If you have xsd.exe generate partial classes, then you could then add interfaces to the ones that have commonality to allow you to work with them polymorphically as apposed to crafting code for each schema.

```<code>// Generated by XSD.exe
namespace A
{
  partial class GeneratedRootXML
  {
      public string Header {get;set;}
      ....
  }
}

// Generated by XSD.exe
namespace B
{
  partial class GeneratedRootXML
  {
      public string Header {get;set;}
      ....
  }
}

// Your code
interface IMyRootXML
{
   public string Header {get;set;}
}

namespace A
{
  partial class GeneratedRootXML : IMyRootXML
  {
  }
}

namespace B
{
  partial class GeneratedRootXML : IMyRootXML
  {
  }
}
</code>```

But how ever you do it its going to be a bit of a mess.

Body:
I've been given around 160 XSDs and want to be able to generate c# classes, I'm not allowed to change the XSDs and they may add more schemas that follow the format that they gave to me.

Each schema declares the root element of the same name with many matching types e.g.:

Document 1:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Root-XML" type="Root-XMLType1"/>
  <xs:complexType name="Root-XMLType1">
    <xs:sequence>
    <xs:element name="Header" type="HeaderStruct"/>
    <xs:element name="Delivery" type="DeliveryType1Struct"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="DeliveryType1Struct">
  <xs:complexContent>
  <xs:restriction base="DeliveryType1Abstract">
    <xs:all>
      <xs:element name="GMTOffset" type="GMTOffsetType"/>
      <xs:element name="UserName" type="UserNameType"/>
    </xs:all>
  </xs:restriction>
  </xs:complexContent>
</xs:complexType>
..... 9000 more lines of types .....
</xs:schema>

Document 2:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Root-XML" type="Root-XMLType2"/>
  <xs:complexType name="Root-XMLType2">
    <xs:sequence>
    <xs:element name="Header" type="HeaderStruct"/>
    <xs:element name="Delivery" type="DeliveryType2Struct"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="DeliveryType2Struct">
  <xs:complexContent>
  <xs:restriction base="DeliveryType2Abstract">
    <xs:all>
      <xs:element name="GMTOffset" type="GMTOffsetType"/>
      <xs:element name="UserName" type="UserNameType"/>
    </xs:all>
  </xs:restriction>
  </xs:complexContent>
</xs:complexType>
..... 9000 more lines of types .....
</xs:schema>

Most of these schemas are the same except for a few added elements here and there.

I tried to use XSD.exe but there were 'this type was already declared' warnings and many missing elements; it seemed like it just picked the last XSD passed to it in the parameters file.

Body:
You could use xsd.exe to generate a set of classes for each schema, and have them each one go into its own .net namespace.

If you have xsd.exe generate partial classes, then you could then add interfaces to the ones that have commonality to allow you to work with them polymorphically as apposed to crafting code for each schema.

// Generated by XSD.exe
namespace A
{
  partial class GeneratedRootXML
  {
      public string Header {get;set;}
      ....
  }
}

// Generated by XSD.exe
namespace B
{
  partial class GeneratedRootXML
  {
      public string Header {get;set;}
      ....
  }
}

// Your code
interface IMyRootXML
{
   public string Header {get;set;}
}

namespace A
{
  partial class GeneratedRootXML : IMyRootXML
  {
  }
}

namespace B
{
  partial class GeneratedRootXML : IMyRootXML
  {
  }
}

But how ever you do it its going to be a bit of a mess.


问:
Batched average euclidian distance
I need to calculate the average euclidian distance between a tensor x and a set of tensors ys (represented in tensorflow as a single tensor with an additional dimension). For a feasible training the calculation has to be batched (only the xs, the ys stay the same), also the calculation has to be differentiable, I don't know if the broadcasting violates this requirement. I know how to calculate the average over all tensors and also the euclidian distance between xs and ys, where xs has the same dimensionality as ys, but here I am a bit lost.</p>

答:
I think I have figured it out (x and y are both of shape (number, input)):

```<code>def pairwiseL2Norm(x, y):
    x_reshaped = tf.reshape(x, shape=[-1, 1, num_input])
    y_reshaped = tf.reshape(y, shape=[1, -1, num_input])
    x_squared = x_reshaped*x_reshaped
    y_squared = y_reshaped*y_reshaped
    multiplied = x_reshaped * y_reshaped

    #x^2-2xy+y^2
    #((x_i)_xy)^2-2*((x_i)_xy)((y_j)_xy)+((y_j)_xy)^2
    combined = x_squared - 2*multiplied + y_squared

    summed = tf.reduce_sum(combined, axis=2)
    return tf.sqrt(summed)
</code>```

and then the average:

```<code>distance = tf.reduce_mean(pairwiseL2Norm(gen_images, features), axis=1)
</code>```

Title: Batched average euclidian distance

Body:
I think I have figured it out (x and y are both of shape (number, input)):

def pairwiseL2Norm(x, y):
    x_reshaped = tf.reshape(x, shape=[-1, 1, num_input])
    y_reshaped = tf.reshape(y, shape=[1, -1, num_input])
    x_squared = x_reshaped*x_reshaped
    y_squared = y_reshaped*y_reshaped
    multiplied = x_reshaped * y_reshaped

    #x^2-2xy+y^2
    #((x_i)_xy)^2-2*((x_i)_xy)((y_j)_xy)+((y_j)_xy)^2
    combined = x_squared - 2*multiplied + y_squared

    summed = tf.reduce_sum(combined, axis=2)
    return tf.sqrt(summed)

and then the average:

distance = tf.reduce_mean(pairwiseL2Norm(gen_images, features), axis=1)


问:
How do I automatically resize text to fit a fixed-size PyGTK label?
I have a fixed-size gtk.Label. I would like to automatically resize the text so that it fits within the Label. Is there an elegant way to do this with fonts that are not fixed width?

```<code>my_label = gtk.Label()

# Short text segment
my_label.set_text( "Short text segment." )

# Long text segment
### Determine required text size here. ###
my_label.set_text( "This is a really long text segment that I would like to resize."
</code>```

答:
I didn't have time to test this, but something along these lines ought to do what you want:

```<code>size = 12000 # thousandths of a point
temp_label = gtk.Label(my_label.get_text())
while temp_label.get_width() > my_label.get_width():
    size -= 100
    temp_label.set_attributes(pango.Attrlist().insert(pango.AttrSize(size))
my_label = temp_label
</code>```

This assumes that you're forcing the width of my_label directly. If my_label is getting it's width from something else (like a parent container) then substitute my_label.get_width() for whatever is the maximum width that you desire.

Essentialy this just drops the font size by 1/10th of a point over and over until the text finally fits. Feel free to tweak the size -= 100 to whatever increment you like (the smaller it is the slower but more fine-grained it will be).

Let me know if that's not quite it and I can refine it later.

Body:
I have a fixed-size gtk.Label. I would like to automatically resize the text so that it fits within the Label. Is there an elegant way to do this with fonts that are not fixed width?

my_label = gtk.Label()

# Short text segment
my_label.set_text( "Short text segment." )

# Long text segment
### Determine required text size here. ###
my_label.set_text( "This is a really long text segment that I would like to resize."

Body:
I didn't have time to test this, but something along these lines ought to do what you want:

size = 12000 # thousandths of a point
temp_label = gtk.Label(my_label.get_text())
while temp_label.get_width() > my_label.get_width():
    size -= 100
    temp_label.set_attributes(pango.Attrlist().insert(pango.AttrSize(size))
my_label = temp_label

This assumes that you're forcing the width of my_label directly. If my_label is getting it's width from something else (like a parent container) then substitute my_label.get_width() for whatever is the maximum width that you desire.

Essentialy this just drops the font size by 1/10th of a point over and over until the text finally fits. Feel free to tweak the size -= 100 to whatever increment you like (the smaller it is the slower but more fine-grained it will be).

Let me know if that's not quite it and I can refine it later.


问:
Can't delete a jar file on windows? Scala/Spark/IntelliJ
I generated a .jar file from my Scala project in IntelliJ, I accidently added some stuff that it doesnt need. But now I cant create a new .jar file because it doesnt have permission to overwrite it, and I cant even remove the .jar file manually?

Im on Windows 10.

If I try to remove it on the command line with rm -r it says no such file or directory.

答: Maybe jar file in use, try to clear cache and rebuild your app in inteljIDE.</p>


问:
.Max() vs OrderByDescending().First()
This is purely for my own knowledge, if I were going to write the code I would just use .Max().

At first thought .Max() only has to do a single pass through numbers to find the max, while the second way has to sort the entire thing enumerable then find the first one. So it's O(n) vs O(n lg n). But then I was thinking maybe it knows it only needs the highest and just grabs it.

Question:
Is LINQ and/or the compiler smart enough to figure out that it doesn't need to sort the entire enumerable and boils the code down to essentially the same as .Max()? Is there a quantifiable way to find out?

```<code>IEnumerable<int> numbers = Enumerable.Range(1, 1000);

int max  = numbers.Max();
int max2 = numbers.OrderByDescending(x => x).First();
</code>```

答:
It appears that OrderedEnumerable is now smart enough to figure out that it doesn't need to sort the list for First and Last().

Note the code at around line 223, TryGetFirst()
https://github.com/dotnet/corefx/blob/ed0ee133ac49cee86f10ca4692b1d72e337bc012/src/System.Linq/src/System/Linq/OrderedEnumerable.cs

Title: .Max() vs OrderByDescending().First()

Body:
This is purely for my own knowledge, if I were going to write the code I would just use .Max().

At first thought .Max() only has to do a single pass through numbers to find the max, while the second way has to sort the entire thing enumerable then find the first one. So it's O(n) vs O(n lg n). But then I was thinking maybe it knows it only needs the highest and just grabs it.

Question:
Is LINQ and/or the compiler smart enough to figure out that it doesn't need to sort the entire enumerable and boils the code down to essentially the same as .Max()? Is there a quantifiable way to find out?

IEnumerable<int> numbers = Enumerable.Range(1, 1000);

int max  = numbers.Max();
int max2 = numbers.OrderByDescending(x => x).First();


问:
Getting an error "str.substr is not a function" when use my browser for the localhost page but server is running?
I am getting the following error when request my webpage after starting the server (the server runs properly, the problem occurs when I request the page):

```<code>TypeError: str.substr is not a function at createGetter (C:\Users\mypath\node_modules\method-override\index.js:88:11)
at methodOverride (C:\Users\mypath\node_modules\method-override\index.js:50:7)
at Layer.handle [as handle_request] (C:\Users\mypath\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\mypath\node_modules\express\lib\router\index.js:312:13)
at C:\Users\mypath\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\mypath\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\mypath\node_modules\express\lib\router\index.js:271:10)
at logger (C:\Users\mypath\node_modules\morgan\index.js:144:5)
at Layer.handle [as handle_request] (C:\Users\mypath\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\mypath\node_modules\express\lib\router\index.js:312:13)
</code>```

I am still learning about the MEAN stack, please bear with me, my server.js is as follows:

```<code>var express = require('express'),
favicon = require('serve-favicon'),
stylus = require('stylus'),
logger = require('morgan'),
methodOverride = require('method-override'),
session = require('express-session'),
bodyParser = require('body-parser'),
multer = require('multer'),
upload = multer({ dest: 'uploads/'}),
errorHandler = require('errorhandler');

var app = express();

function compile(src, path) {
return stylus(src).set('filename', path);
}

app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(logger('dev'));
app.use(methodOverride);
app.use(session(
    {resave: true, saveUninitialized: true,
    secret: 'uwotm8'}
));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));

//app.use(multer());
app.use(stylus.middleware(
    {
        src: __dirname + '/public',
        compile: compile
    }
));

app.use(express.static(__dirname + 'public'));
app.get('/', function(req, res) {
    res.render('index');
});

var port = 3030;
app.listen(port);
console.log('Listening on port ' + port + '...');
</code>```

I installed all dependencies used in the server.js file (I read from a post that this was the new way of doing it as opposed to var express only as in my tutorials), I also commented out multer because I'm not sure how to use it (if I uncomment it I get an error when I run nodemon server.js), I am watching old tutorials as I have no access to modern ones at the moment, any help will be graciously appreciated, thank you.

答: replace app.use(methodOverride); with app.use(methodOverride());

Body:
I am getting the following error when request my webpage after starting the server (the server runs properly, the problem occurs when I request the page):

TypeError: str.substr is not a function at createGetter (C:\Users\mypath\node_modules\method-override\index.js:88:11)
at methodOverride (C:\Users\mypath\node_modules\method-override\index.js:50:7)
at Layer.handle [as handle_request] (C:\Users\mypath\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\mypath\node_modules\express\lib\router\index.js:312:13)
at C:\Users\mypath\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\mypath\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\mypath\node_modules\express\lib\router\index.js:271:10)
at logger (C:\Users\mypath\node_modules\morgan\index.js:144:5)
at Layer.handle [as handle_request] (C:\Users\mypath\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\mypath\node_modules\express\lib\router\index.js:312:13)

I am still learning about the MEAN stack, please bear with me, my server.js is as follows:

var express = require('express'),
favicon = require('serve-favicon'),
stylus = require('stylus'),
logger = require('morgan'),
methodOverride = require('method-override'),
session = require('express-session'),
bodyParser = require('body-parser'),
multer = require('multer'),
upload = multer({ dest: 'uploads/'}),
errorHandler = require('errorhandler');

var app = express();

function compile(src, path) {
return stylus(src).set('filename', path);
}

app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(logger('dev'));
app.use(methodOverride);
app.use(session(
    {resave: true, saveUninitialized: true,
    secret: 'uwotm8'}
));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));

//app.use(multer());
app.use(stylus.middleware(
    {
        src: __dirname + '/public',
        compile: compile
    }
));

app.use(express.static(__dirname + 'public'));
app.get('/', function(req, res) {
    res.render('index');
});

var port = 3030;
app.listen(port);
console.log('Listening on port ' + port + '...');

I installed all dependencies used in the server.js file (I read from a post that this was the new way of doing it as opposed to var express only as in my tutorials), I also commented out multer because I'm not sure how to use it (if I uncomment it I get an error when I run nodemon server.js), I am watching old tutorials as I have no access to modern ones at the moment, any help will be graciously appreciated, thank you.


问:
current location is not working in android emulator
I am following a tutorial to get my current location. I wrote exactly what the tutorial said, but i just do not get my lat/lon. I am using a wifi connection. I tried:

geo fix -77.036519 38.896143

still do not get the lat/lon. My code is as follows;

```<code>import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;

public class TestProviderController extends Activity {
 LocationManager locationManager;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String location_context=Context.LOCATION_SERVICE;
        locationManager=(LocationManager)getSystemService(location_context);
        testProvider();
    }
    public void testProvider(){
     TextView tv = (TextView)findViewById(R.id.myTextView);
     StringBuilder sb = new StringBuilder("Enabled Providers:");

     List<String> providers = locationManager.getProviders(true);

     for (String provider : providers) {

     locationManager.requestLocationUpdates(provider, 1000, 0,
     new LocationListener() {
     public void onLocationChanged(Location location) {}
     public void onProviderDisabled(String provider){}

     public void onProviderEnabled(String provider){}
     public void onStatusChanged(String provider, int status,
     Bundle extras){}
     });
     sb.append("\n").append(provider).append(":");
     Location location = locationManager.getLastKnownLocation(provider);
     if (location != null) {
     double lat = location.getLatitude();
     double lng = location.getLongitude();
     sb.append(lat).append(",").append(lng);
     } else {
     sb.append("No Location");
     }
     }
     tv.setText(sb);
    }
}
</code>```

Can anybody please help about what went wrong?

答: It can apparently take a little time to get the coordinates - here's a link to a similar question </p>

Body:
I am following a tutorial to get my current location. I wrote exactly what the tutorial said, but i just do not get my lat/lon. I am using a wifi connection. I tried:

geo fix -77.036519 38.896143

still do not get the lat/lon. My code is as follows;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;

public class TestProviderController extends Activity {
 LocationManager locationManager;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String location_context=Context.LOCATION_SERVICE;
        locationManager=(LocationManager)getSystemService(location_context);
        testProvider();
    }
    public void testProvider(){
     TextView tv = (TextView)findViewById(R.id.myTextView);
     StringBuilder sb = new StringBuilder("Enabled Providers:");

     List<String> providers = locationManager.getProviders(true);

     for (String provider : providers) {

     locationManager.requestLocationUpdates(provider, 1000, 0,
     new LocationListener() {
     public void onLocationChanged(Location location) {}
     public void onProviderDisabled(String provider){}

     public void onProviderEnabled(String provider){}
     public void onStatusChanged(String provider, int status,
     Bundle extras){}
     });
     sb.append("\n").append(provider).append(":");
     Location location = locationManager.getLastKnownLocation(provider);
     if (location != null) {
     double lat = location.getLatitude();
     double lng = location.getLongitude();
     sb.append(lat).append(",").append(lng);
     } else {
     sb.append("No Location");
     }
     }
     tv.setText(sb);
    }
}

Can anybody please help about what went wrong?


问:
Vertical align not working inside table column
I have a table with 4 cells (2 rows, 2 columns).

Inside every cell I have a table with different heights.

When I display this table I see this:

But I want them to be vertically on the top of their cell, like this:

I have tried to add this class to the external table:

```<code>.externalTable tr td  {
      vertical-align: top;
}
</code>```

or

```<code>.externalTable  {
      vertical-align: top;
}
</code>```

without success... any ideas?

答:
Make sure the td has below CSS

```<code>td {display: table-cell;}
</code>```

Body:
I have a table with 4 cells (2 rows, 2 columns).

Inside every cell I have a table with different heights.

When I display this table I see this:

But I want them to be vertically on the top of their cell, like this:

I have tried to add this class to the external table:

.externalTable tr td  {
      vertical-align: top;
}

or

.externalTable  {
      vertical-align: top;
}

without success... any ideas?

Body:
Make sure the td has below CSS

td {display: table-cell;}


问:
ASP.NET Process.Start work background in task Manger but not come on front on IIS8.5 (Windows 8.1)
i want to execute a .EXE file in mvc 3 application when we run this project locally on browser it work perfectly . Problem is that when we publish this project and host it on the IIS(8.5) server on window 8.1 when we click the button code executed and process start in Task Manger but app not shown on front .

For examples in this case we execute notepad.exe file .

Following is our code in html we make a one button when user click on that button controller method is called  that run code .

when user click on button this is cod that is executed.

```<code> $("#Button11").click(function (event) {

    $.post("/Account/Start_Appl", {}, function (data) {

    });

    event.preventDefault();
});
</code>```

and start Start_Appl Method inside Account controller have following line of code .

```<code> public string Start_Appl()
    {    string path="C:\\Windows\\System32\\notepad.exe";
         ProcessStartInfo psi = new ProcessStartInfo();
         psi.UseShellExecute = true;
         psi.LoadUserProfile = true;
         psi.WorkingDirectory = path;
         psi.FileName = path;

         Process.Start(psi);

        return "ok";

    }
</code>```

i want to execute .EXE file with iis(8.5) any solution to this problem .
i check on the internet but can not find any proper solution for this problem.

i also check this link but not give any help .

ASP.NET Process.Start not working on IIS8 (Windows 8.1)

答:
OK, first off, this is a very odd thing to do - there is going to be a better approach for whatever your problem is.  That said, what I would do in this situation is:

create a database with a JOB_QUEUE table.  exactly what is in this table is up to you, but I'd suggest an ID, a date_added, something to indicate what the job should consist of (e.g. the name of the exe to run?) and a flag to indicate the status of the job (pending/in progress/failed/completed)

modify controller to insert a record into this table with a 'pending' status (this is ALL it does)

write a separate application that runs in a user process (windows forms or console application).  this application could run on the server which hosts IIS or a separate one - all it needs it access to the same database

Make this separate application periodically check the job queue table for jobs with a pending status.

When a new job is detected, the application updates the database so the job is 'in progress' and runs the job.  if successful it updates the job to be 'completed' and if it fails it updates it to be 'failed'.

It then goes back to simply monitoring the table.

There are lots of other things you could use in place of the database for a queue, but this would be quick to write and easy to debug/test as well as making it easy to add multiple clients and persist historical info, and add controller methods to report on jobs requested/completed and progress.

Body:
i want to execute a .EXE file in mvc 3 application when we run this project locally on browser it work perfectly . Problem is that when we publish this project and host it on the IIS(8.5) server on window 8.1 when we click the button code executed and process start in Task Manger but app not shown on front .

For examples in this case we execute notepad.exe file .

Following is our code in html we make a one button when user click on that button controller method is called  that run code .

when user click on button this is cod that is executed.

 $("#Button11").click(function (event) {

    $.post("/Account/Start_Appl", {}, function (data) {

    });

    event.preventDefault();
});

and start Start_Appl Method inside Account controller have following line of code .

 public string Start_Appl()
    {    string path="C:\\Windows\\System32\\notepad.exe";
         ProcessStartInfo psi = new ProcessStartInfo();
         psi.UseShellExecute = true;
         psi.LoadUserProfile = true;
         psi.WorkingDirectory = path;
         psi.FileName = path;

         Process.Start(psi);

        return "ok";

    }

i want to execute .EXE file with iis(8.5) any solution to this problem .
i check on the internet but can not find any proper solution for this problem.

i also check this link but not give any help .

ASP.NET Process.Start not working on IIS8 (Windows 8.1)


问:
iOS app crashes upon opening when switching rotation views
I am trying to develop an app in XCode that will switch to a new view upon rotation.

Here is the code for view1controller.h:

```<code>#import UIKit/UIKit.h

@interface TestViewController : UIViewController {}

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end
</code>```

and here is the code for view1controller.m:

```<code>#import "view1controller.h"

@implementation TestViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
    {
        self.view = landscape;
    } else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
        self.view = portrait;
    }

    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@synthesize portrait,landscape;

@end
</code>```

Anyway so the app opens but it crashes upon opening.

答:
Your brackets in your header are misplaced.

```<code>@interface TestViewController : UIViewController {

    IBOutlet UIView *portrait;
    IBOutlet UIView *landscape;

}

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end
</code>```

Also, @synthesize portrait,landscape; needs to go under @implementation TestViewController

```<code>@implementation TestViewController
@synthesize portrait,landscape;
</code>```

Notice the UIView's in this image:

Body:
I am trying to develop an app in XCode that will switch to a new view upon rotation.

Here is the code for view1controller.h:

#import UIKit/UIKit.h

@interface TestViewController : UIViewController {}

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end

and here is the code for view1controller.m:

#import "view1controller.h"

@implementation TestViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
    {
        self.view = landscape;
    } else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
        self.view = portrait;
    }

    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@synthesize portrait,landscape;

@end

Anyway so the app opens but it crashes upon opening.

Body:
Your brackets in your header are misplaced.

@interface TestViewController : UIViewController {

    IBOutlet UIView *portrait;
    IBOutlet UIView *landscape;

}

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end

Also, @synthesize portrait,landscape; needs to go under @implementation TestViewController

@implementation TestViewController
@synthesize portrait,landscape;

Notice the UIView's in this image:


问:
if QString contains a number
I want to know if a string contains a '1' or '0' so I wrote this code:

```<code>    if ((input.contains('0'))||(input.contains('1'))) {
        ui->answerbox->setText(QString::number(BinToDec(number)));
    }
    else {
        ui->answerbox->setText("Error");
    }
</code>```

If I put in "014", it runs the if block but if I put "4" it runs the else block. What's wrong?

答:
Man this function BinToDec is a total disaster.

```<code>bool success;
auto value = input.toInt(&success, 2);
if (success) {
    ui->answerbox->setText(QString::number(value));
}
else {
    ui->answerbox->setText("Error");
}
</code>```

Title: if QString contains a number

Body:
I want to know if a string contains a '1' or '0' so I wrote this code:

    if ((input.contains('0'))||(input.contains('1'))) {
        ui->answerbox->setText(QString::number(BinToDec(number)));
    }
    else {
        ui->answerbox->setText("Error");
    }

If I put in "014", it runs the if block but if I put "4" it runs the else block. What's wrong?

Body:
Man this function BinToDec is a total disaster.

bool success;
auto value = input.toInt(&success, 2);
if (success) {
    ui->answerbox->setText(QString::number(value));
}
else {
    ui->answerbox->setText("Error");
}


问:
Accessing Localhost and Virtualhost From Emulator in Android Studio?
I want to access localhost from android studio emulator or from genymotion without typing the IP address instead typing as localhost or as domain name.
If you are into web development you could under stand more like we assign domain for IP in the C:\Windows\System32\drivers\etc\hosts file in windows system.
I tried out steps from some blogs but couldn't figure it out.

Please do help me out. Thanks!

答: when you type localhost on emulator, it will point to emulator itself. hosts file in android/linux machines will be under /etc/hosts. try editing the same. </p>


问:
How to return a 2D vector in C++?
```<code>vector <vector<int> > pasTriangleUsingVector(int A)
{
    vector <vector<int> > arr;
    for(int line=0;line<A;line++)
    {
        for(int i=0;i<=line;i++)
        {
            if(i==0 || line==i)
                arr[line][i]=1;
            else
                arr[line][i] = arr[line-1][i-1] + arr[line-1][i];

            //cout<<arr[line][i]<<" ";
        }
     }

     return arr;
}
</code>```

I'm trying to return a vector containing the Pascal Triangle

It's showing segmentation error

答:
The error is somehow not what you're thinking. There's nothing wrong with returning that vector. The error is about accessing that vector.

Consider your local variable definition:

```<code>vector <vector<int> > arr;
</code>```

At the beginning, arr is a vector of size 0, or an empty vector. So accessing arr[0] is out of bounds. operator[] does not perform boundary checking. It simply invokes UB if you try to access out-of-bounds with it. Now you should get it: All later access to arr are out of bounds.

To make sure there's enough space, use std::vector::resize():

```<code>vector <vector<int> > arr;
/**********/
arr.resize(A);
for(int line=0;line<A;line++)
{
    arr[line].resize(line+1);
    for(int i=0;i<=line;i++)
    {
        /* Your stuff here */
    }
 }
</code>```

Title: How to return a 2D vector in C++?

Body:
vector <vector<int> > pasTriangleUsingVector(int A)
{
    vector <vector<int> > arr;
    for(int line=0;line<A;line++)
    {
        for(int i=0;i<=line;i++)
        {
            if(i==0 || line==i)
                arr[line][i]=1;
            else
                arr[line][i] = arr[line-1][i-1] + arr[line-1][i];

            //cout<<arr[line][i]<<" ";
        }
     }

     return arr;
}

I'm trying to return a vector containing the Pascal Triangle

It's showing segmentation error

Body:
The error is somehow not what you're thinking. There's nothing wrong with returning that vector. The error is about accessing that vector.

Consider your local variable definition:

vector <vector<int> > arr;

At the beginning, arr is a vector of size 0, or an empty vector. So accessing arr[0] is out of bounds. operator[] does not perform boundary checking. It simply invokes UB if you try to access out-of-bounds with it. Now you should get it: All later access to arr are out of bounds.

To make sure there's enough space, use std::vector::resize():

vector <vector<int> > arr;
/**********/
arr.resize(A);
for(int line=0;line<A;line++)
{
    arr[line].resize(line+1);
    for(int i=0;i<=line;i++)
    {
        /* Your stuff here */
    }
 }


问:
How to invoke an Action Method in a controller at a particular time
I am in the midst of designing a Job assigning System which is to be developed using ASP.NET MVC framework. One of the requirements is to check the status of a  job (which is assigned to a job operator)  after a particular time (can be 1 hr or  2 hr from the time of job assignment ). if the status is Rejected, teh system need to send an email to Admin.

I actually have an action method in a controller which will search the database for any rejected job and if it find any , an email will be send to the Admin. The email implementation (using .Net Postal library ) is also done inside the action Method.

So my question is

1.How to invoke that particular action method from the controller at a particular time (which can be set in the past. eg: trigger 2 hr from now).

2.Is creating a batch file and assigning it to Task scheduler or windows service is feasible in this scenario THAN implementing something which will check the database directly and send email every x minutes?

答:
```<code>//Check this out for job scheduling
</code>```

// using this you can make custom jobs that will trigger automatically after some time.

//  Install package quartz

//  create a job class

```<code>using System;
using Quartz;

namespace FooBar
{
    public class LoggingJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {

            Common.Logging.LogManager.Adapter.GetLogger("LoggingJob").Info(
                string.Format("Logging job : {0} {1}, and proceeding to log",
                    DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));

        }
    }
}
</code>```

//  Now create your time activated job. Easy

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Common.Logging;

using Quartz;
using Quartz.Impl;

namespace FooBar
{
    class Program
    {

        private static ILog Log = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            try
            {
                // construct a scheduler factory
                ISchedulerFactory schedFact = new StdSchedulerFactory();

                // get a scheduler
                IScheduler sched = schedFact.GetScheduler();
                sched.Start();

                IJobDetail job = JobBuilder.Create<LoggingJob>()
                    .WithIdentity("myJob", "group1")
                    .Build();

                ITrigger trigger = TriggerBuilder.Create()
                    .WithDailyTimeIntervalSchedule
                    (s =>
                        s.WithIntervalInSeconds(10)
                            .OnEveryDay()
                            .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(10, 15))
                    )
                    .Build();

                sched.ScheduleJob(job, trigger);
            }
            catch (ArgumentException e)
            {
                Log.Error(e);
            }
        }
    }
}
</code>```

//  use this for reference
    https://www.codeproject.com/Articles/860893/Scheduling-With-Quartz-Net

Body:
//Check this out for job scheduling

// using this you can make custom jobs that will trigger automatically after some time.

//  Install package quartz

//  create a job class

using System;
using Quartz;

namespace FooBar
{
    public class LoggingJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {

            Common.Logging.LogManager.Adapter.GetLogger("LoggingJob").Info(
                string.Format("Logging job : {0} {1}, and proceeding to log",
                    DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));

        }
    }
}

//  Now create your time activated job. Easy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Common.Logging;

using Quartz;
using Quartz.Impl;

namespace FooBar
{
    class Program
    {

        private static ILog Log = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            try
            {
                // construct a scheduler factory
                ISchedulerFactory schedFact = new StdSchedulerFactory();

                // get a scheduler
                IScheduler sched = schedFact.GetScheduler();
                sched.Start();

                IJobDetail job = JobBuilder.Create<LoggingJob>()
                    .WithIdentity("myJob", "group1")
                    .Build();

                ITrigger trigger = TriggerBuilder.Create()
                    .WithDailyTimeIntervalSchedule
                    (s =>
                        s.WithIntervalInSeconds(10)
                            .OnEveryDay()
                            .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(10, 15))
                    )
                    .Build();

                sched.ScheduleJob(job, trigger);
            }
            catch (ArgumentException e)
            {
                Log.Error(e);
            }
        }
    }
}

//  use this for reference
    https://www.codeproject.com/Articles/860893/Scheduling-With-Quartz-Net


问:
Unlock iPhone X simulator
I have been having a hard time to unlock the iPhone X in simulator.When trying to unlock it says Swipe up to unlock, that's it. Nothing happens when i swipe up, any idea how to unlock ?</p>

答:
Press

```<code>Command + Shift + H.
</code>```

It will work for all the simulators.

Title: Unlock iPhone X simulator

Body:
Press

Command + Shift + H.

It will work for all the simulators.


问:
composer dump-autoload not recognized command

whenever I use composer dump-autoload  with laravel   I get this error

Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
    @php artisan package:discover 'C:\Program' is not recognized as an internal or external command, operable program or batch file. Script
    @php artisan package:discover handling the post-autoload-dump event
    returned with error code 1

I think it has something to do with "environment variables"

so my paths

```<code>C:\ProgramData\Oracle\Java\javapath;
C:\Program Files\iis express\PHP\v7.0;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\Program Files (x86)\QuickTime\QTSystem\;
C:\xampp\php;
C:\ProgramData\ComposerSetup\bin;
C:\Android;C:\Windows\System32;
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;
C:\ProgramFiles\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\Program Files\Git\cmd;
C:\Program Files (x86)\Skype\Phone\;
C:\Program Files (x86)\Brackets\command;
C:\Program Files\nodejs\;
C:\ProgramFiles\Microsoft SQL Server\130\Tools\Binn\;
C:\Program Files\dotnet\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\xampp\php;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\phpspec run;
C:\Users\ahmadz\AppData\Roaming\npm;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\kahlan
</code>```

答:
With Paul Santos answer you will only update all global packages. To update your composer installation you need to use

```<code>composer selfupdate
</code>```

Body:
whenever I use composer dump-autoload  with laravel   I get this error

Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
    @php artisan package:discover 'C:\Program' is not recognized as an internal or external command, operable program or batch file. Script
    @php artisan package:discover handling the post-autoload-dump event
    returned with error code 1

I think it has something to do with "environment variables"

so my paths

C:\ProgramData\Oracle\Java\javapath;
C:\Program Files\iis express\PHP\v7.0;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\Program Files (x86)\QuickTime\QTSystem\;
C:\xampp\php;
C:\ProgramData\ComposerSetup\bin;
C:\Android;C:\Windows\System32;
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;
C:\ProgramFiles\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\Program Files\Git\cmd;
C:\Program Files (x86)\Skype\Phone\;
C:\Program Files (x86)\Brackets\command;
C:\Program Files\nodejs\;
C:\ProgramFiles\Microsoft SQL Server\130\Tools\Binn\;
C:\Program Files\dotnet\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\xampp\php;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\phpspec run;
C:\Users\ahmadz\AppData\Roaming\npm;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\kahlan

Body:
With Paul Santos answer you will only update all global packages. To update your composer installation you need to use

composer selfupdate


问:
Pass $(this) to a function
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

```<code>    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );
</code>```

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

答:
```<code>$('a').hover(function() {
    $(this).closest('.container').find('.box').show();
}, function()  {
    $(this).closest('.container').find('.box').hide();
});
</code>```

Title: Pass $(this) to a function

Body:
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?


问:
Recursion with anagrams
I am attempting to use recursion and keep getting overflow errors. I am not sure what to do.

I want to feed one of my functions with all the anagrams but I am not sure how. I can't fit everything into one function, so I made two: one that makes the anagrams and one that searches through the dictionary to find all the matches. But it's not working, and I have no idea what else to do. And in my anagram function, I want to return back to my permutation function, but I can't without returning a string. I need it to return nothing and go back to the function.

```<code>#include <iostream>
#include <fstream>
#include <istream>
#include <string>
using namespace std;

const int MAXRESULTS = 20;    // Max matches that can be found
const int MAXDICTWORDS = 30000; // Max words that can be read in
const int MAXPERMUTATIONS = 720; //enough permutations for a 6 letter word

                                 //Beginning of assignment functions
//Read Dictionary function that uses recursion
int readDictionary(istream &, string[]);
//Permuation function
int recursivePermute(string, const string[], int, string[]);
//Print function
void recurPrint(const string[], int);
//swap characters in a string
void swap(string*, string*);
//permutation function
string Permutator(string, int, int, int);
//

//End of Assignment functions

int main()
{
    string Permutations[MAXPERMUTATIONS];
    string results[MAXRESULTS];
    string dict[MAXDICTWORDS];
    ifstream dictfile;         // file containing the list of words
    int nwords;                // number of words read from dictionary
    string word;

    dictfile.open("words.txt");
    if (!dictfile) {
        cout << "File not found!" << endl;
        return (1);
    }

    nwords = readDictionary(dictfile, dict);

    cout << "Please enter a string for an anagram: ";
    cin >> word;
    //Make all the permutations and store them in an array

    int numMatches = recursivePermute(word, dict, nwords, results);
    if (numMatches == 0)
        cout << "No matches found" << endl;
    else
         recurPrint(results, numMatches);
}
/***************************************************************************************************
Name: readDictionary
input: ifstream reference, string array
Description: This function returns the number of words added into the array from the dictionary.
****************************************************************************************************/
int readDictionary(istream &file, string DicArr[])
{
    int counter = 0;
    if (counter > MAXDICTWORDS)
        return counter;
    if (getline(file, DicArr[0]))
    {
        counter++;
        return counter += readDictionary(file, DicArr + 1);
    }
    else
        return counter;
}
/*****************************************************************************************************
Name: recursivePermute
Input: string, const string array, int, string array
Description: Places all the permutations of word, which are found in dict into results.
Returns the number of matched words found. This number should not be larger than
MAXRESULTS since that is the size of the array. The size is the number of words
inside the dict array.
*******************************************************************************************************/
int recursivePermute(string word, const string dict[], int size, string results[])
{
    //count to iterate through the dictionary array and keep in bounds
    //numresults to keep track of the number of results
    int numResults = 0;
    //if statement to if the number of results goes over the limit
    if (numResults > MAXRESULTS)
        return numResults;
    if (size == 0)
        return numResults;
    //if there is a match check the dictionary
    if (word == dict[0])
    {
        results[0] = word;
        numResults++;
    }
    numResults += recursivePermute(Permutator(word, 0, word.length() - 1, 0), dict + 1, size - 1, results);

    return numResults;
}
/*******************************************************************************************************
Name: recurPrint
Input:const string array, int
Description: Prints out the results
*********************************************************************************************************/
void recurPrint(const string results[], int size)
{
    if (size == 1)
    {
        cout << "matching word \"" << results[0] << "\" found!\n" << endl;
        return;
    }
    if (size == 0)
        return;
    cout << results[size - 1];
    recurPrint(results, size - 1);
}
/****************************************************************************************************
name: swap
input: string pointer
description: This functions swaps two characters in a string
*****************************************************************************************************/
void swap(string* a, string* b)
{
    string temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
/******************************************************************************************************
********************************************************************************************************/
string Permutator(string word, int beg, int end, int count)
{
    string a;
    if (count == end)
        return word;
    if (beg == end)
        return;

    if(count <= end)
        {
            swap(word[beg], word[count]);
            Permutator(word, beg + 1, end, count);
            swap(word[beg], word[count]);
            Permutator(word, beg, end, count + 1);
        }
}
/******************************************************************************************************
*******************************************************************************************************/
</code>```

ok, so I've narrowed down my problem. I am having issues with this function, which I am using to feed each permutation into my other function that will check each permutation against the dictionary which is an array of strings.

```<code>string Permutator(string word, int beg, int end, int count)
{
    if (count == end)
        return word;
    if (beg == end)

    if (count <= end)
    {
        swap(word[beg], word[count]);
        Permutator(word, beg + 1, end, count);
        swap(word[beg], word[count]);

    }

}
</code>```

This would work if it was void, but I need it to return a string, but when I change the return type my entire algorithm goes out of whack. The loops, which in this assignment can only be recursions, do not work as they are supposed to. I am out of ideas not sure what else I can do.

答:
std::map<std::string, std::vector<std::string>> seems appropriate:

```<code>std::vector<std::string> allWords /*= */;
std::map<std::string, std::vector<std::string>> dictionary;

for (const std::string& word : allWords) {
    auto w = word;
    std::sort(w.begin(), w.end());
    dictionary[w].push_back(word);
}
</code>```

And then

```<code>std::vector<std::string>
find_words_from_anagram(const std::map<std::string, std::vector<std::string>>& dictionary,
                        const std::string& word)
{
    auto w = word;
    std::sort(w.begin(), w.end());

    auto it = dictionary.find(w);
    if (it == dictionary.end()) {
        return {}; // No match.
    }
    return it->second;
}
</code>```

Trick is to normalize entry instead of checking for all permutations.

Title: Recursion with anagrams

Body:
I am attempting to use recursion and keep getting overflow errors. I am not sure what to do.

I want to feed one of my functions with all the anagrams but I am not sure how. I can't fit everything into one function, so I made two: one that makes the anagrams and one that searches through the dictionary to find all the matches. But it's not working, and I have no idea what else to do. And in my anagram function, I want to return back to my permutation function, but I can't without returning a string. I need it to return nothing and go back to the function.

#include <iostream>
#include <fstream>
#include <istream>
#include <string>
using namespace std;

const int MAXRESULTS = 20;    // Max matches that can be found
const int MAXDICTWORDS = 30000; // Max words that can be read in
const int MAXPERMUTATIONS = 720; //enough permutations for a 6 letter word

                                 //Beginning of assignment functions
//Read Dictionary function that uses recursion
int readDictionary(istream &, string[]);
//Permuation function
int recursivePermute(string, const string[], int, string[]);
//Print function
void recurPrint(const string[], int);
//swap characters in a string
void swap(string*, string*);
//permutation function
string Permutator(string, int, int, int);
//

//End of Assignment functions

int main()
{
    string Permutations[MAXPERMUTATIONS];
    string results[MAXRESULTS];
    string dict[MAXDICTWORDS];
    ifstream dictfile;         // file containing the list of words
    int nwords;                // number of words read from dictionary
    string word;

    dictfile.open("words.txt");
    if (!dictfile) {
        cout << "File not found!" << endl;
        return (1);
    }

    nwords = readDictionary(dictfile, dict);

    cout << "Please enter a string for an anagram: ";
    cin >> word;
    //Make all the permutations and store them in an array

    int numMatches = recursivePermute(word, dict, nwords, results);
    if (numMatches == 0)
        cout << "No matches found" << endl;
    else
         recurPrint(results, numMatches);
}
/***************************************************************************************************
Name: readDictionary
input: ifstream reference, string array
Description: This function returns the number of words added into the array from the dictionary.
****************************************************************************************************/
int readDictionary(istream &file, string DicArr[])
{
    int counter = 0;
    if (counter > MAXDICTWORDS)
        return counter;
    if (getline(file, DicArr[0]))
    {
        counter++;
        return counter += readDictionary(file, DicArr + 1);
    }
    else
        return counter;
}
/*****************************************************************************************************
Name: recursivePermute
Input: string, const string array, int, string array
Description: Places all the permutations of word, which are found in dict into results.
Returns the number of matched words found. This number should not be larger than
MAXRESULTS since that is the size of the array. The size is the number of words
inside the dict array.
*******************************************************************************************************/
int recursivePermute(string word, const string dict[], int size, string results[])
{
    //count to iterate through the dictionary array and keep in bounds
    //numresults to keep track of the number of results
    int numResults = 0;
    //if statement to if the number of results goes over the limit
    if (numResults > MAXRESULTS)
        return numResults;
    if (size == 0)
        return numResults;
    //if there is a match check the dictionary
    if (word == dict[0])
    {
        results[0] = word;
        numResults++;
    }
    numResults += recursivePermute(Permutator(word, 0, word.length() - 1, 0), dict + 1, size - 1, results);

    return numResults;
}
/*******************************************************************************************************
Name: recurPrint
Input:const string array, int
Description: Prints out the results
*********************************************************************************************************/
void recurPrint(const string results[], int size)
{
    if (size == 1)
    {
        cout << "matching word \"" << results[0] << "\" found!\n" << endl;
        return;
    }
    if (size == 0)
        return;
    cout << results[size - 1];
    recurPrint(results, size - 1);
}
/****************************************************************************************************
name: swap
input: string pointer
description: This functions swaps two characters in a string
*****************************************************************************************************/
void swap(string* a, string* b)
{
    string temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
/******************************************************************************************************
********************************************************************************************************/
string Permutator(string word, int beg, int end, int count)
{
    string a;
    if (count == end)
        return word;
    if (beg == end)
        return;

    if(count <= end)
        {
            swap(word[beg], word[count]);
            Permutator(word, beg + 1, end, count);
            swap(word[beg], word[count]);
            Permutator(word, beg, end, count + 1);
        }
}
/******************************************************************************************************
*******************************************************************************************************/

ok, so I've narrowed down my problem. I am having issues with this function, which I am using to feed each permutation into my other function that will check each permutation against the dictionary which is an array of strings.

string Permutator(string word, int beg, int end, int count)
{
    if (count == end)
        return word;
    if (beg == end)

    if (count <= end)
    {
        swap(word[beg], word[count]);
        Permutator(word, beg + 1, end, count);
        swap(word[beg], word[count]);

    }

}

This would work if it was void, but I need it to return a string, but when I change the return type my entire algorithm goes out of whack. The loops, which in this assignment can only be recursions, do not work as they are supposed to. I am out of ideas not sure what else I can do.

Body:
std::map<std::string, std::vector<std::string>> seems appropriate:

std::vector<std::string> allWords /*= */;
std::map<std::string, std::vector<std::string>> dictionary;

for (const std::string& word : allWords) {
    auto w = word;
    std::sort(w.begin(), w.end());
    dictionary[w].push_back(word);
}

And then

std::vector<std::string>
find_words_from_anagram(const std::map<std::string, std::vector<std::string>>& dictionary,
                        const std::string& word)
{
    auto w = word;
    std::sort(w.begin(), w.end());

    auto it = dictionary.find(w);
    if (it == dictionary.end()) {
        return {}; // No match.
    }
    return it->second;
}

Trick is to normalize entry instead of checking for all permutations.


问:
QML Repeater and QML Grid Layout with variable number of columns
I have an model that consist of objects with some properties, e.g.:

```<code>ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        color: "green"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        color: "orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        color: "yellow"
        cost: 1.95
    }
}
</code>```

And now I want to display this model using GridLayout. For each property I want to use one element inside GridLayout, e.g:

```<code>GridLayout {
    columns: 3

    Text { text: "Apple" }
    Rectangle { color: "green" }
    SpinBox { value: 2.45 }

    Text { text: "Orange" }
    Rectangle { color: "orange" }
    SpinBox { value: 3.25 }

    Text { text: "Banana" }
    Rectangle { color: "yellow" }
    SpinBox { value: 1.95 }
}
</code>```

The point is that I can easily change the columns property of GridLayout and make my layout narrower (e.g. to fit small screens). I can use Repeater to fill GridLayout. However such approach will fill my GridLayout in wrong order:

```<code>GridLayout {
    columns: 3

    Repeater {
        model: fruitModel
        Text { text: name }
    }

    Repeater {
        model: fruitModel
        Rectangle { color: color }
    }

    Repeater {
        model: fruitModel
        SpinBox { value: value }
    }
}
</code>```

And it is waste to use Layout.column and Layout.row attached properties since I want to easily change number of columns in GridLayout.

Is there any way to fill GridLayout with data from model row by row?

UPD1:

Behaviour that I want to get:

```<code>GridLayout {
    columns: parent.width > 235 ? 3 : 1

    Text { text: "Apple" }
    Rectangle { color: "green"; width: 40; height: 40 }
    SpinBox { value: 2 }

    Text { text: "Orange" }
    Rectangle { color: "orange"; width: 40; height: 40 }
    SpinBox { value: 3 }

    Text { text: "Banana" }
    Rectangle { color: "yellow"; width: 40; height: 40 }
    SpinBox { value: 1 }
}
</code>```

UPD2:
Modified variant from @m7913d:

```<code>GridLayout {
    id: layout
    property int maxColumns: 3
    columns: parent.width > 235 ? maxColumns : 1

    Repeater {
        model: fruitModel
        Text {
            text: name
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index)
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            Layout.preferredWidth: 30
            Layout.preferredHeight: 30
            color: col
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 1)
            Layout.column: layout.columns == maxColumns ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: val
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 2)
            Layout.column: layout.columns == maxColumns ? 2 : 0
        }
    }
}
</code>```

It's working but not easy-to-modify solution plus sometimes during layout resize there is messages QGridLayoutEngine::addItem: Cell (1, 0) already taken.

答:
I would use a Column filled by either Rows or Columns (or any other arrangement) as delegates.

```<code>Column {
    id: rootCol
    anchors.fill: parent
    Repeater {
        model: fruitModel
        delegate: rootCol.width > 300 ? rowDel : colDel
    }

    Component {
        id: rowDel
        Row {
            Text { width: 100; height: 50; text: model.name }
            Rectangle { width: 50; height: 50; color: model.color }
            SpinBox { width: 150; height: 50; value: model.cost }
        }
    }

    Component {
        id: colDel
        Column {
            Text { width: 100; height: 50; text: model.name }
            Rectangle { width: 50; height: 50; color: model.color }
            SpinBox { width: 150; height: 50; value: model.cost}
        }
    }
}
</code>```

Or maybe:

```<code>Column {
    id: rootCol
    anchors.fill: parent
    Repeater {
        model: fruitModel
        delegate: Flow {
            anchors {
                left: parent.left
                right: parent.right
            }

            Text { width: 100; height: 50; text: model.name }
            Rectangle { width: 50; height: 50; color: model.color }
            SpinBox { width: 150; height: 50; value: model.value }
        }
    }
}
</code>```

Body:
I have an model that consist of objects with some properties, e.g.:

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        color: "green"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        color: "orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        color: "yellow"
        cost: 1.95
    }
}

And now I want to display this model using GridLayout. For each property I want to use one element inside GridLayout, e.g:

GridLayout {
    columns: 3

    Text { text: "Apple" }
    Rectangle { color: "green" }
    SpinBox { value: 2.45 }

    Text { text: "Orange" }
    Rectangle { color: "orange" }
    SpinBox { value: 3.25 }

    Text { text: "Banana" }
    Rectangle { color: "yellow" }
    SpinBox { value: 1.95 }
}

The point is that I can easily change the columns property of GridLayout and make my layout narrower (e.g. to fit small screens). I can use Repeater to fill GridLayout. However such approach will fill my GridLayout in wrong order:

GridLayout {
    columns: 3

    Repeater {
        model: fruitModel
        Text { text: name }
    }

    Repeater {
        model: fruitModel
        Rectangle { color: color }
    }

    Repeater {
        model: fruitModel
        SpinBox { value: value }
    }
}

And it is waste to use Layout.column and Layout.row attached properties since I want to easily change number of columns in GridLayout.

Is there any way to fill GridLayout with data from model row by row?

UPD1:

Behaviour that I want to get:

GridLayout {
    columns: parent.width > 235 ? 3 : 1

    Text { text: "Apple" }
    Rectangle { color: "green"; width: 40; height: 40 }
    SpinBox { value: 2 }

    Text { text: "Orange" }
    Rectangle { color: "orange"; width: 40; height: 40 }
    SpinBox { value: 3 }

    Text { text: "Banana" }
    Rectangle { color: "yellow"; width: 40; height: 40 }
    SpinBox { value: 1 }
}

UPD2:
Modified variant from @m7913d:

GridLayout {
    id: layout
    property int maxColumns: 3
    columns: parent.width > 235 ? maxColumns : 1

    Repeater {
        model: fruitModel
        Text {
            text: name
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index)
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            Layout.preferredWidth: 30
            Layout.preferredHeight: 30
            color: col
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 1)
            Layout.column: layout.columns == maxColumns ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: val
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 2)
            Layout.column: layout.columns == maxColumns ? 2 : 0
        }
    }
}

It's working but not easy-to-modify solution plus sometimes during layout resize there is messages QGridLayoutEngine::addItem: Cell (1, 0) already taken.

Body:
I would use a Column filled by either Rows or Columns (or any other arrangement) as delegates.

Column {
    id: rootCol
    anchors.fill: parent
    Repeater {
        model: fruitModel
        delegate: rootCol.width > 300 ? rowDel : colDel
    }

    Component {
        id: rowDel
        Row {
            Text { width: 100; height: 50; text: model.name }
            Rectangle { width: 50; height: 50; color: model.color }
            SpinBox { width: 150; height: 50; value: model.cost }
        }
    }

    Component {
        id: colDel
        Column {
            Text { width: 100; height: 50; text: model.name }
            Rectangle { width: 50; height: 50; color: model.color }
            SpinBox { width: 150; height: 50; value: model.cost}
        }
    }
}

Or maybe:

Column {
    id: rootCol
    anchors.fill: parent
    Repeater {
        model: fruitModel
        delegate: Flow {
            anchors {
                left: parent.left
                right: parent.right
            }

            Text { width: 100; height: 50; text: model.name }
            Rectangle { width: 50; height: 50; color: model.color }
            SpinBox { width: 150; height: 50; value: model.value }
        }
    }
}


问:
When you uploaded an APK that is not signed with the upload certificate; do you have to use the same certificate?
I am using Android Studio and am trying to build a signed apk.
I am building a signed apk using the following steps:
Module -->app
KeyStorePath--> /Users/mshikher/Documents/SchoolCounter/app/Untitled
(SchoolCounter is name of the project).
After entering the keyStorePassword and keyPassword clicked NEXT.
Clicking on both the V1 and V2 versions clicked on Finish.
There was earlier an apk uploaded in the play.console by some other person, and now if I try to upload my apk into the production release I get this error.

```<code>You uploaded an APK that is not signed with the upload certificate. You must use the same certificate. The upload certificate has fingerprint:
[ SHA1: AA:6F:D6:9E:72:B7:9B:C6:45:63:70:69:66:B4:DA:9B:72:6D:3D:23 ]
and the certificate used to sign the APK you uploaded have fingerprint:
[ SHA1: 88:5D:A7:91:A9:5B:2C:66:DD:ED:13:96:37:49:D6:B7:4D:1E:B0:09 ]
You need to use a different version code for your APK because you already have one with version code 1.
</code>```

I have changed the version number also in the build.gradle file:

```<code>versionName "2.0"
</code>```

What should I do to upload my apk in the play.google.com ?

答:
This happens when you sign your apk with different Keystore.

You need to use the same keystore for all version you upload on playstore. Please sign your apk with the same keystore you have used to publish the last apk.

For more information please check this link : https://developer.android.com/studio/publish/app-signing.html

Body:
I am using Android Studio and am trying to build a signed apk.
I am building a signed apk using the following steps:
Module -->app
KeyStorePath--> /Users/mshikher/Documents/SchoolCounter/app/Untitled
(SchoolCounter is name of the project).
After entering the keyStorePassword and keyPassword clicked NEXT.
Clicking on both the V1 and V2 versions clicked on Finish.
There was earlier an apk uploaded in the play.console by some other person, and now if I try to upload my apk into the production release I get this error.

You uploaded an APK that is not signed with the upload certificate. You must use the same certificate. The upload certificate has fingerprint:
[ SHA1: AA:6F:D6:9E:72:B7:9B:C6:45:63:70:69:66:B4:DA:9B:72:6D:3D:23 ]
and the certificate used to sign the APK you uploaded have fingerprint:
[ SHA1: 88:5D:A7:91:A9:5B:2C:66:DD:ED:13:96:37:49:D6:B7:4D:1E:B0:09 ]
You need to use a different version code for your APK because you already have one with version code 1.

I have changed the version number also in the build.gradle file:

versionName "2.0"

What should I do to upload my apk in the play.google.com ?


问:
Parse JSON with mixed known/unknown fields in JAVA
I have simple JSON structure with known fields (A and B for example, typed as String) and some number of unknown fields (foo and bar, and maybe something other, or none of them, type unknown).

```<code>[
    {"A": "Value for A", B: "Value for B", "foo": "foo"},
    {"A": "Value for A", B: "Value for B", "bar": 13},
    {"A": "Value for A", B: "Value for B", "foo": "foo", "val": true}
]
</code>```

I need to parse this JSON to POJO.
Jackson allows to parse this JSON to JsonNode, but JsonNode eats too much memory on huge amount of data.
Is there any solution to do that? I need to get instance of class like this:

```<code>class Simple
{
    public String A;
    public String B;
    public HashMap others;
}
</code>```

答:
You can use POJO with <code>@JsonAnySetter</code> method annotation. And you can actually even perform computations/optimisations in this method if you need them. </p>

```<code>public class Simple {
    private String A;
    private String B;
    private Map other = new HashMap<String,Object>();

    // "any getter" needed for serialization
    @JsonAnyGetter
    public Map any() {
        return other;
    }

    // "any setter" needed for deserialization
    @JsonAnySetter
    public void set(String name, Object value) {
        other.put(name, value);
    }

    // getter and setter for A and B
}
</code>```

Body:
I have simple JSON structure with known fields (A and B for example, typed as String) and some number of unknown fields (foo and bar, and maybe something other, or none of them, type unknown).

[
    {"A": "Value for A", B: "Value for B", "foo": "foo"},
    {"A": "Value for A", B: "Value for B", "bar": 13},
    {"A": "Value for A", B: "Value for B", "foo": "foo", "val": true}
]

I need to parse this JSON to POJO.
Jackson allows to parse this JSON to JsonNode, but JsonNode eats too much memory on huge amount of data.
Is there any solution to do that? I need to get instance of class like this:

class Simple
{
    public String A;
    public String B;
    public HashMap others;
}

Body:
You can use POJO with @JsonAnySetter method annotation. And you can actually even perform computations/optimisations in this method if you need them.

public class Simple {
    private String A;
    private String B;
    private Map other = new HashMap<String,Object>();

    // "any getter" needed for serialization
    @JsonAnyGetter
    public Map any() {
        return other;
    }

    // "any setter" needed for deserialization
    @JsonAnySetter
    public void set(String name, Object value) {
        other.put(name, value);
    }

    // getter and setter for A and B
}


问:
How can I allow visitors to place marks on a diagram using Bootstrap?
I am working on a new XPages application (on a Domino server) that uses the Bootstrap framework to present a responsive web page. Most of the work I'm doing is pretty basic, and I've used the techniques before.

However, the application calls for a facility whereby the visitor has the ability to place marks on a fixed image. For instance, on an motor vehicle accident claim form, the claimant is asked to indicate on a diagram where the damage occurred...

I'd like to present a static image, and allow visitors to place indicators ontop of that image. I'd then like to save the resulting image somehow. If I can't save a consolidated image, I'd like the ability to save the coordinates of the visitor's indicators so that I can simulate the same marked-up diagram in the back end.

Is there a plug-in or documented technique somewhere that I can use to accomplish this, or shall I attempt to 'roll my own'? I haven't been able to find anything that accomplishes something like this.

Thanks in advance for any advice on this one!!

答:
Open the image in a canvas and let the user draw on the canvas. After this save the new image back to Domino.
http://www.xpagedeveloper.com/category/canvas-element</p>