问:
EqualityComparerer<T>.Default.Equals() vs object.Equals() and polymorphism
Once again discussing equality I stumbled on EqualityComparer<T>.Default.Equals(). I prefer to call this method for reference types rather than object.Equals().

Now I think I was dreadfully wrong.

object.Equals() uses overridable instance Equals() method providing correct polymorphic behavior whereas EqualityComparer<T>.Default.Equals() calls IEquatable<T>.Equals() if it's implemetned.

Now consider this small program:

```<code>public class Class1 : IEquatable<Class1>
{
    public int Prop1 { get; set; }

    public bool Equals(Class1 other)
    {
        if (other == null)
            return false;

        return Prop1 == other.Prop1;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }

        return Equals(obj as Class1);
    }
}

public class Class2 : Class1, IEquatable<Class2>
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public bool Equals(Class2 other)
    {
        if (other == null)
            return false;

        return Prop1 == other.Prop1 && Prop2 == other.Prop2;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }

        return Equals(obj as Class2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var c1 = new Class1 {Prop1 = 10};
        var c2 = new Class2 {Prop1 = 10, Prop2 = 5};
        var c3 = new Class2 {Prop1 = 10, Prop2 = 15};

        Console.WriteLine("Object.Equals()");
        Console.WriteLine("C1=C2 {0}",Equals(c1,c2));
        Console.WriteLine("C2=C1 {0}",Equals(c2, c1));
        Console.WriteLine("C2=C3 {0}",Equals(c2, c3));
        Console.WriteLine("C3=C2 {0}", Equals(c3, c2));

        var dec1 = EqualityComparer<Class1>.Default;

        Console.WriteLine();
        Console.WriteLine("EqualityComparer<Class1>.Default.Equals");
        Console.WriteLine("C1=C2 {0}", dec1.Equals(c1, c2));
        Console.WriteLine("C2=C1 {0}", dec1.Equals(c2, c1));
        Console.WriteLine("C2=C3 {0} BUG?", dec1.Equals(c2, c3));
        Console.WriteLine("C3=C2 {0} BUG?", dec1.Equals(c3, c2));

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

It shows how easy it is to bring inconsistency in equality semantics:

Object.Equals()

  C1=C2 False

  C2=C1 False

  C2=C3 False

  C3=C2 False

  EqualityComparer<Class1>.Default.Equals

  C1=C2 False

  C2=C1 False

  C2=C3 True BUG?

  C3=C2 True BUG?

However MSDN Documentation recommdends:

Notes to Implementers If you implement Equals, you should also
  override the base class implementations of Object.Equals(Object) and
  GetHashCode so that their behavior is consistent with that of the
  IEquatable<T>.Equals method. If you do override Object.Equals(Object),
  your overridden implementation is also called in calls to the static
  Equals(System.Object, System.Object) method on your class. In
  addition, you should overload the op_Equality and op_Inequality
  operators. This ensures that all tests for equality return consistent
  results, which the example illustrates.

Starting from this moment I see no reason to implement IEquatable<T> for reference types.
Can anyone tell me when it has any sense?
Should I really treat different equality behavior as inconsistent when we look at the type differently (as base type)?

答:
Today I asked myself which consequences arise when adding IEquatable<T> to a class, and I found your question.

Then I tested your code. For everyone else reading this, here's an answer, instead of only "just do it like that to make it work".

First of all, it's not a bug.

Your problem is, that you specify an EqualityComparer<Class1>, which is only implemented in class1 by public bool Equals(Class1 other).

Therefore, dec1.Equals(c2, c3) will call this function where only the content of class1 is compared.

From your comment BUG? I can see that you expect the content of class2 to be compared as well, just like everybody else would expect, too. To achieve this, you need to change

public bool Equals(Class1 other)

into

public virtual bool Equals(Class1 other)

and override this function in class2, where you then also compare the content of class2.

But that may lead to a quite weird construct. Therefore, for completeness, here's my way of implementation:

In the base class, only type checks:

```<code>//--------------------------------------------------------------------------
public static bool operator == (CClass1 i_value1, CClass1 i_value2)
{
  if (ReferenceEquals (i_value1, i_value2))
    return true;
  if (ReferenceEquals (null, i_value1))
    return false;

  return (i_value1.Equals (i_value2));
}

//--------------------------------------------------------------------------
public static bool operator != (CClass1 i_value1, CClass1 i_value2)
{
  return !(i_value1 == i_value2);
}

///-------------------------------------------------------------------------
public sealed override bool Equals (object i_value)
{
  if (ReferenceEquals (null, i_value))
    return false;
  if (ReferenceEquals (this, i_value))
    return true;

  if (i_value.GetType () != GetType ())
    return false;

  return Equals_EXEC ((CClass1)i_value);
}

///-------------------------------------------------------------------------
public bool Equals (CClass1 i_value)  // not virtual, don't allow overriding!
{
  if (ReferenceEquals (null, i_value))
    return false;
  if (ReferenceEquals (this, i_value))
    return true;

  if (i_value.GetType () != GetType ())
    return false;

  return Equals_EXEC (i_value);
}
</code>```

Still in the base class, content checks:

```<code>///-------------------------------------------------------------------------
protected override bool Equals_EXEC (CClass1 i_value)
{
  return Equals_exec (i_value);
}

//--------------------------------------------------------------------------
private bool Equals_exec (CClass1 i_value)
{
  return variable1 == i_value.variable1
      && variable2 == i_value.variable2
      && ... ;
}
</code>```

In the derived classes, content checks:

```<code>///-------------------------------------------------------------------------
protected override bool Equals_EXEC (CClassN i_value)
{
  return base.Equals_EXEC (i_value)
      && Equals_exec (i_value as CClassN);
}

