问:
assign executables to specific coordinates in MPI Cartesian topology
I want to assign every executable to specific coordinates in Cartesian
topology. Please consider an example and a Makefile. I compile executables
main[0-7] and run them using a command:

```<code>mpiexec \
-np 1 ./main0 : -np 1 ./main1 : \
-np 1 ./main2 : -np 1 ./main3 : \
-np 1 ./main4 : -np 1 ./main5 : \
-np 1 ./main6 : -np 1 ./main7
</code>```

If I sort the output make run | sort -g it always returns:

```<code>N, rank, coords[3]: 0 0   0 0 0
N, rank, coords[3]: 1 1   0 0 1
N, rank, coords[3]: 2 2   0 1 0
N, rank, coords[3]: 3 3   0 1 1
N, rank, coords[3]: 4 4   1 0 0
N, rank, coords[3]: 5 5   1 0 1
N, rank, coords[3]: 6 6   1 1 0
N, rank, coords[3]: 7 7   1 1 1
</code>```

Here N is an id of an executable. It seems work as I want: main0
goes to coordinates (0, 0, 0), main1 goes to coordinates (0, 0, 1) and
so on. Does the standard fix this arrangment?

Makefile

```<code>all: main0 main1 main2 main3 main4 main5 main6 main7

cc=mpicc
main0: main.c; $(cc) -DN=0 $< -o $@
main1: main.c; $(cc) -DN=1 $< -o $@
main2: main.c; $(cc) -DN=2 $< -o $@
main3: main.c; $(cc) -DN=3 $< -o $@
main4: main.c; $(cc) -DN=4 $< -o $@
main5: main.c; $(cc) -DN=5 $< -o $@
main6: main.c; $(cc) -DN=6 $< -o $@
main7: main.c; $(cc) -DN=7 $< -o $@

run: all
    mpiexec \
    -np 1 ./main0 : -np 1 ./main1 : \
    -np 1 ./main2 : -np 1 ./main3 : \
    -np 1 ./main4 : -np 1 ./main5 : \
    -np 1 ./main6 : -np 1 ./main7

clean:; rm -f main[0-7]
</code>```

main.c

```<code>#include <stdio.h>
#include <mpi.h>

#define ndims 3
int rank, coords[ndims];
int    dims[ndims] = {2, 2, 2};
int periods[ndims] = {0, 0, 0};
int reorder = 0;
MPI_Comm cart;

int main(int argc, char *argv[]) {
  MPI_Init(&argc, &argv);
  MPI_Cart_create(MPI_COMM_WORLD, ndims, dims, periods, reorder,   &cart);

  MPI_Comm_rank(cart,   &rank);
  MPI_Cart_coords(cart, rank, ndims,   coords);
  printf("N, rank, coords[3]: %d %d   %d %d %d\n", N, rank, coords[0], coords[1], coords[2]);

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

答:
Does the standard fix this arrangment?

Yes.

If you use mpiexec1 with the following form:

```<code>mpiexec { <above arguments> } : { ... } : { ... } : ... : { ... }
</code>```

8.8 Portable MPI Process Startup says it corresponds to MPI_COMM_SPAWN_MULTIPLE.

In turn,

Their ranks in MPI_COMM_WORLD correspond directly to the order in which the commands are specified in MPI_COMM_SPAWN_MULTIPLE. Assume that m1 processes are generated by the first command, m2 by the second, etc. The processes corresponding to the first command have ranks 0, 1, . . . , m1 −1. The processes in the second command have ranks m1 , m1 +1, . . . , m1 + m2 − 1. The processes in the third have ranks m1 + m2 , m1 + m2 + 1, . . . , m1 + m2 + m3 − 1, etc.

That gives you a consistent mapping from command line to MPI_COMM_WORLD rank. 7.2 Virtual Topologies then gives you the mapping to the coordinates:

Process coordinates in a Cartesian structure begin their numbering at 0. Row-major numbering is always used for the processes in a Cartesian structure.

That said, the approach of compiling a different binary for each rank that just differs by one macro seems silly and not quite elegant.

1: The sepcifications only apply to mpiexec, not mpirun. MPI implementations are not required to provide mpiexec.

Body:
I want to assign every executable to specific coordinates in Cartesian
topology. Please consider an example and a Makefile. I compile executables
main[0-7] and run them using a command:

mpiexec \
-np 1 ./main0 : -np 1 ./main1 : \
-np 1 ./main2 : -np 1 ./main3 : \
-np 1 ./main4 : -np 1 ./main5 : \
-np 1 ./main6 : -np 1 ./main7

If I sort the output make run | sort -g it always returns:

N, rank, coords[3]: 0 0   0 0 0
N, rank, coords[3]: 1 1   0 0 1
N, rank, coords[3]: 2 2   0 1 0
N, rank, coords[3]: 3 3   0 1 1
N, rank, coords[3]: 4 4   1 0 0
N, rank, coords[3]: 5 5   1 0 1
N, rank, coords[3]: 6 6   1 1 0
N, rank, coords[3]: 7 7   1 1 1

Here N is an id of an executable. It seems work as I want: main0
goes to coordinates (0, 0, 0), main1 goes to coordinates (0, 0, 1) and
so on. Does the standard fix this arrangment?

Makefile

all: main0 main1 main2 main3 main4 main5 main6 main7

cc=mpicc
main0: main.c; $(cc) -DN=0 $< -o $@
main1: main.c; $(cc) -DN=1 $< -o $@
main2: main.c; $(cc) -DN=2 $< -o $@
main3: main.c; $(cc) -DN=3 $< -o $@
main4: main.c; $(cc) -DN=4 $< -o $@
main5: main.c; $(cc) -DN=5 $< -o $@
main6: main.c; $(cc) -DN=6 $< -o $@
main7: main.c; $(cc) -DN=7 $< -o $@

run: all
    mpiexec \
    -np 1 ./main0 : -np 1 ./main1 : \
    -np 1 ./main2 : -np 1 ./main3 : \
    -np 1 ./main4 : -np 1 ./main5 : \
    -np 1 ./main6 : -np 1 ./main7

clean:; rm -f main[0-7]

main.c

#include <stdio.h>
#include <mpi.h>

#define ndims 3
int rank, coords[ndims];
int    dims[ndims] = {2, 2, 2};
int periods[ndims] = {0, 0, 0};
int reorder = 0;
MPI_Comm cart;

int main(int argc, char *argv[]) {
  MPI_Init(&argc, &argv);
  MPI_Cart_create(MPI_COMM_WORLD, ndims, dims, periods, reorder,   &cart);

  MPI_Comm_rank(cart,   &rank);
  MPI_Cart_coords(cart, rank, ndims,   coords);
  printf("N, rank, coords[3]: %d %d   %d %d %d\n", N, rank, coords[0], coords[1], coords[2]);

  MPI_Finalize();
}

Body:
Does the standard fix this arrangment?

Yes.

If you use mpiexec1 with the following form:

mpiexec { <above arguments> } : { ... } : { ... } : ... : { ... }

8.8 Portable MPI Process Startup says it corresponds to MPI_COMM_SPAWN_MULTIPLE.

In turn,

Their ranks in MPI_COMM_WORLD correspond directly to the order in which the commands are specified in MPI_COMM_SPAWN_MULTIPLE. Assume that m1 processes are generated by the first command, m2 by the second, etc. The processes corresponding to the first command have ranks 0, 1, . . . , m1 −1. The processes in the second command have ranks m1 , m1 +1, . . . , m1 + m2 − 1. The processes in the third have ranks m1 + m2 , m1 + m2 + 1, . . . , m1 + m2 + m3 − 1, etc.

That gives you a consistent mapping from command line to MPI_COMM_WORLD rank. 7.2 Virtual Topologies then gives you the mapping to the coordinates:

Process coordinates in a Cartesian structure begin their numbering at 0. Row-major numbering is always used for the processes in a Cartesian structure.

That said, the approach of compiling a different binary for each rank that just differs by one macro seems silly and not quite elegant.

1: The sepcifications only apply to mpiexec, not mpirun. MPI implementations are not required to provide mpiexec.


来源: stackexchange

问:
opencart 2.3 install() method not working
I have a payment plugin which is working fine on opencart 2.0 , I tried to install it on opencart 2.3 everything works fine but there is piece of code written in the install() method .. but its not working on opencart 2.3.

I tried to dump in it, but nothing happen, it seems opencart2.3 is not calling my install() method at all.

Additional Information :
The plugin name is Payfort and its on github https://github.com/payfort/opencart2.0-payfort
The plugin is working on both versions 2.0 & 2.3

答:
In OpenCart 2.3.0.2 the install method of class ControllerExtensionExtensionPayment (placed in: admin/controller/extension/extension/payment.php) is called when a payment extension is installed.

In this method the install method of the payment's controller is called:

```<code>// Call install method if it exsits
$this->load->controller('extension/payment/' . $this->request->get['extension'] . '/install');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In OpenCart 2.3.0.2 the install method of class ControllerExtensionExtensionPayment (placed in: admin/controller/extension/extension/payment.php) is called when a payment extension is installed.

In this method the install method of the payment's controller is called:

// Call install method if it exsits
$this->load->controller('extension/payment/' . $this->request->get['extension'] . '/install');


问:
ListView keeps repeating/showing same text because of timer
I'm making a program to send data true USB. In my program I'm making a list view to show what the program is currently doing.
because I'm working with USB I have a timer with a interval of 50, this causes problems when I want to send text to my list view because my text is send 50 times per second in stead of 1 time.

Anyone any idea how to solve this?
Changing my program so when a text is already written in the listbox the program may not send it again is not an option I think because the same action can happen more than 1 time.

Here you can find relevant code.

```<code>    private void ClickMyRadioButton1()
    {
        if (radioOff1.Checked)
        {
            radioOff1.PerformClick();
            ListViewItem lvi = new ListViewItem("All USB's are off");
            listView1.Items.Add(lvi);
        }
    }

    private void tmrUSB_Tick(object sender, EventArgs e)
    {
        //Everything in here is repeated constantly
        USBObject.receiveViaUSB();
        listView1.EnsureVisible(listView1.Items.Count - 1);
        if ( tabPage1 == tabControl1.SelectedTab)
        {
            this.radioOff2.Checked = true;

            if (radioOff1.Checked == true)
            {
                USBObject.fromHostToDeviceBuffer[1] = USB_OFF;
                ClickMyRadioButton1(); //This is what I only want to send one time to my ListBox and not 50 times a second
            }
      }
</code>```

