问:
how to wait untill chain of asyc calls is succeeded
I have a function which is making an async call
and upon sucess, its making another async call

ex:-

```<code>    function1 = () => {
      /*Some required Logic*/
  return fetch("myurl")
      .then((json) => {
        function2(json)

      })
      .catch((error) => {
        console.log(error)
      })
}

function2 = () => {
  /*Some required Logic*/
  return fetch("myurl2")
      .then((json) => {
        callthirdfunction(json)

      })
      .catch((error) => {
        console.log(error)
      })
}
</code>```

now here is the function 3
in which i am dependent on the success of function1

```<code>function3 = () => {
  /*Some required Logic*/
  function1().then(() => {
})
}
</code>```

Issue is it is only waiting untill the function1's asyc call is succeeded its not waiting for function2's async call to succeed

I know i can write like chain of asyn call but its not possible because of unavoidable circumstances

Any suggesstion or leads in this regard would be of great help

答:
If you used async await as you mentioned in your tags, you could just use it like that:

```<code>await function1();
await function2();
await function3();
</code>```

while adding the async keyword to the function declarations:

```<code>function1 = async () => {

}
</code>```

Another option is to promisify your functions, and then call them like that:

```<code>function1()
.then(function2)
.then(function3)
.catch() {}
</code>```

Body:
I have a function which is making an async call
and upon sucess, its making another async call

ex:-

    function1 = () => {
      /*Some required Logic*/
  return fetch("myurl")
      .then((json) => {
        function2(json)

      })
      .catch((error) => {
        console.log(error)
      })
}

function2 = () => {
  /*Some required Logic*/
  return fetch("myurl2")
      .then((json) => {
        callthirdfunction(json)

      })
      .catch((error) => {
        console.log(error)
      })
}

now here is the function 3
in which i am dependent on the success of function1

function3 = () => {
  /*Some required Logic*/
  function1().then(() => {
})
}

Issue is it is only waiting untill the function1's asyc call is succeeded its not waiting for function2's async call to succeed

I know i can write like chain of asyn call but its not possible because of unavoidable circumstances

Any suggesstion or leads in this regard would be of great help

Body:
If you used async await as you mentioned in your tags, you could just use it like that:

await function1();
await function2();
await function3();

while adding the async keyword to the function declarations:

function1 = async () => {

}

Another option is to promisify your functions, and then call them like that:

function1()
.then(function2)
.then(function3)
.catch() {}


来源: stackexchange

问:
how does authenex A-Key 3600 OTP works, how did it authenticate with network
one of my friend working in MNC, one-day bze of some network issues in his company, he came back to home and he started working from home, after connecting to the internet he connected to the organization proxy and he used a device authenex A-Key 3600, as a web developer I didn't understand that device can generate 8 digits random number as password, I know how to generate it, but still I didn't understand how did that OTP authenticate network which is randomly generated in a small device, I believe it's an Offline Device </p>

答:
This device uses HOTP (RFC 4226) algorithm to produce OTPs. Basically, this algorithm just mixing and hashing two things: a secret key and a counter.

The secret key is a random string, known only by an authentication server and by the one's particular device (token). The counter is incremented after each OTP generation.

Working by the same algorithm and knowing the same input data (the secret and the counter) the token and server receive the same result (OTP). So there is no need to have any network between auth server and tokens, they work independently.

Also, please, take into account, that HOTP algorithm is pretty old and nowadays TOTP is more preferable. TOTP algorithm uses current time instead of a counter, so received OTPs has a limited validity period, which is better for security reasons. There is also TOTP tokens with NFC, which can be easily added to any compliant system.

ContentLicense: CC BY-SA 3.0


问:
Angular 2 - send file as a part of form data
Does anyone know how to send picture (file) as a part of form data using AuthHttp (angular2-jwt) service in Angular 2?</p>

答:
Sending a file using authHttp can be done like this: </p>

```<code>let file = new File([blobData], "filename.png");
const url = 'https://example.com/upload';

let formData:FormData = new FormData();
formData.append('file', file, file.name);

this.authHttp.put(url, formData)
      .catch(this.handleError);
</code>```

Body:
Sending a file using authHttp can be done like this:

let file = new File([blobData], "filename.png");
const url = 'https://example.com/upload';

let formData:FormData = new FormData();
formData.append('file', file, file.name);

this.authHttp.put(url, formData)
      .catch(this.handleError);


问:
Python, copying a rank 2 list structure with different values
Using python 3.6

Say I had this dictionary and list structure of keys:

```<code>dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

keys = [['a','b'], ['c','d','e']]
</code>```

Whats the best way to get this?

```<code>values = [[1, 2], [3, 4, 5]]
</code>```

Thanks!

Body:
Using python 3.6

Say I had this dictionary and list structure of keys:

dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

keys = [['a','b'], ['c','d','e']]

Whats the best way to get this?

values = [[1, 2], [3, 4, 5]]

Thanks!

Body:
You can try this:

dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

keys = [['a','b'], ['c','d','e']]

new = [[dictionary[b] for b in i] for i in keys]

Output:

[[1, 2], [3, 4, 5]]


问:
Calling a method inside a Linq query
I want to insert into my table a column named 'S' that will get some string value based on a value it gets from a table column.

For example: for each ID (a.z) I want to gets it's string value stored in another table. The string value is returned from another method that gets it through a Linq query.

Is it possible to call a method from Linq?

Should I do everything in the same query?

This is the structure of the information I need to get:

a.z is the ID in the first square in table #1, from this ID I get another id in table #2, and from that I can get my string value that I need to display under column 'S'.

```<code>var q = (from a in v.A join b in v.B
    on a.i equals b.j
    where a.k == "aaa" && a.h == 0
    select new {T = a.i, S = someMethod(a.z).ToString()})
    return q;
</code>```

The line S = someMethod(a.z).ToString() causing the following error:

Unable to cast object of type 'System.Data.Linq.SqlClient.SqlColumn'
  to type 'System.Data.Linq.SqlClient.SqlMethodCall'.

答:
That is an old question, but I see nobody mention one "hack", that allows to call methods during select without reiterating. Idea is to use constructor and in constructor you can call whatever you wish (at least it works fine in LINQ with NHibernate, not sure about LINQ2SQL or EF, but I guess it should be the same).
Below I have source code for benchmark program, it looks like reiterating approach in my case is about twice slower than constructor approach and I guess there's no wonder - my business logic was minimal, so things like iteration and memory allocation matters.

Also I wished there was better way to say, that this or that should not be tried to execute on database,

```<code>// Here are the results of selecting sum of 1 million ints on my machine:
// Name    Iterations      Percent
// reiterate       294     53.3575317604356%
// constructor     551     100%

public class A
{
    public A()
    {
    }

    public A(int b, int c)
    {
        Result = Sum(b, c);
    }

    public int Result { get; set; }

    public static int Sum(int source1, int source2)
    {
        return source1 + source2;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var range = Enumerable.Range(1, 1000000).ToList();

        BenchmarkIt.Benchmark.This("reiterate", () =>
            {
                var tst = range
                    .Select(x => new { b = x, c = x })
                    .AsEnumerable()
                    .Select(x => new A
                    {
                        Result = A.Sum(x.b, x.c)
                    })
                    .ToList();
            })
            .Against.This("constructor", () =>
            {
                var tst = range
                    .Select(x => new A(x, x))
                    .ToList();
            })
            .For(60)
            .Seconds()
            .PrintComparison();

        Console.ReadKey();
    }
}
</code>```

Title: Calling a method inside a Linq query

Body:
I want to insert into my table a column named 'S' that will get some string value based on a value it gets from a table column.

For example: for each ID (a.z) I want to gets it's string value stored in another table. The string value is returned from another method that gets it through a Linq query.

Is it possible to call a method from Linq?

Should I do everything in the same query?

This is the structure of the information I need to get:

a.z is the ID in the first square in table #1, from this ID I get another id in table #2, and from that I can get my string value that I need to display under column 'S'.

var q = (from a in v.A join b in v.B
    on a.i equals b.j
    where a.k == "aaa" && a.h == 0
    select new {T = a.i, S = someMethod(a.z).ToString()})
    return q;

The line S = someMethod(a.z).ToString() causing the following error:

Unable to cast object of type 'System.Data.Linq.SqlClient.SqlColumn'
  to type 'System.Data.Linq.SqlClient.SqlMethodCall'.

Body:
That is an old question, but I see nobody mention one "hack", that allows to call methods during select without reiterating. Idea is to use constructor and in constructor you can call whatever you wish (at least it works fine in LINQ with NHibernate, not sure about LINQ2SQL or EF, but I guess it should be the same).
Below I have source code for benchmark program, it looks like reiterating approach in my case is about twice slower than constructor approach and I guess there's no wonder - my business logic was minimal, so things like iteration and memory allocation matters.

Also I wished there was better way to say, that this or that should not be tried to execute on database,

// Here are the results of selecting sum of 1 million ints on my machine:
// Name    Iterations      Percent
// reiterate       294     53.3575317604356%
// constructor     551     100%

public class A
{
    public A()
    {
    }

    public A(int b, int c)
    {
        Result = Sum(b, c);
    }

    public int Result { get; set; }

    public static int Sum(int source1, int source2)
    {
        return source1 + source2;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var range = Enumerable.Range(1, 1000000).ToList();

        BenchmarkIt.Benchmark.This("reiterate", () =>
            {
                var tst = range
                    .Select(x => new { b = x, c = x })
                    .AsEnumerable()
                    .Select(x => new A
                    {
                        Result = A.Sum(x.b, x.c)
                    })
                    .ToList();
            })
            .Against.This("constructor", () =>
            {
                var tst = range
                    .Select(x => new A(x, x))
                    .ToList();
            })
            .For(60)
            .Seconds()
            .PrintComparison();

        Console.ReadKey();
    }
}


问:
Popup window size in android
I'm creating a popup window in a listactivity in the event onListItemClick.

```<code>LayoutInflater inflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pop = inflater.inflate(R.layout.popupcontact, null, false);
ImageView atnot = (ImageView)pop.findViewById(R.id.aNot);
height = pop.getMeasuredHeight();
width = pop.getMeasuredWidth();
Log.e("pw","height: "+String.valueOf(height)+", width: "+String.valueOf(width));
atnot.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        pw.dismiss();
    }
});

 pw = new PopupWindow(pop, width, height, true);

 // The code below assumes that the root container has an id called 'main'
 //pw.showAtLocation(v, Gravity.CENTER, 0, 0);
 pw.showAsDropDown(v, 10, 5);
</code>```

Now, the height and width variables were supposed to be height and width of the layout used for the popup window (popupcontact). But they return 0. I guess that is because the layout isn't rendered yet. Does anyone have a clue, how can I control the size of the popup window without needing to use absolute pixel numbers?

答:
I had a similar issue. I solved it by calling:

```<code>pop.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
</code>```

before getting the size of the layout with getMeasuredHeight() and getMeasuredWidth()

ContentLicense: CC BY-SA 2.5

Title: Popup window size in android

Body:
I'm creating a popup window in a listactivity in the event onListItemClick.

LayoutInflater inflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pop = inflater.inflate(R.layout.popupcontact, null, false);
ImageView atnot = (ImageView)pop.findViewById(R.id.aNot);
height = pop.getMeasuredHeight();
width = pop.getMeasuredWidth();
Log.e("pw","height: "+String.valueOf(height)+", width: "+String.valueOf(width));
atnot.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        pw.dismiss();
    }
});

 pw = new PopupWindow(pop, width, height, true);

 // The code below assumes that the root container has an id called 'main'
 //pw.showAtLocation(v, Gravity.CENTER, 0, 0);
 pw.showAsDropDown(v, 10, 5);

Now, the height and width variables were supposed to be height and width of the layout used for the popup window (popupcontact). But they return 0. I guess that is because the layout isn't rendered yet. Does anyone have a clue, how can I control the size of the popup window without needing to use absolute pixel numbers?

Body:
I had a similar issue. I solved it by calling:

pop.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

before getting the size of the layout with getMeasuredHeight() and getMeasuredWidth()


问:
Webpack fonts semantic-ui
I can't get semantic-ui fonts to work with webpack, I still end up with a 404 not found error.

Apparently, the output path of fonts go to the root of my web server
http://localhost/build/fonts/icons.woff2

I need it to be at
http://localhost/my_projet/build/fonts/icons.woff2

答:
From what you wrote this seems to be something you can configure with webpack. I'm aware of two possible ways to do this, however it depends on your configuration which one will be good for you, or if the combination of both will solve your problem.

A) configuring the module.loaders file-loader's (or url-loader's, which is based on file-loader) name parameter to use the full path:

```<code>{
     test: /\.(woff|woff2|ttf|svg|eot)$/,
     loader: 'url-loader?name=/full/path/to/fonts/[name].[ext]'
}
</code>```

B) using output.publicPath

```<code>output: {
    filename: myProjectBundleFileName,
    publicPath: '/full/path/on/host'
},
</code>```

If you use the public path, do not include the full path for the font loader:

```<code>{
     test: /\.(woff|woff2|ttf|svg|eot)$/,
     loader: 'url-loader?name=/fonts/[name].[ext]'
}
</code>```

Title: Webpack fonts semantic-ui

Body:
From what you wrote this seems to be something you can configure with webpack. I'm aware of two possible ways to do this, however it depends on your configuration which one will be good for you, or if the combination of both will solve your problem.

A) configuring the module.loaders file-loader's (or url-loader's, which is based on file-loader) name parameter to use the full path:

{
     test: /\.(woff|woff2|ttf|svg|eot)$/,
     loader: 'url-loader?name=/full/path/to/fonts/[name].[ext]'
}

B) using output.publicPath

output: {
    filename: myProjectBundleFileName,
    publicPath: '/full/path/on/host'
},

If you use the public path, do not include the full path for the font loader:

{
     test: /\.(woff|woff2|ttf|svg|eot)$/,
     loader: 'url-loader?name=/fonts/[name].[ext]'
}


问:
Django - "Relation Does Not Exist" on Fresh Migrations
I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet!

Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way?

```<code>pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate
Traceback (most recent call last):
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
                                                             ^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm
and_line
    utility.execute()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
    self.check()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check
s
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
    for pattern in resolver.url_patterns:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Genius/urls.py", line 12, in <module>
    url(r'^', include('Inventory.urls', namespace="Inventory")),
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Inventory/urls.py", line 3, in <module>
    from Inventory import views
  File "/home/cvcexport/genius/Inventory/views.py", line 67, in <module>
    class SummaryView(InventoryView):
  File "/home/cvcexport/genius/Inventory/views.py", line 70, in SummaryView
    summary_table = build_summary_table()
  File "/home/cvcexport/genius/Inventory/views.py", line 62, in build_summary_table
    table_query = Purchase.inventory.current_summary_data(**kwargs)
  File "/home/cvcexport/genius/Inventory/managers.py", line 31, in current_summary_data
    for item in totals:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
    self._fetch_all()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 109, in __iter__
    for row in compiler.results_iter():
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 789, in results_iter
    results = self.execute_sql(MULTI)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
</code>```

My files are kinda bulky, but this is the Manager that is tripping it up:

