问:
C# Recursive Permutation is Possible? (beginner)
Hi guys im trying to learn permutation and recurtion. And im looking for a way how can i use bought at the same time.

MAIN:

```<code>namespace Recursive_Permutation
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[5] { 0, 0, 0, 0, 0 };
            CalPermutations CP = new CalPermutations();
            CP.Run(array, array.Length-1);

        }
    }
}
</code>```

Here is my Simple code:

```<code>namespace Recursive_Permutation
{
    public class CalPermutations
    {
        public int Run(int[] array,int indexer)
        {
            if (indexer > array.Length)
            {
                return 1;
            }
            else
            {
                for (int i = 0; i <= array.Length; i++)
                {
                    array[indexer] = i;
                    Display(array);
                }
                Run(array, indexer-1);

            }
            return indexer;
        }
        public void Display(int[] array)
        {
            foreach (int num in array)
            {
                Console.Write(num);
            }
            Console.WriteLine();
        }

    }
}
</code>```

And here is the Output of the program:

Question:
it might be simple to other but im kind of confuse now in how can i manipulate it that it still count the first digit (position [0]) 1 to 5 and go next position and (position 1) and add 1 and go back to [0] and start count again till it reaches 5.

i hope that my explanation is understandable.. thx.

答:
Update: added comments on each method as per comment.

```<code>public class Program
{
    public static void Main(string[] args)
    {
        int[] array = new int[] { 0, 0, 0, 0, 0};
        CalPermutations CP = new CalPermutations();
        CP.Run(array, 0);
    }
}

public class CalPermutations
{
    // Prints all the permutations of array, starting at the specified index.
    public void Run(int[] array, int indexer)
    {
        if (indexer < 0 || indexer >= array.Length)
            return;

        // Keep [0, indexer] combination constant, change combination on right i.e. (indexer, Array.length).
        Run(array, indexer+1);

        // All the elements on right have finished, increment current element.
        array[indexer]++;

        // Check if current combination is STILL valid.
        if(array[indexer] <= array.Length)
        {
            // since current combination is still valid, display it, and execute the process again on the new combination.
            Display(array);
            Run(array, indexer);
        }
        else
        {
            // Since current element is out of range, reset it.
            array[indexer] = 1;
        }
    }

    // Prints all the elements in array.
    public void Display(int[] array)
    {
        foreach (int num in array)
            Console.Write(num);
        Console.WriteLine();
    }
}
</code>```

Body:
Hi guys im trying to learn permutation and recurtion. And im looking for a way how can i use bought at the same time.

MAIN:

namespace Recursive_Permutation
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[5] { 0, 0, 0, 0, 0 };
            CalPermutations CP = new CalPermutations();
            CP.Run(array, array.Length-1);

        }
    }
}

Here is my Simple code:

namespace Recursive_Permutation
{
    public class CalPermutations
    {
        public int Run(int[] array,int indexer)
        {
            if (indexer > array.Length)
            {
                return 1;
            }
            else
            {
                for (int i = 0; i <= array.Length; i++)
                {
                    array[indexer] = i;
                    Display(array);
                }
                Run(array, indexer-1);

            }
            return indexer;
        }
        public void Display(int[] array)
        {
            foreach (int num in array)
            {
                Console.Write(num);
            }
            Console.WriteLine();
        }

    }
}

And here is the Output of the program:

Question:
it might be simple to other but im kind of confuse now in how can i manipulate it that it still count the first digit (position [0]) 1 to 5 and go next position and (position 1) and add 1 and go back to [0] and start count again till it reaches 5.

i hope that my explanation is understandable.. thx.

Body:
Update: added comments on each method as per comment.

public class Program
{
    public static void Main(string[] args)
    {
        int[] array = new int[] { 0, 0, 0, 0, 0};
        CalPermutations CP = new CalPermutations();
        CP.Run(array, 0);
    }
}

public class CalPermutations
{
    // Prints all the permutations of array, starting at the specified index.
    public void Run(int[] array, int indexer)
    {
        if (indexer < 0 || indexer >= array.Length)
            return;

        // Keep [0, indexer] combination constant, change combination on right i.e. (indexer, Array.length).
        Run(array, indexer+1);

        // All the elements on right have finished, increment current element.
        array[indexer]++;

        // Check if current combination is STILL valid.
        if(array[indexer] <= array.Length)
        {
            // since current combination is still valid, display it, and execute the process again on the new combination.
            Display(array);
            Run(array, indexer);
        }
        else
        {
            // Since current element is out of range, reset it.
            array[indexer] = 1;
        }
    }

    // Prints all the elements in array.
    public void Display(int[] array)
    {
        foreach (int num in array)
            Console.Write(num);
        Console.WriteLine();
    }
}


来源: stackexchange

问:
How correctly to serialize such JSON by means of GSON Android?
How correctly to serialize such JSON by means of GSON Android?

```<code>  [
        {
            "id": "bitcoin",
            "name": "Bitcoin",
            "symbol": "BTC",
            "rank": "1",
            "price_usd": "15022.7",
            "price_btc": "1.0",
            "24h_volume_usd": "13711300000.0",
            "market_cap_usd": "251264422255",
            "available_supply": "16725650.0",
            "total_supply": "16725650.0",
            "max_supply": "21000000.0",
            "percent_change_1h": "0.94",
            "percent_change_24h": "17.4",
            "percent_change_7d": "47.71",
            "last_updated": "1512638053"
        },
        {
            "id": "ethereum",
            "name": "Ethereum",
            "symbol": "ETH",
            "rank": "2",
            "price_usd": "427.071",
            "price_btc": "0.0291936",
            "24h_volume_usd": "2007350000.0",
            "market_cap_usd": "41078436955.0",
            "available_supply": "96186435.0",
            "total_supply": "96186435.0",
            "max_supply": null,
            "percent_change_1h": "-1.59",
            "percent_change_24h": "-5.64",
            "percent_change_7d": "-3.22",
                "last_updated": "1512638054"
            }
    ]
</code>```

Data class:

```<code>class AllCurrenсyData {

    @SerializedName("")
    @Expose
    var currency: List<Currency>? = null

}

class Currency {

    @SerializedName("price_usd")
    @Expose
    val priceUsd: String? = null

    @SerializedName("symbol")
    @Expose
    val symbol: String? = null

    @SerializedName("last_updated")
    @Expose
    val lastUpdated: String? = null

    @SerializedName("total_supply")
    @Expose
    val totalSupply: String? = null

    @SerializedName("24h_volume_usd")
    @Expose
    val jsonMember24hVolumeUsd: String? = null

    @SerializedName("price_btc")
    @Expose
    val priceBtc: String? = null

    @SerializedName("available_supply")
    @Expose
    val availableSupply: String? = null

    @SerializedName("market_cap_usd")
    @Expose
    val marketCapUsd: String? = null

    @SerializedName("percent_change_1h")
    @Expose
    val percentChange1h: String? = null

    @SerializedName("percent_change_24h")
    @Expose
    val percentChange24h: String? = null

    @SerializedName("name")
    @Expose
    val name: String? = null

    @SerializedName("max_supply")
    @Expose
    val maxSupply: String? = null

    @SerializedName("rank")
    @Expose
    val rank: String? = null

    @SerializedName("id")
    @Expose
    val id: String? = null

    @SerializedName("percent_change_7d")
    @Expose
    val percentChange7d: String? = null
}
</code>```

To implement this I created such classes. But I'm listening to such a stack of errors:

```<code>FATAL EXCEPTION: main
                                                                     Process: it.incode.cryptocoins, PID: 2620
                                                                     io.reactivex.exceptions.OnErrorNotImplementedException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
                                                                         at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
                                                                         at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
                                                                         at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:74)
                                                                         at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.checkTerminated(ObservableObserveOn.java:276)
                                                                         at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
                                                                         at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
                                                                         at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
                                                                         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:6164)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
                                                                      Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
                                                                         at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
                                                                         at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:118)
                                                                         at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:212)
                                                                         at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:41)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableMap.subscribeActual(ObservableMap.java:33)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
                                                                         at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
                                                                         at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                         at java.lang.Thread.run(Thread.java:761)
                                                                      Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
                                                                         at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
                                                                         at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
                                                                         at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:118)
                                                                         at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:212)
                                                                         at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:41)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableMap.subscribeActual(ObservableMap.java:33)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
                                                                         at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
                                                                         at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                         at java.lang.Thread.run(Thread.java:761)
</code>```