//--------------------------------------------------------------------------
private bool Equals_exec (CClassN i_value)
{
  return variable5 == i_value.variable5
      && variable6 == i_value.variable6
      && ... ;
}
</code>```

Body:
Once again discussing equality I stumbled on EqualityComparer<T>.Default.Equals(). I prefer to call this method for reference types rather than object.Equals().

Now I think I was dreadfully wrong.

object.Equals() uses overridable instance Equals() method providing correct polymorphic behavior whereas EqualityComparer<T>.Default.Equals() calls IEquatable<T>.Equals() if it's implemetned.

Now consider this small program:

public class Class1 : IEquatable<Class1>
{
    public int Prop1 { get; set; }

    public bool Equals(Class1 other)
    {
        if (other == null)
            return false;

        return Prop1 == other.Prop1;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }

        return Equals(obj as Class1);
    }
}

public class Class2 : Class1, IEquatable<Class2>
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public bool Equals(Class2 other)
    {
        if (other == null)
            return false;

        return Prop1 == other.Prop1 && Prop2 == other.Prop2;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }

        return Equals(obj as Class2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var c1 = new Class1 {Prop1 = 10};
        var c2 = new Class2 {Prop1 = 10, Prop2 = 5};
        var c3 = new Class2 {Prop1 = 10, Prop2 = 15};

        Console.WriteLine("Object.Equals()");
        Console.WriteLine("C1=C2 {0}",Equals(c1,c2));
        Console.WriteLine("C2=C1 {0}",Equals(c2, c1));
        Console.WriteLine("C2=C3 {0}",Equals(c2, c3));
        Console.WriteLine("C3=C2 {0}", Equals(c3, c2));

        var dec1 = EqualityComparer<Class1>.Default;

        Console.WriteLine();
        Console.WriteLine("EqualityComparer<Class1>.Default.Equals");
        Console.WriteLine("C1=C2 {0}", dec1.Equals(c1, c2));
        Console.WriteLine("C2=C1 {0}", dec1.Equals(c2, c1));
        Console.WriteLine("C2=C3 {0} BUG?", dec1.Equals(c2, c3));
        Console.WriteLine("C3=C2 {0} BUG?", dec1.Equals(c3, c2));

        Console.ReadKey();
    }
}

It shows how easy it is to bring inconsistency in equality semantics:

Object.Equals()

  C1=C2 False

  C2=C1 False

  C2=C3 False

  C3=C2 False

  EqualityComparer<Class1>.Default.Equals

  C1=C2 False

  C2=C1 False

  C2=C3 True BUG?

  C3=C2 True BUG?

However MSDN Documentation recommdends:

Notes to Implementers If you implement Equals, you should also
  override the base class implementations of Object.Equals(Object) and
  GetHashCode so that their behavior is consistent with that of the
  IEquatable<T>.Equals method. If you do override Object.Equals(Object),
  your overridden implementation is also called in calls to the static
  Equals(System.Object, System.Object) method on your class. In
  addition, you should overload the op_Equality and op_Inequality
  operators. This ensures that all tests for equality return consistent
  results, which the example illustrates.

Starting from this moment I see no reason to implement IEquatable<T> for reference types.
Can anyone tell me when it has any sense?
Should I really treat different equality behavior as inconsistent when we look at the type differently (as base type)?

Body:
Today I asked myself which consequences arise when adding IEquatable<T> to a class, and I found your question.

Then I tested your code. For everyone else reading this, here's an answer, instead of only "just do it like that to make it work".

First of all, it's not a bug.

Your problem is, that you specify an EqualityComparer<Class1>, which is only implemented in class1 by public bool Equals(Class1 other).

Therefore, dec1.Equals(c2, c3) will call this function where only the content of class1 is compared.

From your comment BUG? I can see that you expect the content of class2 to be compared as well, just like everybody else would expect, too. To achieve this, you need to change

public bool Equals(Class1 other)

into

public virtual bool Equals(Class1 other)

and override this function in class2, where you then also compare the content of class2.

But that may lead to a quite weird construct. Therefore, for completeness, here's my way of implementation:

In the base class, only type checks:

//--------------------------------------------------------------------------
public static bool operator == (CClass1 i_value1, CClass1 i_value2)
{
  if (ReferenceEquals (i_value1, i_value2))
    return true;
  if (ReferenceEquals (null, i_value1))
    return false;

  return (i_value1.Equals (i_value2));
}

//--------------------------------------------------------------------------
public static bool operator != (CClass1 i_value1, CClass1 i_value2)
{
  return !(i_value1 == i_value2);
}

///-------------------------------------------------------------------------
public sealed override bool Equals (object i_value)
{
  if (ReferenceEquals (null, i_value))
    return false;
  if (ReferenceEquals (this, i_value))
    return true;

  if (i_value.GetType () != GetType ())
    return false;

  return Equals_EXEC ((CClass1)i_value);
}

///-------------------------------------------------------------------------
public bool Equals (CClass1 i_value)  // not virtual, don't allow overriding!
{
  if (ReferenceEquals (null, i_value))
    return false;
  if (ReferenceEquals (this, i_value))
    return true;

  if (i_value.GetType () != GetType ())
    return false;

  return Equals_EXEC (i_value);
}

Still in the base class, content checks:

///-------------------------------------------------------------------------
protected override bool Equals_EXEC (CClass1 i_value)
{
  return Equals_exec (i_value);
}

//--------------------------------------------------------------------------
private bool Equals_exec (CClass1 i_value)
{
  return variable1 == i_value.variable1
      && variable2 == i_value.variable2
      && ... ;
}

In the derived classes, content checks:

///-------------------------------------------------------------------------
protected override bool Equals_EXEC (CClassN i_value)
{
  return base.Equals_EXEC (i_value)
      && Equals_exec (i_value as CClassN);
}

//--------------------------------------------------------------------------
private bool Equals_exec (CClassN i_value)
{
  return variable5 == i_value.variable5
      && variable6 == i_value.variable6
      && ... ;
}


来源: stackexchange

问:
VS 2010 intellisense not working for upconverted project
We have a very big C++ solution with several projects for which intellisense works perfectly in Visual Studio 2008, but not at all in Visual Studio 2010 (not even for structs defined in the same file where they are used).  I've verified that intellisense does work in VS 2010 for other projects on my machine.  I've tried importing one of the problematic projects from a brand-new solution with no success.  Re-building the project files from scratch seems promising, but it would require days of work to follow that path, with no guarantee of success at the end.  Any alternative suggestions are welcome.  The actual error message I get is:

"Intellisense: 'No additional information available'(See 'Troubleshooting IntelliSense in C++ Projects' for further help.)

I've tried that, but there's basically only one suggestion on the MSDN webpage, to make sure "stdafx.h" on the include path, but we're not using precompiled headers and don't include it from anywhere, so I'm pretty sure that's not the problem.

答: Have you deleted all of the generated database (.ncb and .sdf) files?  Corrupted database files is the most likely cause of Visual Studio failing to display IntelliSense.</p>

ContentLicense: CC BY-SA 3.0


问:
how to define a type for an existing npm plugin module?
I try to convert a codebase which uses nodemailer and the nodemailer-html-to-text plugin to typescript.

Nodemailer has @types definitions, but nodemailer-html-to-text has not.

How can I create my own type definitions for this module?

I tried to create a @types/nodemailer-html-to-text.d.ts file in my project:

```<code>declare module 'nodemailer-html-to-text' {
}
</code>```

From here, I would like this file to export a htmlToText function definition of type Mail.PluginFunction, but I don't know how to do it…

答:
found it here module-plugin.d.ts: </p>

```<code>declare module 'nodemailer-html-to-text' {
  import * as Mail from 'nodemailer/lib/mailer'
  export function htmlToText(): Mail.PluginFunction
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to convert a codebase which uses nodemailer and the nodemailer-html-to-text plugin to typescript.

Nodemailer has @types definitions, but nodemailer-html-to-text has not.

How can I create my own type definitions for this module?

I tried to create a @types/nodemailer-html-to-text.d.ts file in my project:

declare module 'nodemailer-html-to-text' {
}

From here, I would like this file to export a htmlToText function definition of type Mail.PluginFunction, but I don't know how to do it…

Body:
found it here module-plugin.d.ts:

declare module 'nodemailer-html-to-text' {
  import * as Mail from 'nodemailer/lib/mailer'
  export function htmlToText(): Mail.PluginFunction
}


问:
Frequently polls happening from delayed job
Hi I am using delayed job active record gem in my production application with Postgres, a lot of background jobs are working through the delayed job

One thing I have noticed in the output of pg:outliers in our production database, the prop_exec_time is 4.5% for this query and almost 1.8 million calls happened in 45 hours.

Query:

UPDATE "delayed_jobs" SET locked_at = $1, locked_by = $2 WHERE id IN (SELECT  id FROM "delayed_jobs"  WHERE ((run_at <= $3 AND (locked_at IS NULL OR locked_at < $4) OR locked_by = $5) AND failed_at IS NULL) ORDER BY priority ASC, run_at ASC LIMIT $6 FOR UPDATE) RETURNING *

As per the delayed job, the polls happen every 5 seconds by default, but this happens even if there is no job to perform. Currently, there is no extra configuration in our app.

I guess I can override the default time of delayed_job, will this make any impact? Any kind of suggestion to reduce the calls

答:
the prop_exec_time is 4.5% for this query and almost 1.8 million calls happened in 45 hours.

4.5% does not seem outrageous.  Is there really a problem here which needs to be solved?

How many jobs went through the queue during that 45 hours?  Was the queue completely empty for that whole time?  The poll is every 5 seconds per worker, so getting 1.8 million calls on an empty queue in 45 hours would take 50 workers.  Do you have that many?

I guess I can override the default time of delayed_job, will this make any impact?

Yes, but it will also delay the responsiveness to your workers detecting new work to do.


问:
firing a jQuery change function at document ready
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

```<code>$('input[name=country]').value('US').trigger('click');
</code>```

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

```<code>$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});
</code>```

答:
Just chain .trigger('change') to the end of the handler assignment.

```<code> // ----------v-------v-----quotation marks are mandatory
$('input[name="country"]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name="country"]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
}).trigger('change');  // <--- RIGHT HERE
</code>```

Or if you only want it to fire on the first element, use triggerHandler() instead.

```<code>        // ...
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
}).triggerHandler('change');  // <--- RIGHT HERE
</code>```

Body:
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

$('input[name=country]').value('US').trigger('click');

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});

Body:
Just chain .trigger('change') to the end of the handler assignment.

 // ----------v-------v-----quotation marks are mandatory
$('input[name="country"]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name="country"]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
}).trigger('change');  // <--- RIGHT HERE

Or if you only want it to fire on the first element, use triggerHandler() instead.

        // ...
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
}).triggerHandler('change');  // <--- RIGHT HERE


问:
How do I reference assets in .vue files when using Vapor?
As I want the assets to be distributed on Cloudfront upon deployment with the correct URLs.

I am not using blade so I can’t use the asset helper. There’s no documentation on this either.

答:
You need to ensure you are storing your images in the correct location so they can be processed correctly at build time.

I made the mistake of storing my images in the /public directory. Instead store your images under /resources and in your .vue files make sure you reference them using a relative path.

E.g.

app.vue

/resources/js/views/app.vue

test.png

/resources/images/test.png

Then in your app.vue reference your images as such:

```<code><img src="../../images/test.png" />
</code>```

Once everything has compiled your images will move to the /public directory.

You then need to inject the CDN via your webpack.mix.js file. Make sure you are setting the resource root to the CDN URL which is passed in via the ASSET_URL by Vapor at build time

```<code>/* Get the Vapor ASSET_URL */
const ASSET_URL = `${process.env.ASSET_URL || ''}/`

/* Set the resource root */
mix.setResourceRoot(ASSET_URL);
</code>```

Body:
You need to ensure you are storing your images in the correct location so they can be processed correctly at build time.

I made the mistake of storing my images in the /public directory. Instead store your images under /resources and in your .vue files make sure you reference them using a relative path.

E.g.

app.vue

/resources/js/views/app.vue

test.png

/resources/images/test.png

Then in your app.vue reference your images as such:

<img src="../../images/test.png" />

Once everything has compiled your images will move to the /public directory.

You then need to inject the CDN via your webpack.mix.js file. Make sure you are setting the resource root to the CDN URL which is passed in via the ASSET_URL by Vapor at build time

/* Get the Vapor ASSET_URL */
const ASSET_URL = `${process.env.ASSET_URL || ''}/`

/* Set the resource root */
mix.setResourceRoot(ASSET_URL);


问:
How can I try catch a val in fetch data successfully?
I am trying to fetch a JSONObject "image" that is sometimes a null value, so I set a try {} catch {} for my val jsonMedia in order to make it nullable but Im not sure if I'm missing something because it doesnt seem to work.

Whenever I comment out the jsonMedia my fetch works fine so I'll focus on just sharing the fetch of the "image" so the data I share doesnt get confusing.

1st. Ill show how the "image" is in the database and what I mean by "sometimes" has a null value
- null:

```<code>{
    "listCar": [
   {
    //other data
    "image": null,
    //other data
   }
 ]
}
</code>```

when it contains an image:

```<code>{
    "listCar": [
   {
    //other data
     "image": {
                "path": "Upload/UploadCarMain/UploadCarMain-200-200/30032235992008220498istanbul_adalarCar195.jpg",
                "name": "30032235992008220498istanbul_adalarCar195.jpg"
            },
    //other data
   }
 ]
}
</code>```