```<code>class EntryManager(Manager):

    def user_create(self, request):
        type = request.POST.get('type', None)
        label = request.POST.get('label', None)
        details = request.POST.get('details', None)
        date_added = date.today()
        sequence = 1 + self.model.objects.filter(type=type, active=True).count()
        label = type + str(sequence) + "- " + label

        entry = self.model.objects.create(
            type=type,
            label=label,
            details=details,
            date_added=date_added,
            sequence=sequence,
            user=request.user
        )

        return entry

    def user_update(self, request, pk):
        entry = self.model.objects.get(id=pk)
        entry.label = entry.type + str(entry.sequence) + "- " + request.POST.get("label")
        entry.details = request.POST.get("details")
        entry.user = request.user

        entry.save()

        return entry

    def user_delete(self, pk):
        entry = self.model.objects.get(id=pk)

        successors = self.model.objects.filter(type=entry.type, active=True, sequence__gt=entry.sequence)
        for obj in successors:
            obj.sequence -= 1
            obj.label = obj.label.split(" ", 1)[1]
            obj.label = obj.type + str(obj.sequence) + "- " + obj.label
            obj.save()

        key = entry.id
        entry.delete()
        return key

    def get_entry_set(self, request):
        """
        Builds selection lists allowing users to link SWOT entries to strategies. Used in swot-matrix.js with
        setStratEntries method.

        Args:
            Request Delivers two relevant variables:
                s_or_w: Indicates "Y-axis" (strength or weakness) requirement.
                o_or_t: Indicates "X-axis" (opportunity or threat) requirement.

        Returns:
            All active entries that match each requested type, packaged in dictionaries and ready for JSON delivery.
        """

        # Build Dictionary of active Strengths or Weaknesses
        s_or_w = request.GET.get("s_or_w")
        strengths_or_weaknesses = self.model.objects.filter(type=s_or_w, active=True)
        s_or_w_data = []
        for entry in strengths_or_weaknesses:
            s_or_w_data.append({
                "id": entry.id,
                "label": entry.label
            })

        # Build Dictionary of active Opportunities or Threats
        o_or_t = request.GET.get("o_or_t")
        opportunities_or_threats = self.model.objects.filter(type=o_or_t, active=True)
        o_or_t_data = []
        for entry in opportunities_or_threats:
            o_or_t_data.append({
                "id": entry.id,
                "label": entry.label,
            })

        # Combine for for JSON delivery.
        data = {
            "s_or_w": s_or_w_data,
            "o_or_t": o_or_t_data
        }

        return data
</code>```

This is the associated model:

```<code>class Entry(GenericObject):
    type = models.CharField(max_length=1, choices=choices.ENTRY_CHOICES)
    sequence = models.IntegerField()
    label = models.CharField(max_length=124)
    actions = managers.EntryManager()
    objects = models.Manager()

    class Meta:
        ordering = ["id"]
</code>```

Am I breaking the rules somewhere? Why is migrate.py complaining about missing columns on a brand new postgres database?

答: I never figured out what was wrong. The error would trip at different points in my managers here and there, but would always be triggered first in the views. I simply commented out all of the views and urlpatterns, ran the migrations and then reverted the files.</p>

Body:
I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet!

Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way?

pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate
Traceback (most recent call last):
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
                                                             ^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm
and_line
    utility.execute()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
    self.check()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check
s
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
    for pattern in resolver.url_patterns:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Genius/urls.py", line 12, in <module>
    url(r'^', include('Inventory.urls', namespace="Inventory")),
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Inventory/urls.py", line 3, in <module>
    from Inventory import views
  File "/home/cvcexport/genius/Inventory/views.py", line 67, in <module>
    class SummaryView(InventoryView):
  File "/home/cvcexport/genius/Inventory/views.py", line 70, in SummaryView
    summary_table = build_summary_table()
  File "/home/cvcexport/genius/Inventory/views.py", line 62, in build_summary_table
    table_query = Purchase.inventory.current_summary_data(**kwargs)
  File "/home/cvcexport/genius/Inventory/managers.py", line 31, in current_summary_data
    for item in totals:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
    self._fetch_all()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 109, in __iter__
    for row in compiler.results_iter():
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 789, in results_iter
    results = self.execute_sql(MULTI)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...

My files are kinda bulky, but this is the Manager that is tripping it up:

class EntryManager(Manager):

    def user_create(self, request):
        type = request.POST.get('type', None)
        label = request.POST.get('label', None)
        details = request.POST.get('details', None)
        date_added = date.today()
        sequence = 1 + self.model.objects.filter(type=type, active=True).count()
        label = type + str(sequence) + "- " + label

        entry = self.model.objects.create(
            type=type,
            label=label,
            details=details,
            date_added=date_added,
            sequence=sequence,
            user=request.user
        )

        return entry

    def user_update(self, request, pk):
        entry = self.model.objects.get(id=pk)
        entry.label = entry.type + str(entry.sequence) + "- " + request.POST.get("label")
        entry.details = request.POST.get("details")
        entry.user = request.user

        entry.save()

        return entry

    def user_delete(self, pk):
        entry = self.model.objects.get(id=pk)

        successors = self.model.objects.filter(type=entry.type, active=True, sequence__gt=entry.sequence)
        for obj in successors:
            obj.sequence -= 1
            obj.label = obj.label.split(" ", 1)[1]
            obj.label = obj.type + str(obj.sequence) + "- " + obj.label
            obj.save()

        key = entry.id
        entry.delete()
        return key

    def get_entry_set(self, request):
        """
        Builds selection lists allowing users to link SWOT entries to strategies. Used in swot-matrix.js with
        setStratEntries method.

        Args:
            Request Delivers two relevant variables:
                s_or_w: Indicates "Y-axis" (strength or weakness) requirement.
                o_or_t: Indicates "X-axis" (opportunity or threat) requirement.

        Returns:
            All active entries that match each requested type, packaged in dictionaries and ready for JSON delivery.
        """

        # Build Dictionary of active Strengths or Weaknesses
        s_or_w = request.GET.get("s_or_w")
        strengths_or_weaknesses = self.model.objects.filter(type=s_or_w, active=True)
        s_or_w_data = []
        for entry in strengths_or_weaknesses:
            s_or_w_data.append({
                "id": entry.id,
                "label": entry.label
            })

        # Build Dictionary of active Opportunities or Threats
        o_or_t = request.GET.get("o_or_t")
        opportunities_or_threats = self.model.objects.filter(type=o_or_t, active=True)
        o_or_t_data = []
        for entry in opportunities_or_threats:
            o_or_t_data.append({
                "id": entry.id,
                "label": entry.label,
            })

        # Combine for for JSON delivery.
        data = {
            "s_or_w": s_or_w_data,
            "o_or_t": o_or_t_data
        }

        return data

This is the associated model:

class Entry(GenericObject):
    type = models.CharField(max_length=1, choices=choices.ENTRY_CHOICES)
    sequence = models.IntegerField()
    label = models.CharField(max_length=124)
    actions = managers.EntryManager()
    objects = models.Manager()

    class Meta:
        ordering = ["id"]

Am I breaking the rules somewhere? Why is migrate.py complaining about missing columns on a brand new postgres database?