Most likely I'm not correctly processing an array of data that does not have a name for serialization. I hope someone will tell me where my mistake is.

答:
You dont need object AllCurrenсyData, you have to change only your call to return list of elements

```<code>fun getData() : Call<List<Currency>>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How correctly to serialize such JSON by means of GSON Android?

  [
        {
            "id": "bitcoin",
            "name": "Bitcoin",
            "symbol": "BTC",
            "rank": "1",
            "price_usd": "15022.7",
            "price_btc": "1.0",
            "24h_volume_usd": "13711300000.0",
            "market_cap_usd": "251264422255",
            "available_supply": "16725650.0",
            "total_supply": "16725650.0",
            "max_supply": "21000000.0",
            "percent_change_1h": "0.94",
            "percent_change_24h": "17.4",
            "percent_change_7d": "47.71",
            "last_updated": "1512638053"
        },
        {
            "id": "ethereum",
            "name": "Ethereum",
            "symbol": "ETH",
            "rank": "2",
            "price_usd": "427.071",
            "price_btc": "0.0291936",
            "24h_volume_usd": "2007350000.0",
            "market_cap_usd": "41078436955.0",
            "available_supply": "96186435.0",
            "total_supply": "96186435.0",
            "max_supply": null,
            "percent_change_1h": "-1.59",
            "percent_change_24h": "-5.64",
            "percent_change_7d": "-3.22",
                "last_updated": "1512638054"
            }
    ]

Data class:

class AllCurrenсyData {

    @SerializedName("")
    @Expose
    var currency: List<Currency>? = null

}

class Currency {

    @SerializedName("price_usd")
    @Expose
    val priceUsd: String? = null

    @SerializedName("symbol")
    @Expose
    val symbol: String? = null

    @SerializedName("last_updated")
    @Expose
    val lastUpdated: String? = null

    @SerializedName("total_supply")
    @Expose
    val totalSupply: String? = null

    @SerializedName("24h_volume_usd")
    @Expose
    val jsonMember24hVolumeUsd: String? = null

    @SerializedName("price_btc")
    @Expose
    val priceBtc: String? = null

    @SerializedName("available_supply")
    @Expose
    val availableSupply: String? = null

    @SerializedName("market_cap_usd")
    @Expose
    val marketCapUsd: String? = null

    @SerializedName("percent_change_1h")
    @Expose
    val percentChange1h: String? = null

    @SerializedName("percent_change_24h")
    @Expose
    val percentChange24h: String? = null

    @SerializedName("name")
    @Expose
    val name: String? = null

    @SerializedName("max_supply")
    @Expose
    val maxSupply: String? = null

    @SerializedName("rank")
    @Expose
    val rank: String? = null

    @SerializedName("id")
    @Expose
    val id: String? = null

    @SerializedName("percent_change_7d")
    @Expose
    val percentChange7d: String? = null
}

To implement this I created such classes. But I'm listening to such a stack of errors:

FATAL EXCEPTION: main
                                                                     Process: it.incode.cryptocoins, PID: 2620
                                                                     io.reactivex.exceptions.OnErrorNotImplementedException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
                                                                         at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
                                                                         at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
                                                                         at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:74)
                                                                         at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.checkTerminated(ObservableObserveOn.java:276)
                                                                         at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
                                                                         at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
                                                                         at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
                                                                         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:6164)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
                                                                      Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
                                                                         at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
                                                                         at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:118)
                                                                         at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:212)
                                                                         at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:41)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableMap.subscribeActual(ObservableMap.java:33)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
                                                                         at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
                                                                         at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                         at java.lang.Thread.run(Thread.java:761)
                                                                      Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
                                                                         at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
                                                                         at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
                                                                         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
                                                                         at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:118)
                                                                         at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:212)
                                                                         at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:41)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableMap.subscribeActual(ObservableMap.java:33)
                                                                         at io.reactivex.Observable.subscribe(Observable.java:10842)
                                                                         at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
                                                                         at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
                                                                         at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
                                                                         at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                         at java.lang.Thread.run(Thread.java:761)

Most likely I'm not correctly processing an array of data that does not have a name for serialization. I hope someone will tell me where my mistake is.

Body:
You dont need object AllCurrenсyData, you have to change only your call to return list of elements

fun getData() : Call<List<Currency>>


问:
SQL join and group problem
First to say I'm using mySQL and my only way of accessing database is over phpMyAdmin since this is for a website.

First I have a table of users like this (table1):

```<code>user_id | name
--------------
      1 | Mike
      2 | Johny
      3 | Bob
</code>```

and another table about their season results (table2):

```<code>user_id | season | result
-------------------------
      1 | 2009   |     10
      1 | 2010   |      8
      1 | 2011   |      5
      2 | 2009   |      7
      2 | 2010   |      3
      3 | 2009   |      1
</code>```

And now I want out the user's name and his last season's result, so something like this:

```<code>user_id | name | season | result
--------------------------------
      1 | Mike |   2011 |      5
      2 | Johny|   2010 |      3
      3 | Bob  |   2009 |      1
</code>```

The closest I have come to something like this was

```<code>SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id
</code>```

But I cannot provide that I want the newest season and it just uses a random one.
Anyone has any ideas how to do this?

best regards,
Rok

答:
```<code>SELECT *
FROM table1, table2,
(SELECT user_id AS lUserid, MAX(season) AS lSeason FROM table2 GROUP BY user_id) AS lTable2
WHERE table1.user_id = table2.user_id
AND table2.user_id = lTable2.lUserid
AND table2.season = lTablle2.lSeason
</code>```

ContentLicense: CC BY-SA 2.5

Title: SQL join and group problem

Body:
First to say I'm using mySQL and my only way of accessing database is over phpMyAdmin since this is for a website.

First I have a table of users like this (table1):

user_id | name
--------------
      1 | Mike
      2 | Johny
      3 | Bob

and another table about their season results (table2):

user_id | season | result
-------------------------
      1 | 2009   |     10
      1 | 2010   |      8
      1 | 2011   |      5
      2 | 2009   |      7
      2 | 2010   |      3
      3 | 2009   |      1

And now I want out the user's name and his last season's result, so something like this:

user_id | name | season | result
--------------------------------
      1 | Mike |   2011 |      5
      2 | Johny|   2010 |      3
      3 | Bob  |   2009 |      1

The closest I have come to something like this was

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id

But I cannot provide that I want the newest season and it just uses a random one.
Anyone has any ideas how to do this?

best regards,
Rok


问:
Extract a youtube video url from a site url using jsoup
I had this code working for the same site but they changed the theme and now i'm struggling. What could i be doing wrong here to get the url of the youtube video? Here's my approach. The example link of the site is http://kabumbu.co.tz/mahojiano-na-masau-bwire/

```<code>Element video = doc.select("div.single-archive iframe").first() ;
          videourl = video.attr("src");
</code>```

答:
The Best Way is</p>

```<code>code =youtubeUrl.substring(youtubeUrl.length() - 11);
</code>```

Body:
I had this code working for the same site but they changed the theme and now i'm struggling. What could i be doing wrong here to get the url of the youtube video? Here's my approach. The example link of the site is http://kabumbu.co.tz/mahojiano-na-masau-bwire/

Element video = doc.select("div.single-archive iframe").first() ;
          videourl = video.attr("src");

Body:
The Best Way is

code =youtubeUrl.substring(youtubeUrl.length() - 11);


问:
How to limit content length response of simplified HTTP request in node?
I would like to setup the simplified HTTP request() client package to abort the download of HTTP resources that are too big.

Let's imagine request() is setup to download an url and the resource size is 5 Gigabytes. I would like request() to stop downloading after 10MB. Usually, when request gets an answer it gets all the HTTP headers and everything behind. Once you manipulate the data, you have already all the downloaded data.

In axios, there is a parameter called maxContentLength but I can't find anything similar for request().

I must also mention, that I don't it to catch an error but only download at least the headers and the beginning of the resource.

答:
You can use the data event in this case of request package also. I tested below and it worked fine for me

```<code>var request = require("request");