Now my fetch data was followed by a course I'm watching the only difference is the values of "image" in the database Im using arent like the course which did not contain null values in their image path

Now here is my "Car" class that is supposed to get the image:

```<code>class Car(other data, val image: String?, other data) {
    override fun toString(): String {
        return "Car(//other data, image='$image', //other data')"
    }
}
</code>```

and here is my fetch code where I am trying to try {} catch(){} my "jsonMedia" image JSONOBject:

```<code>override fun doInBackground(vararg params: String?): ArrayList<Car> {
        Log.d(TAG, "doInBackground starts")

        val carList = ArrayList<Car>()
        try {
            val jsonData = JSONObject(params[0])
            val itemsArray = jsonData.getJSONArray("listCar")

            for (i in 0 until itemsArray.length()) {
                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: IllegalArgumentException) {null}
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)
                Log.d(TAG, ".doInBackground $carObject")
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            Log.e(TAG, "doInBackground: Error processing json data. ${e.message}")
            cancel(true)
            listener.onError(e)
        }

        Log.d(TAG, ".doInBackground ends")
        return carList
    }

    override fun onPostExecute(result: ArrayList<Car>) {
        Log.d(TAG, "onPostExecute starts")
        super.onPostExecute(result)
        listener.onDataAvailable(result)
        Log.d(TAG, ".onPostExecute ends")
    }
}
</code>```

and here is the error I get when i run the code:

```<code>2020-02-14 16:42:16.483 26642-26684/com.example.wasit E/GetFlickrJsonData: doInBackground: Error processing json data. Value null at image of type org.json.JSONObject$1 cannot be converted to JSONObject
</code>```

答:
Just modify the code like this. Exception class is the Parent class of all exception and provide exact cause of error.</p>

```<code>for (i in 0 until itemsArray.length()) {

try {

                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = jsonCar.getJSONObject("image")
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)

} catch (ex: Exception) {
 Log.d(TAG, ex.localizedMessage.toString())
}

            }
</code>```

Body:
I am trying to fetch a JSONObject "image" that is sometimes a null value, so I set a try {} catch {} for my val jsonMedia in order to make it nullable but Im not sure if I'm missing something because it doesnt seem to work.

Whenever I comment out the jsonMedia my fetch works fine so I'll focus on just sharing the fetch of the "image" so the data I share doesnt get confusing.

1st. Ill show how the "image" is in the database and what I mean by "sometimes" has a null value
- null:

{
    "listCar": [
   {
    //other data
    "image": null,
    //other data
   }
 ]
}

when it contains an image:

{
    "listCar": [
   {
    //other data
     "image": {
                "path": "Upload/UploadCarMain/UploadCarMain-200-200/30032235992008220498istanbul_adalarCar195.jpg",
                "name": "30032235992008220498istanbul_adalarCar195.jpg"
            },
    //other data
   }
 ]
}

Now my fetch data was followed by a course I'm watching the only difference is the values of "image" in the database Im using arent like the course which did not contain null values in their image path

Now here is my "Car" class that is supposed to get the image:

class Car(other data, val image: String?, other data) {
    override fun toString(): String {
        return "Car(//other data, image='$image', //other data')"
    }
}

and here is my fetch code where I am trying to try {} catch(){} my "jsonMedia" image JSONOBject:

override fun doInBackground(vararg params: String?): ArrayList<Car> {
        Log.d(TAG, "doInBackground starts")

        val carList = ArrayList<Car>()
        try {
            val jsonData = JSONObject(params[0])
            val itemsArray = jsonData.getJSONArray("listCar")

            for (i in 0 until itemsArray.length()) {
                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: IllegalArgumentException) {null}
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)
                Log.d(TAG, ".doInBackground $carObject")
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            Log.e(TAG, "doInBackground: Error processing json data. ${e.message}")
            cancel(true)
            listener.onError(e)
        }

        Log.d(TAG, ".doInBackground ends")
        return carList
    }

    override fun onPostExecute(result: ArrayList<Car>) {
        Log.d(TAG, "onPostExecute starts")
        super.onPostExecute(result)
        listener.onDataAvailable(result)
        Log.d(TAG, ".onPostExecute ends")
    }
}

and here is the error I get when i run the code:

2020-02-14 16:42:16.483 26642-26684/com.example.wasit E/GetFlickrJsonData: doInBackground: Error processing json data. Value null at image of type org.json.JSONObject$1 cannot be converted to JSONObject

Body:
Just modify the code like this. Exception class is the Parent class of all exception and provide exact cause of error.

for (i in 0 until itemsArray.length()) {

try {

                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = jsonCar.getJSONObject("image")
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)

} catch (ex: Exception) {
 Log.d(TAG, ex.localizedMessage.toString())
}

            }


问:
Operating on every element of a list without for loop
Now I know this question is as bizarre as it sounds, but I have found myself in a situation where I may need to avoid looping over the list, unless I manage to identify the source of the problem.

The problem:

```<code>def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed
</code>```

Is there any other way of accessing list elements in a manner that a for loop would do?

答:
You can use recursion or slicing.</p>

```<code>def print_ele(elements):
    if(len(elements)>0):
        print(elements[0])
        print_ele(elements[1:])

//Or
elements[0:2]
</code>```

Body:
Now I know this question is as bizarre as it sounds, but I have found myself in a situation where I may need to avoid looping over the list, unless I manage to identify the source of the problem.

The problem:

def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed

Is there any other way of accessing list elements in a manner that a for loop would do?

Body:
You can use recursion or slicing.

def print_ele(elements):
    if(len(elements)>0):
        print(elements[0])
        print_ele(elements[1:])

//Or
elements[0:2]


问:
How to Get the URL from the Current Firefox Window via Windows' Command Line?
I need to get the URL from the Current Firefox Window,

but without creating and installing an Add-on.

Is it possible to do it via Windows' Command Line?

By "Command Line" I mean the Command Prompt of Windows,

and not the Console pane inside Firefox..

So I can run:

```<code>firefox.exe -somecommand/parameters
</code>```

and then get the StdOut with the String that is the Current URL

I need this for an outside application, that is not an Add-on..

答:
How are you attempting to access the url?

you can always type

window.location.href
```

into the console?

Body:
I need to get the URL from the Current Firefox Window,

but without creating and installing an Add-on.

Is it possible to do it via Windows' Command Line?

By "Command Line" I mean the Command Prompt of Windows,

and not the Console pane inside Firefox..

So I can run:

firefox.exe -somecommand/parameters

and then get the StdOut with the String that is the Current URL

I need this for an outside application, that is not an Add-on..

Body:
How are you attempting to access the url?

you can always type

window.location.href

into the console?


问:
downloading specific files resides in s3 subfolder into my local machine using boto3
I have a file resides in a s3 bucket subfolder. Bucket name "testbucket", folder name-"folder1". File name:"sample.csv". I want to download that into my local machine: "/Users/sameer/desktop/folder1".

What is the most efficient way to do download that if the file size is more than 3gb

答:
Use the AWS CLI

aws s3 cp s3://testbucket/folder1/sample.csv /Users/sameer/desktop/folder1
```

<p>if you must boto3:</p>

<pre class="lang-py prettyprint-override"><code>import boto3

s3_client = boto3.client('s3')

s3_client.download_file('testbucket', 'folder1/sample.csv', '/Users/sameer/desktop/folder1/sample.csv')
</code>```

Body:
Use the AWS CLI

aws s3 cp s3://testbucket/folder1/sample.csv /Users/sameer/desktop/folder1

if you must boto3:

import boto3

s3_client = boto3.client('s3')

s3_client.download_file('testbucket', 'folder1/sample.csv', '/Users/sameer/desktop/folder1/sample.csv')


问:
Getting if a Column is nullable (declared as not null or implicit declared nullable) using SqlClient on C#
I have this code which shows the database I created using SqlClient, but I don't know how I could check if a column was added as nullable or not nullable in the table.

```<code>string[] defaultTables = { "AspNetUsers", "AspNetRoleClaims", "AspNetUserClaims", "AspNetUserLogins", "AspNetUserRoles", "AspNetUserTokens", "AspNetRoles", "__EFMigrationsHistory" };
dblist.ForEach((string DbName) => {
    strConnection = $@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DbName};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

    using (SqlConnection conn = new SqlConnection(strConnection)) {
        conn.Open();
        using (cmdSql = new SqlCommand(strConnection, conn)) {
            DataTable dt = conn.GetSchema("Tables");

            foreach (DataRow row in dt.Rows) {
                string tablename = row[2].ToString();
                if (!defaultTables.Any(x => x == tablename)) {
                    tables.Add(tablename);

                    using (cmdSql = new SqlCommand($"Select * FROM {tablename}", conn)) {
                        SqlDataReader reader = cmdSql.ExecuteReader();
                        if (reader.Read()) {
                            for (int i = 0; i < reader.FieldCount; i++)
                                Console.Write(reader.GetName(i) + " " + reader.GetDataTypeName(i) + $"" + ',');
                        }
                    }
                }
            }
        }
    }
});
</code>```

答:
It isn't 100% reliable, but GetSchemaTable() on the data-reader can show this, if it knows (which isn't always); specifically, you're looking for the AllowDBNull property. It isn't a great API to look at, though - it returns a DataTable that you need to investigate, so it might need a bit of playing to find what you are after.

citation

Body:
I have this code which shows the database I created using SqlClient, but I don't know how I could check if a column was added as nullable or not nullable in the table.

string[] defaultTables = { "AspNetUsers", "AspNetRoleClaims", "AspNetUserClaims", "AspNetUserLogins", "AspNetUserRoles", "AspNetUserTokens", "AspNetRoles", "__EFMigrationsHistory" };
dblist.ForEach((string DbName) => {
    strConnection = $@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DbName};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

    using (SqlConnection conn = new SqlConnection(strConnection)) {
        conn.Open();
        using (cmdSql = new SqlCommand(strConnection, conn)) {
            DataTable dt = conn.GetSchema("Tables");

            foreach (DataRow row in dt.Rows) {
                string tablename = row[2].ToString();
                if (!defaultTables.Any(x => x == tablename)) {
                    tables.Add(tablename);

                    using (cmdSql = new SqlCommand($"Select * FROM {tablename}", conn)) {
                        SqlDataReader reader = cmdSql.ExecuteReader();
                        if (reader.Read()) {
                            for (int i = 0; i < reader.FieldCount; i++)
                                Console.Write(reader.GetName(i) + " " + reader.GetDataTypeName(i) + $"" + ',');
                        }
                    }
                }
            }
        }
    }
});


问:
ipcRenderer not receiving message from main process
I can see the "Hello from renderer" alert, but not the "Goodbye from renderer" alert.

Running in Windows 10.

And I can't see the "received!" alert, which I should see it the ipcRenderer.on(...) worked.

index.js

```<code>const { app, BrowserWindow} = require("electron");