问:
Developer console's CSS Selector returns wrong results
Using Firefox's or Chrome's developer console, When I type $('a'), It should return all the links on the page in an array (If I select the wrong frame it won't for example, but that is not the problem now). Please someone enlighten me, why do I get single a result using this CSS selector with both Firefox and Chrome on some sites and an array of a's on others (both sites have more than one a tags)?

This worked before, I don't remember it ever not working like this. For reference let's take http://www.useragentstring.com/pages/useragentstring.php

My Firefox console result:

Chrome:

If I do this on stackoverflow, the CSS Selector works too. The Xpath works on every site.

答:
From the Chrome dev tools documentation:

$(selector) returns the reference to the first DOM element with the specified CSS selector. This function is an alias for the document.querySelector() function.

So you get the expected behaviour on useragentstring.com.

On Stackoverflow you get different behaviour because jQuery has been included on the page and the $ variable has been overwritten by the jQuery object which (when called as a function):

Accepts a string containing a CSS selector which is then used to match a set of elements.


问:
Cannot read property 'location' of undefined in React Router example
Trying to do the most simple example possible with React Router.
Every example I've looked at is very different and many include 20 page tutorials. I just want a simple root path to work:

```<code>...
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://npmcdn.com/react-router/umd/react-router.min.js"></script>
...

var insert_point = document.querySelector('#container');

var App = React.createClass({
  render: function() {
    return (
      <div>
        <h1>Simple SPA</h1>
        <ul>
          <li>Home</li>
          <li>Stuff</li>
          <li>Contact</li>
        </ul>
        <div>
        </div>
      </div>
    )
  }
});

ReactDOM.render(
  <ReactRouter.Router>
    <ReactRouter.Route path="/" component={App}>
    </ReactRouter.Route>
  </ReactRouter.Router>,
  insert_point
);
</code>```

答:
Since you're in the browser, you'll need react-router-dom too, a separate package in v4. react-router only contains the core, but for the DOM bindings you need the former package:

```<code><script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
</code>```

Then, get what you need from the global ReactRouterDOM. I find it easier just to use destructuring assignment to get what you need:

```<code>var { BrowserRouter, Route } = ReactRouterDOM;
</code>```

Then you can do:

```<code><BrowserRouter>
  <Route exact path="/" component={App} />
</BrowserRouter>
</code>```

The problem was that you weren't using the correct router -- for the web use BrowserRouter. Then, use Route and make sure to include the exact prop to only match the root route, in this case you can make Route self closing.

Body:
Trying to do the most simple example possible with React Router.
Every example I've looked at is very different and many include 20 page tutorials. I just want a simple root path to work:

...

...

var insert_point = document.querySelector('#container');

var App = React.createClass({
  render: function() {
    return (

Simple SPA

Home

Stuff

Contact

    )
  }
});

ReactDOM.render(
  <ReactRouter.Router>
    <ReactRouter.Route path="/" component={App}>
    </ReactRouter.Route>
  </ReactRouter.Router>,
  insert_point
);

Body:
Since you're in the browser, you'll need react-router-dom too, a separate package in v4. react-router only contains the core, but for the DOM bindings you need the former package:

<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>

Then, get what you need from the global ReactRouterDOM. I find it easier just to use destructuring assignment to get what you need:

var { BrowserRouter, Route } = ReactRouterDOM;

Then you can do:

<BrowserRouter>
  <Route exact path="/" component={App} />
</BrowserRouter>

The problem was that you weren't using the correct router -- for the web use BrowserRouter. Then, use Route and make sure to include the exact prop to only match the root route, in this case you can make Route self closing.


问:
How to retian state in spotfire custom view
I have an winforms application developed inside SpotFire. I have registered the view as below.

registrar.Register(typeof(Control), typeof(CustomVisual), typeof(WinformUI));

But when I switch between pages inside SpotFire client, whole of winforms screen gets refreshed and redrawn.

This causes error. How do we retain the view state in winforms UI.

答:
Default behaviour of SpotFire visualization Add-On and other Visualization tools is it will be re-drawn and refresh on page switch.

In this case we have developed a visualization in c# winforms, on page switch SpotFire disposes all the resources related to Add-On which caused error on redraw/refresh on returning to application after page switch.

To retain the state and to avoid errors we implemented SpotFire properties such as Document Nodes, Undoable nodes instead of normal property classes to retain the state on page switch. Below link explains how to implement/extend the SpotFire Documents.

https://community.tibco.com/wiki/extending-document-using-tibco-spotfirer-document-model-framework-api.


问:
Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark
```<code>#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int x, i=2, k=1;

    for (x=15; x%i ? ++i : ++k, 1<x ; x-- , i++)
    {
        x -= k+i;
        i++;
        printf("X = %d , I = %d , K = %d\n",x,i,k);
    }
    switch(x) {
        case 2: printf("Display 2.\n");
        case 5: printf("Display 5.\n");
        case 0: printf("Display 0.\n");
                break;
        default:
            printf("Display default\n");
    }
system("pause");
    return 0;
}
</code>```

Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark

答:
```<code>if (1 == 1){
  they are equal;
} else {
  they are not equal
}

1 == 1 ? they are equal : they are not equal
</code>```

Two examples are same. It's pseudo code. :)

If condition is true, do left side, else do right side.

In your example author put condition in for loop, but logic is the same.

You can read more, here

Body:
#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int x, i=2, k=1;

    for (x=15; x%i ? ++i : ++k, 1<x ; x-- , i++)
    {
        x -= k+i;
        i++;
        printf("X = %d , I = %d , K = %d\n",x,i,k);
    }
    switch(x) {
        case 2: printf("Display 2.\n");
        case 5: printf("Display 5.\n");
        case 0: printf("Display 0.\n");
                break;
        default:
            printf("Display default\n");
    }
system("pause");
    return 0;
}

Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark

Body:
if (1 == 1){
  they are equal;
} else {
  they are not equal
}

1 == 1 ? they are equal : they are not equal

Two examples are same. It's pseudo code. :)

If condition is true, do left side, else do right side.

In your example author put condition in for loop, but logic is the same.

You can read more, here

ContentLicense: CC BY-SA 4.0


问:
Internet explorer testing
Does anyone know any tools I can use to view my site in different browsers for styling purposes?</p>

答:
Expression Web SuperPreview

IETester

BrowserShots

Title: Internet explorer testing


问:
PrimeNg p-dropdown module does not expand
I have a problem with p-dropdown module in Primeng and Angular 4.

I have filled options with values from loop:

```<code>for(let i = 1; i <= 20; i++) {
            this.iterations = [... this.iterations, { label: i, value: i}]
        }
</code>```

and I am trying to use it in my template:

```<code><p-dropdown [options]="iterations"></p-dropdown>
</code>```

The problem is that dropdown displays first value only (in this case '1'). When I check 'iterations' array or set iterations array statically the problem persists.
I think I included module correctly in my module. Does DropdownModule depend from any other modules?

```<code>import {DropdownModule} from 'primeng/primeng'
</code>```

//edit
I found that it can be something with module html part. Look at image below

Regards

答:
You must import SelectItem in the component

```<code>import {SelectItem} from 'primeng/primeng'
</code>```

and the  objects must to implement this interface

```<code><p-dropdown [options]="iterations"></p-dropdown>
</code>```

where iterations is the array of SelectItem

```<code>iterations: SelectItem[];
</code>```

It is the component

```<code>iterations: SelectItem[];

selectedIteration: string;

ngOnInit() {
    this.iterations = [];
    for(let i = 1; i <= 20; i++) {
        this.iterations.push({ label: i.toString(), value: i.toString() });
    }
}
</code>```

Body:
I have a problem with p-dropdown module in Primeng and Angular 4.

I have filled options with values from loop:

for(let i = 1; i <= 20; i++) {
            this.iterations = [... this.iterations, { label: i, value: i}]
        }

and I am trying to use it in my template:

The problem is that dropdown displays first value only (in this case '1'). When I check 'iterations' array or set iterations array statically the problem persists.
I think I included module correctly in my module. Does DropdownModule depend from any other modules?

import {DropdownModule} from 'primeng/primeng'

//edit
I found that it can be something with module html part. Look at image below

Regards

Body:
You must import SelectItem in the component

import {SelectItem} from 'primeng/primeng'

and the  objects must to implement this interface

<p-dropdown [options]="iterations"></p-dropdown>

where iterations is the array of SelectItem

iterations: SelectItem[];

It is the component

iterations: SelectItem[];

selectedIteration: string;

ngOnInit() {
    this.iterations = [];
    for(let i = 1; i <= 20; i++) {
        this.iterations.push({ label: i.toString(), value: i.toString() });
    }
}


问:
ProvisionException: Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument
I am using Guice in PlayFramework but I am getting runtime error:

```<code>Caused by: com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Could not find a suitable constructor in controllers.DirectUserController. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at controllers.DirectUserController.class(DirectUserController.scala:90)
  while locating com.google.inject.Provider<controllers.DirectUserController>
    for parameter 7 at router.Routes.<init>(Routes.scala:124)
  while locating router.Routes
  while locating play.api.inject.RoutesProvider
  while locating play.api.routing.Router

1 error
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025) ~[guice-4.0.jar:na]
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051) ~[guice-4.0.jar:na]
    at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:321) ~[play_2.11-2.4.3.jar:2.4.3]
    at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:316) ~[play_2.11-2.4.3.jar:2.4.3]
    at play.api.Application$class.routes(Application.scala:111) ~[play_2.11-2.4.3.jar:2.4.3]
</code>```

Here is the code:

```<code>trait FactoryHandlerTrait {
  def getDirectUserFactory: DirectUserFactory

  def getUserRepository: UserRepository

  def getUrlRepository: URLRepository
}

class FactoryHandler(var s: String = "real") extends FactoryHandlerTrait {
  def getDirectUserFactory: DirectUserFactory = {
    //implementation here
  }

  def getUserRepository: UserRepository = {
    //implementation here
  }

  def getUrlRepository: URLRepository = {
    //implementation here
  }
}

class DependencyModule extends Module {

  def configure(binder: Binder) = {
    binder.bind(classOf[FactoryHandlerTrait]).to(classOf[FactoryHandler])
  }
}
</code>```

And here is my Controller:

```<code>class DirectUserController(var factory:FactoryHandlerTrait) extends Controller {
  //rest of the code
}
</code>```

In build.sbt I have added:

```<code>routesGenerator := InjectedRoutesGenerator
</code>```

What am I missing or doing wrong? How to avoid that exception?

I am using Play 2.4.3 and Guice 3.0.

答:
As guice says, either the constructor must have zero arguments or you need to annotate it with @Inject. Neither of these requirements is satisfied for your class FactoryHandler.

When resolving this, you might want to think about whether the parameter s is actually an argument that could be injected by guice (probably not). Therefore, you need to pass that in somehow else. If it's only available at runtime, you might want to take a look at assisted inject. I have described how this works in a previous answer: https://stackoverflow.com/a/35960962/1080523

Body:
I am using Guice in PlayFramework but I am getting runtime error:

Caused by: com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Could not find a suitable constructor in controllers.DirectUserController. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at controllers.DirectUserController.class(DirectUserController.scala:90)
  while locating com.google.inject.Provider<controllers.DirectUserController>
    for parameter 7 at router.Routes.<init>(Routes.scala:124)
  while locating router.Routes
  while locating play.api.inject.RoutesProvider
  while locating play.api.routing.Router

1 error
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025) ~[guice-4.0.jar:na]
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051) ~[guice-4.0.jar:na]
    at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:321) ~[play_2.11-2.4.3.jar:2.4.3]
    at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:316) ~[play_2.11-2.4.3.jar:2.4.3]
    at play.api.Application$class.routes(Application.scala:111) ~[play_2.11-2.4.3.jar:2.4.3]

Here is the code:

trait FactoryHandlerTrait {
  def getDirectUserFactory: DirectUserFactory

  def getUserRepository: UserRepository

  def getUrlRepository: URLRepository
}

class FactoryHandler(var s: String = "real") extends FactoryHandlerTrait {
  def getDirectUserFactory: DirectUserFactory = {
    //implementation here
  }

  def getUserRepository: UserRepository = {
    //implementation here
  }

  def getUrlRepository: URLRepository = {
    //implementation here
  }
}

class DependencyModule extends Module {

  def configure(binder: Binder) = {
    binder.bind(classOf[FactoryHandlerTrait]).to(classOf[FactoryHandler])
  }
}

And here is my Controller:

class DirectUserController(var factory:FactoryHandlerTrait) extends Controller {
  //rest of the code
}

In build.sbt I have added:

routesGenerator := InjectedRoutesGenerator

What am I missing or doing wrong? How to avoid that exception?

I am using Play 2.4.3 and Guice 3.0.


问:
AppKernel.php strange thing
Im trying to set up new project in Symfony. When I added my own Bundle I have this strange thing appear:

PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "ContactBoxBundle" from namespace "ContactBoxBundle".
  Did you forget a "use" statement for another namespace? in /home/doro/projects/ContactBox/app/AppKernel.php:18
  Stack trace:

0 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(450): AppKernel->registerBundles()

1 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(116): Symfony\Component\HttpKernel\Kernel->initializeBundles()

2 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(137): Symfony\Component\HttpKernel\Kernel->boot()

3 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(124): Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()

4 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Component/Console/Applicati in /home/doro/projects/ContactBox/app/AppKernel.php on line 18

My AppKernel looks like that:

```<code>    <?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new ContactBoxBundle\ContactBoxBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

            if ('dev' === $this->getEnvironment()) {
                $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
                $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
            }
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}
</code>```

And I seriously have no idea what is going on, its first time when its happend to me and I made new projects before in Symfony. Any ideas?

composer.json

```<code>{
    "name": "doro/contactbox",
    "license": "proprietary",
    "type": "project",
    "autoload": {
        "psr-4": {
            "": "src/"
        },
        "classmap": [
            "app/AppKernel.php",
            "app/AppCache.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
        ]
    },
    "require": {
        "php": ">=5.5.9",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0",
        "symfony/phpunit-bridge": "^3.0"
    },
    "scripts": {
        "symfony-scripts": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
        ],
        "post-install-cmd": [
            "@symfony-scripts"
        ],
        "post-update-cmd": [
            "@symfony-scripts"
        ]
    },
    "config": {
        "sort-packages": true
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-bin-dir": "bin",
        "symfony-var-dir": "var",
        "symfony-web-dir": "web",
        "symfony-tests-dir": "tests",
        "symfony-assets-install": "relative",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": null
    }
}
</code>```

答:
What is the namespace of your bundle in the file : ContactBoxBundle/ContactBoxBundle.php ?
Refering here, the bundle name AcmeTestBundle  is in the namespace namespace Acme\TestBundle; then the appKernel is new Acme\TestBundle\AcmeTestBundle(),.

Maybe that's your problem.

Title: AppKernel.php strange thing

Body:
Im trying to set up new project in Symfony. When I added my own Bundle I have this strange thing appear:

PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "ContactBoxBundle" from namespace "ContactBoxBundle".
  Did you forget a "use" statement for another namespace? in /home/doro/projects/ContactBox/app/AppKernel.php:18
  Stack trace:

0 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(450): AppKernel->registerBundles()

1 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(116): Symfony\Component\HttpKernel\Kernel->initializeBundles()

2 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(137): Symfony\Component\HttpKernel\Kernel->boot()

3 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(124): Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()

4 /home/doro/projects/ContactBox/vendor/symfony/symfony/src/Symfony/Component/Console/Applicati in /home/doro/projects/ContactBox/app/AppKernel.php on line 18

My AppKernel looks like that:

    <?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new ContactBoxBundle\ContactBoxBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

            if ('dev' === $this->getEnvironment()) {
                $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
                $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
            }
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}

And I seriously have no idea what is going on, its first time when its happend to me and I made new projects before in Symfony. Any ideas?

composer.json

{
    "name": "doro/contactbox",
    "license": "proprietary",
    "type": "project",
    "autoload": {
        "psr-4": {
            "": "src/"
        },
        "classmap": [
            "app/AppKernel.php",
            "app/AppCache.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
        ]
    },
    "require": {
        "php": ">=5.5.9",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0",
        "symfony/phpunit-bridge": "^3.0"
    },
    "scripts": {
        "symfony-scripts": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
        ],
        "post-install-cmd": [
            "@symfony-scripts"
        ],
        "post-update-cmd": [
            "@symfony-scripts"
        ]
    },
    "config": {
        "sort-packages": true
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-bin-dir": "bin",
        "symfony-var-dir": "var",
        "symfony-web-dir": "web",
        "symfony-tests-dir": "tests",
        "symfony-assets-install": "relative",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": null
    }
}