var size = 0;
const MAX_SIZE = 200;
request
    .get('http://google.com/')
    .on('data', function(buffer){
        // decompressed data as it is received

        size += buffer.length;

        if (size > MAX_SIZE) {
            console.log("Aborting this request as it exceeds max size")
            this.abort();
        }
        console.log("data coming");

    }).on('end', function() {
        console.log('ending request')
    })
    .on('response', function (response) {
        console.log(response.statusCode) // 200
        console.log(response.headers['content-type']) // 'image/png'
        response.on('data', function (data) {
            // compressed data as it is received
            console.log('received ' + data.length + ' bytes of compressed data')
            // you can size and abort here also if you want.
        })
    });
</code>```

There are two places where you can do the size checking, either where you get compressed data or where you get uncompressed data (based on example given at https://www.npmjs.com/package/request)

Body:
You can use the data event in this case of request package also. I tested below and it worked fine for me

var request = require("request");

var size = 0;
const MAX_SIZE = 200;
request
    .get('http://google.com/')
    .on('data', function(buffer){
        // decompressed data as it is received

        size += buffer.length;

        if (size > MAX_SIZE) {
            console.log("Aborting this request as it exceeds max size")
            this.abort();
        }
        console.log("data coming");

    }).on('end', function() {
        console.log('ending request')
    })
    .on('response', function (response) {
        console.log(response.statusCode) // 200
        console.log(response.headers['content-type']) // 'image/png'
        response.on('data', function (data) {
            // compressed data as it is received
            console.log('received ' + data.length + ' bytes of compressed data')
            // you can size and abort here also if you want.
        })
    });

There are two places where you can do the size checking, either where you get compressed data or where you get uncompressed data (based on example given at https://www.npmjs.com/package/request)


问:
Are Amazon RDS instances upgradable?
Will I am able to switch (I mean upgrade or downgrade) Amazon RDS instance on need basis or do I have to create a new afresh and go through migration?</p>

答: Yes, they're upgradable. Upgraded RDS instance from SQL Server 2008 to SQL Server 2012 for instance size of about 36 GB, class db-m1-small, storage 200 GB and with no IOPS or Multi AZ. There was no downtime, this process barely took 10 minutes.</p>

Title: Are Amazon RDS instances upgradable?


问:
Regarding dbms_job.submit
I am kind of new to scheduling jobs in Oracle. Consider that i am using dbms_job.submit to run multiple Jobs(Procedure) in oracle. Will each job have different sessions?

```<code>dbms_job.submit(1, 'begin proc; end;' );
dbms_job.submit(2, 'begin proc; end;' );
</code>```

Now the question is will the jobs running (2 jobs mentioned above) have different session id or the same?

The reason i am asking you the question is because imagine that both the jobs are running parallel, and the JOB 1 is gonna commit as it got completed successfully, but during that time JOB 2 got failed and the rollback occurred. During this scenario will the records that is to be committed by JOB1 will also get rollback as well?

答:
The Oracle documentation is quite clear: background jobs run in their own session. So there is no relationship between the sessions of job 1 and job 2.

Incidentally, if you are using a modern version of the database (11g or later) you really should use DBMS_SCHEDULER rather than the deprecated DBMS_JOB. Find out more.

Title: Regarding dbms_job.submit

Body:
I am kind of new to scheduling jobs in Oracle. Consider that i am using dbms_job.submit to run multiple Jobs(Procedure) in oracle. Will each job have different sessions?

dbms_job.submit(1, 'begin proc; end;' );
dbms_job.submit(2, 'begin proc; end;' );

Now the question is will the jobs running (2 jobs mentioned above) have different session id or the same?

The reason i am asking you the question is because imagine that both the jobs are running parallel, and the JOB 1 is gonna commit as it got completed successfully, but during that time JOB 2 got failed and the rollback occurred. During this scenario will the records that is to be committed by JOB1 will also get rollback as well?


问:
2d Mountainy Terrain
Hi i am new on strackoverflow, could anyone help me with 2d Terrain trigonometry algorithm, how to achieve something like in screenshot?

this tutorial helps me a lot but still can't figure out how to create mountain terrain

My attempt evolved to this:

```<code>Vector (v0.x + t * length, center + amplitude * Mathf.Cos (angle * t));
</code>```

thanks in advance

答:
it looks like chain so:

generate n random height points

just the peaks covering your screen or map or whatever.

compute chain between neighbors

the chain length should be bigger then the distance between points. For the math see:

Wiki: Catenary

the equation image was taken from the Wiki page linked.

Title: 2d Mountainy Terrain

Body:
Hi i am new on strackoverflow, could anyone help me with 2d Terrain trigonometry algorithm, how to achieve something like in screenshot?

this tutorial helps me a lot but still can't figure out how to create mountain terrain

My attempt evolved to this:

Vector (v0.x + t * length, center + amplitude * Mathf.Cos (angle * t));

thanks in advance


问:
Timeout in Async Method
I have an async Method named "RequestMessage()". Within this method, I'm going to send a message to a message broker. Since I don't know when to expect the result, I'm using "TaskCompletionSource". I want the async method to terminate, when the reply message arrived (I'll receive an event from the broker).

This works fine so far. Now, my issue is that this message could never be answered, or at least way to late.

I'm looking for a change to implement my own timeout. To do so, I tried a Timer, as well as the Observer of Reactive Extensions. Th issue is always the same - I can't get my main thread and the timer thread syncronized, as I'm using .NET Core 2 and there is no SynchronizationContext.

So, in my code there is an observer ..

```<code>        Observable
        .Interval(TimeSpan.FromSeconds(timeOutInSeconds))
        .Subscribe(
            x =>
            {
                timeoutCallback();
            });
</code>```

If time expires a callback should be called. In my caller method, I handle the callback this way:

```<code>    TimeoutDelegate timeoutHandler = () => throw new WorkcenterRepositoryCommunicationException("Broker communication timed out.", null);
</code>```

As you realized already, this Exception will never be catched, as it is not thrown to the main thread.

How can I sync threads here?

Thanks in advance!

答:
The best way to "fail upon some problem" IMHO would be to throw the appropriate exception, but you can definitely just use return; if you prefer to avoid exceptions.

This will create a completed/faulted task that was completed synchronously, so the caller using await will get a finished task and continue on using the same thread.

CancellationToken allows for the caller to cancel the operation, which isn't the case you are describing.
Task.Yield doesn't terminate any operation, it just enables other tasks to run for some time and reschedules itself for later.

Title: Timeout in Async Method

Body:
I have an async Method named "RequestMessage()". Within this method, I'm going to send a message to a message broker. Since I don't know when to expect the result, I'm using "TaskCompletionSource". I want the async method to terminate, when the reply message arrived (I'll receive an event from the broker).

This works fine so far. Now, my issue is that this message could never be answered, or at least way to late.

I'm looking for a change to implement my own timeout. To do so, I tried a Timer, as well as the Observer of Reactive Extensions. Th issue is always the same - I can't get my main thread and the timer thread syncronized, as I'm using .NET Core 2 and there is no SynchronizationContext.

So, in my code there is an observer ..

        Observable
        .Interval(TimeSpan.FromSeconds(timeOutInSeconds))
        .Subscribe(
            x =>
            {
                timeoutCallback();
            });

If time expires a callback should be called. In my caller method, I handle the callback this way:

    TimeoutDelegate timeoutHandler = () => throw new WorkcenterRepositoryCommunicationException("Broker communication timed out.", null);

As you realized already, this Exception will never be catched, as it is not thrown to the main thread.

How can I sync threads here?

Thanks in advance!


问:
PresentViewController from a presentedViewController is not showing navigation bar
I have three view controllers (vc1, vc2, vc3) and two navigation controllers (nav1, nav2).

nav1 is the entry point of the storyboard.

vc1 is the rootViewController of nav1.

vc2 is the rootViewController of nav2.

nav2 is presented from vc1 through nav1.

Now when I tried to present vc3 from vc2 through nav2, navigation bar is not showing.

答:
Now, the way iOS works, it will never give you an instance of your navigation controller in a presented view controller because when you present a view controller, it is not added to the viewcontroller stack of the navigation controller.
The reason you can see the navigation controller in the other two is because your'e presenting the navigation controller itself and not view controller.


问:
Two md-content next to eachother in md-card

Im trying to get 2 content "boxes" in one md-card. One where the user can enter some textfields, and on the other side i want a logo.

```<code><md-card ng-controller="AuthenticationController">
    <md-content class="left_side" layout-align="center center">

    </md-content>

    <md-content class="right_side" layout-align="right">

    </md-content>