app.on('ready', () => {
  let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
  });

  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send("from-main", "teste");
  });
});
</code>```

index.html

```<code><html>

  <head>
    <title>test</title>

  <script src="./renderer.js"> </script>

  </head>

  <body>
      Wait...
  </body>

</html>
</code>```

renderer.js

```<code>alert('hello from renderer');
const { ipcRenderer } = require('electron');
ipcRenderer.on('from-main', () => { alert('received!');} );
alert('goodbye from renderer');
</code>```

package.json

```<code>{
  "name": "xxx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.0.0"
  }
}
</code>```

答:
```<code>let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
    webPreferences:{
      nodeIntegration:true
    }
  });
</code>```

Please add nodeIntegration when you are creating the browser window.
You are using the Node API at your renderer. When you don't enable nodeIntegration then you won't be able to use any node modules at your renderer js.

To confirm this you can see this error message from your app debug console.

```<code>mainWindow.webContents.on('did-finish-load', () => {
    // open dev tools
    mainWindow.webContents.openDevTools()
    mainWindow.webContents.send("from-main", "teste");
  });
</code>```

Uncaught ReferenceError: require is not defined

This means you didn't enable the nodeIntegration when you are creating the browserWindow.

Body:
I can see the "Hello from renderer" alert, but not the "Goodbye from renderer" alert.

Running in Windows 10.

And I can't see the "received!" alert, which I should see it the ipcRenderer.on(...) worked.

index.js

const { app, BrowserWindow} = require("electron");

app.on('ready', () => {
  let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
  });

  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send("from-main", "teste");
  });
});

index.html

    <title>test</title>

      Wait...

renderer.js

alert('hello from renderer');
const { ipcRenderer } = require('electron');
ipcRenderer.on('from-main', () => { alert('received!');} );
alert('goodbye from renderer');

package.json

{
  "name": "xxx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.0.0"
  }
}

Body:
let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
    webPreferences:{
      nodeIntegration:true
    }
  });

Please add nodeIntegration when you are creating the browser window.
You are using the Node API at your renderer. When you don't enable nodeIntegration then you won't be able to use any node modules at your renderer js.

To confirm this you can see this error message from your app debug console.

mainWindow.webContents.on('did-finish-load', () => {
    // open dev tools
    mainWindow.webContents.openDevTools()
    mainWindow.webContents.send("from-main", "teste");
  });

Uncaught ReferenceError: require is not defined

This means you didn't enable the nodeIntegration when you are creating the browserWindow.


问:
Bulk Map Update on HERE platform
I use a point of sale system that utilizes the HERE API to build maps of my delivery areas.  Recently, I provided my POS provider with an up-to-date parcels list and parcels shapefile and streets center line file from the County GIS department.

Despite providing this pristine data, my POS provider generated delivery maps that STILL do not include the proper streets and addresses.

After much prodding, I learned that my POS provider uses the HERE API to generate its maps.  Thus, it seems that HERE is the problem, not my POS provider.

There is a way to go into the HERE Map Creator and new addresses.  However, I don't have just one address.  I want to provide HERE with the ENTIRE County GIS database to ensure that their service has the most up-to-date maps.

I would call them about this, but they like to hide behind forms and not provide a telephone number.

Any idea how I can reach someone at HERE technologies to help them update entire counties worth of addresses?

Visited their website.  Realized that I could only add single addresses rather than an entire county.

N/A

N/a

答: There is a option to upload the data in the https://upload.here.com/</p>

Title: Bulk Map Update on HERE platform


问:
Randomnly swapping items betwen lists
I'm working on a small script that involves changing one codon (a item on my list) to another, randonmly.
I start by converting the DNA sequence into a list of codons, and then I want the script to choose a random one  and change it to another from a list of codons. The problem is that it only works for the first time that said item apears on the list. (Even if it chooses the last item, it replaces it for the first items that appears on the list that  is equal to that item).
I don't know if I have been clear enough, I'm still learning.
Here's the code: </p>

```<code>import random

codones = ['ATA', 'ATC', 'ATT', 'ATG',
           'ACA', 'ACC', 'ACG', 'ACT',
           'AAC', 'AAT', 'AAA', 'AAG',
           'AGC', 'AGT', 'AGA', 'AGG',
           'CTA', 'CTC', 'CTG', 'CTT',
           'CCA', 'CCC', 'CCG', 'CCT',
           'CAC', 'CAT', 'CAA', 'CAG',
           'CGA', 'CGC', 'CGG', 'CGT',
           'GTA', 'GTC', 'GTG', 'GTT',
           'GCA', 'GCC', 'GCG', 'GCT',
           "GAC", 'GAT', 'GAA', 'GAG',
           'GGA', 'GGC', 'GGG', 'GGT',
           'TCA', 'TCC', 'TCG', 'TCT',
           'TTC', 'TTT', 'TTA', 'TTG',
           'TAC', 'TAT', 'TGC', 'TGT',
           'TGG']

dna = "atgaaaagcatgaaaagc"
DNA = dna.upper()

print(DNA)

print("El gen tiene " + str(int(len(dna)/3)) + " Aa:")

def codones_dna(seq):
    codon = []
    for i in range(0, len(seq), 3):
        codon.append(seq[i:i +3])
    return codon
lista_codones = codones_dna(DNA)
print(lista_codones)

def translate(seq):
    table = {
        'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
        'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
        'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
        'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
        'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
        'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
        'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
        'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
        'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
        'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
        'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
        'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
        'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
        'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
        'TAC':'Y', 'TAT':'Y', 'TGC':'C', 'TGT':'C',
        'TGG':'W'
    }
    protein = " "
    if len(seq) % 3 == 0:
        for i in range(0, len(seq), 3):
            codon = seq[i:i + 3]
            protein += table[codon].lower()
    return protein
protein = translate(DNA)
print(protein)

def mutation(seq):
    for i in range(0, len(seq), 3):
        dna_mut = seq[i:i]
        wt = random.choice(lista_codones)
        mutado = random.choice(codones)
        if wt != mutado:
            dna_mut += seq.replace(wt, mutado, 1)

    return dna_mut

dna_mut = mutation(DNA)
</code>```

答:
Maybe this can be of use:

import re
from random import randint

codones = ['ATA', 'ATC', 'ATT', 'ATG',
           'ACA', 'ACC', 'ACG', 'ACT',
           'AAC', 'AAT', 'AAA', 'AAG',
           'AGC', 'AGT', 'AGA', 'AGG',
           'CTA', 'CTC', 'CTG', 'CTT',
           'CCA', 'CCC', 'CCG', 'CCT',
           'CAC', 'CAT', 'CAA', 'CAG',
           'CGA', 'CGC', 'CGG', 'CGT',
           'GTA', 'GTC', 'GTG', 'GTT',
           'GCA', 'GCC', 'GCG', 'GCT',
           "GAC", 'GAT', 'GAA', 'GAG',
           'GGA', 'GGC', 'GGG', 'GGT',
           'TCA', 'TCC', 'TCG', 'TCT',
           'TTC', 'TTT', 'TTA', 'TTG',
           'TAC', 'TAT', 'TGC', 'TGT',
           'TGG']

dna_sequence = 'atgaaaagcatgaaaagc'

def replace_random_seq(dna: str, replace_list: list):
    sequences = re.findall("\w\w\w", dna)  # searches for 3 letter pattern in dna

    ran_index = sequences[randint(0, len(sequences)]  # get a random index of a sequence
    sequences[ran_index] = replace_list[randint(0, len(replace_list)]  # replace the item in the random index with a random sequence in the sequences list

    new_dna = ""
    for item in sequences:
        new_dna += item

    return new_dna

print(replace_random_seq(dna_sequence, codones))
```

Just used regex to find all 3-letter patterns and replace one with a different one from your list.

Title: Randomnly swapping items betwen lists

Body:
I'm working on a small script that involves changing one codon (a item on my list) to another, randonmly.
I start by converting the DNA sequence into a list of codons, and then I want the script to choose a random one  and change it to another from a list of codons. The problem is that it only works for the first time that said item apears on the list. (Even if it chooses the last item, it replaces it for the first items that appears on the list that  is equal to that item).
I don't know if I have been clear enough, I'm still learning.
Here's the code:

import random