问:
IntegrityError: Not Null constraint failed
I have deleted a class from model.py but whenever I run python manage.py migrate, I get this:

intergrityerror : not null constraint failed: appname_modelclassfieldname.user_id

The most challenging thing is that I had already deleted the model class of the related field django is pointing error at.

答:
You have to create a migration before running migrate. As you have not specified your Django version, here is what you need to do for the most recent version (1.11) which also works down to at least 1.9:

```<code>$ ./manage.py makemigrations # > creates a migration file
$ ./manage.py migrate
</code>```

You can specify the the app in the makemigrations call if you want.

Concerning:

The most challenging thing is that i had already deleted the model class of the related field django is pointing error at .

Use a version system for your own health (e.g. GIT) or an editor that supports local versioning (like PyCharm) - best use both - even if you are working alone. (You are never alone, after some weeks, the code looks like it was written by someone else...)

Body:
You have to create a migration before running migrate. As you have not specified your Django version, here is what you need to do for the most recent version (1.11) which also works down to at least 1.9:

$ ./manage.py makemigrations # > creates a migration file
$ ./manage.py migrate

You can specify the the app in the makemigrations call if you want.

Concerning:

The most challenging thing is that i had already deleted the model class of the related field django is pointing error at .

Use a version system for your own health (e.g. GIT) or an editor that supports local versioning (like PyCharm) - best use both - even if you are working alone. (You are never alone, after some weeks, the code looks like it was written by someone else...)


问:
How to use the methods of the parent class?
Here the SMS_Store inherits the Message, but every time I call the parent method there is the error:

NoneType object does not have attribute 'read_message'.

and also the object stored in the list returns a None value??

```<code>class Message():

    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed=False
        self.from_number= from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def getTime(self):
        return self.time_arrived

    def getText(self):
        return self.text_of_sms

    def setView(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMS_Store(Message):

    def __init__(self):
        self.list_=[]

    def add_new_arrivals(self,from_number, time_arrived, text_of_sms):
        self.list_.append(Message.__init__(self,from_number,time_arrived,text_of_sms))

    def message_count(self):
        return len(self.list_)

    def get_unread_index(self):
        unread =[]
        for i in range(len(self.list_)):
            if(super(SMS_Store,self).check_read() == False):
                unread.append(i)
        return unread

    def read_message(self,index):
        self.list_[index].getText()

    def delete(self,ints):
        a = int(ints)
        self.list_.pop(a)

    def clear():
        for i in list:
            self.list_.pop(i)

inbox = SMS_Store()
inbox.add_new_arrivals(12,9,'some nights i stay up')
inbox.add_new_arrivals(12,5,'cashing in my bad luck')
inbox.add_new_arrivals(14,7,'somenights i call it a draw')
inbox.add_new_arrivals(56,0,'somenights i wish that my lips could built a castle.')
inbox.read_message(0)
</code>```

