text:
Q: C# - Define preference for generic function overloads I have a very simple recursively defined function that prints out the contents of any list, defined as such;
    static string ShowList<T>(IEnumerable<T> iterable)
    {
        return "[" + string.Join(", ", iterable.Select(e => ShowList(e))) + "]";
    }

    static string ShowList(string str)
    {
        return $"\"${str}\"";
    }

    static string ShowList<T>(T elem)
    {
        return elem.ToString();
    }

As you can see, the lowest override is a catch all which applies to any argument. The highest overload only applies to arguments which are enumerables. Ideally I want it to check against and run the most specific overloads first, and then if they all fail, use the general case. But what I find is that it always goes straight for the general case immediately, and just prints out Systems.Generic.Containers.List1[]. Is it possible to give certain overloads more precedence than others, so that the compiler will automatically try those before others?

A: It looks to me that because e(in the delegate for iterable.Select) is of type T, therefore the compiler is going to use the type T overload.  I would suggest, that since all it does is return the ToString() method, eliminate it and change the call in the delegate to ShowList(e.ToString()).  If the ToString() is overloaded you'll most likely get meaningful data, otherwise you'll the object type data.
As for sending the List<List<T>> you'll need a different overload that one won't accept it.

A: The generic resolution does seem to be a little odd. I would think that if an object implements the generic IEnumerable<T>, that this match would be more specific than just matching the generic <T>, but apparently if you have a List<T> the compiler shows preference to matching <T> rather than IEnumerable<T>. I found someone else who was having a similar problem here, and their solution was to overload with List<T>, but that doesn't seem like a good solution, because then you would be overloading everything that implements IEnumerable<T>. I found a simple work around using the is operator
    static string ShowList<T>(IEnumerable<T> iterable)
    {
        return "[" + string.Join(", ", iterable.Select(e => ShowList(e))) + "]";
    }

    static string ShowList<T>(T elem)
    {
        if (elem is IEnumerable<object> iterable)
        {
            //This will force the call to the overload for IEnumerable<T>
            return ShowList(iterable);
        }
        else
        {
            //This call will implicitly call ToString, so it covers the generic
            //object case that needs to call ToString and the case where it is
            //already a string, so the string overload is not needed.
            return $"\"{elem}\"";
        }
    }

Here is code for testing these methods intentionally mixing List with arrays to show that it will work for different items that implement IEnumerable<T>
var list = new List<string[]>(){new string[2]{"hello", "world"}, new string[2]{"foo", "bar"}};
Console.WriteLine(ShowList(list)); //outputs: [["hello", "world"], ["foo", "bar"]]


text:
Q: How can I use parent_id in Django? In my model:
class HomePageFirstModule(models.Model):
    name = models.CharField(max_length=8, unique=True)
    is_active = models.BooleanField(default=True)  # 是否启用

class HomePageSecondModule(models.Model):
    name = models.CharField(max_length=16, unique=True)
    is_active = models.BooleanField(default=True)  # 是否启用
    home_page_first_module = models.ForeignKey(to=HomePageFirstModule) # 所属的第一级模块

class HomePageThridModule(models.Model):
    name = models.CharField(max_length=16, unique=True)
    url = models.CharField(max_length=128)
    is_active = models.BooleanField(default=True)  # 是否启用
    home_page_second_module = models.ForeignKey(to=HomePageSecondModule)  # 所属的第二级模块

Then I use filter method to query out the data:
def get_homepage_module_list():
    """
    获取到可以使用的模块信息
    :return:
    """

    data_query_list = models.HomePageThridModule.objects.filter(
        home_page_second_module__home_page_first_module="1"
    ).values('id', 'name', 'is_active', 'home_page_second_module__name',
             'home_page_second_module__home_page_first_module__name',
             'home_page_second_module__home_page_first_module__is_active',
             'home_page_second_module__is_active'
             )

    data_list_del = []
    data_list = list(data_query_list)
    for item in data_list:
        if (item['is_active'] == False) or (
                    item['home_page_second_module__is_active'] == False
        ) or (
                item['home_page_second_module__home_page_first_module__is_active'] == False
        ):
            data_list_del.append(item)

    for item_del in data_list_del:
        data_list.remove(item_del)

    return data_list

========================

How can I convert this list data :
[
    {
        "home_page_second_module__name": "云主机",
        "home_page_second_module__home_page_first_module__name": "产品",
        "id": 1,
        "name": "云主机子1"
    },
    {
        "home_page_second_module__name": "云主机",
        "home_page_second_module__home_page_first_module__name": "产品",
        "id": 4,
        "name": "云主机子4"
    },
    {
        "home_page_second_module__name": "云硬盘",
        "home_page_second_module__home_page_first_module__name": "产品",
        "id": 2,
        "name": "云硬盘子2"
    },
    {

        "home_page_second_module__name": "云硬盘",
        "home_page_second_module__home_page_first_module__name": "产品",
        "id": 3,
        "name": "云硬盘子3"
    }
]

to this:
[
    {"name":"产品",
     "data":[
        {"name":"云主机",
         "data":[{"name":"云主机子1",
                  "data":{"id":1}},
                 {"name":"云主机子2",
                  "data":{"id":2}}]},
        {"name":"云硬盘",
         "data":[{"name":"云硬盘子1",
                  "data":{"id":3}},
                 {"name":"云硬盘子2",
                  "data":{"id":4}}]}
     ]
    }
]

There should has a arithmetic method to do this, but I tried, do not get that.
I only think of this below little things:
home_page_second_module__name_list = []
home_page_second_module__home_page_first_module__name_list = []
id_list = []
name_list = []

for home_page_second_module__name,home_page_second_module__home_page_first_module__name,id,name  in ori_list:
    if not (home_page_second_module__name_list.__contains__(home_page_second_module__name)):
        home_page_second_module__name_list.append(home_page_second_module__name)
    if not (home_page_second_module__home_page_first_module__name_list.__contains__(home_page_second_module__home_page_first_module__name_list)):
        home_page_second_module__home_page_first_module__name_list.append(home_page_second_module__home_page_first_module__name)

But now I think this is very difficult to do that, and I think mine is wrong way to do that.
Is there a convenient way to realize it?

EDIT
The 产品, 云主机, 云硬盘 may can be deed as parent id.

A: Outdated code, as the original question just asked how to transform a list of dicts into another list of dicts with different outcome
I bet this can optimized a lot but... assuming your dict is named old, I think this might do it:
new = {'name': i['home_page_second_module__home_page_first_module__name'] for i in old if not i['home_page_second_module__home_page_first_module__name'] in old}
new['data'] = [['name': i['home_page_second_module__name'], 'data':[{'name': i['home_page_second_module__name'], 'data': {'id': i['id']}}]] for i in old]

A: You can use django-rest-framework, and use related serializers. relations serializers

redpajama_set_name: RedPajamaStackExchange


text:
Q: Erlang: Functions work in shell but not in YAWS My sole method of debugging (io:format/2) is not working in YAWS. I'm at a loss. My supervisor starts three processes: ETS Manager, YAWS Init, and Ratelimiter. This is successful. I can play around with the rate limiter in the shell... calling the same functions YAWS should be. The difference being the shell behaves as I would expect and I have no idea what is happening in YAWS.
I do know if I spam the command in shell: ratelimiter:limit(IP) it will return true eventually. I can execute the following and it will also return true: ratelimiter:lockout(IP), ratelimiter:blacklist(IP). The limiter is a gen_server.
The functions do the following:

*

*limit/1: Check ETS table if counter > threshold; update counter. If counter > blacklist threshold make entry in mnesia table

*blacklist/1: Check mnesia table if entry exists; Yes: reset timer

*lockout/1: Immediately enters ID into mnesia table

In my arg_rewrite_mod module I'm doing some checks to ensure I'm getting the HTTP requests I expect, namely GET, POST, and HEAD. I thought this would be a nice place to also do the rate limiting. Do it as soon as possible in the web server's chain of events.
All the changes I've made to the arg_rewrite module seem to work except using "printf"s and the limiter. I'm new to the language so I'm not sure my mistake is obvious or not.
Skeleton of my arg_rewrite_mod:
-module(arg_preproc).
-export([arg_rewrite/1]).

-include("limiter_def.hrl").
-include_lib("/usr/lib/yaws/include/yaws_api.hrl").

is_blacklisted(ID) ->
    case ratelimiter:blacklist(ID) of
    false ->    continue;
    true ->     throw(blacklist)
    end.

is_limited(ID) ->
    case ratelimiter:limit(ID) of
    false ->    continue;
    true ->     throw(limit)
    end.

arg_rewrite(A) ->
    Allow = ['GET','POST', 'HEAD'],

    try
        {IP, _} = A#arg.client_ip_port,

        ID = IP,
        is_blacklisted(ID),

io:format("~p ~p ~n",[ID, is_blacklisted(ID)]),

        %% === Allow expected HTTP requests
        HttpReq = (A#arg.req)#http_request.method,

        case lists:member(HttpReq, Allow) of
            true ->
                {_,ReqTgt} = (A#arg.req)#http_request.path,
                PassThru = [".css",".jpg",".jpeg",".png",".js"],
                %% ... much more ...
            false ->
                is_limited(ID),
                throw(http_method_denied)
        end
    catch
        throw:blacklist -> %% Send back a 429;
        throw:limit -> %% Same but no Retry-After;
        throw:http_method_denied ->
        %%Only thrown experienced
            AllowedReq = string:join([atom_to_list(M) || M <- Allow], ","),
            A#arg{state=#rewrite_response{status=405,
                        headers=[{header, {"Allow", AllowedReq}},{header, {connection, "close"}}]
            }};
        Type:Reason -> {error, {unhandled,{Type, Reason}}}
    end.