codones = ['ATA', 'ATC', 'ATT', 'ATG',
           'ACA', 'ACC', 'ACG', 'ACT',
           'AAC', 'AAT', 'AAA', 'AAG',
           'AGC', 'AGT', 'AGA', 'AGG',
           'CTA', 'CTC', 'CTG', 'CTT',
           'CCA', 'CCC', 'CCG', 'CCT',
           'CAC', 'CAT', 'CAA', 'CAG',
           'CGA', 'CGC', 'CGG', 'CGT',
           'GTA', 'GTC', 'GTG', 'GTT',
           'GCA', 'GCC', 'GCG', 'GCT',
           "GAC", 'GAT', 'GAA', 'GAG',
           'GGA', 'GGC', 'GGG', 'GGT',
           'TCA', 'TCC', 'TCG', 'TCT',
           'TTC', 'TTT', 'TTA', 'TTG',
           'TAC', 'TAT', 'TGC', 'TGT',
           'TGG']

dna = "atgaaaagcatgaaaagc"
DNA = dna.upper()

print(DNA)

print("El gen tiene " + str(int(len(dna)/3)) + " Aa:")

def codones_dna(seq):
    codon = []
    for i in range(0, len(seq), 3):
        codon.append(seq[i:i +3])
    return codon
lista_codones = codones_dna(DNA)
print(lista_codones)

def translate(seq):
    table = {
        'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
        'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
        'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
        'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
        'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
        'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
        'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
        'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
        'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
        'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
        'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
        'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
        'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
        'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
        'TAC':'Y', 'TAT':'Y', 'TGC':'C', 'TGT':'C',
        'TGG':'W'
    }
    protein = " "
    if len(seq) % 3 == 0:
        for i in range(0, len(seq), 3):
            codon = seq[i:i + 3]
            protein += table[codon].lower()
    return protein
protein = translate(DNA)
print(protein)

def mutation(seq):
    for i in range(0, len(seq), 3):
        dna_mut = seq[i:i]
        wt = random.choice(lista_codones)
        mutado = random.choice(codones)
        if wt != mutado:
            dna_mut += seq.replace(wt, mutado, 1)

    return dna_mut

dna_mut = mutation(DNA)

Body:
Maybe this can be of use:

import re
from random import randint

codones = ['ATA', 'ATC', 'ATT', 'ATG',
           'ACA', 'ACC', 'ACG', 'ACT',
           'AAC', 'AAT', 'AAA', 'AAG',
           'AGC', 'AGT', 'AGA', 'AGG',
           'CTA', 'CTC', 'CTG', 'CTT',
           'CCA', 'CCC', 'CCG', 'CCT',
           'CAC', 'CAT', 'CAA', 'CAG',
           'CGA', 'CGC', 'CGG', 'CGT',
           'GTA', 'GTC', 'GTG', 'GTT',
           'GCA', 'GCC', 'GCG', 'GCT',
           "GAC", 'GAT', 'GAA', 'GAG',
           'GGA', 'GGC', 'GGG', 'GGT',
           'TCA', 'TCC', 'TCG', 'TCT',
           'TTC', 'TTT', 'TTA', 'TTG',
           'TAC', 'TAT', 'TGC', 'TGT',
           'TGG']

dna_sequence = 'atgaaaagcatgaaaagc'

def replace_random_seq(dna: str, replace_list: list):
    sequences = re.findall("\w\w\w", dna)  # searches for 3 letter pattern in dna

    ran_index = sequences[randint(0, len(sequences)]  # get a random index of a sequence
    sequences[ran_index] = replace_list[randint(0, len(replace_list)]  # replace the item in the random index with a random sequence in the sequences list

    new_dna = ""
    for item in sequences:
        new_dna += item

    return new_dna

print(replace_random_seq(dna_sequence, codones))

Just used regex to find all 3-letter patterns and replace one with a different one from your list.


问:
npm start error with create-react-app
I have a project who I didn't touch for 2 weeks. I take it back and now when I try to run npm start I got this error.

```<code>> react-scripts start

sh: react-scripts: command not found

npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! UpScore@0.6.0 start: `react-scripts start`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the UpScore@0.6.0 start script 'react-scripts start'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the UpScore package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-scripts start
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs UpScore
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls UpScore
npm ERR! There is likely additional logging output above.
</code>```

node 6.7.0

npm 3.10.3

mac sierra 10.12

package.json

```<code>{
  "name": "UpScore",
  "version": "0.6.0",
  "private": true,
  "devDependencies": {
    "react-addons-test-utils": "^15.3.1",
    "react-scripts": "0.4.1",
    "react-test-renderer": "^15.3.1",
    "redux-logger": "^2.6.1"
  },
  "dependencies": {
    "@yoshokatana/medium-button": "^1.1.0",
    "axios": "^0.14.0",
    "bcrypt": "^0.8.7",
    "bcrypt-nodejs": "0.0.3",
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "draft-js": "^0.8.1",
    "draft-js-editor": "^1.7.2",
    "draft-js-export-html": "^0.4.0",
    "ejs": "^2.5.2",
    "email-verification": "^0.4.5",
    "express": "^4.14.0",
    "express-session": "^1.14.1",
    "flexboxgrid": "^6.3.1",
    "highlight.js": "^9.6.0",
    "immutable": "^3.8.1",
    "katex": "^0.6.0",
    "lodash": "^4.15.0",
    "markdown-it-mathjax": "^1.0.3",
    "material-ui": "^0.15.4",
    "medium-editor": "^5.22.0",
    "minutes-seconds-milliseconds": "^1.0.3",
    "moment": "^2.15.0",
    "moment-duration-format": "^1.3.0",
    "mongod": "^1.3.0",
    "mongodb": "^2.2.9",
    "mongoose": "^4.6.0",
    "monk": "^3.1.2",
    "morgan": "^1.7.0",
    "normalize.css": "^3.0.3",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "react-markdown": "^2.4.2",
    "react-medium-editor": "^1.8.1",
    "react-redux": "^4.4.5",
    "react-redux-form": "^0.14.5",
    "react-rich-markdown": "^1.0.1",
    "react-router": "^2.7.0",
    "react-router-redux": "^4.0.5",
    "react-tap-event-plugin": "^1.0.0",
    "react-tinymce": "^0.5.1",
    "redux": "^3.6.0",
    "redux-form": "^6.0.5",
    "redux-form-material-ui": "^4.0.1",
    "redux-promise-middleware": "^4.0.0",
    "redux-thunk": "^2.1.0",
    "reselect": "^2.5.3",
    "screenfull": "^3.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "start:prod": "pushstate-server build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "cd client/api && pm2 start server.js --watch",
    "proxy": "http://128.199.139.144:3000"
  },
  "eslintConfig": {
    "extends": "./node_modules/react-scripts/config/eslint.js"
  }
}
</code>```

I try to clone my repos too and get the same error. If someone can give me some way to find what happen. Thank you

答:
My issue was stemming from permission issues. I solved mine by following this
https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally</p>

Title: npm start error with create-react-app

Body:
I have a project who I didn't touch for 2 weeks. I take it back and now when I try to run npm start I got this error.

> react-scripts start

sh: react-scripts: command not found

npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! UpScore@0.6.0 start: `react-scripts start`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the UpScore@0.6.0 start script 'react-scripts start'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the UpScore package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-scripts start
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs UpScore
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls UpScore
npm ERR! There is likely additional logging output above.

node 6.7.0

npm 3.10.3

mac sierra 10.12

package.json

{
  "name": "UpScore",
  "version": "0.6.0",
  "private": true,
  "devDependencies": {
    "react-addons-test-utils": "^15.3.1",
    "react-scripts": "0.4.1",
    "react-test-renderer": "^15.3.1",
    "redux-logger": "^2.6.1"
  },
  "dependencies": {
    "@yoshokatana/medium-button": "^1.1.0",
    "axios": "^0.14.0",
    "bcrypt": "^0.8.7",
    "bcrypt-nodejs": "0.0.3",
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "draft-js": "^0.8.1",
    "draft-js-editor": "^1.7.2",
    "draft-js-export-html": "^0.4.0",
    "ejs": "^2.5.2",
    "email-verification": "^0.4.5",
    "express": "^4.14.0",
    "express-session": "^1.14.1",
    "flexboxgrid": "^6.3.1",
    "highlight.js": "^9.6.0",
    "immutable": "^3.8.1",
    "katex": "^0.6.0",
    "lodash": "^4.15.0",
    "markdown-it-mathjax": "^1.0.3",
    "material-ui": "^0.15.4",
    "medium-editor": "^5.22.0",
    "minutes-seconds-milliseconds": "^1.0.3",
    "moment": "^2.15.0",
    "moment-duration-format": "^1.3.0",
    "mongod": "^1.3.0",
    "mongodb": "^2.2.9",
    "mongoose": "^4.6.0",
    "monk": "^3.1.2",
    "morgan": "^1.7.0",
    "normalize.css": "^3.0.3",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "react-markdown": "^2.4.2",
    "react-medium-editor": "^1.8.1",
    "react-redux": "^4.4.5",
    "react-redux-form": "^0.14.5",
    "react-rich-markdown": "^1.0.1",
    "react-router": "^2.7.0",
    "react-router-redux": "^4.0.5",
    "react-tap-event-plugin": "^1.0.0",
    "react-tinymce": "^0.5.1",
    "redux": "^3.6.0",
    "redux-form": "^6.0.5",
    "redux-form-material-ui": "^4.0.1",
    "redux-promise-middleware": "^4.0.0",
    "redux-thunk": "^2.1.0",
    "reselect": "^2.5.3",
    "screenfull": "^3.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "start:prod": "pushstate-server build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "cd client/api && pm2 start server.js --watch",
    "proxy": "http://128.199.139.144:3000"
  },
  "eslintConfig": {
    "extends": "./node_modules/react-scripts/config/eslint.js"
  }
}

I try to clone my repos too and get the same error. If someone can give me some way to find what happen. Thank you


问:
How to parse the SubReddits JSON using Codable
The URL I used was "https://www.reddit.com/subreddits/.json" which will give you the JSON format of Reddit's Subreddits.

My Codable Struct Models are as follows:

```<code>struct SubredditsData: Codable {
    let data: SubredditData
}

struct SubredditData: Codable {
    let children: [Children]
}

struct Children: Codable {
    let data: ChildrenData
}

struct ChildrenData: Codable {
    let title: String
    let icon_img: String
    let display_name_prefixed: String
    let name: String
}
</code>```

and of course the Model for the Subreddit

```<code>struct SubredditsModel {
    let title: String
    let display_name_prefixed: String
    let name: String
}
</code>```

I then performed a request and the actual parsing itself

```<code>func parseSubRedditsJSON(_ subredditsRawData: Data) -> [SubredditsModel]? {
    let decoder = JSONDecoder()
    do {
        var subReddits = [SubredditsModel]()
        let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)
        let data = decodedData.data
        let children = data.children
        for item in children {
            let childrenData = item.data
            let title = childrenData.title
            let display_name_prefixed = childrenData.display_name_prefixed
            let name = childrenData.name
            let subReddit = SubredditsModel(title: title, display_name_prefixed: display_name_prefixed, name: name)
            subReddits.append(subReddit)
        }
        return subReddits
    } catch {
        subredditsDelegate?.didFailWithError(error: error)
        return nil
    }
}//end of parseSubRedditsJSON
</code>```

I'm returning the data to the view controller from the request manager via protocol delegate which works fine. The problem is I'm getting an error on this line

```<code>let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)
</code>```

The error says:

```<code>valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 5", intValue: 5),
CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "icon_img", intValue: nil)],
debugDescription: "Expected String value but found null instead.", underlyingError: nil))
</code>```

I must be missing something, or haven't implemented the correct way of parsing using Swift codable.

答:
Because of some of the fields are not optional, it may require string type or null, making it optional will solve this problem.</p>

```<code>struct SubredditsData: Codable {
    let data: SubredditData
 }

 struct SubredditData: Codable {
    let children: [Children]
 }

 struct Children: Codable {
   let data: ChildrenData
 }

 struct ChildrenData: Codable {
   let title: String?
   let icon_img: String?
   let display_name_prefixed: String?
   let name: String?
 }
</code>```

Body:
The URL I used was "https://www.reddit.com/subreddits/.json" which will give you the JSON format of Reddit's Subreddits.

My Codable Struct Models are as follows:

struct SubredditsData: Codable {
    let data: SubredditData
}

struct SubredditData: Codable {
    let children: [Children]
}

struct Children: Codable {
    let data: ChildrenData
}

struct ChildrenData: Codable {
    let title: String
    let icon_img: String
    let display_name_prefixed: String
    let name: String
}

and of course the Model for the Subreddit

struct SubredditsModel {
    let title: String
    let display_name_prefixed: String
    let name: String
}

I then performed a request and the actual parsing itself

func parseSubRedditsJSON(_ subredditsRawData: Data) -> [SubredditsModel]? {
    let decoder = JSONDecoder()
    do {
        var subReddits = [SubredditsModel]()
        let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)
        let data = decodedData.data
        let children = data.children
        for item in children {
            let childrenData = item.data
            let title = childrenData.title
            let display_name_prefixed = childrenData.display_name_prefixed
            let name = childrenData.name
            let subReddit = SubredditsModel(title: title, display_name_prefixed: display_name_prefixed, name: name)
            subReddits.append(subReddit)
        }
        return subReddits
    } catch {
        subredditsDelegate?.didFailWithError(error: error)
        return nil
    }
}//end of parseSubRedditsJSON

I'm returning the data to the view controller from the request manager via protocol delegate which works fine. The problem is I'm getting an error on this line

let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)