I'm using Visual C# 2010.

Thanks

答:
try this, let me know if it works for you:</p>

```<code>    private void ClickMyRadioButton1()
    {
        if (radioOff1.Checked)
        {
            radioOff1.PerformClick();
            ListViewItem lvi = new ListViewItem("All USB's are off");
            listView1.Items.Add(lvi);
        }
    }

    int counter = 0;

    private void tmrUSB_Tick(object sender, EventArgs e)
    {
        if (counter != 50)
        {
           counter++;
           return;
        }
        else
        {
            counter = 0;
        }

        //Everything in here is repeated constantly
        USBObject.receiveViaUSB();
        listView1.EnsureVisible(listView1.Items.Count - 1);
        if ( tabPage1 == tabControl1.SelectedTab)
        {
            this.radioOff2.Checked = true;

            if (radioOff1.Checked == true)
            {
                USBObject.fromHostToDeviceBuffer[1] = USB_OFF;
                ClickMyRadioButton1(); //This is what I only want to send one tine to my ListBox
            }
      }
</code>```

Body:
I'm making a program to send data true USB. In my program I'm making a list view to show what the program is currently doing.
because I'm working with USB I have a timer with a interval of 50, this causes problems when I want to send text to my list view because my text is send 50 times per second in stead of 1 time.

Anyone any idea how to solve this?
Changing my program so when a text is already written in the listbox the program may not send it again is not an option I think because the same action can happen more than 1 time.