</md-card>
</code>```

CSS

```<code>    .left_side {
   height: 100%;
   width: 50%;
   background-color: blue;
   display: flex;
 }

    .right_side {
  height: 100%;
  width: 50%;
  background-color: red;
  display: flex;
  margin-right: 0px;
}
</code>```

I think it's quite simple, but somehow i keep thinking wrong, because i dont get it.

答:
This did the trick for me</p>

```<code><div ng-controller="AppCtrl" class="md-padding selectdemoBasicUsage" ng-cloak="" ng-app="MyApp" id="container">
    <md-content class="md-padding" layout-xs="column" layout="row" layout-align="center center">
        <div flex-xs flex-gt-xs="70" layout="column" layout-align="center center">
            <md-card layout="row" ng-controller="AppCtrl" layout-align="center center">

                <md-content class="left_side" layout-align="center center" layout="column">

                    <md-content id="headerTxt">Welkom!</md-content> <br>
                    <md-content id="formContent" md-colors="orange">

                        <form id="formDetails" ng-submit="" layout="column">
                            <md-input-container class="md-default-theme-theme md-input-has-value">
                                <input autofocus="" autocomplete="off" ng-model="credentials.username" required="" id="input_0" aria-invalid="false" style="">
                                <div class="md-errors-spacer"></div>
                                <label translate="" class="capitalize ng-scope" for="input_0">Gebruikersnaam</label>
                            </md-input-container>

                            <md-input-container>
                                <input type="password" ng-model="credentials.password" required="" id="input_1" aria-invalid="false" style="">
                                <div class="md-errors-spacer"></div>
                                <label translate="" for="input_1">Wachtwoord</label>
                            </md-input-container>
                            <div layout="row" layout-align="end center" class="layout-align-end-center layout-row">

                                <button class="md-primary md-raised capitalize md-button md-default-theme-theme md-ink-ripple" type="submit"
                                       ng-disabled="authenticationForm.$invalid || authenticationForm.proccess.$state.busy">INLOGGEN</button>
                            </div>

                        </form>
                    </md-content>
                </md-content>

                <md-content class="right_side" layout-align="center center">

                    <img width="100px" height="100px">
                </md-content>
            </md-card>
        </div>
    </md-content>
</div>
</code>```

Body:
Im trying to get 2 content "boxes" in one md-card. One where the user can enter some textfields, and on the other side i want a logo.

<md-card ng-controller="AuthenticationController">
    <md-content class="left_side" layout-align="center center">

    </md-content>

    <md-content class="right_side" layout-align="right">

    </md-content>
</md-card>

CSS

    .left_side {
   height: 100%;
   width: 50%;
   background-color: blue;
   display: flex;
 }

    .right_side {
  height: 100%;
  width: 50%;
  background-color: red;
  display: flex;
  margin-right: 0px;
}

I think it's quite simple, but somehow i keep thinking wrong, because i dont get it.

Body:
This did the trick for me

<div ng-controller="AppCtrl" class="md-padding selectdemoBasicUsage" ng-cloak="" ng-app="MyApp" id="container">
    <md-content class="md-padding" layout-xs="column" layout="row" layout-align="center center">
        <div flex-xs flex-gt-xs="70" layout="column" layout-align="center center">
            <md-card layout="row" ng-controller="AppCtrl" layout-align="center center">

                <md-content class="left_side" layout-align="center center" layout="column">

                    <md-content id="headerTxt">Welkom!</md-content> <br>
                    <md-content id="formContent" md-colors="orange">

                        <form id="formDetails" ng-submit="" layout="column">
                            <md-input-container class="md-default-theme-theme md-input-has-value">
                                <input autofocus="" autocomplete="off" ng-model="credentials.username" required="" id="input_0" aria-invalid="false" style="">
                                <div class="md-errors-spacer"></div>
                                <label translate="" class="capitalize ng-scope" for="input_0">Gebruikersnaam</label>
                            </md-input-container>

                            <md-input-container>
                                <input type="password" ng-model="credentials.password" required="" id="input_1" aria-invalid="false" style="">
                                <div class="md-errors-spacer"></div>
                                <label translate="" for="input_1">Wachtwoord</label>
                            </md-input-container>
                            <div layout="row" layout-align="end center" class="layout-align-end-center layout-row">

                                <button class="md-primary md-raised capitalize md-button md-default-theme-theme md-ink-ripple" type="submit"
                                       ng-disabled="authenticationForm.$invalid || authenticationForm.proccess.$state.busy">INLOGGEN</button>
                            </div>

                        </form>
                    </md-content>
                </md-content>

                <md-content class="right_side" layout-align="center center">

                    <img width="100px" height="100px">
                </md-content>
            </md-card>
        </div>
    </md-content>
</div>


问:
Working with mkfifo and transport streams, is this possible?
I want to execute a bash script that would do the following:

Application 'ffmpeg' generates a LIVE transport stream (.ts) file. I need to work on this live streaam (perform de-multiplexing, etc).

Now I know this has to be done via FIFOs; but here is my task.

I need to redirect the output of ffmpeg to write to a fifo, and then another application will work on that fifo contents. This happens continuously in real time until I press, say Ctrl+C.

Is this possible?
Will I have to do this is two terminals?

I'm basically writing a bash script for the above operations (and more) so do I have to invoke two terminals, or maybe fork?

Kindly advise.

Thanks in advance!

答:
FFmpeg does support pipes.
Everything you have to done is approach as follows:

make a fifo

```<code>mkfifo first.ts
</code>```

run ffmpeg with pipe

```<code>ffmpeg -i sample.ts -c copy -muxrate 5000000 pipe:1 > first.ts
</code>```

run any other tools which work with transport stream files, e.g. OpenCaster tool tscbrmuxer which can add e.g. NIT table to transport stream file

```<code>tscbrmuxer b:3008 NIT.ts b:5000000 first.ts > second.ts
</code>```

If you want to stop 2 tools simply kill the last one that uses pipe/fifo. in out case you have to kill tscbrmuxer.

```<code>kill tscbrmuxer
</code>```

OR

If you are not running last tool in the background simply kill it with [ctrl+c]

Thanks to using such an approach (e.g. as a shell script or Python one) all tools that uses pipe/fifo will be terminated due to broken pipe.

I hope this will help you.

Body:
FFmpeg does support pipes.
Everything you have to done is approach as follows:

make a fifo

mkfifo first.ts

run ffmpeg with pipe

ffmpeg -i sample.ts -c copy -muxrate 5000000 pipe:1 > first.ts

run any other tools which work with transport stream files, e.g. OpenCaster tool tscbrmuxer which can add e.g. NIT table to transport stream file

tscbrmuxer b:3008 NIT.ts b:5000000 first.ts > second.ts

If you want to stop 2 tools simply kill the last one that uses pipe/fifo. in out case you have to kill tscbrmuxer.

kill tscbrmuxer

OR

If you are not running last tool in the background simply kill it with [ctrl+c]

Thanks to using such an approach (e.g. as a shell script or Python one) all tools that uses pipe/fifo will be terminated due to broken pipe.

I hope this will help you.


问:
How to create ASPX Page Dynamically
i have two controls on asp.net page , textbox and button and i want to write new page into textbox then when i hit the button i want to create new asp.net web page with textbox text. what do you want me to prefer to do this? is there any step by step tutorial or any code you have done before? thanks for asnwers.

ok more detail about what i want.

textbox control text is "contact" and i click my button control. button take textbox text "contact" and create new web form page which name is "contact.aspx and its code page contact.cs" . thats it. just create new web form page under root directory with button click.

maybe there is a single code line like

Page pg =new Page();
pg.create();

答:
You can use the Page.ParseControl method.

Beware, it does not support everything you can do with a real ASPX or ASHX file, but it works for simple things. An example is available here: Using Page.ParseControl to add new control from Control Tag

Title: How to create ASPX Page Dynamically


问:
Fixing simultaneous memory access error for array of custom class iOS
in my app I've a viewcontroller with tableview and when it load it gives me about 12 simultaneous memory error all in same place where I try to remove the element from my custom array. Below are the related codes

In my viewcontroller where table loads I've accesses the method as below

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    //Some Code

    arrangeTableObject.arrangetableSectionsInOrderForNoteType(withFrameId:tableDataSection.frameId.uintValue)

   //Some code
   return cell
}
</code>```