The error says:

valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 5", intValue: 5),
CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "icon_img", intValue: nil)],
debugDescription: "Expected String value but found null instead.", underlyingError: nil))

I must be missing something, or haven't implemented the correct way of parsing using Swift codable.

Body:
Because of some of the fields are not optional, it may require string type or null, making it optional will solve this problem.

struct SubredditsData: Codable {
    let data: SubredditData
 }

 struct SubredditData: Codable {
    let children: [Children]
 }

 struct Children: Codable {
   let data: ChildrenData
 }

 struct ChildrenData: Codable {
   let title: String?
   let icon_img: String?
   let display_name_prefixed: String?
   let name: String?
 }


问:
javascript how insert "empty" to array?

var array = new Array(5);
array[0] = 1;
array[1] = 1;
array[3] = 1;
array[4] = 1;
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //false
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true```
</div>
</div>
</p>

<p>I want to insert array that have unsetted element.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [1,1]
var arrayToInsert = new Array(3);
arrayToInsert[0] = 1;
arrayToInsert[2] = 1;
array.splice(1, 0, ...arrayToInsert);
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //true, I want to make it false.
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true</code>```

How keep unsetted element after I splice(insert) array that have unsetted element?

答:
Not sure to understand your question, but if you want to unset a value from your array (so, setting it as undefined), you can delete the array element:

const a = [1, 2, 3, 4];
console.log(a);

delete(a[2]);
console.log(a);```

Title: javascript how insert "empty" to array?

Body:
var array = new Array(5);
array[0] = 1;
array[1] = 1;
array[3] = 1;
array[4] = 1;
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //false
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true

I want to insert array that have unsetted element.

var array = [1,1]
var arrayToInsert = new Array(3);
arrayToInsert[0] = 1;
arrayToInsert[2] = 1;
array.splice(1, 0, ...arrayToInsert);
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //true, I want to make it false.
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true

How keep unsetted element after I splice(insert) array that have unsetted element?


问:
Readonly connection string to an access database
I'm trying to connect to an Access database file using a System.Data.OleDb.OleDbConnection.  I need to connect in readonly mode because another application uses it at the same time.  I can connect to the database in read/write no problem but can't seem to find anywhere the correct string for readonly.

I've tried:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;Mode=Read

Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;Extended Properties="ReadOnly=true;"

Thanks.

EDIT:

(I should have put more information in the original question.)

I could connect successfully to the access database when it was on the local machine, but when I tried connecting to the access database on a remote machine with the connection string

```<code>Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;Mode=Read
</code>```

I would get the following error:

```<code>System.Data.OleDb.OleDbException (0x80004005): The Microsoft Office Access database engine cannot open or write to the file '{0}'. It is already opened exclusively by another user, or you need permission to view and write its data.
</code>```

My application is running in a windows service under the local system account.

答: I think that has to be handled either by user permissions that the DB admin would control, or with different cursor types for your recordsets, which you would control.  I don't think the connection string specifies access mode, it just gets you there. ;)</p>

Body:
I'm trying to connect to an Access database file using a System.Data.OleDb.OleDbConnection.  I need to connect in readonly mode because another application uses it at the same time.  I can connect to the database in read/write no problem but can't seem to find anywhere the correct string for readonly.

I've tried:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;Mode=Read

Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;Extended Properties="ReadOnly=true;"

Thanks.

EDIT:

(I should have put more information in the original question.)

I could connect successfully to the access database when it was on the local machine, but when I tried connecting to the access database on a remote machine with the connection string

Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;Mode=Read

I would get the following error:

System.Data.OleDb.OleDbException (0x80004005): The Microsoft Office Access database engine cannot open or write to the file '{0}'. It is already opened exclusively by another user, or you need permission to view and write its data.

My application is running in a windows service under the local system account.


问:
Entity Framework Core: A second operation started on this context before a previous operation completed
I'm working on a ASP.Net Core 2.0 project using Entity Framework Core

```<code><PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0"/>
</code>```

And in one of my list methods I'm getting this error:

```<code>InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
</code>```

This is my method:

```<code>    [HttpGet("{currentPage}/{pageSize}/")]
    [HttpGet("{currentPage}/{pageSize}/{search}")]
    public ListResponseVM<ClientVM> GetClients([FromRoute] int currentPage, int pageSize, string search)
    {
        var resp = new ListResponseVM<ClientVM>();
        var items = _context.Clients
            .Include(i => i.Contacts)
            .Include(i => i.Addresses)
            .Include("ClientObjectives.Objective")
            .Include(i => i.Urls)
            .Include(i => i.Users)
            .Where(p => string.IsNullOrEmpty(search) || p.CompanyName.Contains(search))
            .OrderBy(p => p.CompanyName)
            .ToPagedList(pageSize, currentPage);

        resp.NumberOfPages = items.TotalPage;

        foreach (var item in items)
        {
            var client = _mapper.Map<ClientVM>(item);

            client.Addresses = new List<AddressVM>();
            foreach (var addr in item.Addresses)
            {
                var address = _mapper.Map<AddressVM>(addr);
                address.CountryCode = addr.CountryId;
                client.Addresses.Add(address);
            }

            client.Contacts = item.Contacts.Select(p => _mapper.Map<ContactVM>(p)).ToList();
            client.Urls = item.Urls.Select(p => _mapper.Map<ClientUrlVM>(p)).ToList();
            client.Objectives = item.Objectives.Select(p => _mapper.Map<ObjectiveVM>(p)).ToList();
            resp.Items.Add(client);
        }

        return resp;
    }