Here you can find relevant code.

    private void ClickMyRadioButton1()
    {
        if (radioOff1.Checked)
        {
            radioOff1.PerformClick();
            ListViewItem lvi = new ListViewItem("All USB's are off");
            listView1.Items.Add(lvi);
        }
    }

    private void tmrUSB_Tick(object sender, EventArgs e)
    {
        //Everything in here is repeated constantly
        USBObject.receiveViaUSB();
        listView1.EnsureVisible(listView1.Items.Count - 1);
        if ( tabPage1 == tabControl1.SelectedTab)
        {
            this.radioOff2.Checked = true;

            if (radioOff1.Checked == true)
            {
                USBObject.fromHostToDeviceBuffer[1] = USB_OFF;
                ClickMyRadioButton1(); //This is what I only want to send one time to my ListBox and not 50 times a second
            }
      }

I'm using Visual C# 2010.

Thanks

Body:
try this, let me know if it works for you:

    private void ClickMyRadioButton1()
    {
        if (radioOff1.Checked)
        {
            radioOff1.PerformClick();
            ListViewItem lvi = new ListViewItem("All USB's are off");
            listView1.Items.Add(lvi);
        }
    }

    int counter = 0;

    private void tmrUSB_Tick(object sender, EventArgs e)
    {
        if (counter != 50)
        {
           counter++;
           return;
        }
        else
        {
            counter = 0;
        }

        //Everything in here is repeated constantly
        USBObject.receiveViaUSB();
        listView1.EnsureVisible(listView1.Items.Count - 1);
        if ( tabPage1 == tabControl1.SelectedTab)
        {
            this.radioOff2.Checked = true;

            if (radioOff1.Checked == true)
            {
                USBObject.fromHostToDeviceBuffer[1] = USB_OFF;
                ClickMyRadioButton1(); //This is what I only want to send one tine to my ListBox
            }
      }


问:
Convert CSV to XML when CSV contains both character and number data
From this thread, I got the basic info on how to parse CSV to create XML. Unfortunately, the text fields (all enclosed in quotes) sometimes contain commas, so line.split(',') gives me too many columns. I can't figure out how to parse the CSV so line.split(',') distinguishes between commas within a text field, and commas separating fields. Any thoughts on how to do that?

Thanks!

答: What about using the pipe character "|"?  This often happens with CSV files and a better approach is to seperate on pipes.</p>

ContentLicense: CC BY-SA 2.5


问:
angular 2 share array through service
hello guys I am trying to share an array in Angular 2 trough a service from component 1 to component 2 but instead I get nothing here is my code

My Service

```<code>private employeeIdList = new Subject<any>();
employeeIdList$ = this.employeeIdList.asObservable();

public setEmployeeList(employeeIdList){
    this.employeeIdList.next(employeeIdList);
}
</code>```

From component 1 I am trying to do this:

```<code>this.sharedService.setEmployeeList(this.employeeId);
</code>```

this.employeId is an array of elements

and when I try to access it like this

```<code>this.sharedService.employeeIdList$.subscribe(employeeList => {
  console.log(employeeList);
})
</code>```

I get nothing, can you help me out to figure this out

thank you guys

答:
I assume it's a timing issue that the event gets emitted before the receiver was able to subscribe. To work around use BehaviorSubject or ReplaySubject

```<code>private employeeIdList = new BehaviorSubject<any>();
</code>```

Another possible cause is that you provided the service at more than one place which might cause you to get more than one instance where one is emitting the event but the receiver is subscribing to another instance.

Title: angular 2 share array through service

Body:
hello guys I am trying to share an array in Angular 2 trough a service from component 1 to component 2 but instead I get nothing here is my code

My Service

private employeeIdList = new Subject<any>();
employeeIdList$ = this.employeeIdList.asObservable();

public setEmployeeList(employeeIdList){
    this.employeeIdList.next(employeeIdList);
}

From component 1 I am trying to do this:

this.sharedService.setEmployeeList(this.employeeId);

this.employeId is an array of elements

and when I try to access it like this

this.sharedService.employeeIdList$.subscribe(employeeList => {
  console.log(employeeList);
})

I get nothing, can you help me out to figure this out

thank you guys

Body:
I assume it's a timing issue that the event gets emitted before the receiver was able to subscribe. To work around use BehaviorSubject or ReplaySubject

private employeeIdList = new BehaviorSubject<any>();

Another possible cause is that you provided the service at more than one place which might cause you to get more than one instance where one is emitting the event but the receiver is subscribing to another instance.


问:
Why does PSeq.map with computation expression seem to hang?
I'm writing a scraper using FSharp.Collections.ParallelSeq and a retry computation. I would like to retrieve HTML from multiple pages in parallel, and I would like to retry requests when they fail.

For example:

```<code>open System
open FSharp.Collections.ParallelSeq

type RetryBuilder(max) =
  member x.Return(a) = a               // Enable 'return'
  member x.Delay(f) = f                // Gets wrapped body and returns it (as it is)
                                       // so that the body is passed to 'Run'
  member x.Zero() = failwith "Zero"    // Support if .. then
  member x.Run(f) =                    // Gets function created by 'Delay'
    let rec loop(n) =
      if n = 0 then failwith "Failed"  // Number of retries exceeded
      else try f() with _ -> loop(n-1)
    loop max

let retry = RetryBuilder(4)

let getHtml (url : string) = retry {
    Console.WriteLine("Get Url")
    return 0;
}

//A property/field?
let GetHtmlForAllPages =
    let pages = {1 .. 10}
    let allHtml = pages |> PSeq.map(fun x -> getHtml("http://somesite.com/" + x.ToString())) |> Seq.toArray
    allHtml

[<EntryPoint>]
let main argv =
    let htmlForAllPages = GetHtmlForAllPages
    0 // return an integer exit code
</code>```

When I try to interact with GetHtmlForAllPages from main the code seems to hang. Stepping through the code shows me that PSeq.map begins work on the first four values of pages.

What's going on that causes the retry computation expression to never start/complete? Is there some weird interplay between PSeq and retry?

The code works as expected if I make GetHtmlForAllPages a function and invoke it. I'm curious what's going on when GetHtmlForAllPages is a field?

答:
Looks like you're deadlocking within a static constructor. The scenario is described here:

The CLR uses an internal lock to ensure that static constructor:

is only called once

gets executed before creation of any instance of the
class or before accessing any static members.

With this behaviour of
CLR, there is a potential opportunity of a deadlock if we perform any
asynchronous blocking operation in a static constructor. (...)

The main thread will wait for the helper thread to complete within the
static constructor. Since the helper thread is accessing the instance
method, it will first try to acquire the internal lock. As internal
lock is already acquired by the main thread, we will end-up in a
deadlock situation.

Using Parallel LINQ (or any other similar library like FSharp.Collections.ParallelSeq) in a static constructor will make you run into that problem.

Unfortunately, a static constructor of a compiler-generated class is what you get for your GetHtmlForAllPages value. From ILSpy (with C# formatting):

```<code>namespace <StartupCode$ConsoleApplication1>
{
    internal static class $Program
    {
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal static readonly Program.RetryBuilder retry@17;

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal static readonly int[] GetHtmlForAllPages@24;

        [DebuggerBrowsable(DebuggerBrowsableState.Never), DebuggerNonUserCode, CompilerGenerated]
        internal static int init@;

        static $Program()
        {
            $Program.retry@17 = new Program.RetryBuilder(4);
            IEnumerable<int> pages = Operators.OperatorIntrinsics.RangeInt32(1, 1, 10);
            ParallelQuery<int> parallelQuery = PSeqModule.map<int, int>(new Program.allHtml@26(), pages);
            ParallelQuery<int> parallelQuery2 = parallelQuery;
            int[] allHtml = SeqModule.ToArray<int>((IEnumerable<int>)parallelQuery2);
            $Program.GetHtmlForAllPages@24 = allHtml;
        }
    }
}
</code>```

and in your actual Program class:

```<code>[CompilationMapping(SourceConstructFlags.Value)]
public static int[] GetHtmlForAllPages
{
    get
    {
        return $Program.GetHtmlForAllPages@24;
    }
}
</code>```

That's where the deadlock is coming from.

As soon as you change GetHtmlForAllPages to be a function (by adding ()) it is no longer part of that static constructor, which makes the program work as expected.

Body:
I'm writing a scraper using FSharp.Collections.ParallelSeq and a retry computation. I would like to retrieve HTML from multiple pages in parallel, and I would like to retry requests when they fail.

For example:

open System
open FSharp.Collections.ParallelSeq

type RetryBuilder(max) =
  member x.Return(a) = a               // Enable 'return'
  member x.Delay(f) = f                // Gets wrapped body and returns it (as it is)
                                       // so that the body is passed to 'Run'
  member x.Zero() = failwith "Zero"    // Support if .. then
  member x.Run(f) =                    // Gets function created by 'Delay'
    let rec loop(n) =
      if n = 0 then failwith "Failed"  // Number of retries exceeded
      else try f() with _ -> loop(n-1)
    loop max

let retry = RetryBuilder(4)

let getHtml (url : string) = retry {
    Console.WriteLine("Get Url")
    return 0;
}

//A property/field?
let GetHtmlForAllPages =
    let pages = {1 .. 10}
    let allHtml = pages |> PSeq.map(fun x -> getHtml("http://somesite.com/" + x.ToString())) |> Seq.toArray
    allHtml

[<EntryPoint>]
let main argv =
    let htmlForAllPages = GetHtmlForAllPages
    0 // return an integer exit code

When I try to interact with GetHtmlForAllPages from main the code seems to hang. Stepping through the code shows me that PSeq.map begins work on the first four values of pages.

What's going on that causes the retry computation expression to never start/complete? Is there some weird interplay between PSeq and retry?

The code works as expected if I make GetHtmlForAllPages a function and invoke it. I'm curious what's going on when GetHtmlForAllPages is a field?

Body:
Looks like you're deadlocking within a static constructor. The scenario is described here:

The CLR uses an internal lock to ensure that static constructor:

is only called once

gets executed before creation of any instance of the
class or before accessing any static members.

With this behaviour of
CLR, there is a potential opportunity of a deadlock if we perform any
asynchronous blocking operation in a static constructor. (...)

The main thread will wait for the helper thread to complete within the
static constructor. Since the helper thread is accessing the instance
method, it will first try to acquire the internal lock. As internal
lock is already acquired by the main thread, we will end-up in a
deadlock situation.

Using Parallel LINQ (or any other similar library like FSharp.Collections.ParallelSeq) in a static constructor will make you run into that problem.

Unfortunately, a static constructor of a compiler-generated class is what you get for your GetHtmlForAllPages value. From ILSpy (with C# formatting):

namespace <StartupCode$ConsoleApplication1>
{
    internal static class $Program
    {
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal static readonly Program.RetryBuilder retry@17;

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal static readonly int[] GetHtmlForAllPages@24;

        [DebuggerBrowsable(DebuggerBrowsableState.Never), DebuggerNonUserCode, CompilerGenerated]
        internal static int init@;

        static $Program()
        {
            $Program.retry@17 = new Program.RetryBuilder(4);
            IEnumerable<int> pages = Operators.OperatorIntrinsics.RangeInt32(1, 1, 10);
            ParallelQuery<int> parallelQuery = PSeqModule.map<int, int>(new Program.allHtml@26(), pages);
            ParallelQuery<int> parallelQuery2 = parallelQuery;
            int[] allHtml = SeqModule.ToArray<int>((IEnumerable<int>)parallelQuery2);
            $Program.GetHtmlForAllPages@24 = allHtml;
        }
    }
}

and in your actual Program class:

[CompilationMapping(SourceConstructFlags.Value)]
public static int[] GetHtmlForAllPages
{
    get
    {
        return $Program.GetHtmlForAllPages@24;
    }
}

That's where the deadlock is coming from.

As soon as you change GetHtmlForAllPages to be a function (by adding ()) it is no longer part of that static constructor, which makes the program work as expected.


问:
Child class instantiation, automatically set the discriminator property for me (Code First)
I have a parent abstract class:

```<code>public abstract class Transaction
{
    public int ID { get; set; }
    public string TransactionDescr { get; set; }
    public DateTime TransactionDate { get; set; }
    public int TransactionType { get; protected set; }
}
</code>```

And some real child classes that I want to set the TransactionType property when it instantiated.

In my database, I have a TransactionType column  which I use as the discriminator.

This is my idea:

```<code>public class TransactAdd : Transaction
{
    public TransactAdd()
    {
        TransactionType = 1;
    }
}
public class TransactDeduct : Transaction
{
    public TransactDeduct()
    {
        TransactionType = 2;
    }
}
public class TransactTransfer : Transaction
{
    public TransactTransfer()
    {
        TransactionType = 3;
    }
}
</code>```

Is it a good idea to set the TransactionType in class constructor?? am I right? or is there a better way?

By the way, finally, I save the parent class Transaction in the database using Dapper.

I add the solution, thanks to @flobjective

UPDATE(Solution)

```<code>public abstract class Transaction
{
    public int ID { get; set; }
    public string TransactionDescr { get; set; }
    public DateTime TransactionDate { get; set; }
    public abstract int TransactionType { get; }
}

public class TransactAdd : Transact
{
    public override int TransactType
    {
        get
        {
            return 1;
        }
    }
}
public class TransactDeduct : Transact
{
    public override int TransactType
    {
        get
        {
            return 2;
        }
    }
}
public class TransactTransfer : Transact
{
    public override int TransactType
    {
        get
        {
            return 3;
        }
    }
}
</code>```

答:
One weakness of your solution is that you have to remember to set the transaction type. In case somebody else adds a new Transaction class he may forget and this will lead to a wrong TransactionType value of 1.

Other than that intTransactionType has protected setter which means somebody could later change the type which could lead to problems.

You could create an abstract method (Get)TransactionType that forces each concrete implementation to return an int. However that still does not ensure that you use unique integers for all types.

Body:
I have a parent abstract class:

public abstract class Transaction
{
    public int ID { get; set; }
    public string TransactionDescr { get; set; }
    public DateTime TransactionDate { get; set; }
    public int TransactionType { get; protected set; }
}

And some real child classes that I want to set the TransactionType property when it instantiated.

In my database, I have a TransactionType column  which I use as the discriminator.

This is my idea:

public class TransactAdd : Transaction
{
    public TransactAdd()
    {
        TransactionType = 1;
    }
}
public class TransactDeduct : Transaction
{
    public TransactDeduct()
    {
        TransactionType = 2;
    }
}
public class TransactTransfer : Transaction
{
    public TransactTransfer()
    {
        TransactionType = 3;
    }
}

Is it a good idea to set the TransactionType in class constructor?? am I right? or is there a better way?

By the way, finally, I save the parent class Transaction in the database using Dapper.

I add the solution, thanks to @flobjective

UPDATE(Solution)

public abstract class Transaction
{
    public int ID { get; set; }
    public string TransactionDescr { get; set; }
    public DateTime TransactionDate { get; set; }
    public abstract int TransactionType { get; }
}

public class TransactAdd : Transact
{
    public override int TransactType
    {
        get
        {
            return 1;
        }
    }
}
public class TransactDeduct : Transact
{
    public override int TransactType
    {
        get
        {
            return 2;
        }
    }
}
public class TransactTransfer : Transact
{
    public override int TransactType
    {
        get
        {
            return 3;
        }
    }
}


问:
Editing data in multiple columns from front-end
I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..</p>

```<code><?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID =  $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "<div style='overflow-x:auto;'><table border = '1'><font size = '2' face='verdana'>
<th>TND ID</th><th>Site name S1</th><th>Site name S2</th><th>Call sign S1</th><th>Idea ID S1</th><th>Call sign S2</th><th>Idea ID S2</th><th>Site to integrate</th><th>True azimuth (°) S1</th><th>True azimuth (°) S2</th><th>Pathlength (km)</th><th>TR Antenna diameter (m)</th><th>TR Antenna height (m) S1</th><th>TR Antenna height (m) S2</th><th>Channel ID S1</th><th>Channel ID S2</th><th>Design frequency S1</th><th>Design frequency S2</th><th>Polarization</th><th>Radio model</th><th>TX power (dBm)</th><th>Receive signal (dBm)</th><th>Planning Remarks</th><th>Projects Remarks Uploaded by</th><th>O & M Remarks Uploaded by</th><th>Planning Remarks Uploaded by</th><th>TXN NOC Remarks Uploaded by</th></tr>";

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

        echo "<tr><td>".$row["TND_ID"]."</td><td>".$row["Site_name_S1"]."</td><td>".$row["Site_name_S2"]."</td><td>".$row["Call_sign_S1"]."</td><td>".$row["Idea_ID_S1"]."</td><td>".$row["Call_sign_S2"]."</td><td>".$row["Idea_ID_S2"]."</td><td>".$row["Site_to_integrate"]."</td><td>".$row["True_azimuth_S1"]."</td><td>".$row["True_azimuth_S2"]."</td><td>".$row["Path_length_(km)"]."</td><td>".$row["TR_Antenna_diameter_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S2"]."</td><td>".$row["#1_Channel_ID_S1"]."</td><td>".$row["#1_Channel_ID_S2"]."</td><td>".$row["#1_Design_frequency_S1"]."</td><td>".$row["#1_Design_frequency_S2"]."</td><td>".$row["Polarization"]."</td><td>".$row["Radio_model_S1"]."</td><td>".$row["TX_power_(dBm)_S1"]."</td><td>".$row["Receive_signal_(dBm)_S1"]."</td><td>".$row["Planning_Remarks"]."</td><td>".$row["Projects_remarksupdated_user_name"]."</td><td>".$row["O_M_remarksupdated_user_name"]."</td><td>".$row["Planning_remarksupdated_user_name"]."</td><td>".$row["txn_noc_remarksupdated_user_name"]."</td></tr>";

}
echo "</table></div>";
$link->close();
?>
</code>```

答:
You can use Ajax
Just a fragment of code:
.............

```<code>     <td><input type="text" row_id=".$some_row_num_from_table."
col-name=".$some_col_name_from_table." disabled class="some-val" value=".$some_from_base."></td>
</code>```

.............

than little Ajax

```<code>$('.some-val').dblclick(function() {
  $(this).attr('disabled', false);
});

$('.some-val').blur(function() {
  $(this).attr('disabled', true);
  var send_data = { 'row_id':$(this).attr('row_id'),
                    'col-name':$(this).attr('col-name'),
                    'myval':$(this).val()
                   };
   $.ajax({
     url:'your_url.php',
     data:send_data,
     method: 'post',
     success: function(data){...}
  });
});

your_url.php

if(isset($_POST['row_id'])){
  $sql = "UPDATE mytablename SET `".$_POST['col-name']."` = ".$_POST['myval']." WHERE `row_id` = ".$_POST['row_id'];
$link->query($sql); // it s bad query without protect of sql injection JUST DEMO
}
</code>```

Body:
I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..

<?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID =  $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "

TND ID	Site name S1	Site name S2	Call sign S1	Idea ID S1	Call sign S2	Idea ID S2	Site to integrate	True azimuth (°) S1	True azimuth (°) S2	Pathlength (km)	TR Antenna diameter (m)	TR Antenna height (m) S1	TR Antenna height (m) S2	Channel ID S1	Channel ID S2	Design frequency S1	Design frequency S2	Polarization	Radio model	TX power (dBm)	Receive signal (dBm)	Planning Remarks	Projects Remarks Uploaded by	O & M Remarks Uploaded by	Planning Remarks Uploaded by	TXN NOC Remarks Uploaded by
";

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

        echo "
".$row["TND_ID"]."	".$row["Site_name_S1"]."	".$row["Site_name_S2"]."	".$row["Call_sign_S1"]."	".$row["Idea_ID_S1"]."	".$row["Call_sign_S2"]."	".$row["Idea_ID_S2"]."	".$row["Site_to_integrate"]."	".$row["True_azimuth_S1"]."	".$row["True_azimuth_S2"]."	".$row["Path_length_(km)"]."	".$row["TR_Antenna_diameter_(m)_S1"]."	".$row["TR_Antenna_height_(m)_S1"]."	".$row["TR_Antenna_height_(m)_S2"]."	".$row["#1_Channel_ID_S1"]."	".$row["#1_Channel_ID_S2"]."	".$row["#1_Design_frequency_S1"]."	".$row["#1_Design_frequency_S2"]."	".$row["Polarization"]."	".$row["Radio_model_S1"]."	".$row["TX_power_(dBm)_S1"]."	".$row["Receive_signal_(dBm)_S1"]."	".$row["Planning_Remarks"]."	".$row["Projects_remarksupdated_user_name"]."	".$row["O_M_remarksupdated_user_name"]."	".$row["Planning_remarksupdated_user_name"]."	".$row["txn_noc_remarksupdated_user_name"]."
";

}
echo "

";
$link->close();
?>

Body:
You can use Ajax
Just a fragment of code:
.............

     <td><input type="text" row_id=".$some_row_num_from_table."
col-name=".$some_col_name_from_table." disabled class="some-val" value=".$some_from_base."></td>

.............

than little Ajax

$('.some-val').dblclick(function() {
  $(this).attr('disabled', false);
});

$('.some-val').blur(function() {
  $(this).attr('disabled', true);
  var send_data = { 'row_id':$(this).attr('row_id'),
                    'col-name':$(this).attr('col-name'),
                    'myval':$(this).val()
                   };
   $.ajax({
     url:'your_url.php',
     data:send_data,
     method: 'post',
     success: function(data){...}
  });
});

your_url.php

if(isset($_POST['row_id'])){
  $sql = "UPDATE mytablename SET `".$_POST['col-name']."` = ".$_POST['myval']." WHERE `row_id` = ".$_POST['row_id'];
$link->query($sql); // it s bad query without protect of sql injection JUST DEMO
}


问:
How to submit a form without reloading page on ajax success
I want to submit a form with ajax on ajax success that means i don't want to reload the page when the form is submitted on ajax success. I tried

```<code>if (response.success == true ) {
$form = $("#formname");
var form = $form.serializeArray();
form.push({
   name: window.csrfTokenName,
   value: window.csrfTokenValue
})
</code>```

The page didnt reload on this but, the form was also not submitted. I also tried document.form['formname'].submit() but that reloaded the page.
Please Help

答:
If you want to submit a form without reloading the page, you have to use Ajax requests. At the same time you have to prevent browser from native form submission. To prevent from submission use something like this

```<code>$('yourbuttonselector').click(function(e) {
    e.preventDefault();
});
</code>```

And for form submission without reloading use Ajax - $.post() for example.

Body:
I want to submit a form with ajax on ajax success that means i don't want to reload the page when the form is submitted on ajax success. I tried

if (response.success == true ) {
$form = $("#formname");
var form = $form.serializeArray();
form.push({
   name: window.csrfTokenName,
   value: window.csrfTokenValue
})

The page didnt reload on this but, the form was also not submitted. I also tried document.form['formname'].submit() but that reloaded the page.
Please Help

Body:
If you want to submit a form without reloading the page, you have to use Ajax requests. At the same time you have to prevent browser from native form submission. To prevent from submission use something like this

$('yourbuttonselector').click(function(e) {
    e.preventDefault();
});

And for form submission without reloading use Ajax - $.post() for example.


问:
how to make interstatial ads come in every 5 minutes using angular js
hello there im new for anngualrJs and ionic framework. i want to  make interstatial ads come in every 5 minutes using angualrJs  in ionic 1 project. Any body help me.

My code is

```<code>admobid = {};

if( /(android)/i.test(navigator.userAgent) ) {
    admobid = { // for Android
        banner: 'ca-app-pub-2343423432432423/324324324324',
        interstitial: 'ca-app-pub-2343423432432423/324324324324'
    };
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
    admobid = { // for iOS
        banner: 'ca-app-pub-2343423432432423/324324324324',
        interstitial: 'ca-app-pub-2343423432432423/324324324324'
    };
} else {
    admobid = { // for Windows Phone
        banner: 'ca-app-pub-2343423432432423/324324324324',
        interstitial: 'ca-app-pub-2343423432432423/324324324324'
    };
}

if(window.AdMob) AdMob.createBanner( {
adId:admobid.banner,
isTesting:false,
position:AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow:true} );

if(Window.AdMob) AdMob.prepareInterstitial({
    adId:admobid.interstitial,
    isTesting:false,
    autoShow:false
  });

});
</code>```

i dont know where to add the code for interstatial ads to come in every 5 min

Thank you!

答:
You can see the complete example here: https://github.com/appfeel/admob-google-cordova/wiki/showInterstitialAd

Be carefull with this, Google will be willing to reject your app if it is considered that interstitials are shown unexpectedly while user is reading app content.

Basically the idea is to set a timeout and request a new ad. When the ad is available, you show it and reset the timeo

ContentLicense: CC BY-SA 4.0

Body:
hello there im new for anngualrJs and ionic framework. i want to  make interstatial ads come in every 5 minutes using angualrJs  in ionic 1 project. Any body help me.

My code is

admobid = {};

if( /(android)/i.test(navigator.userAgent) ) {
    admobid = { // for Android
        banner: 'ca-app-pub-2343423432432423/324324324324',
        interstitial: 'ca-app-pub-2343423432432423/324324324324'
    };
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
    admobid = { // for iOS
        banner: 'ca-app-pub-2343423432432423/324324324324',
        interstitial: 'ca-app-pub-2343423432432423/324324324324'
    };
} else {
    admobid = { // for Windows Phone
        banner: 'ca-app-pub-2343423432432423/324324324324',
        interstitial: 'ca-app-pub-2343423432432423/324324324324'
    };
}

if(window.AdMob) AdMob.createBanner( {
adId:admobid.banner,
isTesting:false,
position:AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow:true} );

if(Window.AdMob) AdMob.prepareInterstitial({
    adId:admobid.interstitial,
    isTesting:false,
    autoShow:false
  });

});

i dont know where to add the code for interstatial ads to come in every 5 min

Thank you!


问:
Is XHTML really Xtensible?
Is there any way (server- or client-side) that I can actually extend HTML to include new tags?  For example, it would be cool if I could write something like a schema fragment that defined a blogpost, which contains a postname, a postauthor, a posttime, and a postcontent, and thereafter refer to blogpost in my HTML rather than resorting to the basic HTML div and p tags.

答: That would be awesome.  Here is an article explaining why it won't work.  Basically, you can extend the markup.  But HTML browsers won't know how to interpret your new tags.

Title: Is XHTML really Xtensible?


问:
if not break not working in python server
I have created a client server setup from a tutorial, but the server is stuck in the while loop below and i can't figure out why.
I have searched through the questions on here and as far as I can see it should work.

I'm sure it will be something simple. I'm new to Python so any help would be appreciated.
Please know this is my first question so i hope it works ok.

I'm using python 3.5.2

```<code># create a client thread
def clientthread(conn):
    # sending message to the client
    message = 'Welcome to the Server. Type something and hit Enter\n'
    conn.send(message.encode())  # send only takes a string

    while 1:
        # receiving from client
        data = conn.recv(1024)
        if not data.decode(): break
        reply = 'OK ' + data.decode()
        conn.sendall(reply.encode())

    # came out of loop
    conn.close()

# keep server up
while 1:

    # accept incomming connections
    conn, addr = soc.accept()

    # display client info
    print('Connected with' + addr[0] + ':' + str(addr[1]))
    # start a new thread takes function name and a tupal
    start_new_thread(clientthread, (conn, ))

soc.close()
</code>```

答: Figured out the issue, I was using telnet to test the server and it adds a \r\n to the end which the server see's as data so never shuts down. Added code to check for this and works fine now</p>

Body:
I have created a client server setup from a tutorial, but the server is stuck in the while loop below and i can't figure out why.
I have searched through the questions on here and as far as I can see it should work.

I'm sure it will be something simple. I'm new to Python so any help would be appreciated.
Please know this is my first question so i hope it works ok.

I'm using python 3.5.2

# create a client thread
def clientthread(conn):
    # sending message to the client
    message = 'Welcome to the Server. Type something and hit Enter\n'
    conn.send(message.encode())  # send only takes a string

    while 1:
        # receiving from client
        data = conn.recv(1024)
        if not data.decode(): break
        reply = 'OK ' + data.decode()
        conn.sendall(reply.encode())

    # came out of loop
    conn.close()

# keep server up
while 1:

    # accept incomming connections
    conn, addr = soc.accept()

    # display client info
    print('Connected with' + addr[0] + ':' + str(addr[1]))
    # start a new thread takes function name and a tupal
    start_new_thread(clientthread, (conn, ))

soc.close()


问:
How to return DataSet (xsd) in WCF
I have a library that returns a DataSet on a certain method. I need to expose this DataSet over WCF, the client app will use this as a datasource for a report generator (DevExpress XtraReport to be exact). The DataSet contains about 58 DataTables, including a table containing configurations for the report.

How can I get this dataset over wcf to the client (ASP.NET MVC)

current code

```<code>public ReponseData GetReportData (RequestData request){
 var reportData = library.GetReportData(request.Param1, reqest.Param2)   //returns DataSet

   var respone = new ResponseData {
        RequiredField = value, //requied for validation on the client
      //When I put DataSet here my wcf just breaks entirely
      //.. what to do here to send over the DataSet??
   };
return response;

}
</code>```

答:
The solution is use the DataSet’s methods to get the data in XML format and pass the XML string instead of the DataSet itself to the service.</p>

```<code>PassDataSet(dsDataSet.GetXmlSchema(), dsDataSet.GetXml())
</code>```

Title: How to return DataSet (xsd) in WCF

Body:
I have a library that returns a DataSet on a certain method. I need to expose this DataSet over WCF, the client app will use this as a datasource for a report generator (DevExpress XtraReport to be exact). The DataSet contains about 58 DataTables, including a table containing configurations for the report.

How can I get this dataset over wcf to the client (ASP.NET MVC)

current code

public ReponseData GetReportData (RequestData request){
 var reportData = library.GetReportData(request.Param1, reqest.Param2)   //returns DataSet

   var respone = new ResponseData {
        RequiredField = value, //requied for validation on the client
      //When I put DataSet here my wcf just breaks entirely
      //.. what to do here to send over the DataSet??
   };
return response;

}

Body:
The solution is use the DataSet’s methods to get the data in XML format and pass the XML string instead of the DataSet itself to the service.

PassDataSet(dsDataSet.GetXmlSchema(), dsDataSet.GetXml())


问:
Fetch and display image from MS SQL in Android
I am fetching the image (datatype is image) from the MS SQL database and the format i am getting is as follows.

```<code>[encoded data, 18092 characters]
</code>```

I tried to convert it into bitmap image and i am getting error message.  Can anyone please help me figure out the issue?

This is the code used for converting to image.

```<code>byte[] blob = string.getBytes();
Bitmap theImage = BitmapFactory.decodeByteArray(blob, 0, blob.length);
imageview.setImageBitmap(theImage);
</code>```

**String is the data from image field of SQL database.

答:
I Hope this will help,in imgByte  you are getting a long String in format as   shown by you

```<code>         String imgByte ="your string in question";

        try{
            byte [] encodeByte= Base64.decode(imgByte,Base64.DEFAULT);
            Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            imageview.setImageBitmap(bitmap);
        }catch(Exception e){
            e.getMessage();

        }
</code>```

while Storing im encoding it

```<code>            Bitmap photo = bitmap;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
            byte[] bArray = bos.toByteArray();
            String encodedImage = Base64.encodeToString(bArray, Base64.DEFAULT);
            db.upDateConatct(worldPopulation,worldPopulation.getRank(),encodedImage);
</code>```

Body:
I am fetching the image (datatype is image) from the MS SQL database and the format i am getting is as follows.

[encoded data, 18092 characters]

I tried to convert it into bitmap image and i am getting error message.  Can anyone please help me figure out the issue?

This is the code used for converting to image.

byte[] blob = string.getBytes();
Bitmap theImage = BitmapFactory.decodeByteArray(blob, 0, blob.length);
imageview.setImageBitmap(theImage);

**String is the data from image field of SQL database.

Body:
I Hope this will help,in imgByte  you are getting a long String in format as   shown by you

         String imgByte ="your string in question";

        try{
            byte [] encodeByte= Base64.decode(imgByte,Base64.DEFAULT);
            Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            imageview.setImageBitmap(bitmap);
        }catch(Exception e){
            e.getMessage();

        }

while Storing im encoding it

            Bitmap photo = bitmap;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
            byte[] bArray = bos.toByteArray();
            String encodedImage = Base64.encodeToString(bArray, Base64.DEFAULT);
            db.upDateConatct(worldPopulation,worldPopulation.getRank(),encodedImage);


问:
Matplotlib - Set the limits for text wrapping
I am trying to generate a plot having four quarters, each having some text saying something about that quarter. However, when I am trying to wrap the text I don't know how to set the limits for text. For example, in the attached figure, I want to limit the text to x=0. However, it is going until the end of x-axis limits. Please find attached the code and corresponding plot the code is generating.

```<code>import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt

import numpy as np
from textwrap import wrap

font = {'size': 22}
matplotlib.rc('font', **font)
fig = plt.figure(figsize=(8, 8))
plt.axis([-10, 10, -10, 10])

ax = plt.gca()

ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.xlabel('Energy ($kWh$)')
ax.xaxis.set_label_coords(0.85, .48)
ax.xaxis.set_ticks_position('bottom')
ax.set_xlim(-10, 10)
ax.xaxis.set_ticks([])

plt.ylabel('Discomfort ($\%$)', rotation=0)
ax.yaxis.set_label_coords(0.7, 0.01)
ax.yaxis.set_ticks_position('left')
ax.set_ylim(-10, 10)
ax.yaxis.set_ticks([])

ax.annotate(
    'Reference Point', xy=(0, 0), xycoords='data',
    xytext=(-10, 2), textcoords='data', wrap=True,
    arrowprops=dict(facecolor='black'))

t = "This is a really long string that I'd rather have wrapped so that
it doesn't go outside of the figure, but if it's long enough it will go
off the top or bottom!"

ax.text(-10, 3.5, t, ha='left', wrap=True, fontsize=20)
plt.tight_layout()
plt.savefig('sample.png')
</code>```

答:
As can be seen in the auto wrap demo, wrapping happens at the figure limits. While this is not very comfortable, and I can imagine many cases, where this would not help at all, here, it allows to wrap the text by choosing the correct alignment.

```<code>ax.text(0.49, 0.98, t, ha='right',va="top", wrap=True,
        fontsize=20, transform=ax.transAxes)
ax.text(0.51, 0.98, t, ha='left',va="top", wrap=True,
        fontsize=20, transform=ax.transAxes)
ax.text(0.49, 0.49, t, ha='right',va="top", wrap=True,
        fontsize=20, transform=ax.transAxes)
</code>```

Body:
I am trying to generate a plot having four quarters, each having some text saying something about that quarter. However, when I am trying to wrap the text I don't know how to set the limits for text. For example, in the attached figure, I want to limit the text to x=0. However, it is going until the end of x-axis limits. Please find attached the code and corresponding plot the code is generating.

import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt

import numpy as np
from textwrap import wrap

font = {'size': 22}
matplotlib.rc('font', **font)
fig = plt.figure(figsize=(8, 8))
plt.axis([-10, 10, -10, 10])

ax = plt.gca()

ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.xlabel('Energy ($kWh$)')
ax.xaxis.set_label_coords(0.85, .48)
ax.xaxis.set_ticks_position('bottom')
ax.set_xlim(-10, 10)
ax.xaxis.set_ticks([])

plt.ylabel('Discomfort ($\%$)', rotation=0)
ax.yaxis.set_label_coords(0.7, 0.01)
ax.yaxis.set_ticks_position('left')
ax.set_ylim(-10, 10)
ax.yaxis.set_ticks([])

ax.annotate(
    'Reference Point', xy=(0, 0), xycoords='data',
    xytext=(-10, 2), textcoords='data', wrap=True,
    arrowprops=dict(facecolor='black'))

t = "This is a really long string that I'd rather have wrapped so that
it doesn't go outside of the figure, but if it's long enough it will go
off the top or bottom!"

ax.text(-10, 3.5, t, ha='left', wrap=True, fontsize=20)
plt.tight_layout()
plt.savefig('sample.png')

Body:
As can be seen in the auto wrap demo, wrapping happens at the figure limits. While this is not very comfortable, and I can imagine many cases, where this would not help at all, here, it allows to wrap the text by choosing the correct alignment.

ax.text(0.49, 0.98, t, ha='right',va="top", wrap=True,
        fontsize=20, transform=ax.transAxes)
ax.text(0.51, 0.98, t, ha='left',va="top", wrap=True,
        fontsize=20, transform=ax.transAxes)
ax.text(0.49, 0.49, t, ha='right',va="top", wrap=True,
        fontsize=20, transform=ax.transAxes)


问:
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/animation/AnimatorCompatHelper
After updating Android Studio to version 2.3. Every time I swipe my ViewPager I keep getting this error and the app crashes:

```<code>03-23 17:19:19.437 28523-28523/? E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.irokotv.plus, PID: 28523
   java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/animation/AnimatorCompatHelper;
       at android.support.v7.widget.DefaultItemAnimator.resetAnimation(DefaultItemAnimator.java:515)
       at android.support.v7.widget.DefaultItemAnimator.animateAdd(DefaultItemAnimator.java:218)
       at android.support.v7.widget.SimpleItemAnimator.animateAppearance(SimpleItemAnimator.java:114)
       at android.support.v7.widget.RecyclerView.animateAppearance(RecyclerView.java:3528)
       at android.support.v7.widget.RecyclerView$4.processAppeared(RecyclerView.java:461)
       at android.support.v7.widget.ViewInfoStore.process(ViewInfoStore.java:249)
       at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3385)
       at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3135)
       at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1766)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
       at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
       at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1364)
       at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:846)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
       at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
       at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
       at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
       at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
       at com.android.internal.policy.DecorView.onLayout(DecorView.java:818)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2615)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2331)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1490)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7027)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
       at android.view.Choreographer.doCallbacks(Choreographer.java:702)
       at android.view.Choreographer.doFrame(Choreographer.java:638)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
       at android.os.Handler.handleCallback(Handler.java:751)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6688)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
</code>```

The app use to work well before the update. I already cleaned the project. Invalidate caches and run a gradle clean. No idea what else what I can do/try. My coworker can build the project and it works without any issue.

答: Just generate an "APK" instead of instant run, and it will work perfectly.</p>

Body:
After updating Android Studio to version 2.3. Every time I swipe my ViewPager I keep getting this error and the app crashes:

03-23 17:19:19.437 28523-28523/? E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.irokotv.plus, PID: 28523
   java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/animation/AnimatorCompatHelper;
       at android.support.v7.widget.DefaultItemAnimator.resetAnimation(DefaultItemAnimator.java:515)
       at android.support.v7.widget.DefaultItemAnimator.animateAdd(DefaultItemAnimator.java:218)
       at android.support.v7.widget.SimpleItemAnimator.animateAppearance(SimpleItemAnimator.java:114)
       at android.support.v7.widget.RecyclerView.animateAppearance(RecyclerView.java:3528)
       at android.support.v7.widget.RecyclerView$4.processAppeared(RecyclerView.java:461)
       at android.support.v7.widget.ViewInfoStore.process(ViewInfoStore.java:249)
       at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3385)
       at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3135)
       at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1766)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
       at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
       at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1364)
       at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:846)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
       at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
       at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
       at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
       at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
       at com.android.internal.policy.DecorView.onLayout(DecorView.java:818)
       at android.view.View.layout(View.java:18793)
       at android.view.ViewGroup.layout(ViewGroup.java:5952)
       at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2615)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2331)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1490)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7027)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
       at android.view.Choreographer.doCallbacks(Choreographer.java:702)
       at android.view.Choreographer.doFrame(Choreographer.java:638)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
       at android.os.Handler.handleCallback(Handler.java:751)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6688)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)