I can spam curl -I -X HEAD <<any page>> as fast as I can in a bash shell and all I get is HTTP 200. The ETS table has zero entries as well. Using PUT I get a HTTP 405 as intended. I can ratelimiter:lockout({MY_IP}) and get the web page to load in my browser and a HTTP 200 with curl.
I'm confused. Is it the way I started YAWS?
start() ->
    os:putenv("YAWSHOME", ?HOMEPATH_YAWS),
    code:add_patha(?MODPATH_YAWS),

    ok = case (R = application:start(yaws)) of
        {error, {already_started, _}} -> ok;
        _ -> R
    end,

    {ok,self()}. %% Tell supervisor everything okay in a manner it expects.

I did this because I thought it would be "easier."

A: When starting Yaws as part of another application, it's important to use its embedding support. One important thing the Yaws embedding startup code does is set the application environment variable embedded to true:
application:set_env(yaws, embedded, true),

Yaws checks this variable in several of its code paths, especially during initialization, in order to avoid assuming that it's running as a stand-alone daemon process.
Regarding rate limiting, rather than using an arg rewriter, you might consider using a shaper. The yaws_shaper module provides a behavior that expects its callback module to implement two functions:

*

*check/1: yaws_shaper calls this to allow the callback module to decide whether to allow the request from the client. It passes client host information as the callback argument. Your shaper callback module returns either the atom allow to allow the request to proceed, or the tuple {deny, Status, Message} where Status is an HTTP status code to return to the client, such as 429 to indicate the client is making too many requests, and Message is any extra HTML to be returned to the client. (It might be nice if Message could include a reply header such as Retry-After as well; this is something I'll consider adding to Yaws.)

*update/3: yaws_shaper calls this when the response for a client is ready to be returned. The first argument is the client host information, the second argument is the number of "hits" (the value 1 for each request), and the third argument is the number of bytes being delivered in response to the client's request. Your shaper callback module can return ok from update/3 (Yaws does not use the return value).
A shaper can use this framework to track how many requests each client is making and how much data Yaws is delivering to each client, and use that information to limit or deny particular clients.
And finally, while "printf debugging" works, it's less than ideal especially in Erlang, which has built-in tracing. You should consider learning the dbg module so you can trace any function you want, see who called it, see what arguments are being passed to it, see what it returns, etc.


text:
Q: Java inner class and static nested class - binary diff There are many reasons to choose one design over another, and there are really good answers to it found in here:

*

*Java inner class and static nested class
I am curious if there are any performance or memory/storage difference when choosing static inner class via a regular class.
How does the difference looks like after compilation?
To be clear, This question is not about giving advice what to use in each case. I just want to learn how Java works here, behind the scene.

A: The static nested class is the simplest form: it works just like a top level class, the only difference is the scope in which it is declared. Nothing is hidden there.
The non-static nested class have a hidden reference to an instance of the enclosing class, that's why you can reference non-static fields of the enclosing class from inside the inner class.
When you define an anonymous class in a method, you will also have a copy of all the local variables declare in the method and referenced from within the anonymous class. If the method is non-static, you will also have the hidden reference to the enclosing class.


text:
Q: AngularJS and NodeJS http-server: rewrite URL I'm using NodeJS http-server to code an AngularJS App.
I'm having a problem. When I try to access directly the url in the browser the Angular does not intercept the URL to show me the content.
If I type the URL manually like: http://127.0.0.1:8080/#!/clients it works, but not when I type directly: http://127.0.0.1:8080/clients
I want the http://127.0.0.1:8080/#! as default in the http-server.
I'm using in AngularJS the html5 mode and the hash prefix:
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');

Is there a way to rewrite the url from http-server with the default /#!/ before the address?

A:
Note: Below is an example of a more complex Express.js URL rewriting situation, where you may not wish to "catch all" routes, but instead discern between routes for views and routes for the server-side api. All solutions I could find only showed a generic catch-all approach, which did not fit practical application for an app whom requires access to server-side routes. If you do simply want the "catch all", see the other yellow note at the bottom of this answer for links on how to set that up.

If you turn off html5 mode, by default, you should be in hashbang (#!) mode...Turning on html5Mode allows you to remove the hashbang (#!), if you wish.
Here's more about the different modes:
https://docs.angularjs.org/guide/$location
HTML5 mode being enabled, gives you normal looking, non-hashbang URLs. Normally, when HTML5 mode is enabled, you'll hit the issue you described where pages within your app will load OK internally, but if you try and enter the URL directly into your browser (or access it via a bookmark), you'll get a Cannot GET error.
First, be sure you've set a <base> tag in the <head> your primary index file, like this:
<head>
    <!-- all your script tags, etc etc -->
    <base href="/">
    <!-- rest of your front-end dependencies etc -->
</head>

That way Angular will know which is your primary index to load partials within.
Secondly, I will try and tell you how I approached re-writing my URLs in Express to solve the issue you have described. My answer may be somewhat incomplete, as I am still learning, and in truth, I do not fully understand why, once HTML5 mode is enabled in Angular, that the routing does not work properly. There also may be better ways to approach the problem as opposed to how I solved mine.
It seemed that once I switched to HTML5 mode, Angular intercepted my routes and was causing an issue when I was trying to use the $http service to request server-side api routes.
It seemed like turning on HTML5 mode basically took over all of my routing, and I had to find a way to tell Express to either pass a route to Angular or to continue the route (away from angular) using next(). This was my best assessment.
What I Did:

*

*Enabled HTML5 mode [as you have done in your example], and set a
<base> in my index file (as noted above).

*Rewrote my routing in ExpressJS using the native express.Router():

*

*See: https://expressjs.com/en/guide/routing.html

*At the very bottom of that page are instructions for express.Router()

*I'll show you how I did it below

My Approach/Pseudo-code:
I setup a method in my Router so that if the incoming request contained /api/ (checked via regex), I would invoke ExpressJS's next() method and continue along in the route, which would hit the server controller. Otherwise, if the URL did not contain /api/, I the appropriate view page was delivered, in which Angular took over.
How I setup my express.Router():

*

*I created a middleware folder in my app and created a file called api-check.js.
// Setup any Dependencies:
var express = require('express'),
    router = express.Router(), // very important!
    path = require('path');

// Setup Router Middleware:
    /*
        Notes: The `apiChecker` function below will run any time a request is made.
        The API Checker will do a regex comparison to see if the request URL contained
        the `/api/` pattern, to which instead of serving the HTML file for HTML5 mode,
        it will instead `next()` along so the API route can reach the appropriate
        server-side controller.
    */
router.use(function apiChecker (req, res, next) {
    console.log('/// ROUTER RUNNING ///'); // will print on every route
    console.log('URL:', req.originalUrl); // will show requested URL
    var regex = /(\/api\/)/g; // pattern which checks for `/api/` in the URL
    if (regex.test(req.originalUrl)) { // if the URL contains the pattern, then `next()`
        console.log('THIS IS AN API REQUEST'); // api detected
        next();
    } else { // if the URL does not contain `/api`:
        res.sendFile(path.join(__dirname, './../../client/index.html'));     // delivers index.html which angular-route will then load appropriate partial
    }
})

module.exports = router; // exports router (which now has my apiChecked method attached to it)

How I added my express.Router() to my Express App:
Depending upon how your code is modularized, etc, just go ahead and in the right place require your module (you will have to adjust the direct path depending upon your project), and then app.use() the module to intercept all of your routes and direct them to your Router:
// Get Router:
var apiCheck = require('./../middleware/api-check');

// Use Router to intercept all routes:
app.use('/*', apiCheck);

Now, any route (thus the /*) will go through the express.Router() apiChecker() function, and be assessed. If the requesting URL contains /api, then next() will be invoked and the server-side controller will be reached. Otherwise, if the /api slug is not detected in the URL, then the primary index.html base file will be sent, so that Angular can deliver the appropriate view via $routeProvider.

Note: If you don't need to discern between incoming routes, and just want to "catch all" incoming routes and hand back your <base> index file, you can do as outlined in another stackoverflow answer here. That answer uses app.get() to catch all GET requests to hand back your index. If you also need to catch POST requests or others, you may want to instead use app.all(), in place of app.get() in the aforementioned example. This will catch all routes, whether GET, POST, etc. Read more in the Express documentation here.

This was my personal solution, and there may be better, but this solved my problem! Would be interested to know what others recommend! Of course the downside to this, is that I have to build all of my internal api routes to include /api/ in them, however that seems to be OK in design overall, and maybe even useful in keeping me from confusing my routes from front-side views.
Hope this at least helps somewhat, let me know if you need any clarifications :)


text:
Q: percentage margin with constraintlayout? I'm learning how to use ConstraintLayout and have found a few good tutorials to have views width and height in percentage. I know I can probably add an empty view to 'create' margin, but it doesn't seem right. Is there a way to things like marginEnd='10%'?

A: Trick #3:
for the percentage from both sides
 app:layout_constraintWidth_percent=".80"

A: You might want nested constraints with
app:layout_constraintWidth_percent="0.9"
    app:layout_constraintHorizontal_bias="0.25"

XML Example without bias:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:focusable="true"
        android:focusableInTouchMode="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintWidth_percent="0.9">
        <View
            android:id="@+id/view"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@color/colorAccent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"/>
        </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>

Xml Example With bias
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:focusable="true"
        android:focusableInTouchMode="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintWidth_percent="0.9"
        app:layout_constraintHorizontal_bias="0.25">
        <View
            android:id="@+id/view"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@color/colorAccent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"/>
        </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>

https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout#Bias

A: There're two ways to add percentage margin using ConstraintLayout.
#1 Guideline
Simply add vertical guideline to your layout and constraint view to that guideline:
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/view"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.9" />

</android.support.constraint.ConstraintLayout>

#2 Constraint weight
Add Space, place it on the very left side of parent, group your view and Space into "spread" chain and set app:layout_constraintHorizontal_weight="90" to your view and app:layout_constraintHorizontal_weight="10" to Space. It works very similar to LinearLayout's weight.
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/view"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintHorizontal_weight="90"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/space"
        app:layout_constraintBottom_toBottomOf="parent" />

    <Space
        android:id="@+id/space"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintHorizontal_weight="10"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

</android.support.constraint.ConstraintLayout>

As a result, your view has end margin with value of 10% of parent width:


text:
Q: How can I use abstract method in proper manner? I am implementing library system as Exercise, in that I have created one abstract class :
 public abstract class RentalItem
{
    .....
    public RentalItem() { }
    public RentalItem(string itemID, string title, int qty,float price, PeriodType period) {
        ItemID = itemID;
        Title = title;
        No_Of_Copies = qty;
        Period = period;
    }
    public abstract void addItem(string itemId, string title, int no_of_copies,float price,PeriodType p);
   .....
}

Afterwards, I have created MovieItem class, which inherits RentalItem  class :
now this class has extra fields. as below :
public Movie(string itemId, string title, int no_of_copies, float price, PeriodType p, MovieType type, string actor, string director)
        : base(itemId, title, no_of_copies, price, p)
    {

        this.Type = type;
        this.Actors = actor;
        this.Director = director;
    }

public override void addItem(string itemId, string title, int no_of_copies,float price,PeriodType p){};

But actully I want to implement addItem method such away, it takes base parameters + additional parameters as below :
public void addItem(string itemId, string title, int no_of_copies, float price, PeriodType p, MovieType type, string actor, string director)

So how can I use abstract method? And if I am implementing my own addItem(...) method then what is use of abstract class ?

A: When using an abstract method you have to override the method, which means you have to adhere to the original signature of the abstract method. You can not add or remove parameters from the original signature.
If you need to change the signature, then it's not appropriate to use an abstract method

A: You are trying to abstract 2 things that is different. Is adding a RentalItem is same with adding a MovieItem? If yes then you can abstract the method. Otherwise, better not abstract it.
EDIT:
Maybe I am not clear with my statement. Now look at example of this code:
RentalItem rent = new RentalItem();
rent.AddItem(..params);

Is the usage of AddItem method in RentalItem class. Now for the MovieItem class:
MovieItem mv = new MovieItem();
mv.AddItem(..params);

Now looks fine. However, because MovieItem is inherited by RentalItem, we can implement it like this:
RentalItem item = new MovieItem();
item.AddItem(..params);

This comes the problem. We can see that the MovieItem.AddItem is different with RentalItem.AddItem, because it cannot be invoked by RentalItem, and both method accept different parameter. Now what we can do?
First, if does not needed or if not logically same, let the MovieItem as a new class instead inherited from RentalItem.
Second, if you need inheritance, let the RentalItem and MovieItem become only the entity with just properties and not method. And for handling the AddItem, you create another class like RentalItemCollection and MovieItemCollection which in logic does not has relation each other.

A: Method signatures have to remain the same in order for abstract classes to work.
If your addItem method from Movie class has more parameters, you can deal with that by changing its signature to accept List or Dictionary or some other collection, or you can encapsulate parameters in a new class named RentalItemProperties.


text:
Q: Giving parameters to bash via command line I have a bash script in which I want to run a a bunch of files of different times. Instead of creating a lot of if statements or creating a lot of bash scripts I was thinking if there's a way to accept which files to run in bash via command line.

#!/bin/bash

#generating training data

i_hard=0
i_soft=0
i_neutral=0

for entry in /home/noor/popGen/sweeps/slim_script/final/*
do
    if [[ $entry == *"hard_FIXED"* ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/hard_$i_hard.txt
        i_hard=$((i_hard+1))
    fi

    if [[ $entry == *"soft_FIXED"* ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/soft_$i_soft.txt
        i_soft=$((i_soft+1))
    fi
    if [[ $entry == *"neutral"* ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/neutral_$i_neutral.txt
        i_neutral=$((i_neutral+1))
    fi
done

What I want to do is:

#!/bin/bash

i=0

for entry in /home/final/*
do
    if [[ $entry == *parameter* ]]; then
        echo "It's there!"
        /home/stuff/build/./slim $entry > /home/final/parameter_$i.txt
        i=$((i+1))
    fi
done

So I want 'parameter' is what I want to give through command line which can be hard_FIXED, hard_0, and so on.
How can I achieve that?

A: The Shell Script Parameters by default are assigned as:
$N

Here: N is Number starting from 0.
Also, $0 refers to script file itself or the Shell.
So, the parameters passed to Shell Script are available as:
$1, $2, $3 and so on.
For example:
./script.sh hard_FIXED

hard_FIXED will be available as $1.
So, inside the script you can capture them and use as needed.

A: The first argument to bash from a command line can be found with the positional parameter $1, so if I got your intentions right:
#!/bin/bash

#generating training data

i_hard=0
i_soft=0
i_neutral=0

for entry in /home/noor/popGen/sweeps/slim_script/final/*
do
    if [[ $entry == $1 ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/hard_$i_hard.txt
        i_hard=$((i_hard+1))
    fi

    if [[ $entry == $1 ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/soft_$i_soft.txt
        i_soft=$((i_soft+1))
    fi
    if [[ $entry == $1 ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/neutral_$i_neutral.txt
        i_neutral=$((i_neutral+1))
    fi
done

A: Look how the parameters are used here.
#!/bin/bash

# parameter 1 directory
# parameter 2 entry
# check number arguments
if (( $# != 2 )); then
   echo "Usage: $0 directory entry"
   exit 1
fi

# different way of testing, now check directory
test -d "$1" || { echo "$1 is not a directory"; exit 1; }

i=0

for entry in /home/final/*${2}*
do
   # No need for testing [[ $entry == *parameter* ]], this is part of the loop
   echo "${entry}: It's there!"
   /home/stuff/build/slim "${entry}" > /home/final/${2}_$i.txt
   # Alternative for i=$((i+1))
   ((i++))
done


text:
Q: How to read an array and analyse the input I was just wondering is there some way to read an array and then based upon the letters entered do something?
Like for example: if the roman numeral; MM was entered is there some way to see that 2 M's were entered and display the value for M?
output would be: 1000+1000.
Could you just tell me the name of the function, because it is for an assignment I dont want someone doing it for me, I just dont know where to start from.
example: char romanNumerals[2] = {"MMMCMXCVIII"};

A: Your best bet is to use the  scanf function from stdio.h.
char str[3];
scanf("%s", str);

would store up to two characters from the standard input and the null terminator (\0)  into the char array pointed at by str.

A: char romanNumerals[2] = {"MMMCMXCVIII"};

Is not right as it can only hold 1 element(+1 for the \0). Change it to
char romanNumerals[] = "MMMCMXCVIII";

The compiler will choose the correct size for the array when doing the above initialization.
Then,you need a variable to add the sum of each roman number. So create
int sum=0;

And you need to loop the length of array times as you want to check each letter.
int i,len=strlen(romanNumerals);
for(i = 0;i < len;i++)
{
//body of for loop
}

string.h should be included in order to use strlen function which returns the length of a string.
Now,check each letter inside the body of the for loop using
if(romanNumerals[i]=='M')
    sum=sum+1000;
else if(romanNumerals[i]=='C')
    sum=sum+/*the corresponding value*/;
else if(...)
    sum=sum+/*value*/;
//etc etc

And then at last,print sum.

A: All other answers are correct, but keep in mind that if you just sum the input letters with a lookup (M=1000, C=100, X=10, V=5, I=1), having "MMMCMXCVIII" would mean 3000+100+1000+10+100+5+3 = 4218 and this is not what "MMMCMXCVIII" means in roman numerals (it actually means 3998 ).

A: For reasons explained in the link supplied by NSimon (see 1st comment) scanf() is not the best option when the input string length isn't known.
Other options are fgets() and getline(). The thing to remember is that a properly formed string is terminated by a null character - usually written '\0'. Hence if all else fails, you can always read char for char using the fgetc() function in a loop of some sort and stop when either your buffer is full or the '\0' is found.
So much for reading the array. When it comes to evaluating roman numerals, the best approach is to start at the back. Roman numerals have a (niot quite so simple) ordering:
I < V < X < L < C < D < M
Reading backwards you need to follow some straight forward rules:

*

*The least significant packet is always last (i.e. IXL is wrong, it should be LIX = 59)

*If X or V is preceeded by I then subract 1 otherwise add the value.

*If L or C is preceeded by X then subtract 10 otherwise add the value.

*If D or M is preceeded by C then subtract 100 otherwise add the value.

Note that M & D can only ever be preceeded by C or M. L & C can only be preceeded by X or C. X & V can only be preceeded by I or X. Anything else indicates a malformed number.
Thus working from the back it should be reasonably easy to obtain the correct value.


text:
Q: PMD + jenkins [linux] - class net.sourceforge.pmd.PMD not found
I need to run PMD on my Jenkins server [LINUX].
Everything works fine on my Windows machine with sh.exe but when I am trying to run it on Jenkins I get the following error:

Error: Could not find or load main class net.sourceforge.pmd.PMD

I know it means that it cannot find the main class but the exact same thing works on my local env.
Both machines have java version "1.7.0_111" and pmd-bin-5.5.2. What is wrong with this? Please help.

Thank You.


text:
Q: PrismaORM PostgreSQL create migration error inside Docker container I have my NestJS application that use PrismaORM for connection to PostgreSQL. But building of docker file crashes after executing npx prisma migrate dev --name init with error Can't reach database server at postgres:5432
My docker-compose.yml
version: "3.8"
services:
    api:
        build:
            dockerfile: Dockerfile
            context: .
        depends_on:
            - postgres
        env_file:
            - ./.env
        ports:
            - "8080:5000"

    postgres:
        image: postgres:10.4
        ports:
            - "5432:5432"
        environment:
            POSTGRES_USER: user
            POSTGRES_PASSWORD: password
            POSTGRES_DB: db
        volumes:
            - ./postgres-data:/var/lib/postgresql/data
        env_file:
            - ./.env

**My Dockerfile
**
FROM node:16

WORKDIR /qmessanger/src/server

COPY package*.json ./

COPY prisma ./prisma/

COPY .env ./

COPY . .

RUN npm install

RUN npm run build
RUN npx prisma generate
RUN npx prisma migrate dev --name init

EXPOSE 8080

CMD [ "node", "dist/main" ]

My .env config
DATABASE_URL="postgresql://user:password@postgres:5432/db"
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=db

My prisma config
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

A: The issue is that you're trying to run the migration before the postgres service is running. You would need to run the migration as part of your startup command or entrypoint.
Here is an example of a similar problem in Django and they used an entrypoint script to run the migration:
How do you perform Django database migrations when using Docker-Compose?


text: Q: How to read a file path from database column and display the contents using angular I have a requirement to  read a file path from a database column and display the contents in a  popup using Angular. The files can be of type  image, pdf , video etc. The files path will have filenames that can be accessed remotely /locally.


text:
Q: "Any" path in Django? Is it possible to define a route that will be redirected to if Django could not find a match in the defined URLs?
For example, let's say I have:
urlpatterns = [
    path('ajaxlogin', views.ajax_login, name='ajaxlogin'),
    path('ajaxprofile', views.ajax_profile, name='ajaxprofile'),
]

Can I define a "dynamic" URL of a specific view that will be redirected to if the path doesn't exist? Suppose I enter the URLs /ajaxsignup and /ajaxdelete, which are not defined, but have them redirected to a URL of a certain view?
In other words:
urlpatterns = [
    path('ajaxlogin', views.ajax_login, name='ajaxlogin'),
    path('ajaxprofile', views.ajax_profile, name='ajaxprofile'),
    path('every-other-url', views.another_view, name='path-everything-else'),
]

I know there's Django's error handlers, but are there any other ways to achieve this? I have my frontend based separately on a React application, so I'd very much appreciate a "dynamic" URL rather than using Django's default 404 responses.
I suspect that if path couldn't do it, I could use the old url with regex -- but I still have no clue.
Thanks in advance.

A: Just add a wildcard re_path at the end of your urlpatterns:
from django.http import HttpResponse
from django.urls import re_path

def http_response(request):
    return HttpResponse('
Hello HttpResponse
')

urlpatterns = [
    path('ajaxlogin', views.ajax_login, name='ajaxlogin'),
    path('ajaxprofile', views.ajax_profile, name='ajaxprofile'),
    path('every-other-url', views.another_view, name='path-everything-else'),
    re_path(r'.*', http_response), # only if the above routes don't trigger a match
]

It processes routes in order, so if it doesn't find a route before it hits the wildcard, it will return that one.


text:
Q: HTTP Error 404.17 - Not Found, on window server 2012 with 2.0 application pool I have a 2.0 .Net framework application which I moved to windows server 2012 with the same application pool setting of v2.0 and integrated mode. For some reason it throws HTTP Error 404.17 - Not Found error. I have followed https://support.microsoft.com/en-us/kb/2019689 and it does not work yet.
Also see my web.config as per the above page setting:

Any help would be great.

A: Make sure you have .NET 3.5 installed on the server.  For some strange reason, I believe 3.5 handles all previous versions of .NET as well.  I've seen cases where even if you have 2.0 installed and are running a 2.0 pool, you still need 3.5 installed.

A: I had the same problem (with a .net 4 webapp).
In the past you could resolve this with a aspnet_regiis command.
In Windows server you can resolve this by uninstalling asp.net [your version]. and the re-installing the same version.
This will reregister the correct IIS mappings
You can access these settings in the Server Manager


text:
Q: Trying to install pandas-datareader but I am getting an error. I can't figure a way to get around it. Anybody know why this is happening? I am using Jupyter Notebooks through Anaconda.
When tyring to install pandas-datareader I enter the following:
!pip install pandas-datareader

and I get this as a result:
/Users/nicpeck/opt/anaconda3/bin/pip: line 4: import: command not found
/Users/nicpeck/opt/anaconda3/bin/pip: line 5: import: command not found
from: can't read /var/mail/pip._internal
/Users/nicpeck/opt/anaconda3/bin/pip: line 10: syntax error near unexpected token `('
/Users/nicpeck/opt/anaconda3/bin/pip: line 10: `    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])'

I tried this as well:
!conda install pandas-datareader

and I get this result:
/Users/nicpeck/opt/anaconda3/bin/conda: line 3: import: command not found
/Users/nicpeck/opt/anaconda3/bin/conda: line 6: syntax error near unexpected token `sys.argv'
/Users/nicpeck/opt/anaconda3/bin/conda: line 6: `if len(sys.argv) > 1 and sys.argv[1].startswith('shell.') and sys.path and sys.path[0] == '':'

Anybody have any suggestions????


text:
Q: How to get the name of the shell running using a script? I'd like to run a shell script that prints the name of the shell running it.
So far I've been using echo $SHELL but that variable may not be set and does not give the name of the current shell running the script.
I've tried with ps -p $$ but this only works when using it directly in the terminal as in the script it gives me the name of the script file.
I have not found a good solution to this problem.
Current script:
#!/bin/bash
echo $SHELL

Thanks
EDIT: Just in case, I mean that I want to get the name of the command interpreter running the script by using a script.

A: Does something along these lines do what you want?
me@server2:~$ cat test
#!/bin/sh
X=$(ps h -p $$ -o args='' | cut -f1 -d' ')
echo "Running --> $X"

me@server2:~$ ./test
Running --> /bin/sh
me@server2:~$ sh test
Running --> sh
me@server2:~$ bash test
Running --> bash
me@server2:~$

A: After some tests, this seems to work on linux:
gawk 'BEGIN{RS="\0"}; NR==1{print; exit}' /proc/$$/cmdline

Requires a non-portable gawk feature.
Edit: An account of what happens here
The file /proc/PID/cmdline contains the complete command line from PID. $$ expands to the current shell's PID. This file contains a NULL-byte seperated list of the complete command line. gawk is instructed to split the records ("lines") on the NULL-byte, and print the first one it encounters.
This would be a slightly shorter one:
gawk 'BEGIN{RS="\0"}; {print; exit}' /proc/$$/cmdline

A: You can use
stat -tc '%N' /proc/$$/exe | cut -d' ' -f3

to get the name of the shell running the script


text:
Q: Does Pytorch PTQ (Post Training Quantization) actually use quantized integer weights for inference? After Pytorch Post training quantization, I find that the forward propagation of the quantized model still seems to use dequantized float32 weights, rather than using quantized int8. Below I attached the PTQ example given on the Pytorch quantization documentation. I used hook to see their result in forward propagation. I find that if I use dequantized float tensors to manually do the calculation myself, I get the same result as their forward propagation output that supposedly should be using int8. Feel free to try to code yourself.
How does Pytorch PTQ do forward propagation? Do they use float32 or int8 weights? What does it mean to be quantized if it still need to store and use float32 values for inference.
import torch

# define a floating point model where some layers could be statically quantized
class M(torch.nn.Module):
    def __init__(self):
        super(M, self).__init__()
        # QuantStub converts tensors from floating point to quantized
        self.quant = torch.quantization.QuantStub()
        self.conv = torch.nn.Conv2d(1, 1, 1)
        self.relu = torch.nn.ReLU()
        # DeQuantStub converts tensors from quantized to floating point
        self.dequant = torch.quantization.DeQuantStub()

    def forward(self, x):
        # manually specify where tensors will be converted from floating
        # point to quantized in the quantized model
        x = self.quant(x)
        x = self.conv(x)
        x = self.relu(x)
        # manually specify where tensors will be converted from quantized
        # to floating point in the quantized model
        x = self.dequant(x)
        return x

# create a model instance
model_fp32 = M()

# model must be set to eval mode for static quantization logic to work
model_fp32.eval()

model_fp32.qconfig = torch.quantization.get_default_qconfig('fbgemm')

model_fp32_fused = torch.quantization.fuse_modules(model_fp32, [['conv', 'relu']])

# Prepare the model for static quantization. This inserts observers in
# the model that will observe activation tensors during calibration.
model_fp32_prepared = torch.quantization.prepare(model_fp32_fused)

# calibrate the prepared model to determine quantization parameters for activations
# in a real world setting, the calibration would be done with a representative dataset
input_fp32 = torch.randn(4, 1, 4, 4)
model_fp32_prepared(input_fp32)

# Convert the observed model to a quantized model.
model_int8 = torch.quantization.convert(model_fp32_prepared)

# hooks to retrieve inputs, outputs and weights of conv layer (fused conv + relu)
conv_inputs = []
conv_weights = []
conv_outputs = []
hooks = []
for hook in hooks:
    hook.remove()
def hook_fn(m, i, o):
    global conv_inputs, conv_outputs, conv_weights
    conv_inputs = i[0] # [0] because conv_inputs is a tuple and we only care about the first item
    conv_weights = m.weight()
    conv_outputs = o
hooks.append(model_int8.conv.register_forward_hook(hook_fn))

# run forward pass
res = model_int8(input_fp32)

relu = torch.nn.ReLU()

# Manually dequantize and manually compute output
# Note that convolution is just a simple multiplication because it's a 1x1 kernel with 1 channel
conv_float_input = (conv_inputs.int_repr().int() - conv_inputs.q_zero_point())*conv_inputs.q_scale()
conv_float_weight = conv_weights.int_repr() * conv_weights.q_per_channel_scales()
conv_float_output = conv_float_input * conv_float_weight + model_int8.conv.bias()
manual_output_1 = (relu(conv_float_output / model_int8.conv.scale)).round()
print("manual_output_1:\n", manual_output_1)

# Use built-in dequantize() and manually compute output
# Note that convolution is just a simple multiplication because it's a 1x1 kernel with 1 channel
conv_float_output = conv_inputs.dequantize()*conv_weights.dequantize() + model_int8.conv.bias()
manual_output_2 = relu((conv_float_output / model_int8.conv.scale).round())
print("manual_output_2:\n", manual_output_2)

# Output produced by forward() pass
print("output produced by forward():\n", conv_outputs.int_repr())

# print the difference between manual input and output generated by forward (0.0 means no difference)
print("manual_output_1 and conv_outputs differ by: ", end = "")
print((manual_output_1 - conv_outputs.int_repr()).sum().item())

print("manual_output_2 and conv_outputs differ by: ", end = "")
print((manual_output_2 - conv_outputs.int_repr()).sum().item())


text:
Q: 'FBLoginButton' conform to 'View' I try to create a Facebook button but when I call it in the VStack it says: 'Referencing initializer 'init(alignment:spacing:content:)' on 'VStack' requires that 'FBLoginButton' conform to 'View'', So why isn't it working because FBLoginButton is a button after all.
here's the code:
struct ContentView: View {
    var body: some View {
        VStack(alignment: .center) {
            FBLoginButton(frame: CGRectMake(0, 0, 100, 100), permissions: ["email"])
        }
    }
}

A: First of all needs to create class which implements UIViewRepresentable protocol.
import FBSDKLoginKit
import SwiftUI
struct FacebookLoginButton: UIViewRepresentable {
    typealias UIViewType = FBLoginButton

    func makeUIView(context: Context) -> UIViewType {
        FBLoginButton()
    }

    func updateUIView(_ uiView: FBLoginButton, context: Context) { }
}

After all this FacebookLoginButton can be used in SwiftUI like this:
var body: some View {
    FacebookLoginButton()
}

A: Facebook SDK still uses UIKit, and FBLoginButton is UIView from UIKit, not View" from SwiftUI.
You need to use loginmanger which does most of the work and embed it inside swiftui Button.
Check link below which will be helpful.
https://gist.github.com/zydeico/8bb9c772e944d1490335e1615aaf4960


text:
Q: How to pass global structure pointers as call by reference to a function? #include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node{
    int data;
    struct node* link;
};
struct node *head1=NULL;
struct node *tail1;
void insertAtLast(struct node* head,struct node* tail,int num){
    struct node* newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=num;
    newnode->link=NULL;
    if (head==NULL){
        printf("Came here");
        head=newnode;
        tail=newnode;
        if (head1==newnode){
            printf("Head1 changes");
        }
    }
    else{
        tail->link=newnode;
        tail=newnode;
    }
}
int main(){
    int n1;
    printf("Enter the number of elements in list1: ");
    scanf("%d",&n1);
    int i,t;
    printf("Enter the elements- ");
    for (i=0;i<n1;i++){
        scanf("%d",&t);
        insertAtLast(head1,tail1,t);
    }
    struct node* temp=head1;
    while (temp!=NULL){
        printf("%d",temp->data);
        temp=temp->link;
    }
    return 0;
}

The value of head1 is not changing even though I pass by reference. Even after assigning head1 and tail1 as pointer, they are not modified when they are passed by reference and modified inside the function.


text:
Q: Python, loop program Can someone tell me what i am doing wrong? I am writing a program using loops in Python 3.x, but when i execute program i am getting a traceback error:
multiple of 13 is 195 and factors are as follows
Traceback (most recent call last):
  File "C:/Users/Darlene/Desktop/Chapter 4/program4_2.py", line 19, in
    list1.append(j)
AttributeError: 'dict' object has no attribute 'append'
this is the code i entered:
def main():
    for i in reversed(list(range(100,201))):
    if i%13==0:
        print("multiple of 13 is",i,"and factors are as follows")
        list1 = {}
        for j in list(range(2,i+1)):
            if i%j == 00:
            list1.append(j)
        print(list1)
main()

A: As commented by Luke Park, list1 = {} will declare a dictionary. What you need is list1 = [].
Also, range will already return a range type that can be handled by most methods and loops so there's no need to cast it to a list.

A: list1 must be an list like so...
list1 = []

you defined it as an dict, and as python said
'dict' object has no attribute 'append'


text:
Q: Why does Visual Studio only allow one link per file in a project? I would like to have a file in several different projects of a solution, however, Visual Studio only allows one link per solution to the file. Is there a way around this?
What is the issue of having several soft links to a single file within a VS project?
Update: I have added the link as described from the comments below, it seems that the issue is on a per project basis. There can not be multiple links to the same file within the project. When I attempt to add the link I receive the following error - "There is already a link to ''. A project cannot have more than one link to the same file."

A: You could create several links to one file on ONE project, but manually and VS will not show it in project tree.
unload project and add for example links:
<Content Include="..\..\_Common\js\JQuery\jquery.js">
  <Link>Sites\OrgCatalogSite\Design\js\JQuery\jquery.js</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

<Content Include="..\..\_Common\js\JQuery\jquery.js">
  <Link>Sites\TasksManagersSite\Design\js\JQuery\jquery.js</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

A: I am using Visual Studio 2008 Professional, and it allows the same file from one project to be soft-linked to every other project, independently of the number of solution files you are using.

A: Not sure what you want to achieve or what kind of file it is, but you could create a new project with that file in it and reference that project from each of the projects that require it? If its a code file, then its will be within scope, if its some other file with "Copy Always" then it will be copied into the various projects bin folder when built?

A: I wish I could add more than one link to the same .XSD/.WSDL file in one project.
In details.
The server is in java (WebSphere Application Server/7.0). The client dll in c#. We use contract-first approach.
In Visual Studio 2008 I Add Service Reference. But instead of my original WSDL/XSD contracts it retrieves dummy XService.wsdl and XService_schema1.xsd and generates "not so dev friendly" code (with message wrappers, xFieldSpecified stuff, dummy ArrayOfx collections...). So what I do? I change Reference.svcmap so that it includes exactly original WSDL/XSD contracts and paste them from where they belongs. That's ok, I get dev friendly code and I am happy.
But what if someone changes the server contract? Here I can't just Update Service Reference. I have to copy-paste new contracts to my Service Reference folder any time contract been changed.
To sum up, I need to add my original WSDL/XSD files As Links to all Service Reference folders in order to simplify contract changing process. Just check out new WSDL/XSD, right click Reference.svcmap > Run Custom Tool.
Isn't that worthy feature?


text:
Q: C# Win form. Getting a list of books displayed in a rich text box I want to get the book author and the book title displayed in my rich text box. Here is a sample of my code:
        // Opretter info på bog
        book.Author = "Hej Preben";
        book.Title = "Hvem sagde hej?";

        // tilføjer bogen til metoden
        library.AddBook(book);
        richTextBoxBooks.Text = library.GetAllBooks().ToString();

The GetallBooks is returning title and author (and a id), but when i look at my windows form, my textbox is displaying this:
My list is working, I just want to know how I can get the correct info displayed, insted of this.
Im feeling stuck, so have not tried many things

A: Use a foreach loop on your list:
    string books = "";
    foreach(var item in someList)//replace someList with name of your list
      { //as long as [0] is not id you will have [0], [1], [2] to choose from

        books += item[0].ToString() + System.Environment.NewLine + item[1].ToString();

      }

richTextBoxBooks.Text = books;

I woud also make yor textbox read only, and multiline.
someList could be replaced by library.GetAllBooks() as long as it returns a list.

A: Try this
Book and Library classes
namespace WinFormsApp1
{
    internal class Book
    {
        public string Author { get; private set; }
        public string Title { get; private set; }
        public Book(string author, string title)
        {
            Author = author;
            Title = title;
        }
    }

    internal class Library
    {
        private List<Book> _books { get; set; } = new List<Book>();
        public void AddBook(Book book)
        {
            _books.Add(book);
        }
        public List<Book> GetAllBooks()
        {
            return _books;
        }
    }
}

Button click event
private void button1_Click(object sender, EventArgs e)
{
    var library = new Library();
    library.AddBook(new Book("Author One", "Title One"));
    library.AddBook(new Book("Author Two", "Title Two"));
    library.AddBook(new Book("Author Three", "Title Three"));

    foreach (Book book in library.GetAllBooks())
    {
        richTextBox1.Text = $"{richTextBox1.Text}{book.Author} - {book.Title}{Environment.NewLine}";
    }
}

Result


text:
Q: How to plot a single node using tidygraph objects in R? I was wondering if it is possible to plot a tidygraph object with a single node? For example, if I create some data and a tidygraph object with 2 nodes, that would look like this:
library(tidygraph)
library(graph)
nodes <- data.frame(name = c('var1', 'var2'), value = c(3, 10))
edges <- data.frame(from = c(1),
                    to = c(2))

tg <- tbl_graph(nodes = nodes, edges = edges)

ggraph(tg, "partition") +
  geom_node_tile(aes(fill = name)) +
  scale_y_reverse() +
  theme_void()

However, I was wondering if I could plot a tidygraph object that contains just 1 node. For example, if my data had no edge data associated with it, like so:
nodes <- data.frame(name = c('var1'), value = c(3))
tg <- tbl_graph(nodes = nodes)

When I try to plot the above, I get the error:

Error in layout[, 1] : incorrect number of dimensions

Which makes sense because there is no edge data. I, naively, tried to set the edge data to something like:
edges <- data.frame(from = c(1),
                    to = c(1))

But this throws back an error as well.
I was wondering if there is a way to achieve what Im trying to do?

A: You could create a two-row node data frame with the same row repeated twice, the same for the edges data frame. Create the plot object and remove the second row of its data component.
library(tidygraph)
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#>
#>     filter
library(ggraph)
#> Loading required package: ggplot2

nodes <- data.frame(name = c('var1'), value = c(3, 3))
edges <- data.frame(from = c(1, 1),
                    to = c(1, 1))

tg <- tbl_graph(nodes = nodes, edges = edges)

p <- ggraph(tg, "partition") +
  geom_node_tile(aes(fill = name)) +
  scale_y_reverse() +
  theme_void()

#Remove second node
p$data <- p$data[-2, ]

p

Created on 2022-03-28 by the reprex package (v2.0.1)


text:
Q: Converting enums to symbols in Julia I have a definition of an enum as below. I would like to map each instance of the enum into the corresponding symbol. I can do this by manually constructing an array symbols and indexing into it. Is there a way of accomplishing this without specifying the array of symbols by hand?
@enum MyEnum A=1 B=2 C=3

symbols = [:A, :B, :C]

function enumToSymbol(x::MyEnum) :: Symbol
    return symbols[Int(x)]
end

@assert enumToSymbol(A) == :A

A: Just use Symbol:
julia> @enum MyEnum A=1 B=2 C=3

julia> Symbol(A)
:A

julia> x = A
A::MyEnum = 1

julia> Symbol(x)
:A

as it is defined as follows:
Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol

in particular you have an un-exported:
julia> Base.Enums.namemap(typeof(x))
Dict{Int32,Symbol} with 3 entries:
  2 => :B
  3 => :C
  1 => :A


text:
Q: using xsl:fallback correctly I'm trying to incorporate xsl:fallback into my stylesheets. I am using Saxon9.5.1.23-HE.
I tried this code in a named template that I'm calling:
<xsl:newstuff>
    <xsl:text>blabla</xsl:text>
    <xsl:fallback>
       <xsl:message>
          Fallback worked!
       </xsl:message>
    </xsl:fallback>
</xsl:newstuff>

But instead of "Fallback worked", I get the message that the element newstuff is unkown.
Am I doing something wrong or does it have to do with the version of Saxon I am using?
I havent found anything on the Saxon website yet.
Thanks for your help!

A: <xsl:fallback> is only processed in forwards-compatible mode when the version="..." on the xsl:stylesheet element is greater than the maximum version supported by the processor in question (i.e. "I only understand XSLT 2.0 but this stylesheet is 4.0, so I'll give you the benefit of the doubt").  If the processor understands the version of XSLT that you claim for your stylesheet then it is correct to reject elements it does not recognise rather than using the fallback ("I understand XSLT 2.0, this stylesheet is 2.0, therefore I know for certain that this element is wrong").


text:
Q: Notion-like editing and layout with a convenient freeform collaborative editor in WordPress? I spend a lot of time developing technical content that revolves around software and network engineering. I used to do some content creation and blogging on this topic as well as creating documentation for clients, but I got tired of some of challenges of doing some of the more freeform things that I wanted to do and ended up rolling back over to traditional word processing.
A few months ago I discovered Notion and was floored by some of the opportunities to really create flexible documents that didn't fit within the normal realm of editing for the web. This has been really neat, but simultaneously I simply can't use their publishing platform for most of the work I do for various reasons.
Is there a Notion-like editing system (plugin) that allows both the Notion freeform style of document creation along with the accompanying collaboration for editors to collaborate on document creation in realtime for WordPress?
A huge bonus would also being able to do the editing in or with Markdown as well if desired.
I'd just love to bring the editing elements of Notion into content creation.


text:
Q: WordPress MySQL & PHP Performance have a website (www.americanbankingnews.com) that gets 40,000-50,000 page views today. It's currently sitting on a dedicated quad-core Xeon server with 8GB of ram. The site is powered by WordPress and MySQL (sitting on the same server) and I'm currently using W3 Total Cache for page and MySQL query Caching.
Unfortunately, that doesn't seem to be enough. During peak traffic times, my servers are getting a few HTTP 500 errors and pages that aren't cached load slowly.
I'm currently not using Xcache or any other PHP cache/acceleration tools.
Are there additional steps that I should take to try to optimize MySQL and PHP performance? Or should I fork over for an additional server. Specifically, I'd be interested in additional suggestions to improve MySQL performance and whether or not tools like xcache might help in this situation

A: Hi Matthew Paulson,
I see your using W3 Total Cache but your database and object cache is set to disk.  Caching objects and your database to disk can actually have a negative performance effect especially if your getting that much traffic.
You can read more about the effects on caching database and objects to disk in an article I wrote on how to set up W3 Total Cache  The plugin author agreed with the instructions in my settings.
To really see the benefit of database and object caching you need to be using a PHP opcode cache like APC.  You can follow the copy and paste instructions in the plugin FAQ to compile and set up APC.  If your on Ubuntu or Debian you can simply run the command:  apt-get apc-php5 to install.
Like others have also mentioned you will get a huge performance boost and enable your site to scale much larger by setting up a reverse proxy with Nginx.
I give detailed instructions on how to configure and set it up in my  WordPress Performance Stack. article.
You should also read some of the other questions and answers on here.  A lot of good performance and scaling advice has been given.
Good luck on your quest.  Managing your own server can be very stressful sometimes.
Edit
Just to show the performance you can gain by installing Nginx as a reverse proxy I'm posting an Apache Benchmark test I just ran on my server:
x-wing ~: ab -n 1000 -c 80 http://wp-performance.com/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking wp-performance.com (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

Server Software:        nginx/0.8.54
Server Hostname:        wp-performance.com
Server Port:            80

Document Path:          /
Document Length:        3132 bytes

Concurrency Level:      80
Time taken for tests:   0.066 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      3605000 bytes
HTML transferred:       3132000 bytes
Requests per second:    15164.15 [#/sec] (mean)
Time per request:       5.276 [ms] (mean)
Time per request:       0.066 [ms] (mean, across all concurrent requests)
Transfer rate:          53385.52 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2   0.6      1       3
Processing:     1    4   0.8      4       5
Waiting:        1    3   0.8      3       5
Total:          3    5   0.6      5       7

Percentage of the requests served within a certain time (ms)
  50%      5
  66%      5
  75%      6
  80%      6
  90%      6
  95%      6
  98%      6
  99%      6
 100%      7 (longest request)

Theoretically it's able to handle over 15,000 requests per second.  (Same Network)

A: Lots of similar questions and answers:
https://wordpress.stackexchange.com/search?q=mysql+optimize
It comes down to using tools - like mysqltuner - to investigate the bottlenecks, checking logs for errors and memory usage, php opcode-caching, clearing post/page revisons to get the DB down to size, etc.

A: Hi @Matthew Paulson:
You may be asking the wrong question.
With your traffic you may want to look at at front-end cache using nginx. Here are Q&As for nginx here on the site, lots of relevant articles in a Google search, and plugin that can interface WordPress to nginx at wordpress.org and lastly an article on installing and configuring:

*

*https://wordpress.stackexchange.com/search?q=nginx

*http://www.google.com/search?q=nginx+wordpress

*http://wordpress.org/extend/plugins/search.php?q=nginx

*http://elasticdog.com/2008/02/howto-install-wordpress-on-nginx/
If that doesn't help or if you don't want to do it for some other reason please let us know what plugins you are using. Most of the time with WordPress performance problems are not the obvious but instead they are result of some poorly written plugins.

A: Do you have insight in what exactly is becoming a bottleneck under high load? It could be different type of resource (CPU load, sustaining network conenctions, running out of memory, etc).
General things:

*

*opcode cache (keeping compiled PHP code in memory) is a must;

*you seem to have memory to burn, so it's worth trying memory-based object cache (W3TC supports it, look into that). It will make a lot of stuff more persistent and move load away from MySQL;

*if web server software is bottleneck (you don't mention what you run, Apache?) you might want to look into alternative  web server (like nginx) or reverse proxy (again - you have memory to burn, I heard good things about Varnish).

A: You weren't kidding, just tried going to your site and got a 500 internal error. Perhaps you can lower the number of plugins you are using and make sure all images are optimized, etc. to make page sizes smaller so they consume less bandwidth to load hence less errors.
You may also want to look into HIP HOP for PHP . I never implemented it but it was released open source by the facbook people who after creating and using it saw their server load go down by about 30%. Basically it takes regular php files, converts them to C++ binaries and serves those out.

A: The hardware you have should easily cope with the stated traffic (as a benchmark, a site I run peaks at ~40k daily page views on a 2GB Slicehost VPS) - so that suggests something  grossly wrong.
So, as other people have said, the first thing you need to do is understand where the problem(s) is/are.

*

*What information does top give you when you're under load? Are you using swap memory, is your load spiking, when you sort by memory and cpu% what are the top processes?

*Can you install something like munin to give you an insight into your server?

*Assuming you're running Apache, how is it configured - the important things to know are:

*

*Timeout

*KeepAlive

*MaxKeepAliveRequests

*KeepAliveTimeout

*(assuming you're running Apache in prefork mode) - all the config lines in the prefork section of your apache conf file.

*Running this command - ps -ylC httpd --sort:rss will give you a indication of how much memory Apache processes are using.

*Install mtop and mysqltuner - from what I remember both are available via apt-get. You should also turn on MySQL slow logging - you normally just need to uncomment a line in your my.cnf file.

*

*mtop gives you a real time view of what SQL queries are running (slowly). mysqltuner will give you some sense of what changes you need to make to your MySQL configuration

*As suggested by others, what happens if you turn off plugins during a busy period? Does the site speed up? What plugins do you have installed?

*Do you have any idea of how much traffic you're getting during your busy periods - eg 4000 page views in 10 minutes.
Armed with information from these sources, you'll have a much better idea of what's going wrong.

A: i dont know what programs you installed but maybe its APC - Zend problem:
http://www.ivankristianto.com/web-development/server/alternative-php-cache-apc-not-compatible-with-zend-optimizer/1726/

This problem happen in my VPS after i
  install Alternative PHP cache (APC).
  And also i already have Zend optimizer
  installed on the same VPS. After i
  installed APC, my WordPress blog show
  strange behavior. Sometimes i got
  Error 500 Internal Server Error, and
  sometimes i got PHP fatal error.


text:
Q: Exclude Domain in Exim config We have been using exim through cpanel to send email this is because they support an SMTP relay to send email.
We have just moved over to Google Apps for our mail and we have a bit of a problem.
If you're on one of our websites and you have a mail script setup to send an email and that particular email is going to a domain that is hosted on the cPanel account, it won't send through the relay. It treats it as an internal email. I want it to go through the relay.
smart_route:
driver = manualroute
domains = !+local_domains
transport = remote_smtp_smtpauth
route_list = * smtp.sendgrid.net:587

I've tried removing the domains = !+local_domains line from the config and it seems to work. The only problem is that all emails that come to the server try to send again through to relay and it just gets stuck in a loop.
Is there away I can exclude a domain from the list so it will treat it as an external email address?

A: This is a simple one. If you go to WHM > Edit DNS > example.com on the cPanel server where the account is located. At the bottom of the DNS editor screen is going to be a few options; Automatic, Remote, Local, and Backup.
You will want to change this to Remote. The reason for this is when the sendmail function is run is is sending on the server, so the server assumes that mail should be delivered locally. By changing the option to remote it forces the server to do a DNS lookup and deliver mail to Google's Servers.


text:
Q: Why am I getting negative one bytes for my output? I tried to develop a simple metadata visualizer tool using C for visualizer engine for "png" file but I'm getting -1 for my output and I don't know why. Can someone show me where is the error?
#include <stdio.h>
int main ()
{
    FILE *file_input;
    unsigned char c; //unsigned
    long int counter=0L;
    long int saizFail, curPos=0L, current=0L;

    if ((file_input = fopen("C:\\Users\\User\\Pictures\\timetable.png", "rb"))=NULL)
         printf("File cannot be opened");

    fseek(file_input, 0L, SEEK_END); //
    saizFail=ftell(file_input);
    rewind(file_input);

    printf("File size = %ld bytes\n\n", saizFail);

    while (counter<100)
    {
        c=fgetc(file_input);
        printf("counter %ld >> %X\n", counter, c);
        counter++;

    }

    printf(">>File size = %ld bytes\n\n", saizFail);

    fclose(file_input);
    getchar();
}

A: You meant to use ==, but used = instead.
This line:
if ((file_input = fopen("C:\\Users\\User\\Pictures\\timetable.png", "rb"))=NULL)

Should be:
if ((file_input = fopen("C:\\Users\\User\\Pictures\\timetable.png", "rb"))==NULL)


text:
Q: How to redirect to Laravel route when call came from JS Ajax I am trying to create a redirect to a route in laravel controller where the call to this controller came from an Ajax call in a js file.
Example: I loaded a view localhost:8000/viewone, in this view I run a js code that does an Ajax call to a Laravel route : routeone. In the controller function linked to routeone, the code does some data processing and then needs to load an other view : viewTwo.
The problem is that the viewTwoloading doesn't occur and all I get is the view HTML code in my return statement in onsuccess function of the Ajax call.
What I tried :
Create a controller inked to viewTwo by creating a new route routeTwo,
in my routeonecontroller I redirect to this route with session data.
return redirect()->route('routeTwo')->with(['data'=>$data])
In the routeTwocontroller I get the session data and return the viewTwo.
$data = \Session::get('data');
return view('viewTwo',['data'=>$data]);

It still doesn't work. What happens is that viewTwoloading happens as an XHR request and I get the HTML page which would have been loaded in the main browser view ( like the first view ) as XHR response data.
Question : How to force redirect to/load view when call came from Js AJAX function.

A: by load or render html from ajax do like this in first view page

by ajax success function add this line
$('.newView').html(data.html);

in controller
$view = view("viewnamewhatuhave",compact('data'))->render();

by view facade
$view =  View::make('viewnamewhatuhaveset',[$data])->render();

return response()->json(['html' => $view]);


text:
Q: Android AsyncHttpClient - "Content-Type not allowed!" Regardless of types provided Good Day all.
My first time posting on SO, never had to before.  Reading was always enough.  Now, I'm just woefully stuck using AsyncHttpClient library for Android.  It works fabulously in every other response besides downloading files, at least for me over the last day and a half of being stuck. :-)
Code:
@Override
public void onClick(DialogInterface dialog, int which) {

    int userId = ((App)getActivity().getApplicationContext()).getUserId();

    String url = ZenApi.getAbsoluteUrl("api/attachments/" + userId + "/" +
            attachments[which]);
    selectedFile = attachments[which].toString();

    String[] allowedContentTypes = new String[] {"application/octet-stream",
        "text/html; charset=ISO-8859-1", "image/png", "image/jpeg",
        "image/bmp", "application/pdf", "text/html; charset=UTF-8", "image/png;charset=UTF-8" };

    BinaryHttpResponseHandler handler = new BinaryHttpResponseHandler(allowedContentTypes) {
        @Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
        };

        @Override
        public void onFinish() {
            ChooseMessageAttachmentFragment.this.dismiss();
            super.onFinish();
        }

        @Override
        public void onProgress(int bytesWritten, int totalSize) {
            // TODO Auto-generated method stub
            super.onProgress(bytesWritten, totalSize);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                byte[] binaryData, Throwable error) {
            Toast.makeText(getActivity(), "Failed to load file: " + error.getMessage(), Toast.LENGTH_LONG).show();
        }
        @Override
        public void onSuccess(int statusCode, byte[] binaryData) {
            File file = new File(getActivity().getFilesDir(), selectedFile);
            if (file.exists()) {
                try {
                    FileOutputStream stream = new FileOutputStream(file.getPath());
                    stream.write(binaryData[0]);
                    stream.close();

                    MimeTypeMap mimemap = MimeTypeMap.getSingleton();
                    String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
                    String type = mimemap.getMimeTypeFromExtension(ext);
                    if (type == null ) {
                        type = "*/*";
                    }

                    Intent intent = new Intent();
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), type);
                    startActivity(intent);

                } catch (java.io.IOException e) {
                    Toast.makeText(getActivity(), "Error downloading file", Toast.LENGTH_SHORT).show();
                }
            }

        }

    };

    ZenApi.post(url, null, handler);

}

The url used is correctly formed (I checked) and every other call using this library (JSON, Login POSTs) all work fine.
I've researched and tried everything that I can think of or have read through google searches or SO hits on this particular library in conjunction with this error and I have tried just about every imaginable MimeType to include to the call, still with the same error.  I really would like to get this to work so I don't have to refactor all my code to use built in httpclients which is my next step I think.  I also like this library very much.

*

*Trying to download a simple png file.

*The backend API call that serves up the image is working and has been for a year with different clients (browser, Titanium App, etc).

*Connection is over SSL

*All other calls (not involving downloading of files) to our backend work correctly with this library.
Any help would be appreciated.  Thanks!

A: You can check exactly what kind of file is returned by your backend. Just overwrite the onFailure in your BinaryHttpResponseHandler like this:
@Override
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error)
{
    Log.e(TAG, "onFailure!"+ error.getMessage());
    for (Header header : headers)
    {
        Log.i(TAG, header.getName()+" / "+header.getValue());
    }
}