In my another swift class arrangeTableObject.swift this is how I've used the methods

```<code>//My custom array is defined as
var tableSections : [TableSection]?

func arrangetableSectionsInOrderForNoteType(type: NoteType){

        var tableIndex = 0

        if tableSectionForItemType(itemType: .tableItemNoteItems) != nil  {

            let noteItemSection = tableSectionForItemType(itemType: .tableItemNoteItems)
            removetableSectionWithFrameId(itemType: . tableItemNoteItems)
            tableSections?.insert(noteItemSection!, at: tableIndex)
            tableIndex += 1
        }

        if let commentSection = tableSectionForItemType(itemType: .tableItemComment) {
            removetableSectionWithFrameId(itemType: .tableItemComment)
            tableSections?.insert(commentSection, at: tableIndex)
            tableIndex+=1
        }

        if tableSectionForItemType(itemType: .tableItemAtAGlance) != nil {

            let otherSection = tableSectionForItemType(itemType: .tableItemOtherItems)
            removetableSectionWithFrameId(itemType: . tableItemOtherItems)
            tableSections?.insert(otherSection!, at: tableIndex)
            tableIndex += 1

        }

    }
</code>```

//This is the method where it shows error

```<code>func removetableSectionWithFrameId(itemType : tableItemType){

        if tableSections?.count != 0 {
            for section in tableSections! {

                if section.itemType == itemType {
                 //Error points to this line below
                        self.tableSections?.remove(at: self.tableSections!.index(of: section)!)
                }
            }
        }
    }
</code>```

For fixing I tried to add sync lock using the method below

```<code>func sync(lock: NSObject, closure: () -> Void) {
        objc_sync_enter(lock)
        closure()
        objc_sync_exit(lock)
    }
</code>```

I tried to modify the section where the error occurred as below but it still throws me the same error

```<code>if section.itemType == itemType {
                    sync(lock: tableSections! as NSObject){
                        self.tableSections?.remove(at: self.tableSections!.index(of: section)!)
                }
        }
</code>```

Any advice or guidance is appreciated.

答:
The possible cause is you are removing the elements from array while iterating it.

Try the following and see if you have any issue

```<code>tableSections = tableSections.filter { $0.itemType != itemType }
</code>```

Body:
in my app I've a viewcontroller with tableview and when it load it gives me about 12 simultaneous memory error all in same place where I try to remove the element from my custom array. Below are the related codes

In my viewcontroller where table loads I've accesses the method as below

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    //Some Code

    arrangeTableObject.arrangetableSectionsInOrderForNoteType(withFrameId:tableDataSection.frameId.uintValue)

   //Some code
   return cell
}

In my another swift class arrangeTableObject.swift this is how I've used the methods

//My custom array is defined as
var tableSections : [TableSection]?

func arrangetableSectionsInOrderForNoteType(type: NoteType){

        var tableIndex = 0

        if tableSectionForItemType(itemType: .tableItemNoteItems) != nil  {

            let noteItemSection = tableSectionForItemType(itemType: .tableItemNoteItems)
            removetableSectionWithFrameId(itemType: . tableItemNoteItems)
            tableSections?.insert(noteItemSection!, at: tableIndex)
            tableIndex += 1
        }

        if let commentSection = tableSectionForItemType(itemType: .tableItemComment) {
            removetableSectionWithFrameId(itemType: .tableItemComment)
            tableSections?.insert(commentSection, at: tableIndex)
            tableIndex+=1
        }

        if tableSectionForItemType(itemType: .tableItemAtAGlance) != nil {

            let otherSection = tableSectionForItemType(itemType: .tableItemOtherItems)
            removetableSectionWithFrameId(itemType: . tableItemOtherItems)
            tableSections?.insert(otherSection!, at: tableIndex)
            tableIndex += 1

        }

    }

//This is the method where it shows error

func removetableSectionWithFrameId(itemType : tableItemType){

        if tableSections?.count != 0 {
            for section in tableSections! {

                if section.itemType == itemType {
                 //Error points to this line below
                        self.tableSections?.remove(at: self.tableSections!.index(of: section)!)
                }
            }
        }
    }

For fixing I tried to add sync lock using the method below

func sync(lock: NSObject, closure: () -> Void) {
        objc_sync_enter(lock)
        closure()
        objc_sync_exit(lock)
    }

I tried to modify the section where the error occurred as below but it still throws me the same error

if section.itemType == itemType {
                    sync(lock: tableSections! as NSObject){
                        self.tableSections?.remove(at: self.tableSections!.index(of: section)!)
                }
        }

Any advice or guidance is appreciated.

Body:
The possible cause is you are removing the elements from array while iterating it.

Try the following and see if you have any issue

tableSections = tableSections.filter { $0.itemType != itemType }


问:
Python inheritance (OOP)
I want create inheritor (descadent) of python's class time. I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance. Where is problem,please?

```<code>from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass
</code>```

答:
time.time is a function not a class. You cannot inherit from a function. In the module time struct_time is defined as a class.

```<code>from time import struct_time as time

class MyTime(time) :
    def __init__(self, time_as_sequence) :
        time.__init__(self, time_as_sequence)

        # Do what you like
</code>```

Title: Python inheritance (OOP)

Body:
I want create inheritor (descadent) of python's class time. I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance. Where is problem,please?

from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass

Body:
time.time is a function not a class. You cannot inherit from a function. In the module time struct_time is defined as a class.

from time import struct_time as time

class MyTime(time) :
    def __init__(self, time_as_sequence) :
        time.__init__(self, time_as_sequence)

        # Do what you like


问:
MySQL date and datetime formats unrecognised by Data Studio
I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for date and datetime fields.

I have these 2 fields in phpmyadmin (field name, field type, output):

Validated_date datetime 2017-09-27 12:31:04

Expiration_date date 2017-12-24

In Data Studio I've set these types, but none of them are recognised:

Validated_date  Date Hour (YYYYMMDDHH)

Expiration_date Date (YYYYMMDD)

I tried to format the field with date_format in my SELECT:

```<code>DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"
</code>```

I even tried other date_formats but they're never recognised as dates in Data Studio:

```<code>DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"
</code>```

Any idea?

答:
I've never tried directly with Data Studio but when I extract datetime fields from mySQL to use in BigQuery I use:

CONVERT(DATETIME2(0), [DATETIME_FIELD])

This removed any milliseconds which generally cause problems and convert it to a recognisable datetime format for Google

Body:
I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for date and datetime fields.

I have these 2 fields in phpmyadmin (field name, field type, output):

Validated_date datetime 2017-09-27 12:31:04

Expiration_date date 2017-12-24

In Data Studio I've set these types, but none of them are recognised:

Validated_date  Date Hour (YYYYMMDDHH)

Expiration_date Date (YYYYMMDD)

I tried to format the field with date_format in my SELECT:

DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"

I even tried other date_formats but they're never recognised as dates in Data Studio:

DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"

Any idea?


问:
Scroll sticky header not working
I have attempted to use the basic HTML, CSS and also Javascript to make the header, "Category" fixed to the top like the sticky header when scrolled but mine isn't working. I have done researched on how it was done but I can't seem to implement it into my work here. I am a newbie here, still learning how to code. Help is much appreciated thanks.

Here's the code.

     var wrap = $("#wrap");