The app use to work well before the update. I already cleaned the project. Invalidate caches and run a gradle clean. No idea what else what I can do/try. My coworker can build the project and it works without any issue.


问:
Is there is a chance to overcome the scan data of 1 mb in parallel asynchronous in dynamodb
When I am scanning the data, it is having a limit of 1MB for 1 segment. To display all the data in one segment is possible in asynchronous parallel in dynamodb.</p>

答:
When doing a parallel scan, each Scan API call will return at most 1MB of data. So, if you increase the number of segments enough, you will be able to get all of your data in one trip. According to the documentation, the maximum number of segments is 1 million. That means that as long as you have enough provisioned read throughput on your table, and the size of your table is less than 976GB, reading the entire table in one round trip is possible. Each 1MB page will incur 128 RCU if ConsistentRead=false. Therefore, if each partition supports up to 3000 Reads per second, each partition can support reading up to 23 segments in parallel. Dividing 1 million segments by 23 segments per partition yields 43479 partitions required to support a simultaneous read of 976GB.

To create a table with 43479 partitions or more, find the next largest power of 2. In this case, the next largest power of 2 to 43479 is 2^16=65536. Provision a table with 65536*750 = 49152000 WPS and 49152000 RPS to create it with 65536 partitions. The instantaneous RCU consumption of this parallel scan will be 128 * 1000000 = 128 million RCU, so you would need to re-provision your table at 128 million RPS before performing the parallel scan.