This can also provide you other information to solve your problem.
Hope this helps


text:
Q: Are there any events so rare that I can compare them to the odds of this event? I have calculated the likelihood of an event to be $1$ in $1.07 \times 10^{2867}$.
I'm looking for a way to describe to a layperson how unlikely this event is to occur, but the number is so mind boggling large I can't find a way to put it into words.
Any suggestions would be appreciated

A: It is the probability of the proverbial monkey hacking a typewriter and producing the first page of Hamlet.

A: There's about $n=10^{80}$ atoms in the universe and about $p=4\times 10^{27}$ atoms in the human body. If you choose arbitrarily $p$ atoms in the universe, what is the probability that these atoms are exactly the atoms you are composed of at the instant you finish this sentence?
It's $\binom{n}{p}^{-1}$


text:
Q: I have some problem with OOMMF simulation    Specify Oxs_ScriptUZeeman [subst {
      script_args total_time
      script {SmoothStep $step_height [expr {$rise_time*1e-12}]}
      multiplier [expr {0.001/$mu0}]
   }]

   proc SmoothStep { Hnom risetime t } {
      set t [expr {$t/$risetime}]
      if {$t<=0.0} {
         set g 0.0
         set gp 0.0
      } elseif {$t>=1.0} {
         set g  $Hnom
         set gp 0.0
      } else {
         global pi
         set g [expr {0.5*$Hnom*(1-cos($pi*$t))}]
         set gp [expr {0.5*$Hnom*$pi*sin($pi*$t)/$risetime}]
      }
      return [list $g 0 0 $gp 0 0]
   }