</code>```

I'm a bit lost especially because it works when I run it locally, but when I deploy to my staging server (IIS 8.5) it gets me this error and it was working normally. The error started to appear after I increase the max length of one of my models. I also updated the max length of the corresponding View Model. And there are many other list methods that are very similar and they are working.

I had a Hangfire job running, but this job doesn't use the same entity. That's all I can think to be relevant. Any ideas of what could be causing this?

答:
First, upvote (at the least) alsami's answer.  That got me on the right path.

But for those of you doing IoC, here is a little bit of a deeper dive.

My error (same as others)

One or more errors occurred. (A second operation started on this
  context before a previous operation completed. This is usually caused
  by different threads using the same instance of DbContext. For more
  information on how to avoid threading issues with DbContext, see
  https://go.microsoft.com/fwlink/?linkid=2097913.)

My code setup.  "Just the basics"...

```<code>public class MyCoolDbContext: DbContext{
    public DbSet <MySpecialObject> MySpecialObjects {        get;        set;    }
}
</code>```

and

```<code>public interface IMySpecialObjectDomainData{}
</code>```

and (note MyCoolDbContext is being injected)

```<code>public class MySpecialObjectEntityFrameworkDomainDataLayer: IMySpecialObjectDomainData{
    public MySpecialObjectEntityFrameworkDomainDataLayer(MyCoolDbContext context) {
        /* HERE IS WHERE TO SET THE BREAK POINT, HOW MANY TIMES IS THIS RUNNING??? */
        this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);
    }
}
</code>```

and

```<code>public interface IMySpecialObjectManager{}
</code>```

and

```<code>public class MySpecialObjectManager: IMySpecialObjectManager
{
    public const string ErrorMessageIMySpecialObjectDomainDataIsNull = "IMySpecialObjectDomainData is null";
    private readonly IMySpecialObjectDomainData mySpecialObjectDomainData;

    public MySpecialObjectManager(IMySpecialObjectDomainData mySpecialObjectDomainData) {
        this.mySpecialObjectDomainData = mySpecialObjectDomainData ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectDomainDataIsNull, (Exception)null);
    }
}
</code>```

And finally , my multi threaded class, being called from a Console App(Command Line Interface app)

```<code>    public interface IMySpecialObjectThatSpawnsThreads{}
</code>```

and

```<code>public class MySpecialObjectThatSpawnsThreads: IMySpecialObjectThatSpawnsThreads
{
    public const string ErrorMessageIMySpecialObjectManagerIsNull = "IMySpecialObjectManager is null";

    private readonly IMySpecialObjectManager mySpecialObjectManager;

    public MySpecialObjectThatSpawnsThreads(IMySpecialObjectManager mySpecialObjectManager) {
        this.mySpecialObjectManager = mySpecialObjectManager ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectManagerIsNull, (Exception)null);
    }
}
</code>```

and the DI buildup.  (Again, this is for a console application (command line interface)...which exhibits slight different behavior than web-apps)

```<code>private static IServiceProvider BuildDi(IConfiguration configuration) {
    /* this is being called early inside my command line application ("console application") */

    string defaultConnectionStringValue = string.Empty; /* get this value from configuration */

    ////setup our DI
    IServiceCollection servColl = new ServiceCollection()
        ////.AddLogging(loggingBuilder => loggingBuilder.AddConsole())

        /* THE BELOW TWO ARE THE ONES THAT TRIPPED ME UP.  */
        .AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
    .AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()

    /* so the "ServiceLifetime.Transient" below................is what you will find most commonly on the internet search results */
     # if (MY_ORACLE)
        .AddDbContext<ProvisioningDbContext>(options => options.UseOracle(defaultConnectionStringValue), ServiceLifetime.Transient);
     # endif

     # if (MY_SQL_SERVER)
        .AddDbContext<ProvisioningDbContext>(options => options.UseSqlServer(defaultConnectionStringValue), ServiceLifetime.Transient);
     # endif

    servColl.AddSingleton <IMySpecialObjectThatSpawnsThreads,        MySpecialObjectThatSpawnsThreads>();

    ServiceProvider servProv = servColl.BuildServiceProvider();

    return servProv;
}
</code>```

The ones that surprised me were the (change to) transient for

```<code>        .AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
    .AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()