wrap.on("scroll", function(e) {

  if (this.scrollTop > 100) {
    wrap.addClass("fix-category");
  } else {
    wrap.removeClass("fix-category");
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">

               <!-- jQuery first, then Tether, then Bootstrap JS. -->
            <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

          </head>
          <body>

          <div role="main" ng-controller="cartController" ng-init="init()">
          <div class="wrap" id="wrap">

          <header>
           <nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top" style="background-color: #ffffff;">
          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>

          <img class="cursor-pointer hidelogo" src="" width="50" height="60" id="rsvp_logo" alt="Logo">

          <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
            <ul class="navbar-nav">
              <li class="nav-item active dropdown">
                <i class="fa fa-globe" aria-hidden="true"></i>
                 <span id="selected" class="caret">Language </span>
                 <div class="dropdown-menu" aria-labelledby="languageDropdown">
                  English
                  中文
                </div>
              </li>

              <li class="nav-item dropdown">
                <i class="fa fa-sort-amount-asc" aria-hidden="true"></i>
                <span id="sort" class="caret">Sort</span>
                  <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink" ng-model="selectedOrder">
                  Category
                  Date and Time
                  Availability
                </div>
              </li>
              <li class="nav-item">
                <i class="fa fa-filter" aria-hidden="true"></i>
                Topics
              </li>
               <li class="nav-item">
                <i class="fa fa-print" aria-hidden="true"></i> Print
              </li>
              <li class="nav-item">
                <i class="fa fa-shopping-cart" aria-hidden="true"></i>
                Cart
              </li>
            </ul>
          </div>
        </nav>
          </header>

   <div class="container">
  <div class="jumbotron blue">
      <div class="row">
      <div class="col white" >
     Activity
      </div>
       <div class="col white">
       <i class="fa fa-calendar-o" aria-hidden="true"></i>
     Date

      </div>
       <div class="col white">
          <i class="fa fa-map-marker" aria-hidden="true"></i>

        Venue
         </div>
        </div>
        </div>
    </div>

     <div class="category">
         <b>Category 1</b>
    </div>

<div class="container">
<div class="row">
<div class="col">
National Senior Volunteer Month Opening Ceremony
</div>

<div class="col">
30 December 2017<br>
</div>

<div class="col">
9.00am - 12.00pm
</div>

<div class="col">
Auditorium
</div>

<div class="col">
<!-- <td ng-class="getTableColourBySection(colourIndex, 'defaultCellClass')">
    <input ng-if='(session.session_id != null && session.roles[0].attendee_count < session.roles[0].count) || checkboxSessions[session.session_id] == true' ng-model="checkboxSessions[session.session_id]" ng-change="checkSelectedSession(session, checkboxSessions[session.session_id])" type="checkbox">
       <span ng-if="session.session_id == null">No Session </span>
          <span ng-if="session.attendance_count >= session.activity.target_number">Session full</span>
    <span ng-if="session.roles[0].attendee_count >= session.roles[0].count">Full Session </span>
       </td> -->
       <b>18 available</b>
 </div>
<div class="col">
       <button type="button" class="btn btn-primary btn-lg" id="btnAdd" ng-submit="add()">
       <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
   </button>
</div>

<div class="col">
 <button class="btn btn-light btn-lg" type="button" data-toggle="collapse" data-target="#demo">Detail
  <span><i id="toggle-demo" class="fa fa-caret-down" aria-hidden="true"></i></span>
</button>
     </div>
      </div>
         </div>
      <div id="demo" class="col collapse in">
   </div>

<div class="category">
  <b>Enrichment and Learning</b>
</div>

            </body>
            </html>

    <style>

    .category
    {
      width: 100%;
      height: 40px;
      background : #EEEEEE;
      padding: 5px;
    }

    .header
    {
     height: 100px;
    }

    .wrap
    {
     overflow: auto;
     position: relative;
    }

    .fix-category .category
    {
     position:fixed;
     height: 40px;
     left: 0;
        font-family: 'Lato', sans-serif;
    }
    </style></code>```

答:
nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top" style="background-color: #ffffff;"

this. Change this and add sticky-top to make it sticky to the top when you scroll down

 nav class="navbar navbar-toggleable-md sticky-top navbar-light bg-faded fixed-top

Title: Scroll sticky header not working

Body:
I have attempted to use the basic HTML, CSS and also Javascript to make the header, "Category" fixed to the top like the sticky header when scrolled but mine isn't working. I have done researched on how it was done but I can't seem to implement it into my work here. I am a newbie here, still learning how to code. Help is much appreciated thanks.

Here's the code.

     var wrap = $("#wrap");

wrap.on("scroll", function(e) {

  if (this.scrollTop > 100) {
    wrap.addClass("fix-category");
  } else {
    wrap.removeClass("fix-category");
  }

});

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">

          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

          </button>

                 Language

                  English
                  中文

                Sort

                  Category
                  Date and Time
                  Availability

                Topics

                 Print

                Cart

     Activity

     Date

        Venue

         Category 1

National Senior Volunteer Month Opening Ceremony

30 December 2017

9.00am - 12.00pm

Auditorium

       18 available

       <button type="button" class="btn btn-primary btn-lg" id="btnAdd" ng-submit="add()">
        ADD
   </button>

 <button class="btn btn-light btn-lg" type="button" data-toggle="collapse" data-target="#demo">Detail

</button>

  Enrichment and Learning


问:
js code for adding width of a class is not working
I want to change the width by adding 20%. My div class width in percentage. For example i have div with width 20%. I am using class name for stylesheet. When each time the page loading it want increase by 10%. The code is shown below. the avascript code document.getElementsByClassName("box")[0].style.width; is not working` proper. Please help me.

html

```<code><div class="box">
</code>```

var width = document.getElementsByClassName("box")[0].style.width;

var n = width + 20%;

width = n;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
  width:40%;
  height:300px;
  background-color:red;
}</code>```

```

答:
This line has a syntax error

width + 20%;

If you want to calculate percentage then

```<code>width = width + width*20/100;
</code>```

Edit

As @Rory pointed out in the comments, your width value isn't getting set because width value isn't getting fetched correctly at first place, here is the updated code

```<code>var ele = document.getElementsByClassName("box")[0];
var width = parseInt(window.getComputedStyle(ele).width); //get computed style instead of style property
width = width + width*20/100;
document.getElementsByClassName("box")[0].style.width = width;
</code>```

Edit 2

As pointed out by @Anant, if you want to increase with in percentage, then

```<code>var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;
var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;
</code>```

Demo

var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;

var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
  width:40%;
  height:300px;
  background-color:red;
}</code>```

```

Body:
I want to change the width by adding 20%. My div class width in percentage. For example i have div with width 20%. I am using class name for stylesheet. When each time the page loading it want increase by 10%. The code is shown below. the avascript code document.getElementsByClassName("box")[0].style.width; is not working` proper. Please help me.

html

var width = document.getElementsByClassName("box")[0].style.width;

var n = width + 20%;

width = n;

.box{
  width:40%;
  height:300px;
  background-color:red;
}

Body:
This line has a syntax error

width + 20%;

If you want to calculate percentage then

width = width + width*20/100;

Edit

As @Rory pointed out in the comments, your width value isn't getting set because width value isn't getting fetched correctly at first place, here is the updated code

var ele = document.getElementsByClassName("box")[0];
var width = parseInt(window.getComputedStyle(ele).width); //get computed style instead of style property
width = width + width*20/100;
document.getElementsByClassName("box")[0].style.width = width;

Edit 2

As pointed out by @Anant, if you want to increase with in percentage, then

var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;
var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;

Demo

var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;

var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;

.box{
  width:40%;
  height:300px;
  background-color:red;
}

<div class="box">
</div>


问:
Understanding functions with variable scoping
For this code :

```<code>A <- 100; B <- 20

f1 <- function(a) {
  B <- 100
  f2 <- function(b) {
    A <<- 200
    B <<- 1000
  }
  f2(a)
}

f1(B)
cat(A)
cat(B)
</code>```

The following is the output :

```<code>> cat(A)
200
> cat(B)
20
</code>```

Here is my understanding of above code :
The function f1 is invoked with parameter B that has value 20. Within f1 a local variable B is created ( B <- 100 ), f1.B does not have an effect on the variable B
initialiazed outside function call f1 as f1.B is locally scoped to the function f1. A new function f2 is created within f1 that accepts a single argument b.
Within f1 the function f2 is invoked passing as paramter a to f2. f2 does not makes use of its argument b. f2 modifies A using the global operator <-- and sets it to 200. This
why cat(A) outputs 200.

My understanding is incorrect as B is set to 20 when I expect 1000 ? As A is set to 200 in f2 using <-- . d should same not also occur for B ?

答:
The function f1 is invoked with parameter B that has value 20.

No, I don't think so. It is invoked with a parameter a that has the same value as the B in the global environment. B is not directly involved in this point.

You then assign a 100 to a different B, which you call f1.B in your post. (Note that, following the previous statement, that B is created here, not overwritten.)

Then when using the <<- operator, it traverses up in scope, going from f2 (where no B exists) to f1, where it finds this "f1.B" and assigns a 1000.

Similarly, when using the <<- on A, it traverses up. It finds no A in either f2 or f1, but does in the global environment and assigns it there.

You then print to old original B, which has never been altered.

From the help:

<<- and ->> (...) cause a search to be made through parent environments for an existing definition of the variable being
  assigned. If such a variable is found (and its binding is not locked)
  then its value is redefined, otherwise assignment takes place in the
  global environment.

So for B, "such a variable is found", while for A "assignment takes place in the global environment."

Conclusion: <<- is confusing, and often better to be avoided.

Body:
For this code :

A <- 100; B <- 20

f1 <- function(a) {
  B <- 100
  f2 <- function(b) {
    A <<- 200
    B <<- 1000
  }
  f2(a)
}

f1(B)
cat(A)
cat(B)

The following is the output :

> cat(A)
200
> cat(B)
20

Here is my understanding of above code :
The function f1 is invoked with parameter B that has value 20. Within f1 a local variable B is created ( B <- 100 ), f1.B does not have an effect on the variable B
initialiazed outside function call f1 as f1.B is locally scoped to the function f1. A new function f2 is created within f1 that accepts a single argument b.
Within f1 the function f2 is invoked passing as paramter a to f2. f2 does not makes use of its argument b. f2 modifies A using the global operator <-- and sets it to 200. This
why cat(A) outputs 200.

My understanding is incorrect as B is set to 20 when I expect 1000 ? As A is set to 200 in f2 using <-- . d should same not also occur for B ?


问:
Typescript typecasting a response to a class
I have a model class p

```<code>class P {
    constructor(public ids: number[]) {
        console.log(ids);
    }
}
</code>```

On calling service api I got response like :

```<code>var response: any = { ids: "this is string" }
</code>```

Now when we create an instance of model P using 'response'

```<code>let p1 = new P(response.ids);
</code>```

this should produce error : ids type mismatch

but there is no error.

Now question is How to reject response, if it doesn't match given model type?

答: Typescript gets compiled to javascript so there are no types on runtime. If you want to display that message you have to check this explicitly. Something like Test for array of string type in TypeScript</p>

Body:
I have a model class p

class P {
    constructor(public ids: number[]) {
        console.log(ids);
    }
}

On calling service api I got response like :

var response: any = { ids: "this is string" }

Now when we create an instance of model P using 'response'

let p1 = new P(response.ids);

this should produce error : ids type mismatch

but there is no error.

Now question is How to reject response, if it doesn't match given model type?


问:
How can i set global get variable in jsp
I make jsp pages and in that jsp page I have form with post method.

After form submission my get variable unset(naturally).Is there any way to keep get variable after form submission?

my code:

```<code><form method="POST" >
<input type="hidden" name="qty" value="10" />
                        <input type="text" name="eprice" value="3600" />
                        <input type="text" name="tprice" value="36000" />
                        <input type="text" name="type" value="request" />
<input type="submit" value="save" />
</form>
</code>```

After form submission I need url parameters too.

Here is my url before:

http://localhost:8080/q/product.jsp?page=2&saved=1

After form submission get variable unsets and url will changed to:

http://localhost:8080/q/product.jsp

How to keep get data after form submission and still access url parameters?

In php we simply do :

$_GET['page']=2;

How can we handle it in JSP?

答:
For this, you can use the JSP's Implicit Objects.

In your JSP, add hidden fields which map to the URL parameters like this:

```<code><input type="hidden" name="page" value="${param.page}" />
<input type="hidden" name="saved" value="${param.saved}" />
</code>```

Here, the param implicit object will map a request parameter name to a single value. For more information, you can check the other features on the DOCS.

Body:
I make jsp pages and in that jsp page I have form with post method.

After form submission my get variable unset(naturally).Is there any way to keep get variable after form submission?

my code:

<form method="POST" >
<input type="hidden" name="qty" value="10" />
                        <input type="text" name="eprice" value="3600" />
                        <input type="text" name="tprice" value="36000" />
                        <input type="text" name="type" value="request" />
<input type="submit" value="save" />
</form>

After form submission I need url parameters too.

Here is my url before:

http://localhost:8080/q/product.jsp?page=2&saved=1

After form submission get variable unsets and url will changed to:

http://localhost:8080/q/product.jsp

How to keep get data after form submission and still access url parameters?

In php we simply do :

$_GET['page']=2;

How can we handle it in JSP?

Body:
For this, you can use the JSP's Implicit Objects.

In your JSP, add hidden fields which map to the URL parameters like this:

<input type="hidden" name="page" value="${param.page}" />
<input type="hidden" name="saved" value="${param.saved}" />

Here, the param implicit object will map a request parameter name to a single value. For more information, you can check the other features on the DOCS.


问:
Reducing amount of if/if code (C++)
In my program I have to create an object, which looks like that:

Library::Param1<Library::Param2>::Param3 (don't know how to name Param, types maybe?)
Similar to std::vector<std::string>::iterator.

So, these Param's need to be changed by strings. For example:

```<code>if(param1 == "1_VALUE1")
{
    if(param2 == "2_VALUE1")
    {
        MyLib::1_VALUE1<MyLib::2_VALUE1>::Param3 obj;
        //Obj is used
    }
    //15+ similar if-statements, where only 2_VALUE1 changes
}
/*15+ similar if-statements, where only 1_VALUE1 changes,
  but the contents remain same (again 15+ if-statements)*/
</code>```

using namespace MyLib; is not neseccary.

So, I need to reduce amount of those if-statements, but I do not know the way to do it. I think it could be done with templates, but I am not familiar with them, so, I guess, I would need a code sample.

Sorry for the bad english, if any more info is needed - let me know. Thank you.

--- EDIT: Library (CryptoPP) type-definitions:

Since errors are only on Param1, posting one variation of it:

```<code>//! CBC mode with ciphertext stealing
template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation
{
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Encryption, CBC_CTS_Encryption> Encryption;
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
};
</code>```

答:
I agree with Mark B that a factory would be nice, but I'm not sure if this is possible if you do not have a base class that all these types inherit from. If I understand the problem correcty, you have 15 types for Value 1 and 15 types for Value2 which leads to  15*15 if-statements. You can reduce them to 2*15 with the following approach: (untested)

---EDIT1: changed order of methods ---

template
    void level2()
    {
      typename T1_T2::Param3 obj;
      doSomething(obj);
    }

```<code>template <template<class> class T1>
void level1(std::string param2)
{
 if (param2 == "2_VALUE1")
   level2<T1<MyLib::2_Value1> >();
 if (param2 == "2_VALUE1")
   level2<T1<MyLib::2_Value2> >();
 ...
}

void level0(std::string param1, std::string param2)
{
 if (param1 == "1_VALUE1")
   level1<MyLib::1_Value1>(param2);
 if (param2 == "1_VALUE2")
   level1<MyLib::1_Value2>(param2);
 ...
}
</code>```

--- EDIT2 ---

To help you figure out why you can't compile, you can start with this sample code (compiles on Visual Studio 2008):

```<code>void doSomething(int x)
{
}

struct Type2_1 {};

template <class T2>
struct Type1_1
{
    typedef int Param3;
};

template <class T2>
struct Type1_2
{
    typedef int Param3;
};

template <template<class> class T1>
void level1(std::string param2)
{
 if (param2 == "2_VALUE1")
   level2<T1<Type2_1> >();
}

void level0(std::string param1, std::string param2)
{
 if (param1 == "1_VALUE1")
   level1<Type1_1>(param2);
 if (param2 == "1_VALUE2")
   level1<Type1_2>(param2);
}

template <class T1_T2>
void level2()
{
  typename T1_T2::Param3 obj;
  doSomething(obj);
}

int main(int argc, char* argv[])
{
  level0("1_VALUE1", "2_VALUE1");
  return 0;
}
</code>```

Please note that "doSomething()" should be whatever you want MyLib to do with your obj; Returning obj from level0/1/2 won't work without a base class.

Title: Reducing amount of if/if code (C++)

Body:
In my program I have to create an object, which looks like that:

Library::Param1<Library::Param2>::Param3 (don't know how to name Param, types maybe?)
Similar to std::vector<std::string>::iterator.

So, these Param's need to be changed by strings. For example:

if(param1 == "1_VALUE1")
{
    if(param2 == "2_VALUE1")
    {
        MyLib::1_VALUE1<MyLib::2_VALUE1>::Param3 obj;
        //Obj is used
    }
    //15+ similar if-statements, where only 2_VALUE1 changes
}
/*15+ similar if-statements, where only 1_VALUE1 changes,
  but the contents remain same (again 15+ if-statements)*/

using namespace MyLib; is not neseccary.

So, I need to reduce amount of those if-statements, but I do not know the way to do it. I think it could be done with templates, but I am not familiar with them, so, I guess, I would need a code sample.

Sorry for the bad english, if any more info is needed - let me know. Thank you.

--- EDIT: Library (CryptoPP) type-definitions:

Since errors are only on Param1, posting one variation of it:

//! CBC mode with ciphertext stealing
template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation
{
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Encryption, CBC_CTS_Encryption> Encryption;
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
};

Body:
I agree with Mark B that a factory would be nice, but I'm not sure if this is possible if you do not have a base class that all these types inherit from. If I understand the problem correcty, you have 15 types for Value 1 and 15 types for Value2 which leads to  15*15 if-statements. You can reduce them to 2*15 with the following approach: (untested)

---EDIT1: changed order of methods ---

template
    void level2()
    {
      typename T1_T2::Param3 obj;
      doSomething(obj);
    }

template <template<class> class T1>
void level1(std::string param2)
{
 if (param2 == "2_VALUE1")
   level2<T1<MyLib::2_Value1> >();
 if (param2 == "2_VALUE1")
   level2<T1<MyLib::2_Value2> >();
 ...
}

void level0(std::string param1, std::string param2)
{
 if (param1 == "1_VALUE1")
   level1<MyLib::1_Value1>(param2);
 if (param2 == "1_VALUE2")
   level1<MyLib::1_Value2>(param2);
 ...
}

--- EDIT2 ---

To help you figure out why you can't compile, you can start with this sample code (compiles on Visual Studio 2008):

void doSomething(int x)
{
}

struct Type2_1 {};

template <class T2>
struct Type1_1
{
    typedef int Param3;
};

template <class T2>
struct Type1_2
{
    typedef int Param3;
};

template <template<class> class T1>
void level1(std::string param2)
{
 if (param2 == "2_VALUE1")
   level2<T1<Type2_1> >();
}

void level0(std::string param1, std::string param2)
{
 if (param1 == "1_VALUE1")
   level1<Type1_1>(param2);
 if (param2 == "1_VALUE2")
   level1<Type1_2>(param2);
}

template <class T1_T2>
void level2()
{
  typename T1_T2::Param3 obj;
  doSomething(obj);
}

int main(int argc, char* argv[])
{
  level0("1_VALUE1", "2_VALUE1");
  return 0;
}

Please note that "doSomething()" should be whatever you want MyLib to do with your obj; Returning obj from level0/1/2 won't work without a base class.


答:
TypeScript compiles to JavaScript. During runtime, so when you are calling the service API, the types or typehinting are unknown. These are all only relevant during the compilation step.

You should manually check if the api is responding with the correct types using either typeof, or instanceof if you are checking for an object. In case if ids is an array of numbers, you can do this:

```<code>isArrayOfNumbers(array: any): boolean {
  return Array.isArray(array) && array.every(value => typeof value === 'number');
}
</code>```

Title: Typescript typecasting a response to a class

Body:
TypeScript compiles to JavaScript. During runtime, so when you are calling the service API, the types or typehinting are unknown. These are all only relevant during the compilation step.

You should manually check if the api is responding with the correct types using either typeof, or instanceof if you are checking for an object. In case if ids is an array of numbers, you can do this:

isArrayOfNumbers(array: any): boolean {
  return Array.isArray(array) && array.every(value => typeof value === 'number');
}


问:
Is it possible to draw a path of coordinates and navigate between them, using Google Maps or other apps?
This is a simple question.

I know it's possible to request to navigate to a specific place, as shown here.

I know there are also some other APIs for Google Maps (here and here), but I don't see an option to send multiple coordinates, to see the path between them, and navigate between them.

For the Web version, there is the ability for waypoints (example here and here), but not for Android.

Is it possible to do it, via Google Maps, or another app?

Or maybe even in the Google Maps API (within the current app) ?

答:
Since V3 Google Maps Directions API support up to 23 waypoints (excluding the origin and destination) when calculating routes:

https://maps.googleapis.com/maps/api/directions/json?origin=sydney,au&destination=perth,au&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008&key=YOUR_API_KEY

So, you can draw polyline with up to 23 points and send they coords in request.

UPDATE:
Please see this tutorial.

UPDATE 2:

Example opening navigation mode of Google Maps app for route Tel-Aviv to Jerusalem via Kiryat Malakhi, Beit+Guvrin and geopoint (31.696342, 35.011337) via Intent:

```<code>Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("https://www.google.com/maps/dir/?api=1&" +
                                "origin=3780+St+1,+Tel-Aviv+Yafo,+Israel&destination=Jerusalem,+Israel&travelmode=driving" +
                                "&waypoints=Kiryat+Malakhi,+Israel%7CBeit+Guvrin,+Israel%7C31.696342, 35.011337"));