I simulated mif file that is littele bit changed from yoyo.mif file which is contained with oommf file. but it's not working now. Program said that Can't use non-numeric string as operand of '/'. I tried to solve this problem, but it does not resolved yet.


text:
Q: The import cucumber cannot be resolved in Runner Class for Gradle Project I don't whats wrong with my Gradle Dependencies but when I try to import import cucumber.api.junit.Cucumber; then I get error The import cucumber cannot be resolved
Below is my Gradle file:
apply plugin: 'java'

version = '1.0-SNAPSHOT'

dependencies {
    compile group: 'info.cukes', name: 'cucumber-java', version: '1.2.5'
    testCompile group: 'info.cukes', name: 'cucumber-junit', version: '1.2.5'
    compile group: 'info.cukes', name: 'cucumber-core', version: '1.2.5'
    testCompile group: 'info.cukes', name: 'cucumber-picocontainer', version: '1.2.5'
    compile group: 'info.cukes', name: 'cucumber-guice', version: '1.2.5'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

repositories {
    mavenCentral()
}

My Runner Class is:
package Runner;

import org.junit.runner.RunWith;
import cucumber.api.junit.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
Cucumber.options(
    features = "\\src\\test\\java\\Feature",
    glue = {"\\src\\main\\java\\Steps\\"},
    tags = {"@ignored"},
    format = {"json:target/cucumber/wikipedia.json","html:target/cucumber/wikipedia.html","pretty"}
)
public class RunnerMain {
}

When I comment @RunWith, CucumberOptions and remove the imports, then run command gradle build then I don't see any error and all goes well.
I don't know what wrong I am doing here.

A: Replace Cucumber.options with @CucumberOptions and try once


text:
Q: Ambiguous reference to member 'subscript' when using Google maps route The below code works fine in Xcode 7.1 but when I upgrade to Xcode 8 and swift 3 I get this error, I had searched on internet for same problem in stackoverflow but none of them answer my question.
func drawRoute() {

    clearRoute()
    //  self.routePolyline = nil
    // self.routePolyline.map = nil

    let route = mapTk.overviewPolyline!["points"] as String //error here

    //var overViewPolyLine = routes![0]["overview_polyline"]["points"].string

    let path: GMSPath = GMSPath(fromEncodedPath: route)
    routePolyline = GMSPolyline(path: path)
    routePolyline.map = viewMap
}

here is the class mapTK for more info:
import Foundation

import UIKit
import CoreLocation
import MapKit

///This Class is designed for the detail methods that contact google maps server like GeoCode, GetDirection and Calculate distance and time
class MapTK: NSObject {
    let baseURLGeocode = "https://maps.googleapis.com/maps/api/geocode/json?"

    var lookupAddressResults: Dictionary<NSObject, AnyObject>!

    var fetchedFormattedAddress: String!

    var fetchedAddressLongitude: Double!

    var fetchedAddressLatitude: Double!

    let baseURLDirections = "https://maps.googleapis.com/maps/api/directions/json?"

    var selectedRoute: Dictionary<NSObject, AnyObject>!

    var overviewPolyline: Dictionary<NSObject, AnyObject>!

    var originCoordinate: CLLocationCoordinate2D!

    var destinationCoordinate: CLLocationCoordinate2D!

    var originAddress: String!

    var destinationAddress: String!

    var totalDistanceInMeters: UInt = 0

    var totalDistance: String!

    var totalDurationInSeconds: UInt = 0

    var totalDuration: String!

    /*  private let errorDictionary = ["NOT_FOUND" : "At least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded",
    "ZERO_RESULTS":"No route could be found between the origin and destination",
    "MAX_WAYPOINTS_EXCEEDED":"Too many waypointss were provided in the request The maximum allowed waypoints is 8, plus the origin, and destination",
    "INVALID_REQUEST":"The provided request was invalid. Common causes of this status include an invalid parameter or parameter value",
    "OVER_QUERY_LIMIT":"Service has received too many requests from your application within the allowed time period",
    "REQUEST_DENIED":"Service denied use of the directions service by your application",
    "UNKNOWN_ERROR":"Directions request could not be processed due to a server error. Please try again"]

    */

    override init() {
        super.init()
    }

        ///the geocodeAddress is getting information from googlemaps with JSON it receive the geocode information
    func geocodeAddress(address: String!, withCompletionHandler completionHandler: @escaping ((_: String, _: Bool) -> Void)) {
        if let lookupAddress = address {
            var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
            //geocodeURLString = geocodeURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!

            let geocodeURL = NSURL(string: geocodeURLString)

           // dispatch_Dispatch.Queue.mainasync(dispatch_get_main_queue(), { () -> Void in
            DispatchQueue.main.async {

            let geocodingResultsData = NSData(contentsOf: geocodeURL! as URL)

               // let error: NSError?

               do
               {
                let dictionary = try JSONSerialization.jsonObject(with: geocodingResultsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

                // try NSJSONSerialization.JSONObjectWithData(directionsData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
              /*
                if (error != nil) {
                    print(error)
                    completionHandler(status: "", success: false)
                }

*/
 //               else {
                    // Get the response status.
                    let status = dictionary?["status"]as! String
              //   let status = dictionary["status"] as! [AnyObject]

                    if status == "OK" {
                        let allResults = dictionary?["results"] as! Array<Dictionary<NSObject, AnyObject>>
                        self.lookupAddressResults = allResults[0]

                        // Keep the most important values.
                        self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"]? as? String
                        let geometry = self.lookupAddressResults["geometry"] as! Dictionary<NSObject, AnyObject>
                        self.fetchedAddressLongitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lng"] as! NSNumber).doubleValue
                        self.fetchedAddressLatitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lat"] as! NSNumber).doubleValue

                        completionHandler(status, true)
                    }
                    else {
                        completionHandler(status, false)
                    }
               } catch let error as NSError {

                print(error)
                }
            }
        }
        else {
            completionHandler("No valid address.", false)
        }
    }

    ///getDirection method is using JSON to receive waypoints for making route for drawing polyline, as its name suggests it get the direciton inforamtion, first it send lat and lng the receive a dictionary and that dictionary give all the infrmation need to draw route like waypoints

    func getDirections(origin: String!, destination: String!, waypoints: Array<String>!, travelMode: TravelModes!, completionHandler: @escaping ((_ status: String, _ success: Bool) -> Void)) {
        if let originLocation = origin {
            if let destinationLocation = destination {
                var directionsURLString = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation //+ "&key=AIzaSyDsDqj0EMYZ-C4lGF3tmbntZtzurLl6_J4"

                if let routeWaypoints = waypoints {
                    directionsURLString += "&waypoints=optimize:true"

                    for waypoint in routeWaypoints {
                        directionsURLString += "|" + waypoint
                    }
                }
                if let _ = travelMode {
                    var travelModeString = ""

                    switch travelMode.rawValue {
                    case TravelModes.walking.rawValue:
                        travelModeString = "walking"

                    case TravelModes.bicycling.rawValue:
                        travelModeString = "bicycling"

                    default:
                        travelModeString = "driving"
                    }

                directionsURLString += "&mode=" + travelModeString
            }

              //  directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(NSUTF8StringEncoding)!

              //  directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

             //  directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!

                /// directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

                directionsURLString = directionsURLString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

//let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

                //var url = NSURL(urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()))
                //let savePath = (documentDirectory as NSString).stringByAppendingPathComponent("mergeVideo-\(date).mov")

                let directionsURL = NSURL(string: directionsURLString)

              //  DispatchQueue.main.asynchronously(execute: { () -> Void in

                     DispatchQueue.main.async {
                    let directionsData = NSData(contentsOf: directionsURL! as URL)

                   // var error: NSError?

                    do {
 let dictionary = try JSONSerialization.jsonObject(with: directionsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

                        /*
                        if (error != nil) {
                        print(error)
                        completionHandler(status: "", success: false)
                    }
*/
                   // else {
                        let status = dictionary?["status"] as! String

                        if status == "OK" {
                            self.selectedRoute = (dictionary?["routes"] as! Array<Dictionary<NSObject, AnyObject>>)[0]
                            self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject>

                            let legs = self.selectedRoute["legs"] as! Array<Dictionary<NSObject, AnyObject>>

                            let startLocationDictionary = legs[0]["start_location"] as! Dictionary<NSObject, AnyObject>
                            self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double)

                            let endLocationDictionary = legs[legs.count - 1]["end_location"]as! Dictionary<NSObject, AnyObject>
                            self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double)

                            self.originAddress = legs[0]["start_address"] as! String
                            self.destinationAddress = legs[legs.count - 1]["end_address"] as! String

                            self.calculateTotalDistanceAndDuration()

                            completionHandler(status, true)

                        }
                        else {
                            completionHandler(status, false)
                        }

                    } catch let error as NSError {

                        print(error)
                    }

                  }
                    }

            else {
                completionHandler("Destination is nil.", false)
            }
        }

        else {
            completionHandler("Origin is nil", false)
        }

    }

/// this method below is for the calculation of Distance adn Duration of each location for travel

    func calculateTotalDistanceAndDuration() {
        let legs = self.selectedRoute["legs"] as! Array<NSDictionary>

        totalDistanceInMeters = 0
        totalDurationInSeconds = 0

        for leg in legs {
            totalDistanceInMeters += (leg["distance"] as! Dictionary<NSObject, AnyObject>)["value"] as! UInt
            totalDurationInSeconds += (leg["duration"]as! Dictionary<NSObject, AnyObject>)["value"] as! UInt
        }

        let distanceInKilometers: Double = Double(totalDistanceInMeters / 1000)
        totalDistance = "Total Distance: \(distanceInKilometers) Km"

        let mins = totalDurationInSeconds / 60
        let hours = mins / 60
        let days = hours / 24
        let remainingHours = hours % 24
        let remainingMins = mins % 60
        let remainingSecs = totalDurationInSeconds % 60

        totalDuration = "Duration: \(days) d, \(remainingHours) h, \(remainingMins) mins, \(remainingSecs) secs"
    }

}

A: Use
Dictionary<String, Any>

as JSON dictionary type.
JSON keys are required to be String anyway and
AnyObject has been changed to Any in Swift 3.
Edit :
I recommend to use a type alias for the JSON dictionary type
typealias JSONObject = [String:Any] // synonym of Dictionary<String, Any>

Then you can write
var lookupAddressResults: JSONObject!
...
var selectedRoute: JSONObject!
var overviewPolyline: JSONObject!

and the parsing code
...
    if status == "OK" {
        let allResults = dictionary?["results"] as! Array<JSONObject>
        self.lookupAddressResults = allResults[0]

        // Keep the most important values.
        self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as? String
        let geometry = self.lookupAddressResults["geometry"] as! JSONObject
        self.fetchedAddressLongitude = ((geometry["location"] as! JSONObject)["lng"] as! NSNumber).doubleValue
        self.fetchedAddressLatitude = ((geometry["location"] as! JSONObject)["lat"] as! NSNumber).doubleValue

        completionHandler(status, true)
      }

...

You can also replace
( ... as! NSNumber).doubleValue

with
... as! Double