For any of this to work, you will need to request increases to your account-level and table level provisioned capacity limits. Otherwise, in us-east-1, default table provisioning limits are 40k rps and 40k wps per table. If you provision a table at 40k reads per second, you can read a maximum of 312 segments in parallel, or 312 MB.


答:
Sounds like HTML5 is right up your alley!

You can use elements like section to wrap up all your posts, and article for each post, plus basics like header, nav, and footer.  There isn't fine grained elements like postauthor or posttime but you can provide other attributes to help define these.

Hmm, seems I spoke to soon, you can use this too:

```<code><time pubdate datetime="2010-11-13T20:00+09:00">Posted Nov 13.</time>
</code>```

Title: Is XHTML really Xtensible?

Body: Is there any way (server- or client-side) that I can actually extend HTML to include new tags?  For example, it would be cool if I could write something like a schema fragment that defined a blogpost, which contains a postname, a postauthor, a posttime, and a postcontent, and thereafter refer to blogpost in my HTML rather than resorting to the basic HTML div and p tags.

Body:
Sounds like HTML5 is right up your alley!

You can use elements like section to wrap up all your posts, and article for each post, plus basics like header, nav, and footer.  There isn't fine grained elements like postauthor or posttime but you can provide other attributes to help define these.

Hmm, seems I spoke to soon, you can use this too:

<time pubdate datetime="2010-11-13T20:00+09:00">Posted Nov 13.</time>


问:
Selecting siblings of parent of $(this) element
I need to update the id of all li that are siblings of the parent of the $(this) element by dynamically counting the present li that belong to the same "family" every time one is removed.

Note that there's more than one ul.customFieldUl on the page and more than one li.customFieldLi in each.

$('.customFieldUl').on('click', '.remove-button', function() {
  var field = $(this).parents('li.customFieldLi');
  if (field.length) {
    field.remove();

    // PROBLEMATIC SELECTOR BELOW:
    $(this).parent().siblings().each(function(i) {
      var id = i + 1;

      $(this).prop('id', 'field_' + id);
      $(this).find('label#top_title').html('Custom Field #: ' + id + ' »');
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

答:
You need to target siblings() of LI before removing the LI element.

$('.customFieldUl').on('click', '.remove-button', function() {
  var field = $(this).closest('li.customFieldLi');
  //Take reference of siblings
  var siblings = field.siblings();

  //Remove element
  field.remove();

  // Now iterate and update properties.
  siblings.each(function(i) {
    var id = i + 1;
    $(this).prop('id', 'field_' + id);
    $(this).find('label#top_title').html('Custom Field #: ' + id + ' »');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

Identifiers in HTML must be unique, You are using id="top_title" multiple times which renders HTML invalid

Note: I totally agree with @Rory's comment, changing id attributes dynamically is not a good idea

Body:
I need to update the id of all li that are siblings of the parent of the $(this) element by dynamically counting the present li that belong to the same "family" every time one is removed.

Note that there's more than one ul.customFieldUl on the page and more than one li.customFieldLi in each.

$('.customFieldUl').on('click', '.remove-button', function() {
  var field = $(this).parents('li.customFieldLi');
  if (field.length) {
    field.remove();

    // PROBLEMATIC SELECTOR BELOW:
    $(this).parent().siblings().each(function(i) {
      var id = i + 1;

      $(this).prop('id', 'field_' + id);
      $(this).find('label#top_title').html('Custom Field #: ' + id + ' »');
    });
  }
});

    Additional Field

Remove

    Additional Field

Remove

Body:
You need to target siblings() of LI before removing the LI element.

$('.customFieldUl').on('click', '.remove-button', function() {
  var field = $(this).closest('li.customFieldLi');
  //Take reference of siblings
  var siblings = field.siblings();

  //Remove element
  field.remove();

  // Now iterate and update properties.
  siblings.each(function(i) {
    var id = i + 1;
    $(this).prop('id', 'field_' + id);
    $(this).find('label#top_title').html('Custom Field #: <b>' + id + '</b> &raquo;');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
</ul>

Identifiers in HTML must be unique, You are using id="top_title" multiple times which renders HTML invalid

Note: I totally agree with @Rory's comment, changing id attributes dynamically is not a good idea


问:
C Pointers about the different data type
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

```<code>int a=3,*p=&a;
char c=r,*cha=&r;
</code>```

why can't we do like

```<code>int *c;
char r=a;
c=&r;
</code>```

答:
Batcheba has already 4 good reasons. Let me give some less important ones:

function pointer and data pointer are not even compatible according to the standard (Harvard architecture with separate code and data address spaces, memory models of segmented architectures, etc.).

the optimizer can exploit the fact that pointer on different types generally do not overlap and can elide a lot of memory loads that way (https://en.wikipedia.org/wiki/Pointer_aliasing)

Body:
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

int a=3,*p=&a;
char c=r,*cha=&r;

why can't we do like

int *c;
char r=a;
c=&r;


问:
Get the composite data from 2 independent mysql table
I want fetch the composite data from the two different or independent table.
Here is my structure of tables.

table 1:

```<code>CREATE TABLE `keywords` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `keyword` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `keyword` (`keyword`)
)
</code>```

in this table data is like:

```<code>+----+---------+
| id | keyword |
+----+---------+
|  2 | apple   |
|  1 | Banana  |
|  8 | ginger  |
|  6 | grapes  |
|  7 | guava   |
| 10 | milk    |
|  3 | onion   |
|  4 | potato  |
|  9 | tea     |
|  5 | tomato  |
+----+---------+
</code>```

table 2;

```<code>CREATE TABLE `Rfps` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
)
</code>```

in this table data is like:

```<code>+----+----------------------------------+
| id | subject                          |
+----+----------------------------------+
|  1 | I would like to have some banana |
|  2 | I need some tea                  |
|  3 | I like grapes                    |
|  4 | yes. Beer, Banana, Onion         |
|  5 | capsicum                         |
+----+----------------------------------+
</code>```

My Moto is to fetch the id of subjects in table 2 those have the keywords of table1.

I created one query like:

```<code>select * from Rfps where CONCAT(subject) REGEXP (select GROUP_CONCAT(keyword SEPARATOR '|') as keyword from keywords);
</code>```

This is giving the result as:

```<code>+----+----------------------------------+
| id | subject                          |
+----+----------------------------------+
|  1 | I would like to have some banana |
|  2 | I need some tea                  |
|  3 | I like grapes                    |
|  4 | yes. Beer, Banana, Onion         |
|  5 | capsicum                         |
+----+----------------------------------+
</code>```

But not getting the id of keywords, or keyword.

But if i fetch like:

```<code>select Rfps.id,Rfps.subject,keywords.id,keywords.keyword from Rfps,keywords where CONCAT(subject) REGEXP (select GROUP_CONCAT(keyword SEPARATOR '|') as keyword from keywords);
</code>```

this is giving the data as:

```<code>+----+----------------------------------+----+---------+
| id | subject                          | id | keyword |
+----+----------------------------------+----+---------+
|  1 | I would like to have some banana |  2 | apple   |
|  2 | I need some tea                  |  2 | apple   |
|  3 | I like grapes                    |  2 | apple   |
|  4 | yes. Beer, Banana, Onion         |  2 | apple   |
|  1 | I would like to have some banana |  1 | Banana  |
|  2 | I need some tea                  |  1 | Banana  |
|  3 | I like grapes                    |  1 | Banana  |
|  4 | yes. Beer, Banana, Onion         |  1 | Banana  |
|  1 | I would like to have some banana |  8 | ginger  |
|  2 | I need some tea                  |  8 | ginger  |
|  3 | I like grapes                    |  8 | ginger  |
|  4 | yes. Beer, Banana, Onion         |  8 | ginger  |
|  1 | I would like to have some banana |  6 | grapes  |
|  2 | I need some tea                  |  6 | grapes  |
|  3 | I like grapes                    |  6 | grapes  |
|  4 | yes. Beer, Banana, Onion         |  6 | grapes  |
|  1 | I would like to have some banana |  7 | guava   |
|  2 | I need some tea                  |  7 | guava   |
|  3 | I like grapes                    |  7 | guava   |
|  4 | yes. Beer, Banana, Onion         |  7 | guava   |
|  1 | I would like to have some banana | 10 | milk    |
|  2 | I need some tea                  | 10 | milk    |
|  3 | I like grapes                    | 10 | milk    |
|  4 | yes. Beer, Banana, Onion         | 10 | milk    |
|  1 | I would like to have some banana |  3 | onion   |
|  2 | I need some tea                  |  3 | onion   |
|  3 | I like grapes                    |  3 | onion   |
|  4 | yes. Beer, Banana, Onion         |  3 | onion   |
|  1 | I would like to have some banana |  4 | potato  |
|  2 | I need some tea                  |  4 | potato  |
|  3 | I like grapes                    |  4 | potato  |
|  4 | yes. Beer, Banana, Onion         |  4 | potato  |
|  1 | I would like to have some banana |  9 | tea     |
|  2 | I need some tea                  |  9 | tea     |
|  3 | I like grapes                    |  9 | tea     |
|  4 | yes. Beer, Banana, Onion         |  9 | tea     |
|  1 | I would like to have some banana |  5 | tomato  |
|  2 | I need some tea                  |  5 | tomato  |
|  3 | I like grapes                    |  5 | tomato  |
|  4 | yes. Beer, Banana, Onion         |  5 | tomato  |
+----+----------------------------------+----+---------+
</code>```

Repetitive rows.

答:
CONCAT() is putting strings together. Having it only on one column is useless and prevents the potential use of an index.

Regexp is also overkill. Use LIKE instead.

This query is giving the correct result:

```<code>select
*
from
keywords k
join Rfps r on r.subject like concat('%', k.keyword, '%');
</code>```

Body:
I want fetch the composite data from the two different or independent table.
Here is my structure of tables.

table 1:

CREATE TABLE `keywords` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `keyword` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `keyword` (`keyword`)
)

in this table data is like:

+----+---------+
| id | keyword |
+----+---------+
|  2 | apple   |
|  1 | Banana  |
|  8 | ginger  |
|  6 | grapes  |
|  7 | guava   |
| 10 | milk    |
|  3 | onion   |
|  4 | potato  |
|  9 | tea     |
|  5 | tomato  |
+----+---------+

table 2;

CREATE TABLE `Rfps` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
)

in this table data is like:

+----+----------------------------------+
| id | subject                          |
+----+----------------------------------+
|  1 | I would like to have some banana |
|  2 | I need some tea                  |
|  3 | I like grapes                    |
|  4 | yes. Beer, Banana, Onion         |
|  5 | capsicum                         |
+----+----------------------------------+

My Moto is to fetch the id of subjects in table 2 those have the keywords of table1.

I created one query like:

select * from Rfps where CONCAT(subject) REGEXP (select GROUP_CONCAT(keyword SEPARATOR '|') as keyword from keywords);

This is giving the result as:

+----+----------------------------------+
| id | subject                          |
+----+----------------------------------+
|  1 | I would like to have some banana |
|  2 | I need some tea                  |
|  3 | I like grapes                    |
|  4 | yes. Beer, Banana, Onion         |
|  5 | capsicum                         |
+----+----------------------------------+

But not getting the id of keywords, or keyword.

But if i fetch like:

select Rfps.id,Rfps.subject,keywords.id,keywords.keyword from Rfps,keywords where CONCAT(subject) REGEXP (select GROUP_CONCAT(keyword SEPARATOR '|') as keyword from keywords);

this is giving the data as:

+----+----------------------------------+----+---------+
| id | subject                          | id | keyword |
+----+----------------------------------+----+---------+
|  1 | I would like to have some banana |  2 | apple   |
|  2 | I need some tea                  |  2 | apple   |
|  3 | I like grapes                    |  2 | apple   |
|  4 | yes. Beer, Banana, Onion         |  2 | apple   |
|  1 | I would like to have some banana |  1 | Banana  |
|  2 | I need some tea                  |  1 | Banana  |
|  3 | I like grapes                    |  1 | Banana  |
|  4 | yes. Beer, Banana, Onion         |  1 | Banana  |
|  1 | I would like to have some banana |  8 | ginger  |
|  2 | I need some tea                  |  8 | ginger  |
|  3 | I like grapes                    |  8 | ginger  |
|  4 | yes. Beer, Banana, Onion         |  8 | ginger  |
|  1 | I would like to have some banana |  6 | grapes  |
|  2 | I need some tea                  |  6 | grapes  |
|  3 | I like grapes                    |  6 | grapes  |
|  4 | yes. Beer, Banana, Onion         |  6 | grapes  |
|  1 | I would like to have some banana |  7 | guava   |
|  2 | I need some tea                  |  7 | guava   |
|  3 | I like grapes                    |  7 | guava   |
|  4 | yes. Beer, Banana, Onion         |  7 | guava   |
|  1 | I would like to have some banana | 10 | milk    |
|  2 | I need some tea                  | 10 | milk    |
|  3 | I like grapes                    | 10 | milk    |
|  4 | yes. Beer, Banana, Onion         | 10 | milk    |
|  1 | I would like to have some banana |  3 | onion   |
|  2 | I need some tea                  |  3 | onion   |
|  3 | I like grapes                    |  3 | onion   |
|  4 | yes. Beer, Banana, Onion         |  3 | onion   |
|  1 | I would like to have some banana |  4 | potato  |
|  2 | I need some tea                  |  4 | potato  |
|  3 | I like grapes                    |  4 | potato  |
|  4 | yes. Beer, Banana, Onion         |  4 | potato  |
|  1 | I would like to have some banana |  9 | tea     |
|  2 | I need some tea                  |  9 | tea     |
|  3 | I like grapes                    |  9 | tea     |
|  4 | yes. Beer, Banana, Onion         |  9 | tea     |
|  1 | I would like to have some banana |  5 | tomato  |
|  2 | I need some tea                  |  5 | tomato  |
|  3 | I like grapes                    |  5 | tomato  |
|  4 | yes. Beer, Banana, Onion         |  5 | tomato  |
+----+----------------------------------+----+---------+

Repetitive rows.

Body:
CONCAT() is putting strings together. Having it only on one column is useless and prevents the potential use of an index.

Regexp is also overkill. Use LIKE instead.

This query is giving the correct result:

select
*
from
keywords k
join Rfps r on r.subject like concat('%', k.keyword, '%');


问:
Entity Framework AsNoTracking() Infinite Navigation Property
I have implementation like this:

```<code>var query = this.DbContext.Set<T>();

if (includeProperties != null && includeProperties.Any())
{
    foreach (var includeProperty in includeProperties)
    {
        if (!String.IsNullOrEmpty(includeProperty))
        {
            query = query.Include(includeProperty);
        }
    }
}

return await query.Where<T>(predicate).ToListAsync();
</code>```

I'd like to make this query AsNoTracking() and I'm interested if its important where to call AsNoTracking()?

Does it make any difference if I put it here:

```<code>var query = this.DbContext.Set<T>().AsNoTracking();
</code>```

or here:

```<code>return await query.Where<T>(predicate).AsNoTracking().ToListAsync();
</code>```

Will both perform query .AsNoTracking() same way or not?

Also I'm interested if .Include() is also affected by any of these .AsNoTracking() or do I have to put additional .AsNoTracking() like this:

```<code>query = query.Include(includeProperty).AsNoTracking();
</code>```

I'm having trouble with .Include() because I get infinite recursive navigation properties and when using Automapper I get stackoverflow, so I'm not quite sure if I'm using AsNoTracking() correctly (or AsNoTracking() doesn't affect infinite nesting of properties, although I read that somewhere, but only tracks changes in Context for further CUD operations?)

I also have these in my Context subclass:

```<code>this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
</code>```

Though my main problem is inifinite navigation property references, I'd really appreciate if someone could also explain correct usage of AsNoTracking() from beginning of question (although, for example, it doesn't have anything to do with the problem).

Thank you.

答:
No it's not important where to call AsNoTracking(). Basically all it does is sets ObjectQuery.MergeOption (and some other properties) on internal ObjectQuery, so it doesn't matter where to do that until actual query execution.

Yes, all Includeed entities will also not be tracked by a context.

No, LazyLoadingEnabled = false, ProxyCreationEnabled = false and AsNoTracking() will not solve all your infinite recursion problems, especially if you are using includes. Look for how to map such recursive entities with automapper correctly, doing anything on EF side will not help.

Body:
I have implementation like this:

var query = this.DbContext.Set<T>();

if (includeProperties != null && includeProperties.Any())
{
    foreach (var includeProperty in includeProperties)
    {
        if (!String.IsNullOrEmpty(includeProperty))
        {
            query = query.Include(includeProperty);
        }
    }
}

return await query.Where<T>(predicate).ToListAsync();

I'd like to make this query AsNoTracking() and I'm interested if its important where to call AsNoTracking()?

Does it make any difference if I put it here:

var query = this.DbContext.Set<T>().AsNoTracking();

or here:

return await query.Where<T>(predicate).AsNoTracking().ToListAsync();

Will both perform query .AsNoTracking() same way or not?

Also I'm interested if .Include() is also affected by any of these .AsNoTracking() or do I have to put additional .AsNoTracking() like this:

query = query.Include(includeProperty).AsNoTracking();

I'm having trouble with .Include() because I get infinite recursive navigation properties and when using Automapper I get stackoverflow, so I'm not quite sure if I'm using AsNoTracking() correctly (or AsNoTracking() doesn't affect infinite nesting of properties, although I read that somewhere, but only tracks changes in Context for further CUD operations?)

I also have these in my Context subclass:

this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;

Though my main problem is inifinite navigation property references, I'd really appreciate if someone could also explain correct usage of AsNoTracking() from beginning of question (although, for example, it doesn't have anything to do with the problem).

Thank you.


问:
Horizontal scroll in ionic 2
I have been trying to implement horizontal scroll in ionic 2 page. But the content always gets vertically scrolled.

I tried writing my own css by setting 'overflow-x to scroll'. But it didn't work. I also tried ionic's ion-scroll component by setting  'scrollX= true'. But the entire content got hidden. i.e it was not visible on the page at all. Below is the sample code i used for ion-scroll. Not sure what exactly i am missing here.

Any guidance on this pls?. (I am new to Ionic 2 and CSS. So sorry if the question is too simple.)

```<code><ion-navbar *navbar primary>
    <ion-title>
        Title
    </ion-title>
</ion-navbar>

<ion-content>
    <ion-scroll scrollX="true">

        <ion-card>
            <ion-card-content>
                content
            </ion-card-content>
        </ion-card>
        <ion-card>
            <ion-card-content>
                content
            </ion-card-content>
        </ion-card>

    </ion-scroll>
</ion-content>
</code>```

答:
None of the answers here worked for me. What I ended up with is the following HTML.

```<code><ion-scroll scrollX style="height:200px;">
  <div class="scroll-item">
    Item 1
  </div>
  <div class="scroll-item">
    Item 2
  </div>
</ion-scroll>
</code>```

Along with this SCSS. It's important that the child elements are display: inline-block.

```<code>ion-scroll[scrollX] {
  white-space: nowrap;
  .scroll-item {
    display: inline-block;
  }
}
</code>```

Title: Horizontal scroll in ionic 2

Body:
I have been trying to implement horizontal scroll in ionic 2 page. But the content always gets vertically scrolled.

I tried writing my own css by setting 'overflow-x to scroll'. But it didn't work. I also tried ionic's ion-scroll component by setting  'scrollX= true'. But the entire content got hidden. i.e it was not visible on the page at all. Below is the sample code i used for ion-scroll. Not sure what exactly i am missing here.

Any guidance on this pls?. (I am new to Ionic 2 and CSS. So sorry if the question is too simple.)

<ion-navbar *navbar primary>
    <ion-title>
        Title
    </ion-title>
</ion-navbar>

<ion-content>
    <ion-scroll scrollX="true">

        <ion-card>
            <ion-card-content>
                content
            </ion-card-content>
        </ion-card>
        <ion-card>
            <ion-card-content>
                content
            </ion-card-content>
        </ion-card>

    </ion-scroll>
</ion-content>

Body:
None of the answers here worked for me. What I ended up with is the following HTML.

<ion-scroll scrollX style="height:200px;">
  <div class="scroll-item">
    Item 1
  </div>
  <div class="scroll-item">
    Item 2
  </div>
</ion-scroll>

Along with this SCSS. It's important that the child elements are display: inline-block.

ion-scroll[scrollX] {
  white-space: nowrap;
  .scroll-item {
    display: inline-block;
  }
}


问:
Why is the time zone not set correctly from characters
I wonder, why R does not get the correct time zone. Do I miss something?

```<code>my_str <- c("2016-01-01 00:04:52 CET", "2016-01-01 00:09:52 CET",
            "2016-01-01 00:18:04 CET", "2016-01-01 00:18:49 CET")
my_t <- as.POSIXct(my_str)
attributes(my_t)
# $class
# [1] "POSIXct" "POSIXt"
#
# $tzone
# [1] ""

my_t <- lubridate::ymd_hms(my_str)
attributes(my_t)
# $tzone
# [1] "UTC"
#
# $class
# [1] "POSIXct" "POSIXt"
</code>```

This "solves" the problem but I wonder why I have to take care about the obvious:

```<code>my_t <- as.POSIXct(my_str, tz="CET")
attributes(my_t)
# $class
# [1] "POSIXct" "POSIXt"
#
# $tzone
# [1] "CET"
</code>```

答:
The awesome anytime package solves the issue:

```<code>my_str <- c("2016-01-01 00:04:52 CET", "2016-01-01 00:09:52 CET",
            "2016-01-01 00:18:04 CET", "2016-01-01 00:18:49 CET")
library(anytime)

my_t <- anytime(my_str)

attributes(my_t)
#> $class
#> [1] "POSIXct" "POSIXt"
#>
#> $tzone
#> [1] "Europe/Berlin"
</code>```

Body:
I wonder, why R does not get the correct time zone. Do I miss something?

my_str <- c("2016-01-01 00:04:52 CET", "2016-01-01 00:09:52 CET",
            "2016-01-01 00:18:04 CET", "2016-01-01 00:18:49 CET")
my_t <- as.POSIXct(my_str)
attributes(my_t)
# $class
# [1] "POSIXct" "POSIXt"
#
# $tzone
# [1] ""

my_t <- lubridate::ymd_hms(my_str)
attributes(my_t)
# $tzone
# [1] "UTC"
#
# $class
# [1] "POSIXct" "POSIXt"

This "solves" the problem but I wonder why I have to take care about the obvious:

my_t <- as.POSIXct(my_str, tz="CET")
attributes(my_t)
# $class
# [1] "POSIXct" "POSIXt"
#
# $tzone
# [1] "CET"

Body:
The awesome anytime package solves the issue:

my_str <- c("2016-01-01 00:04:52 CET", "2016-01-01 00:09:52 CET",
            "2016-01-01 00:18:04 CET", "2016-01-01 00:18:49 CET")
library(anytime)

my_t <- anytime(my_str)

attributes(my_t)
#> $class
#> [1] "POSIXct" "POSIXt"
#>
#> $tzone
#> [1] "Europe/Berlin"


问:
In excel, How to calculate cricket overs completed and overs left to bowl from a cricket table?
This image will give an idea what I exactly looking for. The completed cells calculated and return the overs completed value and the empty cells calculated the remaining overs value. Please help me.</p>

答:
You need to insert 4 extra col after Over Total.
1 Over Status 2 Over Comp 3 Over Rem 4 Total Ovrs

To find Total Runs in I2 write this,,
=if(and(b2<>"", c2<>"", d2<>"", e2<>"", f2<>"", g2<>"", h2<>""), sum(b2:h2), "")

To find Over status in J2 write this,,
=if(and(I2>=0,I2<> "")," OvrCom", "OvrRem")

IN K2 =Countif(J2:J6," OvrCom")

IN L2 =Countif(J2:J6, "OvrRem")

IN M2 =(k2+L2)

NB I've calculated using 5 over, you adjust cell add accordingly.


问:
Bootstrap show all dropdown on hover
I want all of my dropdown menus to be displayed on hover in any of the menus. I have this code

```<code>ul.nav li.dropdown:hover ul.dropdown-menu{
    display: block;
}
</code>```

But it works only on one menu item where my mouse is. I want all of them to show up. Thank you for your help!

答:
Use a bit of jQuery to do this :

```<code>$("ul.nav").children("li.dropdown").hover(function(){
  var $this = $(this);
  $this.slideDown({duration: /*some duration in ms*/, queue: false});
  $("ul.dropdown-menu").each(function(index, elem){
    $(this).slideDown({duration: /*some duration in ms*/, queue: false});
  });
},function(){
  var $this = $(this);
  $this.slideUp({duration: /*some duration in ms*/, queue: false});
  $("ul.dropdown-menu").each(function(index, elem){//index and elem are required by the each() function
    $(this).slideUp({duration: /*some duration in ms*/, queue: false});
  });
});
</code>```

This should slide down everything on hover and slide up everything when mouse leaves (not hover anymore).

Title: Bootstrap show all dropdown on hover

Body:
I want all of my dropdown menus to be displayed on hover in any of the menus. I have this code

ul.nav li.dropdown:hover ul.dropdown-menu{
    display: block;
}

But it works only on one menu item where my mouse is. I want all of them to show up. Thank you for your help!

Body:
Use a bit of jQuery to do this :

$("ul.nav").children("li.dropdown").hover(function(){
  var $this = $(this);
  $this.slideDown({duration: /*some duration in ms*/, queue: false});
  $("ul.dropdown-menu").each(function(index, elem){
    $(this).slideDown({duration: /*some duration in ms*/, queue: false});
  });
},function(){
  var $this = $(this);
  $this.slideUp({duration: /*some duration in ms*/, queue: false});
  $("ul.dropdown-menu").each(function(index, elem){//index and elem are required by the each() function
    $(this).slideUp({duration: /*some duration in ms*/, queue: false});
  });
});

This should slide down everything on hover and slide up everything when mouse leaves (not hover anymore).


问:
Magento - CSS is not loading in magento
I have installed Magento on live server. But the problem is that its not loading css. I have double checked .htaccess file but There is nothing any issue in it. I have given full access permission on Var, Media & app/etc folder.

Please let me know that what is the issue ?

Thanks in advance.

Alex S.

答:
I will suggest follow step by step.

There is 2 case:

1) You can see your CCS directly from URL, so browser load it by direct URL, example: http://your-magento/skin/frontend/your-package/your-theme/css/styles.css, so in this case you should check points connected with Magento:

Check/Correct Base URL from config or DB

Clear Cache

Clear Sessions

Check Configurations

2) If your CSS is not loading by direct URL. So in this case it is not connected with Magento at all.
In this case you should check follwoing points:

Check files and folders permissions

Check rewrite rules and modules

Server Log files to find error

Check .htaccess for existance and for correctness.

Important, check all .htaccess files in all sub-folders.

In my case, I differed this 2 cases and start seaching my issue in second case.

I found .htaccess in folder /skin/frontend/your-package/your-theme/
The content was following:

```<code>Order deny,allow
Deny from all
</code>```

Remove this file and your CSS files will be loaded.
I don't know how this file was created, I don't have file like this in parent theme. I think Magento is automatically created it. Be attentive and follow changes with GIT.

Title: Magento - CSS is not loading in magento

Body:
I will suggest follow step by step.

There is 2 case:

1) You can see your CCS directly from URL, so browser load it by direct URL, example: http://your-magento/skin/frontend/your-package/your-theme/css/styles.css, so in this case you should check points connected with Magento:

Check/Correct Base URL from config or DB

Clear Cache

Clear Sessions

Check Configurations

2) If your CSS is not loading by direct URL. So in this case it is not connected with Magento at all.
In this case you should check follwoing points:

Check files and folders permissions

Check rewrite rules and modules

Server Log files to find error

Check .htaccess for existance and for correctness.

Important, check all .htaccess files in all sub-folders.

In my case, I differed this 2 cases and start seaching my issue in second case.

I found .htaccess in folder /skin/frontend/your-package/your-theme/
The content was following:

Order deny,allow
Deny from all

Remove this file and your CSS files will be loaded.
I don't know how this file was created, I don't have file like this in parent theme. I think Magento is automatically created it. Be attentive and follow changes with GIT.


问:
Fastlane command not found
I am trying to install fastlane. I have Xcode installed. I installed fastlane using the command sudo gem install fastlane. I now go into my project folder and type fastlane init and get the error:

-bash: fastlane: command not found.

I see that fastlane is installed and can see it here

/Users/username/.gem/ruby/2.0.0/gems/fastlane-1.70.0/bin

on my Mac.

I tried adding this to my PATH, but I still get the same error.  My path is

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:./Users/username/.gem/ruby/2.0.0/gems/

What am I missing here?

答:
I got run into similar issue last week. I installed fastlane using homebrew on mac, but it was showing the same error.

I tried installing it using Ruby and it worked like a charm. Here is the command.

```<code>sudo gem install fastlane -NV
</code>```

Also seems like you have not installed command line tools for xcode.

Install them using xcode-select --install

Title: Fastlane command not found

Body:
I got run into similar issue last week. I installed fastlane using homebrew on mac, but it was showing the same error.

I tried installing it using Ruby and it worked like a charm. Here is the command.

sudo gem install fastlane -NV

Also seems like you have not installed command line tools for xcode.

Install them using xcode-select --install