答:
It's unclear where that error could be coming from since read_message() is only called by the inbox.read_message(0) statement at the end of your code, which wouldn't produce it (although the return value of the read_message() method is always None, since there's no explicit return statement in it).

Regardless, to answer the titular question, to do that explicitly you would use the super() method—but that's not the problem here which is that the SMS_Store class shouldn't be a subclass of Message at all, since it's not a specialization of the Message class...rather it's a container of Message instances.

Below is reworked version of your code that shows how to separate these two classes and get most if not all of the methods working. It also now mostly follows PEP 8 - Style Guide for Python Code recommendations.

```<code>class Message:
    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed = False
        self.from_number = from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def get_time(self):
        return self.time_arrived

    def get_text(self):
        return self.text_of_sms

    def set_viewed(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMS_Store:
    def __init__(self):
        self.list_ = []

    def add_new_arrival(self, from_number, time_arrived, text_of_sms):
        self.list_.append(Message(from_number, time_arrived, text_of_sms))

    def message_count(self):
        return len(self.list_)

    def get_unread_index(self):
        unread = []
        for (i, message) in enumerate(self.list_):
            if not message.check_read():
                unread.append(i)
        return unread

    def read_message(self, index):
        message_text = self.list_[index].get_text()
        self.list_[index].set_viewed()
        return message_text

    def delete(self, index):
        self.list_.pop(index)

    def clear():
        self.list_.clear()

inbox = SMS_Store()

inbox.add_new_arrival(12, 9, 'some nights i stay up')
inbox.add_new_arrival(12, 5, 'cashing in my bad luck')
inbox.add_new_arrival(14, 7, 'somenights i call it a draw')
inbox.add_new_arrival(56, 0, 'somenights i wish that my lips could built a castle.')

print(inbox.get_unread_index())  # -> [0, 1, 2, 3]
print(inbox.read_message(0))     # -> some nights i stay up
print(inbox.get_unread_index())  # -> [1, 2, 3]
</code>```

Body:
Here the SMS_Store inherits the Message, but every time I call the parent method there is the error:

NoneType object does not have attribute 'read_message'.

and also the object stored in the list returns a None value??

class Message():

    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed=False
        self.from_number= from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def getTime(self):
        return self.time_arrived

    def getText(self):
        return self.text_of_sms

    def setView(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMS_Store(Message):

    def __init__(self):
        self.list_=[]

    def add_new_arrivals(self,from_number, time_arrived, text_of_sms):
        self.list_.append(Message.__init__(self,from_number,time_arrived,text_of_sms))

    def message_count(self):
        return len(self.list_)

    def get_unread_index(self):
        unread =[]
        for i in range(len(self.list_)):
            if(super(SMS_Store,self).check_read() == False):
                unread.append(i)
        return unread

    def read_message(self,index):
        self.list_[index].getText()

    def delete(self,ints):
        a = int(ints)
        self.list_.pop(a)

    def clear():
        for i in list:
            self.list_.pop(i)

inbox = SMS_Store()
inbox.add_new_arrivals(12,9,'some nights i stay up')
inbox.add_new_arrivals(12,5,'cashing in my bad luck')
inbox.add_new_arrivals(14,7,'somenights i call it a draw')
inbox.add_new_arrivals(56,0,'somenights i wish that my lips could built a castle.')
inbox.read_message(0)

Body:
It's unclear where that error could be coming from since read_message() is only called by the inbox.read_message(0) statement at the end of your code, which wouldn't produce it (although the return value of the read_message() method is always None, since there's no explicit return statement in it).

Regardless, to answer the titular question, to do that explicitly you would use the super() method—but that's not the problem here which is that the SMS_Store class shouldn't be a subclass of Message at all, since it's not a specialization of the Message class...rather it's a container of Message instances.

Below is reworked version of your code that shows how to separate these two classes and get most if not all of the methods working. It also now mostly follows PEP 8 - Style Guide for Python Code recommendations.

class Message:
    def __init__(self, from_number, time_arrived, text_of_sms):
        self.has_been_viewed = False
        self.from_number = from_number
        self.time_arrived = time_arrived
        self.text_of_sms = text_of_sms

    def get_time(self):
        return self.time_arrived

    def get_text(self):
        return self.text_of_sms

    def set_viewed(self):
        self.has_been_viewed = True

    def check_read(self):
        return self.has_been_viewed

class SMS_Store:
    def __init__(self):
        self.list_ = []

    def add_new_arrival(self, from_number, time_arrived, text_of_sms):
        self.list_.append(Message(from_number, time_arrived, text_of_sms))

    def message_count(self):
        return len(self.list_)

    def get_unread_index(self):
        unread = []
        for (i, message) in enumerate(self.list_):
            if not message.check_read():
                unread.append(i)
        return unread

    def read_message(self, index):
        message_text = self.list_[index].get_text()
        self.list_[index].set_viewed()
        return message_text

    def delete(self, index):
        self.list_.pop(index)

    def clear():
        self.list_.clear()

inbox = SMS_Store()

inbox.add_new_arrival(12, 9, 'some nights i stay up')
inbox.add_new_arrival(12, 5, 'cashing in my bad luck')
inbox.add_new_arrival(14, 7, 'somenights i call it a draw')
inbox.add_new_arrival(56, 0, 'somenights i wish that my lips could built a castle.')

print(inbox.get_unread_index())  # -> [0, 1, 2, 3]
print(inbox.read_message(0))     # -> some nights i stay up
print(inbox.get_unread_index())  # -> [1, 2, 3]


问:
Angular2 / Jasmine: Spy on unit testing methods doesn't see called method
I've got a problem with detecting spy have called an function. It's a unit test of service.
I've tried two different approaches with TestBed.get on method (in ' it should check only status') and spy on injected dummy class  ("in it should login unknown to facebook"), but neither of them doesnt seem to work
I've done some print to see if method is used, and there are shown.
Here's a spec file:

```<code>import { TestBed, inject, async } from '@angular/core/testing';

import {FacebookServiceMock } from './../test-helpers/facebook-service-mock';
import { SocialsServiceDummy } from './../test-helpers/socialsServiceDummy';
import { ErrorDouble } from './../test-helpers/errorDouble';

import { ErrorsService } from './../../app/services/errors.service';
import { social_config, SocialConfig, SOCIAL_CONFIG } from './../../app/socials/social-config';
import { SocialsService } from './../../app/services/socials.service';
import { FacebookLoginService } from './../../app/services/facebook-login.service';
import { FacebookService } from 'ngx-facebook';

describe('Facebook-login-service test', () => {
    let socialsServiceSpy: any;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [
                FacebookLoginService,
                { provide: FacebookService, useFactory: () => { return new FacebookServiceMock() }},
                { provide: SocialsService, useFactory: () => {  return new SocialsServiceDummy() }},
                { provide: ErrorsService, useFactory: () => { return new ErrorDouble() } },
                { provide: social_config, useValue: SOCIAL_CONFIG }
            ]
        });

    });

    beforeEach(() => {
        socialsServiceSpy = TestBed.get(SocialsService);
        spyOn(socialsServiceSpy, 'updateAccount');

    });

    afterEach(()=>{
        TestBed.resetTestingModule();

    });

    it('should login unknown to facebook',
        async(inject([FacebookLoginService, FacebookService, SocialsService, ErrorsService, social_config], (facebookLoginService, FacebookServiceMock, SocialsServiceDummy, ErrorDouble, SOCIAL_CONFIG) => {
                let mockReturn = {
                    status: "unknown",
                    authResponse: {
                        userID: '123456',
                        accessToken: 'token',
                        expiresIn: 3600
                    }
                };

                spyOn(FacebookServiceMock, 'getLoginStatus').and.returnValue(Promise.resolve(mockReturn));
                spyOn(SocialsServiceDummy, 'addNewSocialAccount').and.callThrough();
                spyOn(facebookLoginService, 'loginToFacebook').and.callThrough();

                facebookLoginService.checkLoginStatus();
                expect(facebookLoginService.loginToFacebook).toHaveBeenCalled();
                expect(SocialsServiceDummy.addNewSocialAccount).toHaveBeenCalledWith('facebook', mockReturn.authResponse.userID, mockReturn.authResponse.accessToken, mockReturn.authResponse.expiresIn);
            })
        ));

    it('should check only status',
        async(inject([FacebookLoginService, FacebookService, SocialsService, ErrorsService, social_config], (facebookLoginService, FacebookServiceMock, SocialsServiceDummy, ErrorDouble, SOCIAL_CONFIG) => {
                let mockReturn = {
                    status: "connected",
                    authResponse: {
                        userID: '123456',
                        accessToken: 'token',
                        expiresIn: 3600
                    }
                };
                spyOn(FacebookServiceMock, 'getLoginStatus').and.returnValue(Promise.resolve(mockReturn));
               // spyOn(SocialsServiceDummy, 'updateAccount').and.callThrough();

                facebookLoginService.checkLoginStatus();
                expect(socialsServiceSpy.updateAccount).toHaveBeenCalledWith('facebook', mockReturn.authResponse.userID, mockReturn.authResponse.accessToken, mockReturn.authResponse.expiresIn);

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

The FacebookLoginService looks like this:

```<code>/**
 * Created by Daniel on 2017-06-19.
 */
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { FacebookService, LoginResponse, LoginOptions } from 'ngx-facebook';
import { ErrorsService } from './errors.service';
import { social_config, SocialConfig } from './../socials/social-config';
import { NewSocialAccount } from './../shared/models/new-social-account';
import { SocialsService } from "./socials.service";

@Injectable()

export class FacebookLoginService {
    private loginOptions : LoginOptions = {
        scope: this.socialConfig.facebook.scope
    }

    private attemptToLogin =  new Subject<boolean>()
    private newSocialAccount =  new Subject<any>();

    login$ = this.attemptToLogin.asObservable();
    newSocial$ = this.newSocialAccount.asObservable();

    constructor(
        private facebookService: FacebookService,
        private socialsService: SocialsService,
        private errorsService: ErrorsService,
        @Inject(social_config) private socialConfig: SocialConfig
    ) {}

    initSocials() : void {
        this.facebookService.init({appId: this.socialConfig.facebook.appId, version: this.socialConfig.facebook.version});
    }

    checkLoginStatus() : void{
        this.facebookService.getLoginStatus().then(
            (res) => {
                if(res.status == "connected") {
                    const updatedAccount = this.createNewAccountObject('facebook', res.authResponse.userID, res.authResponse.accessToken, res.authResponse.expiresIn);
                    this.socialsService.updateAccount(updatedAccount).then(
                        () => {
                            this.attemptToLogin.next(true);
                        },
                        error => {
                            this.errorsService.startErrorAction(error);
                        }
                    )
                } else {
                   this.loginToFacebook();
                }
            },
            error => {
                alert('Unable to connect with Facebook. Please try later');
            }
        )
    }

    loginToFacebook() : void {
        this.facebookService.login(this.loginOptions).then(
            (res: LoginResponse) => {
                const newAccount = this.createNewAccountObject('facebook', res.authResponse.userID, res.authResponse.accessToken, res.authResponse.expiresIn);
                this.socialsService.addNewSocialAccount(newAccount).then(
                    (res) => {
                        this.confirmLoginNewSocialAccount(res, 'facebook');
                    },
                    error => {
                        this.errorsService.startErrorAction(error);
                    }
                )
            },
            error => {
                alert('Unable to connect with Facebook. Please try later');
            }
        )

    }

    logout(): void {
        this.facebookService.logout();
    }

    private createNewAccountObject(socialStr: string, userStr: string, tokenStr: string, expiresNr: number): NewSocialAccount {
            return {
                social: socialStr,
                userID: userStr,
                token: tokenStr,
                expires:  expiresNr
            };
        }

    private confirmLoginNewSocialAccount(response: any, accountType: string) {
        this.newSocialAccount.next({login: response.login, social: accountType});

    }
}
</code>```

Here is dummy file from injected social service

```<code>import { SocialAccount} from './../../app/shared/models/social-account';
import { NewSocialAccount} from './../../app/shared/models/new-social-account';

export class SocialsServiceDummy {

    getSocials(): Promise<SocialAccount[]> {
      let socials =  [

      ];
      return Promise.resolve(socials);
    }

    addNewSocialAccount(newAccount: NewSocialAccount) : Promise<any>{
      let social4 = {login: 'facebook', userId: '1fsdf42343', token: 'some_token', expire: 3600};
      return Promise.resolve(social4);
    }

    deleteAccount(id: number): Promise<void> {
      return Promise.resolve(null);
    }

    updateAccount(account: SocialAccount ):  Promise<void>{
        return Promise.resolve(null);
    }

}
</code>```

I've resigned from FacebookServiceMock and use it only as injected stub, and return result from spy.
Error double and social_config are also stub.

I would be very glad for some help in what am I doing wrong

Cheers.

答:
I used the spyOn differenty. Maybe this works:

```<code>let spy = spyOn(new Date(), 'toString');
expect(spy.calls.count()>0).toBeTruthy();
</code>```

Body:
I've got a problem with detecting spy have called an function. It's a unit test of service.
I've tried two different approaches with TestBed.get on method (in ' it should check only status') and spy on injected dummy class  ("in it should login unknown to facebook"), but neither of them doesnt seem to work
I've done some print to see if method is used, and there are shown.
Here's a spec file:

import { TestBed, inject, async } from '@angular/core/testing';

import {FacebookServiceMock } from './../test-helpers/facebook-service-mock';
import { SocialsServiceDummy } from './../test-helpers/socialsServiceDummy';
import { ErrorDouble } from './../test-helpers/errorDouble';

import { ErrorsService } from './../../app/services/errors.service';
import { social_config, SocialConfig, SOCIAL_CONFIG } from './../../app/socials/social-config';
import { SocialsService } from './../../app/services/socials.service';
import { FacebookLoginService } from './../../app/services/facebook-login.service';
import { FacebookService } from 'ngx-facebook';

describe('Facebook-login-service test', () => {
    let socialsServiceSpy: any;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [
                FacebookLoginService,
                { provide: FacebookService, useFactory: () => { return new FacebookServiceMock() }},
                { provide: SocialsService, useFactory: () => {  return new SocialsServiceDummy() }},
                { provide: ErrorsService, useFactory: () => { return new ErrorDouble() } },
                { provide: social_config, useValue: SOCIAL_CONFIG }
            ]
        });

    });

    beforeEach(() => {
        socialsServiceSpy = TestBed.get(SocialsService);
        spyOn(socialsServiceSpy, 'updateAccount');

    });

    afterEach(()=>{
        TestBed.resetTestingModule();

    });

    it('should login unknown to facebook',
        async(inject([FacebookLoginService, FacebookService, SocialsService, ErrorsService, social_config], (facebookLoginService, FacebookServiceMock, SocialsServiceDummy, ErrorDouble, SOCIAL_CONFIG) => {
                let mockReturn = {
                    status: "unknown",
                    authResponse: {
                        userID: '123456',
                        accessToken: 'token',
                        expiresIn: 3600
                    }
                };

                spyOn(FacebookServiceMock, 'getLoginStatus').and.returnValue(Promise.resolve(mockReturn));
                spyOn(SocialsServiceDummy, 'addNewSocialAccount').and.callThrough();
                spyOn(facebookLoginService, 'loginToFacebook').and.callThrough();

                facebookLoginService.checkLoginStatus();
                expect(facebookLoginService.loginToFacebook).toHaveBeenCalled();
                expect(SocialsServiceDummy.addNewSocialAccount).toHaveBeenCalledWith('facebook', mockReturn.authResponse.userID, mockReturn.authResponse.accessToken, mockReturn.authResponse.expiresIn);
            })
        ));

    it('should check only status',
        async(inject([FacebookLoginService, FacebookService, SocialsService, ErrorsService, social_config], (facebookLoginService, FacebookServiceMock, SocialsServiceDummy, ErrorDouble, SOCIAL_CONFIG) => {
                let mockReturn = {
                    status: "connected",
                    authResponse: {
                        userID: '123456',
                        accessToken: 'token',
                        expiresIn: 3600
                    }
                };
                spyOn(FacebookServiceMock, 'getLoginStatus').and.returnValue(Promise.resolve(mockReturn));
               // spyOn(SocialsServiceDummy, 'updateAccount').and.callThrough();

                facebookLoginService.checkLoginStatus();
                expect(socialsServiceSpy.updateAccount).toHaveBeenCalledWith('facebook', mockReturn.authResponse.userID, mockReturn.authResponse.accessToken, mockReturn.authResponse.expiresIn);

            })
        ));
});

The FacebookLoginService looks like this:

/**
 * Created by Daniel on 2017-06-19.
 */
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { FacebookService, LoginResponse, LoginOptions } from 'ngx-facebook';
import { ErrorsService } from './errors.service';
import { social_config, SocialConfig } from './../socials/social-config';
import { NewSocialAccount } from './../shared/models/new-social-account';
import { SocialsService } from "./socials.service";

@Injectable()

export class FacebookLoginService {
    private loginOptions : LoginOptions = {
        scope: this.socialConfig.facebook.scope
    }

    private attemptToLogin =  new Subject<boolean>()
    private newSocialAccount =  new Subject<any>();

    login$ = this.attemptToLogin.asObservable();
    newSocial$ = this.newSocialAccount.asObservable();

    constructor(
        private facebookService: FacebookService,
        private socialsService: SocialsService,
        private errorsService: ErrorsService,
        @Inject(social_config) private socialConfig: SocialConfig
    ) {}

    initSocials() : void {
        this.facebookService.init({appId: this.socialConfig.facebook.appId, version: this.socialConfig.facebook.version});
    }

    checkLoginStatus() : void{
        this.facebookService.getLoginStatus().then(
            (res) => {
                if(res.status == "connected") {
                    const updatedAccount = this.createNewAccountObject('facebook', res.authResponse.userID, res.authResponse.accessToken, res.authResponse.expiresIn);
                    this.socialsService.updateAccount(updatedAccount).then(
                        () => {
                            this.attemptToLogin.next(true);
                        },
                        error => {
                            this.errorsService.startErrorAction(error);
                        }
                    )
                } else {
                   this.loginToFacebook();
                }
            },
            error => {
                alert('Unable to connect with Facebook. Please try later');
            }
        )
    }

    loginToFacebook() : void {
        this.facebookService.login(this.loginOptions).then(
            (res: LoginResponse) => {
                const newAccount = this.createNewAccountObject('facebook', res.authResponse.userID, res.authResponse.accessToken, res.authResponse.expiresIn);
                this.socialsService.addNewSocialAccount(newAccount).then(
                    (res) => {
                        this.confirmLoginNewSocialAccount(res, 'facebook');
                    },
                    error => {
                        this.errorsService.startErrorAction(error);
                    }
                )
            },
            error => {
                alert('Unable to connect with Facebook. Please try later');
            }
        )

    }

    logout(): void {
        this.facebookService.logout();
    }

    private createNewAccountObject(socialStr: string, userStr: string, tokenStr: string, expiresNr: number): NewSocialAccount {
            return {
                social: socialStr,
                userID: userStr,
                token: tokenStr,
                expires:  expiresNr
            };
        }

    private confirmLoginNewSocialAccount(response: any, accountType: string) {
        this.newSocialAccount.next({login: response.login, social: accountType});

    }
}

Here is dummy file from injected social service

import { SocialAccount} from './../../app/shared/models/social-account';
import { NewSocialAccount} from './../../app/shared/models/new-social-account';

export class SocialsServiceDummy {

    getSocials(): Promise<SocialAccount[]> {
      let socials =  [

      ];
      return Promise.resolve(socials);
    }

    addNewSocialAccount(newAccount: NewSocialAccount) : Promise<any>{
      let social4 = {login: 'facebook', userId: '1fsdf42343', token: 'some_token', expire: 3600};
      return Promise.resolve(social4);
    }

    deleteAccount(id: number): Promise<void> {
      return Promise.resolve(null);
    }

    updateAccount(account: SocialAccount ):  Promise<void>{
        return Promise.resolve(null);
    }

}

I've resigned from FacebookServiceMock and use it only as injected stub, and return result from spy.
Error double and social_config are also stub.

I would be very glad for some help in what am I doing wrong

Cheers.

Body:
I used the spyOn differenty. Maybe this works:

let spy = spyOn(new Date(), 'toString');
expect(spy.calls.count()>0).toBeTruthy();