</code>```

Note, I think because IMySpecialObjectManager was being injected into "MySpecialObjectThatSpawnsThreads", those injected objects needed to be Transient to complete the chain.

The point being.......it wasn't just the (My)DbContext that needed .Transient...but a bigger chunk of the DI Graph.

Debugging Tip:

This line:

```<code>this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);
</code>```

Put your debugger break point there.  If your MySpecialObjectThatSpawnsThreads is making N number of threads (say 10 threads for example)......and that line is only being hit once...that's your issue.  Your DbContext is crossing threads.

BONUS:

I would suggest reading this below url/article (oldie but goodie) about the differences web-apps and console-apps

https://mehdi.me/ambient-dbcontext-in-ef6/

Here is the header of the article in case the link changes.

MANAGING DBCONTEXT THE RIGHT WAY WITH ENTITY FRAMEWORK 6: AN IN-DEPTH
  GUIDE Mehdi El Gueddari

I hit this issue with WorkFlowCore  https://github.com/danielgerlag/workflow-core

```<code>public interface IMySpecialObjectDomainData{}
</code>```0

sample code below.. to help future internet searchers

```<code>public interface IMySpecialObjectDomainData{}
</code>```1

and

```<code>public interface IMySpecialObjectDomainData{}
</code>```2

Body:
I'm working on a ASP.Net Core 2.0 project using Entity Framework Core

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0"/>

And in one of my list methods I'm getting this error:

InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()

This is my method:

    [HttpGet("{currentPage}/{pageSize}/")]
    [HttpGet("{currentPage}/{pageSize}/{search}")]
    public ListResponseVM<ClientVM> GetClients([FromRoute] int currentPage, int pageSize, string search)
    {
        var resp = new ListResponseVM<ClientVM>();
        var items = _context.Clients
            .Include(i => i.Contacts)
            .Include(i => i.Addresses)
            .Include("ClientObjectives.Objective")
            .Include(i => i.Urls)
            .Include(i => i.Users)
            .Where(p => string.IsNullOrEmpty(search) || p.CompanyName.Contains(search))
            .OrderBy(p => p.CompanyName)
            .ToPagedList(pageSize, currentPage);

        resp.NumberOfPages = items.TotalPage;

        foreach (var item in items)
        {
            var client = _mapper.Map<ClientVM>(item);

            client.Addresses = new List<AddressVM>();
            foreach (var addr in item.Addresses)
            {
                var address = _mapper.Map<AddressVM>(addr);
                address.CountryCode = addr.CountryId;
                client.Addresses.Add(address);
            }

            client.Contacts = item.Contacts.Select(p => _mapper.Map<ContactVM>(p)).ToList();
            client.Urls = item.Urls.Select(p => _mapper.Map<ClientUrlVM>(p)).ToList();
            client.Objectives = item.Objectives.Select(p => _mapper.Map<ObjectiveVM>(p)).ToList();
            resp.Items.Add(client);
        }

        return resp;
    }

I'm a bit lost especially because it works when I run it locally, but when I deploy to my staging server (IIS 8.5) it gets me this error and it was working normally. The error started to appear after I increase the max length of one of my models. I also updated the max length of the corresponding View Model. And there are many other list methods that are very similar and they are working.

I had a Hangfire job running, but this job doesn't use the same entity. That's all I can think to be relevant. Any ideas of what could be causing this?

Body:
First, upvote (at the least) alsami's answer.  That got me on the right path.

But for those of you doing IoC, here is a little bit of a deeper dive.

My error (same as others)

One or more errors occurred. (A second operation started on this
  context before a previous operation completed. This is usually caused
  by different threads using the same instance of DbContext. For more
  information on how to avoid threading issues with DbContext, see
  https://go.microsoft.com/fwlink/?linkid=2097913.)

My code setup.  "Just the basics"...

public class MyCoolDbContext: DbContext{
    public DbSet <MySpecialObject> MySpecialObjects {        get;        set;    }
}

and

public interface IMySpecialObjectDomainData{}

and (note MyCoolDbContext is being injected)

public class MySpecialObjectEntityFrameworkDomainDataLayer: IMySpecialObjectDomainData{
    public MySpecialObjectEntityFrameworkDomainDataLayer(MyCoolDbContext context) {
        /* HERE IS WHERE TO SET THE BREAK POINT, HOW MANY TIMES IS THIS RUNNING??? */
        this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);
    }
}

and

public interface IMySpecialObjectManager{}

and

public class MySpecialObjectManager: IMySpecialObjectManager
{
    public const string ErrorMessageIMySpecialObjectDomainDataIsNull = "IMySpecialObjectDomainData is null";
    private readonly IMySpecialObjectDomainData mySpecialObjectDomainData;

    public MySpecialObjectManager(IMySpecialObjectDomainData mySpecialObjectDomainData) {
        this.mySpecialObjectDomainData = mySpecialObjectDomainData ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectDomainDataIsNull, (Exception)null);
    }
}

And finally , my multi threaded class, being called from a Console App(Command Line Interface app)

    public interface IMySpecialObjectThatSpawnsThreads{}

and

public class MySpecialObjectThatSpawnsThreads: IMySpecialObjectThatSpawnsThreads
{
    public const string ErrorMessageIMySpecialObjectManagerIsNull = "IMySpecialObjectManager is null";

    private readonly IMySpecialObjectManager mySpecialObjectManager;

    public MySpecialObjectThatSpawnsThreads(IMySpecialObjectManager mySpecialObjectManager) {
        this.mySpecialObjectManager = mySpecialObjectManager ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectManagerIsNull, (Exception)null);
    }
}

and the DI buildup.  (Again, this is for a console application (command line interface)...which exhibits slight different behavior than web-apps)

private static IServiceProvider BuildDi(IConfiguration configuration) {
    /* this is being called early inside my command line application ("console application") */

    string defaultConnectionStringValue = string.Empty; /* get this value from configuration */

    ////setup our DI
    IServiceCollection servColl = new ServiceCollection()
        ////.AddLogging(loggingBuilder => loggingBuilder.AddConsole())

        /* THE BELOW TWO ARE THE ONES THAT TRIPPED ME UP.  */
        .AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
    .AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()

    /* so the "ServiceLifetime.Transient" below................is what you will find most commonly on the internet search results */
     # if (MY_ORACLE)
        .AddDbContext<ProvisioningDbContext>(options => options.UseOracle(defaultConnectionStringValue), ServiceLifetime.Transient);
     # endif

     # if (MY_SQL_SERVER)
        .AddDbContext<ProvisioningDbContext>(options => options.UseSqlServer(defaultConnectionStringValue), ServiceLifetime.Transient);
     # endif

    servColl.AddSingleton <IMySpecialObjectThatSpawnsThreads,        MySpecialObjectThatSpawnsThreads>();

    ServiceProvider servProv = servColl.BuildServiceProvider();

    return servProv;
}

The ones that surprised me were the (change to) transient for

        .AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
    .AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()

Note, I think because IMySpecialObjectManager was being injected into "MySpecialObjectThatSpawnsThreads", those injected objects needed to be Transient to complete the chain.

The point being.......it wasn't just the (My)DbContext that needed .Transient...but a bigger chunk of the DI Graph.

Debugging Tip:

This line:

this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);

Put your debugger break point there.  If your MySpecialObjectThatSpawnsThreads is making N number of threads (say 10 threads for example)......and that line is only being hit once...that's your issue.  Your DbContext is crossing threads.

BONUS:

I would suggest reading this below url/article (oldie but goodie) about the differences web-apps and console-apps

https://mehdi.me/ambient-dbcontext-in-ef6/

Here is the header of the article in case the link changes.

MANAGING DBCONTEXT THE RIGHT WAY WITH ENTITY FRAMEWORK 6: AN IN-DEPTH
  GUIDE Mehdi El Gueddari

I hit this issue with WorkFlowCore  https://github.com/danielgerlag/workflow-core

  <ItemGroup>
    <PackageReference Include="WorkflowCore" Version="3.1.5" />
  </ItemGroup>

sample code below.. to help future internet searchers

 namespace MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Workflows
    {
        using System;
        using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Constants;
        using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Glue;
        using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.WorkflowSteps;

        using WorkflowCore.Interface;
        using WorkflowCore.Models;

        public class MySpecialObjectInterviewDefaultWorkflow : IWorkflow<MySpecialObjectInterviewPassThroughData>
        {
            public const string WorkFlowId = "MySpecialObjectInterviewWorkflowId";

            public const int WorkFlowVersion = 1;

            public string Id => WorkFlowId;

            public int Version => WorkFlowVersion;

            public void Build(IWorkflowBuilder<MySpecialObjectInterviewPassThroughData> builder)
            {
                builder
                             .StartWith(context =>
                    {
                        Console.WriteLine("Starting workflow...");
                        return ExecutionResult.Next();
                    })

                        /* bunch of other Steps here that were using IMySpecialObjectManager.. here is where my DbContext was getting cross-threaded */

                    .Then(lastContext =>
                    {
                        Console.WriteLine();

                        bool wroteConcreteMsg = false;
                        if (null != lastContext && null != lastContext.Workflow && null != lastContext.Workflow.Data)
                        {
                            MySpecialObjectInterviewPassThroughData castItem = lastContext.Workflow.Data as MySpecialObjectInterviewPassThroughData;
                            if (null != castItem)
                            {
                                Console.WriteLine("MySpecialObjectInterviewDefaultWorkflow complete :)  {0}   -> {1}", castItem.PropertyOne, castItem.PropertyTwo);
                                wroteConcreteMsg = true;
                            }
                        }

                        if (!wroteConcreteMsg)
                        {
                            Console.WriteLine("MySpecialObjectInterviewDefaultWorkflow complete (.Data did not cast)");
                        }

                        return ExecutionResult.Next();
                    }))

                    .OnError(WorkflowCore.Models.WorkflowErrorHandling.Retry, TimeSpan.FromSeconds(60));

            }
        }
    }

and

ICollection<string> workFlowGeneratedIds = new List<string>();
                for (int i = 0; i < 10; i++)
                {
                    MySpecialObjectInterviewPassThroughData currentMySpecialObjectInterviewPassThroughData = new MySpecialObjectInterviewPassThroughData();
                    currentMySpecialObjectInterviewPassThroughData.MySpecialObjectInterviewPassThroughDataSurrogateKey = i;

                    ////  private readonly IWorkflowHost workflowHost;
                    string wfid = await this.workflowHost.StartWorkflow(MySpecialObjectInterviewDefaultWorkflow.WorkFlowId, MySpecialObjectInterviewDefaultWorkflow.WorkFlowVersion, currentMySpecialObjectInterviewPassThroughData);
                    workFlowGeneratedIds.Add(wfid);
                }


问:
login as a user and admin at the same time in laravel
I am working on a laravel project in which from ADMIN panel I can log in in the user module, but when I want to go back from the browser the admin panel is not working means admin is logout. is there any method in which I can log in in both module admin and user.</p>

答: Use an incognito browser window for your admin tasks, which will enable you to be logged in to the same app twice.</p>


问:
Currently we are using image as checkbox using CSS now when I click the checkbox i want to hide the image and show the background color
Currently we are using image as checkbox using CSS
now when I click the checkbox
I want to hide the image and show the background color.

My Demo is:

What I need?

答:
I have just hidden the checkbox. This works with HTML and CSS alone.

Hope this helps you.

.demofile label {
  margin: 10px;
}

.demofile {
  position: relative;
  width: 100px;
  float: left;
  margin: 10px;
  display: table;
}

.demofile label span {
  position: absolute;
  top: 40px;
  left: 0;
  width: 100%;
  text-align: center;
}

.demofile label img {
  height: 100px;
  width: 100px;
  opacity: 1;
}

.demofile input[type=checkbox]:checked+label img {
  opacity: 0.5;
}

.demofile input[type=checkbox]:checked+label .bgcolor {
  background: green;
  height: 100px;
  width: 100px;
  left: 0;
  top: 0;
  position: absolute;
  margin: 0 10px;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="demofile">
  <input type="checkbox" id="n1" name="n1" style="display: none;" /><label for="n1"><img src="https://www.kcloudtechnologies.com/wp-content/uploads/2016/04/dummy-post-square-1-300x300.jpg" width="20" height="20" />
<div class="bgcolor"><span>text value</span></div>
</label>
</div>

<div class="demofile">
  <input type="checkbox" id="n2" name="n2" style="display: none;" /><label for="n2"><img src="https://www.kcloudtechnologies.com/wp-content/uploads/2016/04/dummy-post-square-1-300x300.jpg" width="20" height="20" />
<div class="bgcolor"><span>text value</span></div>
</label>
</div>

<div class="demofile">
  <input type="checkbox" id="n50" name="n50" style="display: none;" /><label for="n50"><img src="https://www.kcloudtechnologies.com/wp-content/uploads/2016/04/dummy-post-square-1-300x300.jpg" width="20" height="20" />
<div class="bgcolor"><span>text value</span></div>
</label>
</div></code>```

Body:
I have just hidden the checkbox. This works with HTML and CSS alone.

Hope this helps you.

.demofile label {
  margin: 10px;
}

.demofile {
  position: relative;
  width: 100px;
  float: left;
  margin: 10px;
  display: table;
}

.demofile label span {
  position: absolute;
  top: 40px;
  left: 0;
  width: 100%;
  text-align: center;
}

.demofile label img {
  height: 100px;
  width: 100px;
  opacity: 1;
}

.demofile input[type=checkbox]:checked+label img {
  opacity: 0.5;
}

.demofile input[type=checkbox]:checked+label .bgcolor {
  background: green;
  height: 100px;
  width: 100px;
  left: 0;
  top: 0;
  position: absolute;
  margin: 0 10px;
  color: #fff;
}

<div class="demofile">
  <input type="checkbox" id="n1" name="n1" style="display: none;" /><label for="n1"><img src="https://www.kcloudtechnologies.com/wp-content/uploads/2016/04/dummy-post-square-1-300x300.jpg" width="20" height="20" />
<div class="bgcolor"><span>text value</span></div>
</label>
</div>

<div class="demofile">
  <input type="checkbox" id="n2" name="n2" style="display: none;" /><label for="n2"><img src="https://www.kcloudtechnologies.com/wp-content/uploads/2016/04/dummy-post-square-1-300x300.jpg" width="20" height="20" />
<div class="bgcolor"><span>text value</span></div>
</label>
</div>

<div class="demofile">
  <input type="checkbox" id="n50" name="n50" style="display: none;" /><label for="n50"><img src="https://www.kcloudtechnologies.com/wp-content/uploads/2016/04/dummy-post-square-1-300x300.jpg" width="20" height="20" />
<div class="bgcolor"><span>text value</span></div>
</label>
</div>


问:
Xcode does not detect custom font
I added custom font in xcode, target membership is checked but it does not seen in custom fonts menu.

target membership

location

info.plist

copy bundle resources

答:
You should add your custom font to info.plist too. did you do that ?
you should add a row with Fonts provided by application and enter your font names in that array

Title: Xcode does not detect custom font