startActivity(intent);
</code>```

Result:

Parameter details here.

Body:
Since V3 Google Maps Directions API support up to 23 waypoints (excluding the origin and destination) when calculating routes:

https://maps.googleapis.com/maps/api/directions/json?origin=sydney,au&destination=perth,au&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008&key=YOUR_API_KEY

So, you can draw polyline with up to 23 points and send they coords in request.

UPDATE:
Please see this tutorial.

UPDATE 2:

Example opening navigation mode of Google Maps app for route Tel-Aviv to Jerusalem via Kiryat Malakhi, Beit+Guvrin and geopoint (31.696342, 35.011337) via Intent:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("https://www.google.com/maps/dir/?api=1&" +
                                "origin=3780+St+1,+Tel-Aviv+Yafo,+Israel&destination=Jerusalem,+Israel&travelmode=driving" +
                                "&waypoints=Kiryat+Malakhi,+Israel%7CBeit+Guvrin,+Israel%7C31.696342, 35.011337"));
startActivity(intent);

Result:

Parameter details here.


问:
C# Html parsing
I'm trying to parse HTML in my C# project without success, I am using a HtmlAgilityPack lib to do so, I can get some of the HTML body text but not all of it for some reason.
I need to grab the div with ID of latestPriceSection, and filter to the USD value from https://www.monero.how/widget

My function (doesn't work)

```<code>public void getXMRRate()
{
    HtmlWeb web = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument document = web.Load("https://www.monero.how/widget");
    HtmlNode[] nodes = document.DocumentNode.SelectNodes("//a").Where(x => x.InnerHtml.Contains("latestPriceSection")).ToArray();
    foreach (HtmlNode item in nodes)
    {
        Console.WriteLine(item.InnerHtml);
    }
}
</code>```

答: You need to retrieve JSON-data from https://www.monero.how/widgetLive.json, because widget use this resource in Ajax request.</p>

Title: C# Html parsing

Body:
I'm trying to parse HTML in my C# project without success, I am using a HtmlAgilityPack lib to do so, I can get some of the HTML body text but not all of it for some reason.
I need to grab the div with ID of latestPriceSection, and filter to the USD value from https://www.monero.how/widget

My function (doesn't work)

public void getXMRRate()
{
    HtmlWeb web = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument document = web.Load("https://www.monero.how/widget");
    HtmlNode[] nodes = document.DocumentNode.SelectNodes("//a").Where(x => x.InnerHtml.Contains("latestPriceSection")).ToArray();
    foreach (HtmlNode item in nodes)
    {
        Console.WriteLine(item.InnerHtml);
    }
}