问:
Problem Connecting to WCF Service on a Server
I have set up a WCF service on a server which lives in its own Workgroup.  I've tried to make a TCP/IP connection to it from a client that lives on the corporate domain.  When I try to open a connection, I get a SecurityNegotiationException with the message:

"A remote side security requirement
  was not fulfilled during
  authentication.  Try increasing the
  ProtectionLevel and/or
  ImpersonationLevel." The inner
  exception reads: "The network logon
  failed"

After speaking with some coworkers about the issues and performing some google research, I came to the conclusion that the issue is that the client is attempting to log on to the server using my corporate network login and password.  Since the server is not part of the corporate network, it has no knowledge of my corporate identity and then rejects the login / connection attempt.  Whether this analysis is correct or not, I have no idea.

Google results seem to suggest that perhaps the solution is that I need to impersonate user account that exists on the server machine.   --I have also stumbled across this codeproject article which demonstrates user impersonation.  Since the only account on the server is Administrator with no password, I tried domain as the computer's ip address as "10.0.0.11", username as "Administrator", and password as "".
http://www.codeproject.com/KB/dotnet/UserImpersonationInNET.aspx?display=Print
Unfortunately, it fails with the message:

"Logon failure: unknown user name or bad password"

Another hint to the problem: When the client and server are both machines on the corporate network, there are no connection problems at all.

How can I resolve the error and complete the connection to the server?
Even though it is not a best practice, I am completely okay with removing any security so I can keep this project moving forward

答:
I know of no way to have a workgroup trust a domain, which means you have a couple of choices, as i see it

Add another endpoint in your WCF service that uses HTTP (a web service endpoint) and use this from the domain. This gets around the security problem, as you can impersonate here, or even set up a specific user that can access goodies in your workgroup server.

Whack down security in the WCF service. i would have to think about how to do this, but it is not a good idea anyway.

Create a domain and get a trust relationship.

The code project you mentioned is not dealing with impersonation in a way that is directly useful to WCF, as the authentication happens before you can even hit this code. I imagine you can whack at the framework bits to do it, but that would be nasty. There might be a way to use the code in an HTTP endpoint, but that can already be done without incurring the overhead of adding code that circumvents windows security.

OwnerDisplayName: MedicineMan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: MedicineMan

OwnerDisplayName: Gregory A Beamer


来源: stackexchange

问:
Which date class should I use in Android?
I'm making a small Calendar application with some specific functions for my userbase but I'm not sure which calendar that is best to use. I've been using the internal Calendar class so far but recently noticed that I probably should have used GregorianCalendar instead.

So I'm about to change Calendar but wanted to know if thats the calendar I should use or if there is any better alternative. I was looking a bit at JodaTime but it seem to have some performance problem on Android phones. I also found a library called Date4J. Anyone who has tested either of them on Android and can recommend them? Or should I stick with the internal classes?

答: android.text.format.Time is "a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes".  It's what I prefer to use, unless I want some of the fancy things offered by Joda-Time.</p>

ContentLicense: CC BY-SA 3.0


问:
Trigger an alert at a specific time on Google Script
I'm very new to scripting so if anyone knows how to do this it'd be great help!

I have a user that logs in on business days at ~9 am, and has to do something before 9.30 am. To remind and insist that it's done I want to have an alert that says to do it, if a certain cell is not empty. Ideally it would check at 9, 9.10, 9.20 and 9.30, and pop up each time until it's done.

I tried to set up a trigger every 10 minutes, but I read that you can't use triggers with UI.

```<code>function startCustomTrigger()
{
  ScriptApp.newTrigger('alerta').timeBased().everyMinutes(10).create();
}
</code>```

So I thought of making it an onEdit script when new date().getMinutes() is 0/10/20/30, and it worked, but then it keeps popping up when you continue working on the sheet for the whole minute.  Adding new date().getSeconds() doesn't work because it's too short of a time window and easy to miss.

This is my current code:

```<code>function alerta() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var s = ss.getActiveSheet();
  var motosS = ss.getSheetByName("Motos - mañana");
  var motosRange = motosS.getRange(3, 1)
  var ui = SpreadsheetApp.getUi();
  var date = new Date();
  var day = date.getDay();
  var hrs = date.getHours();
  var min = date.getMinutes()
  var sec = date.getSeconds()

  Logger.log(date)
  Logger.log(day)
  Logger.log(hrs)
  Logger.log(min)
  Logger.log(sec)

  if (motosRange == "" && (day >= 1) && (day <= 5) && (hrs = 9)){
      if (min == 0 || min == 14 || min == 20 || min == 30){
      var response = ui.alert('IMPRIMIR MOTOS PARA LA MAÑANA',
                            "Hay que anotar el sector de las ventas de ayer e imprimir las motos para la mañana.",
                            ui.ButtonSet.OK_CANCEL);
                         }
  }
  }
</code>```

答:
Use Script properties to store the alert status between function calls

Explanation

Script properties allow you to cache variables which are accessible by the subsequent script run

Create a property that is set to true if the alert has been shown already

Set the property back to false once one minute (or any other timespan you desire) has passed

The latter can be done with a time-driven trigger, or - easier - with Utilities.sleep().

The idea is that you check within the if statement the status of your boolean and do not show the alert again while the variable is true

Sample:

```<code>function alerta() {
  //initial setup
  if(!PropertiesService.getScriptProperties().getProperty("alreadyNotified")){
    PropertiesService.getScriptProperties().setProperty("alreadyNotified", false)
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var s = ss.getActiveSheet();
  var motosS = ss.getSheetByName("Motos - mañana");
  var motosRange = motosS.getRange(3, 1).getValue()
  var ui = SpreadsheetApp.getUi();
  var date = new Date();
  var day = date.getDay();
  var hrs = date.getHours();
  var min = date.getMinutes()
  var sec = date.getSeconds()

  Logger.log(date)
  Logger.log(day)
  Logger.log(hrs)
  Logger.log(min)
  Logger.log(sec)
  var alertStatus = PropertiesService.getScriptProperties().getProperty("alreadyNotified");
  //put "false" in quotes because Scriptproperties store the value as a string
  if (alertStatus == "false" && motosRange == "" && (day >= 1) && (day <= 5) && (hrs = 9)){
    if (min == 0 || min == 14 || min == 20 || min == 30){
      PropertiesService.getScriptProperties().setProperty("alreadyNotified", true);
      var response = ui.alert('IMPRIMIR MOTOS PARA LA MAÑANA',
                              "Hay que anotar el sector de las ventas de ayer e imprimir las motos para la mañana.",
                              ui.ButtonSet.OK_CANCEL);
      Utilities.sleep(60*1000);
      PropertiesService.getScriptProperties().setProperty("alreadyNotified", false);
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm very new to scripting so if anyone knows how to do this it'd be great help!

I have a user that logs in on business days at ~9 am, and has to do something before 9.30 am. To remind and insist that it's done I want to have an alert that says to do it, if a certain cell is not empty. Ideally it would check at 9, 9.10, 9.20 and 9.30, and pop up each time until it's done.

I tried to set up a trigger every 10 minutes, but I read that you can't use triggers with UI.

function startCustomTrigger()
{
  ScriptApp.newTrigger('alerta').timeBased().everyMinutes(10).create();
}

So I thought of making it an onEdit script when new date().getMinutes() is 0/10/20/30, and it worked, but then it keeps popping up when you continue working on the sheet for the whole minute.  Adding new date().getSeconds() doesn't work because it's too short of a time window and easy to miss.

This is my current code:

function alerta() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var s = ss.getActiveSheet();
  var motosS = ss.getSheetByName("Motos - mañana");
  var motosRange = motosS.getRange(3, 1)
  var ui = SpreadsheetApp.getUi();
  var date = new Date();
  var day = date.getDay();
  var hrs = date.getHours();
  var min = date.getMinutes()
  var sec = date.getSeconds()

  Logger.log(date)
  Logger.log(day)
  Logger.log(hrs)
  Logger.log(min)
  Logger.log(sec)

  if (motosRange == "" && (day >= 1) && (day <= 5) && (hrs = 9)){
      if (min == 0 || min == 14 || min == 20 || min == 30){
      var response = ui.alert('IMPRIMIR MOTOS PARA LA MAÑANA',
                            "Hay que anotar el sector de las ventas de ayer e imprimir las motos para la mañana.",
                            ui.ButtonSet.OK_CANCEL);
                         }
  }
  }

Body:
Use Script properties to store the alert status between function calls

Explanation

Script properties allow you to cache variables which are accessible by the subsequent script run

Create a property that is set to true if the alert has been shown already

Set the property back to false once one minute (or any other timespan you desire) has passed

The latter can be done with a time-driven trigger, or - easier - with Utilities.sleep().

The idea is that you check within the if statement the status of your boolean and do not show the alert again while the variable is true

Sample:

function alerta() {
  //initial setup
  if(!PropertiesService.getScriptProperties().getProperty("alreadyNotified")){
    PropertiesService.getScriptProperties().setProperty("alreadyNotified", false)
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var s = ss.getActiveSheet();
  var motosS = ss.getSheetByName("Motos - mañana");
  var motosRange = motosS.getRange(3, 1).getValue()
  var ui = SpreadsheetApp.getUi();
  var date = new Date();
  var day = date.getDay();
  var hrs = date.getHours();
  var min = date.getMinutes()
  var sec = date.getSeconds()

  Logger.log(date)
  Logger.log(day)
  Logger.log(hrs)
  Logger.log(min)
  Logger.log(sec)
  var alertStatus = PropertiesService.getScriptProperties().getProperty("alreadyNotified");
  //put "false" in quotes because Scriptproperties store the value as a string
  if (alertStatus == "false" && motosRange == "" && (day >= 1) && (day <= 5) && (hrs = 9)){
    if (min == 0 || min == 14 || min == 20 || min == 30){
      PropertiesService.getScriptProperties().setProperty("alreadyNotified", true);
      var response = ui.alert('IMPRIMIR MOTOS PARA LA MAÑANA',
                              "Hay que anotar el sector de las ventas de ayer e imprimir las motos para la mañana.",
                              ui.ButtonSet.OK_CANCEL);
      Utilities.sleep(60*1000);
      PropertiesService.getScriptProperties().setProperty("alreadyNotified", false);
    }
  }
}


问:
How to declare variables for Win32 APIs?
I'd like a general guide for how to write VBA declare statements for using arbitrary Win32 APIs. Not a list of declare statements for some selection of Win32 APIs (which probably doesn't include the API I'm looking for now or the one I'll be looking for six months from now).

A general guide would educate me on how different C / Win32 data types should be handled. For both 32-bit or 64-bit Office.

This topic on adapting VBA for 64-bit Office tells me I can use LongPtr and that Office 32-bit or 64-bit will adapt that as appropriate. That's only useful if I know when a Long was needed for 32-bit.

This VB.Net topic says 'As Any' isn't supported but that's VB.Net, not VBA.  I gather that 'As Any' is appropriate for VBA but when do I use it? For APIs that take VOID or pVOID or LPVOID?

As a specific example, I need to adapt this declare:

```<code>Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSrc As Any, ByVal ByteLen As Long)
</code>```

Per MSDN, the last parameter is SIZE_T:

```<code>void CopyMemory(
_In_       PVOID  Destination,
_In_ const VOID   *Source,
_In_       SIZE_T Length
);
</code>```

I've seen some adaptations for 64-bit Office leave this in the declare as ByVal ... As Long but others change it to LongPtr. What is correct?

I don't want to hang on a kernel call gone bad.

Is there a general guide to figure out how any Win32 API should be handled?

答:
a general guide for how to write VBA declare statements for using arbitrary Win32 APIs.

This is how I do it.

I go to https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types and find the data type I need (Ctrl+F).

If it's defined in the terms of another type from the same page, I look up that too (Ctrl+F), until I arrive at a basic type.

Then I use the appropriately sized type from VB. int is Long, short is Integer, char* is String, wchar_t* is LongPtr where you need to pass StrPtr, void* is LongPtr.

I gather that 'As Any' is still appropriate for VBA. But when do I use it? For APIs that take VOID? Or pVOID? or LPVOID?

As Any is helpful when

You don't want to declare the actual type it receives (e.g. it's a complex structure, the parameter is optional, and you are not using it)

There can be multiple different things that can be passed there and you want to be passing them all at different points

Otherwise it's always possible, safe and correct to redeclare As Any using the actual type specified in the API header. Often it's a pointer, which is ByVal LongPtr.

Keeping As Any puts more responsibility on the caller, but gives them more flexibility. Redeclaring As Any as an actual type removes the danger at the cost of said flexibility.

CopyMemory is a very fine example of this principle.

The declaration of pDest As Any, pSrc As Any is most flexible, and can be used as:

Dim a As Long, b As Long

CopyMemory a, b, ...                             ' Copying from variable b to a (a = b)
CopyMemory ByVal VarPtr(a), ByVal VarPtr(b), ... ' Same
```

<pre class="lang-vb prettyprint-override"><code>Dim a As LongPtr, b As LongPtr

CopyMemory ByVal a, ByVal b, ...   ' Copying from memory pointed to by b to memory pointed to by a
</code>```

which is flexible, but if you misuse it:

Dim a As Long, b As Long

CopyMemory ByVal a, ByVal b, ...  ' Wrong: passing values as pointers; likely memory access violation
CopyMemory VarPtr(a), VarPtr(b), ... ' Wrong: passing pointers to pointers;
                                     ' Overwrites the temporary storage VB provides
                                     ' No crash, but no meaningful copying either
```

<pre class="lang-vb prettyprint-override"><code>Dim a As LongPtr, b As LongPtr

CopyMemory a, b, ...              ' Likely wrong: copying the pointer value of b into a (a = b)
</code>```

you can crash and/or corrupt the data.

Having declared the same parameters as ByVal pDest As LongPtr, ByVal pSrc As LongPtr, you lose the ability to pass Longs ByRef like in the first example and will need to explicitly use VarPtr each time, but you won't need to think too much how to call the function. There is still some danger though, because you can still call it as CopyMemory a, b with Long parameters, and it will crash for passing values as pointers, but at least you will see from the function definition what you are passing something wrong, while As Any doesn't give you a hint.

Body:
I'd like a general guide for how to write VBA declare statements for using arbitrary Win32 APIs. Not a list of declare statements for some selection of Win32 APIs (which probably doesn't include the API I'm looking for now or the one I'll be looking for six months from now).

A general guide would educate me on how different C / Win32 data types should be handled. For both 32-bit or 64-bit Office.

This topic on adapting VBA for 64-bit Office tells me I can use LongPtr and that Office 32-bit or 64-bit will adapt that as appropriate. That's only useful if I know when a Long was needed for 32-bit.

This VB.Net topic says 'As Any' isn't supported but that's VB.Net, not VBA.  I gather that 'As Any' is appropriate for VBA but when do I use it? For APIs that take VOID or pVOID or LPVOID?

As a specific example, I need to adapt this declare:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSrc As Any, ByVal ByteLen As Long)

Per MSDN, the last parameter is SIZE_T:

void CopyMemory(
_In_       PVOID  Destination,
_In_ const VOID   *Source,
_In_       SIZE_T Length
);

I've seen some adaptations for 64-bit Office leave this in the declare as ByVal ... As Long but others change it to LongPtr. What is correct?

I don't want to hang on a kernel call gone bad.

Is there a general guide to figure out how any Win32 API should be handled?

Body:
a general guide for how to write VBA declare statements for using arbitrary Win32 APIs.

This is how I do it.

I go to https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types and find the data type I need (Ctrl+F).

If it's defined in the terms of another type from the same page, I look up that too (Ctrl+F), until I arrive at a basic type.

Then I use the appropriately sized type from VB. int is Long, short is Integer, char* is String, wchar_t* is LongPtr where you need to pass StrPtr, void* is LongPtr.

I gather that 'As Any' is still appropriate for VBA. But when do I use it? For APIs that take VOID? Or pVOID? or LPVOID?

As Any is helpful when

You don't want to declare the actual type it receives (e.g. it's a complex structure, the parameter is optional, and you are not using it)

There can be multiple different things that can be passed there and you want to be passing them all at different points

Otherwise it's always possible, safe and correct to redeclare As Any using the actual type specified in the API header. Often it's a pointer, which is ByVal LongPtr.

Keeping As Any puts more responsibility on the caller, but gives them more flexibility. Redeclaring As Any as an actual type removes the danger at the cost of said flexibility.

CopyMemory is a very fine example of this principle.

The declaration of pDest As Any, pSrc As Any is most flexible, and can be used as:

Dim a As Long, b As Long

CopyMemory a, b, ...                             ' Copying from variable b to a (a = b)
CopyMemory ByVal VarPtr(a), ByVal VarPtr(b), ... ' Same

Dim a As LongPtr, b As LongPtr

CopyMemory ByVal a, ByVal b, ...   ' Copying from memory pointed to by b to memory pointed to by a

which is flexible, but if you misuse it:

Dim a As Long, b As Long

CopyMemory ByVal a, ByVal b, ...  ' Wrong: passing values as pointers; likely memory access violation
CopyMemory VarPtr(a), VarPtr(b), ... ' Wrong: passing pointers to pointers;
                                     ' Overwrites the temporary storage VB provides
                                     ' No crash, but no meaningful copying either

Dim a As LongPtr, b As LongPtr

CopyMemory a, b, ...              ' Likely wrong: copying the pointer value of b into a (a = b)

you can crash and/or corrupt the data.

Having declared the same parameters as ByVal pDest As LongPtr, ByVal pSrc As LongPtr, you lose the ability to pass Longs ByRef like in the first example and will need to explicitly use VarPtr each time, but you won't need to think too much how to call the function. There is still some danger though, because you can still call it as CopyMemory a, b with Long parameters, and it will crash for passing values as pointers, but at least you will see from the function definition what you are passing something wrong, while As Any doesn't give you a hint.


问:
Symbol in MatLab / Simulink
input temperature:

input parameters with calculation:

Where can I find these symbols in Simulink

答: They are From and Goto blocks. I would advise using them as little as possible, as they make a Simulink model more difficult to read in my view. You also need to consider the Goto Tag Visibility when using Goto blocks.</p>

Title: Symbol in MatLab / Simulink


问:
Trying to plot a graph using a list of column names using seaborn
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.

```<code>fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)

for aa in listA:
    for j in range(2):
        for i in range(2):
            ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
</code>```

Output plot

答:
```<code>fig, ax = plt.subplots(2,2, figsize=(15,5))
a = 0
for j in range(2):
    for i in range(2):
        sns.lineplot(x='time', y=listA[a], data=new_df[new_df['transportation_type']=='walking'], ax=ax[i,j])
        a+=1
</code>```

Body:
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.

fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)

for aa in listA:
    for j in range(2):
        for i in range(2):
            ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')

Output plot


问:
noobie Iterating over list to display series
I'm trying to generate the fibonacci series here. Not necessarily looking for an answer specific to that series but why the loop I've created here won't generate a list with upto 20 values for an input of '0'.

So far I've tried appending within and before the loop. The result I get is [0,1]. It doesn't seem to add to the list beyond that.

```<code>series = []
value = input("Enter an integer: \n")
i = int(value)
series.append(i)
if series[0] == 0:
    series.append(1)
    for i in series[2:20]:
        series[i]=series[i-1]+series[i-2]
        series.append(i)
print(series)
</code>```

答:
After doing series.append(1) you series values [0,1] only so series[2:20] == [] and you iterate on nothing and fill in nothing. And you cannot access an index that is not already allocated, so you can't do series[i] and you did not reach that index yet, you just need to append the values

```<code>if series[0] == 0:
    series.append(1)
    for i in range(2, 20):
        series.append(series[i - 1] + series[i - 2])
</code>```

series[2:20] returns values of series from index 2 included to 20 excluded

range(2,20) generates values 2 included to 20 ecluded

Body:
I'm trying to generate the fibonacci series here. Not necessarily looking for an answer specific to that series but why the loop I've created here won't generate a list with upto 20 values for an input of '0'.

So far I've tried appending within and before the loop. The result I get is [0,1]. It doesn't seem to add to the list beyond that.

series = []
value = input("Enter an integer: \n")
i = int(value)
series.append(i)
if series[0] == 0:
    series.append(1)
    for i in series[2:20]:
        series[i]=series[i-1]+series[i-2]
        series.append(i)
print(series)

Body:
After doing series.append(1) you series values [0,1] only so series[2:20] == [] and you iterate on nothing and fill in nothing. And you cannot access an index that is not already allocated, so you can't do series[i] and you did not reach that index yet, you just need to append the values

if series[0] == 0:
    series.append(1)
    for i in range(2, 20):
        series.append(series[i - 1] + series[i - 2])

series[2:20] returns values of series from index 2 included to 20 excluded

range(2,20) generates values 2 included to 20 ecluded


问:
Error: model item passed into the dictionary is of type '....List', but this dictionary requires a model of type '...IEnumerable`
I encountered this error while trying to render an asp.net MVC 3.0 application.
I am working with DAB Architecture (3 projects) CAFM.Web, CAFM.Business, and CAFM.Data projects.

CAFM.Data includes

CAFMEntities : Entity FrameWork
ITabMaster : Interface
namespace CAFM.Data.Interfaces
{
    public interface ITabMaster
    {
        TabMaster GetTabMasterById(Int64 id);
        IEnumerable FindTabMasterByName(string name);
        void AddTabMaster(TabMaster tabmaster);
        IEnumerable GetAllTabMaster();
    }
}

CAFM.Business includes
reference of CAFM.Data
namespace CAFM.Business.Repositories
{
    public class TabMasterRepository : ITabMaster
    {
        public int colID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

```<code>    private CAFMEntities _context;

    public TabMasterRepository()
    {
        //IUnitOfWork unitOfWork = new CAFMEntities();
        _context = new CAFMEntities();
    }

    public TabMasterRepository(IUnitOfWork unitOfWork)
    {
        if (unitOfWork == null)
            throw new ArgumentNullException("unitOfWork");

        _context = unitOfWork as CAFMEntities;
    }

    public IEnumerable<TabMaster> GetAllTabMaster()
    {
        //(extension)List<Movie> IEnumerable<Movie>.ToList<Movie>()
        //List<TabMaster> tabmasters = _context.TabMasters.ToList();
        return _context.TabMasters.ToList() ;// .AsEnumerable<TabMaster>();//.ToList();
        //return tabmasters;
    }

    public TabMaster GetTabMasterById(Int64 id)
    {
        return _context.TabMasters.Where(c => c.colID == id).Single();
    }

    public IEnumerable<TabMaster> FindTabMasterByName(string name)
    {
        return _context.TabMasters.Where(c => c.LastName.StartsWith(name)).AsEnumerable<TabMaster>(); //.ToList();
    }

    public void AddTabMaster(TabMaster tabmaster)
    {
        _context.TabMasters.AddObject(tabmaster);
    }
}
</code>```

}

CAFM.Web includes
reference of CAFM.Data
namespace CAFM.Web.Controllers
{
    public class TabMasterController : Controller
    {
        //
        // GET: /TabMaster/

```<code>    public ViewResult Index()
    {

        //Error comes in following line. (_context.TabMasters.ToList() is successfully return all the values but error is The model item passed into the dictionary is ... during rendering HTML
        TabMasterRepository tr = new TabMasterRepository();
        return View(tr.GetAllTabMaster());
    }

}
</code>```

}

Index.cshtml contains

@model IEnumerable
@{
    Layout = null;
}

    TabMaster

        List of Movies

        @Html.ActionLink("Create New", "Create")

                ID

                First Name

                Last Name

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.colID)

                    @Html.DisplayFor(modelItem => item.FirstName)

                    @Html.DisplayFor(modelItem => item.LastName)

        }

Error Description:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[CAFM.Data.TabMaster]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[CAFM.Business.Repositories.TabMasterRepository]'.

Please provide your valuable suggestion to resolve above error.

Your answer would be appreciated!
Thanks,
Imdadhusen

答:
I don't understand why do you want your repository in a view. Did you try to change model to

```<code>@model List<CAFM.Data.TabMaster>
</code>```

In MVC you should pass data between controller and view thru ViewModels

Body:
I encountered this error while trying to render an asp.net MVC 3.0 application.
I am working with DAB Architecture (3 projects) CAFM.Web, CAFM.Business, and CAFM.Data projects.

CAFM.Data includes

CAFMEntities : Entity FrameWork
ITabMaster : Interface
namespace CAFM.Data.Interfaces
{
    public interface ITabMaster
    {
        TabMaster GetTabMasterById(Int64 id);
        IEnumerable FindTabMasterByName(string name);
        void AddTabMaster(TabMaster tabmaster);
        IEnumerable GetAllTabMaster();
    }
}

CAFM.Business includes
reference of CAFM.Data
namespace CAFM.Business.Repositories
{
    public class TabMasterRepository : ITabMaster
    {
        public int colID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

    private CAFMEntities _context;

    public TabMasterRepository()
    {
        //IUnitOfWork unitOfWork = new CAFMEntities();
        _context = new CAFMEntities();
    }

    public TabMasterRepository(IUnitOfWork unitOfWork)
    {
        if (unitOfWork == null)
            throw new ArgumentNullException("unitOfWork");

        _context = unitOfWork as CAFMEntities;
    }

    public IEnumerable<TabMaster> GetAllTabMaster()
    {
        //(extension)List<Movie> IEnumerable<Movie>.ToList<Movie>()
        //List<TabMaster> tabmasters = _context.TabMasters.ToList();
        return _context.TabMasters.ToList() ;// .AsEnumerable<TabMaster>();//.ToList();
        //return tabmasters;
    }

    public TabMaster GetTabMasterById(Int64 id)
    {
        return _context.TabMasters.Where(c => c.colID == id).Single();
    }

    public IEnumerable<TabMaster> FindTabMasterByName(string name)
    {
        return _context.TabMasters.Where(c => c.LastName.StartsWith(name)).AsEnumerable<TabMaster>(); //.ToList();
    }

    public void AddTabMaster(TabMaster tabmaster)
    {
        _context.TabMasters.AddObject(tabmaster);
    }
}

}

CAFM.Web includes
reference of CAFM.Data
namespace CAFM.Web.Controllers
{
    public class TabMasterController : Controller
    {
        //
        // GET: /TabMaster/

    public ViewResult Index()
    {

        //Error comes in following line. (_context.TabMasters.ToList() is successfully return all the values but error is The model item passed into the dictionary is ... during rendering HTML
        TabMasterRepository tr = new TabMasterRepository();
        return View(tr.GetAllTabMaster());
    }

}

}

Index.cshtml contains

@model IEnumerable
@{
    Layout = null;
}

    TabMaster

        List of Movies

        @Html.ActionLink("Create New", "Create")

                ID

                First Name

                Last Name

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.colID)

                    @Html.DisplayFor(modelItem => item.FirstName)

                    @Html.DisplayFor(modelItem => item.LastName)

        }

Error Description:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[CAFM.Data.TabMaster]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[CAFM.Business.Repositories.TabMasterRepository]'.

Please provide your valuable suggestion to resolve above error.

Your answer would be appreciated!
Thanks,
Imdadhusen

Body:
I don't understand why do you want your repository in a view. Did you try to change model to

@model List<CAFM.Data.TabMaster>

In MVC you should pass data between controller and view thru ViewModels


问:
SettingWithCopyWarning even when using .loc[row_indexer,col_indexer] = value
This is one of the lines in my code where I get the SettingWithCopyWarning:

```<code>value1['Total Population']=value1['Total Population'].replace(to_replace='*', value=4)
</code>```

Which I then changed to :

```<code>row_index= value1['Total Population']=='*'
value1.loc[row_index,'Total Population'] = 4
</code>```

This still gives the same warning. How do I get rid of it?

Also, I get the same warning for a convert_objects(convert_numeric=True) function that I've used, is there any way to avoid that.

```<code> value1['Total Population'] = value1['Total Population'].astype(str).convert_objects(convert_numeric=True)
</code>```

This is the warning message that I get:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
```

答:
I have no idea how bad the data storage/memory implications are with this but it fixes it every time for your average dataframe:

```<code>def addCrazyColFunc(df):
    dfNew = df.copy()
    dfNew['newCol'] = 'crazy'
    return dfNew
</code>```

Just like the message says... make a copy and you're good to go.  Please if someone can fix the above without the copy, please comment.  All the above loc stuff doesn't work for this case.

Body:
This is one of the lines in my code where I get the SettingWithCopyWarning:

value1['Total Population']=value1['Total Population'].replace(to_replace='*', value=4)

Which I then changed to :

row_index= value1['Total Population']=='*'
value1.loc[row_index,'Total Population'] = 4

This still gives the same warning. How do I get rid of it?

Also, I get the same warning for a convert_objects(convert_numeric=True) function that I've used, is there any way to avoid that.

 value1['Total Population'] = value1['Total Population'].astype(str).convert_objects(convert_numeric=True)

This is the warning message that I get:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Body:
I have no idea how bad the data storage/memory implications are with this but it fixes it every time for your average dataframe:

def addCrazyColFunc(df):
    dfNew = df.copy()
    dfNew['newCol'] = 'crazy'
    return dfNew

Just like the message says... make a copy and you're good to go.  Please if someone can fix the above without the copy, please comment.  All the above loc stuff doesn't work for this case.


问:
input texbox value not working in textbox javascript
I would like to know how to allow max value based on min entered in textbox and should allow only numbers and no special characters and alphabets,

I have two text box, min and max,
min can allow only numbers both positive and negative but no special characters and alphabets

max value should be greater than min value and not allow special characters and alphabets

Here is my code, max not working proper.

```<code>class Sample extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      min: "",
      max: ""
    }
 }
hanldeMin = (e) => {
    if (e.target.value !== "") {
      this.setState({
        min: e.target.value
      })
    }
  }

 handleMax = (e) => {
    if (e.target.value !== "") {
      if (parseInt(e.target.value) < parseInt(this.state.min)) {
        e.target.value = "";
      }
      this.setState({
        max: e.target.value
      })
    }
  }
render(){
return (
 <React.Fragment>
   <div className="row">

       <div className="col-lg-5 col-sm-5 noPadding noMargin">
                <input
                  type="text"
                  placeholder="min"
                  className="form-control"
                  id="minavlitems"
                  value={this.state.min}
                  onChange={(event) => {
                    if (isNaN(Number(event.target.value))) {
                      return;
                    } else {
                      this.hanldeMin(event);
                    }
                  }}
                />
              </div>
              <div className="col-lg-1 col-sm-1 alignCenter noPadding noMargin">
                <b>-</b>
              </div>
              <div className="col-lg-6 col-sm-6 noPadding noMargin">
                <input
                  type="text"
                  min={this.state.min}
                  className="form-control"
                  placeholder="max"
                  id="maxavlitems"
                  value={this.state.max}
                  onChange={(event) => {
                    if (isNaN(Number(event.target.value))) {
                      return;
                    } else {
                       this.hanldeMax(event);
                    }
                  }}
                />
              </div>
             </div>
   </div>
 </React.Fragment>

)

}

}

</code>```

答:
Please check the example where I used regular expression to input only positive/negative number.

Here is the Code Sand Box

Here is the example:

```<code>import React from "react";

export default class Sample extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            min: "",
            max: ""
        }
    }

    isValid = (e) => {
        let regEx = /^-?\d*\.?\d{0,6}$/;
        let text = e.target.value;
        return (text.match(regEx) !== null);
    };

    handleMin = (e) => {
        if (this.isValid(e)) {
            this.setState({
                min: e.target.value
            })
        }
    };

    handleMax = (e) => {
        console.log(e.target.value, 'onblur');
        if (this.isValid(e)) {
            if (parseInt(e.target.value) <= parseInt(this.state.min)) {
                e.target.value = "";
            }
            this.setState({
                max: e.target.value
            })
        }
    };

    handleChange = (e) => {
        this.setState({
            max: e.target.value
        })
    };

    render() {
        return (
            <React.Fragment>
                <div className="row">
                    <div className="col-lg-5 col-sm-5 noPadding noMargin">
                        <input
                            type="text"
                            placeholder="min"
                            className="form-control"
                            id="minavlitems"
                            value={this.state.min}
                            onChange={this.handleMin}
                        />
                    </div>
                    <div className="col-lg-1 col-sm-1 alignCenter noPadding noMargin">
                        <b>-</b>
                    </div>
                    <div className="col-lg-6 col-sm-6 noPadding noMargin">
                        <input
                            type="text"
                            min={this.state.min}
                            className="form-control"
                            placeholder="max"
                            id="maxavlitems"
                            value={this.state.max}
                            onChange={this.handleChange}
                            onBlur={this.handleMax}
                        />
                    </div>
                    <button onClick={() => {
                        console.log(this.state, 'state')
                    }}>Show mix and max value in console
                    </button>
                </div>
            </React.Fragment>
        )
    }
}
</code>```

Body:
I would like to know how to allow max value based on min entered in textbox and should allow only numbers and no special characters and alphabets,

I have two text box, min and max,
min can allow only numbers both positive and negative but no special characters and alphabets

max value should be greater than min value and not allow special characters and alphabets

Here is my code, max not working proper.

class Sample extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      min: "",
      max: ""
    }
 }
hanldeMin = (e) => {
    if (e.target.value !== "") {
      this.setState({
        min: e.target.value
      })
    }
  }

 handleMax = (e) => {
    if (e.target.value !== "") {
      if (parseInt(e.target.value) < parseInt(this.state.min)) {
        e.target.value = "";
      }
      this.setState({
        max: e.target.value
      })
    }
  }
render(){
return (
 <React.Fragment>

                <input
                  type="text"
                  placeholder="min"
                  className="form-control"
                  id="minavlitems"
                  value={this.state.min}
                  onChange={(event) => {
                    if (isNaN(Number(event.target.value))) {
                      return;
                    } else {
                      this.hanldeMin(event);
                    }
                  }}
                />

                -

                <input
                  type="text"
                  min={this.state.min}
                  className="form-control"
                  placeholder="max"
                  id="maxavlitems"
                  value={this.state.max}
                  onChange={(event) => {
                    if (isNaN(Number(event.target.value))) {
                      return;
                    } else {
                       this.hanldeMax(event);
                    }
                  }}
                />

 </React.Fragment>

)

}

}

Body:
Please check the example where I used regular expression to input only positive/negative number.

Here is the Code Sand Box

Here is the example:

import React from "react";

export default class Sample extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            min: "",
            max: ""
        }
    }

    isValid = (e) => {
        let regEx = /^-?\d*\.?\d{0,6}$/;
        let text = e.target.value;
        return (text.match(regEx) !== null);
    };

    handleMin = (e) => {
        if (this.isValid(e)) {
            this.setState({
                min: e.target.value
            })
        }
    };

    handleMax = (e) => {
        console.log(e.target.value, 'onblur');
        if (this.isValid(e)) {
            if (parseInt(e.target.value) <= parseInt(this.state.min)) {
                e.target.value = "";
            }
            this.setState({
                max: e.target.value
            })
        }
    };

    handleChange = (e) => {
        this.setState({
            max: e.target.value
        })
    };

    render() {
        return (
            <React.Fragment>
                <div className="row">
                    <div className="col-lg-5 col-sm-5 noPadding noMargin">
                        <input
                            type="text"
                            placeholder="min"
                            className="form-control"
                            id="minavlitems"
                            value={this.state.min}
                            onChange={this.handleMin}
                        />
                    </div>
                    <div className="col-lg-1 col-sm-1 alignCenter noPadding noMargin">
                        <b>-</b>
                    </div>
                    <div className="col-lg-6 col-sm-6 noPadding noMargin">
                        <input
                            type="text"
                            min={this.state.min}
                            className="form-control"
                            placeholder="max"
                            id="maxavlitems"
                            value={this.state.max}
                            onChange={this.handleChange}
                            onBlur={this.handleMax}
                        />
                    </div>
                    <button onClick={() => {
                        console.log(this.state, 'state')
                    }}>Show mix and max value in console
                    </button>
                </div>
            </React.Fragment>
        )
    }
}


问:
Update Xcode version on hosted machines
I can see that my hosted build machine has Xcode 11.3 installed however Apple has since then released 11.4.x and 11.5

How do we go about asking Microsoft to updating the hosted build machines? They used to update the machines a few days after Apple released updates.

答:
Guess you were using macOS X Mojave 10.14.  It's using Xcode 11.3.1 (default) in the image.

You should use macOS X Catalina 10.15 when you select the host agent.

It's using Xcode 11.4.1 as default and also include 11.5 in the image.

If you have to use macOSX 10.14,  since that image do not include Xcode 11.4.x and 11.5, you may need to use a self-hosted agent that includes the exact versions of software that you need.

Title: Update Xcode version on hosted machines


问:
Reading from flash that's not part of the application
I'm programming bare-metal embedded, so no OS etc. on a STM32L4 (ARM Cortex M4). I have a separate page in flash, which is written by a bootloader (it is not and should not be part of my application binary, this is a must). In this page, I store configuration parameters that will be used in my application. This configuration page may change, but not during runtime, after a change I reset the processor.

How can I access this data in flash most nicely?

My definition of nice is (in this order of priority):
- support for (u)int32_t, (u)int8_t, bool, char[fixed-size]
- little overhead when compared to #define PARAM (1) or constexpr
- typesafe usage (i.e. uint8_t var = CONFIG_CHAR_ARRAY shall issue atleast a warning)
- no RAM copy
- readability of the configuration parameters while debugging (using STM32CubeIDE)

The solution shall scale for all possible 2048 bytes of the flashpage. Code generation is anyhow part of the process.

So far, I have tested two variants (I am coming from plain C but am using (potentially modern) C++ in this project). My current testcase is

```<code>    if (param) function_call();
</code>```

but it should also work for other cases such as

```<code>    for(int i = 0; i < param2; i++)
</code>```

define with pointer cast

```<code>#define CONF_PARAM1 (*(bool*)(CONFIG_ADDRESS + 0x0083))
</code>```

Which leads to (using -Os):

```<code>8008872:    4b1b        ldr r3, [pc, #108]  ; (80088e0 <_Z16main_applicationv+0xac>)
8008874:    781b        ldrb    r3, [r3, #0]
8008876:    b10b        cbz r3, 800887c <_Z16main_applicationv+0x48>
8008878:    f7ff ff56   bl  8008728 <_Z10function_callv>

80088e0:    0801f883    .word   0x0801f883
</code>```

const variable

```<code>const bool CONF_PARAM1 = *(bool*)(CONFIG_ADDRESS + 0x0083);
</code>```

leading to

```<code>800887c:    4b19        ldr r3, [pc, #100]  ; (80088e4 <_Z16main_applicationv+0xb0>)
800887e:    781b        ldrb    r3, [r3, #0]
8008880:    b10b        cbz r3, 8008886 <_Z16main_applicationv+0x52>
8008882:    f000 f899   bl  8008728 <_Z10function_callv>

80088e4:    200000c0    .word   0x200000c0
</code>```

I dislike option 2, as it adds a RAM copy (would not scale well for 2048 bytes of config), option 1 looks like very old c style and does not help while debugging. I struggle to find another option using the linker script, as I do not find a way to not end up with the variable being in the application's binary.

Is there any better way of doing this?

答:
No need to re-invent the wheel - placing data in flash is a fairly common use-case in embedded systems. When dealing with such data flash, there are some important considerations:

All data must sit at the very same address, with the same type, from case to case. This means that struct is problematic because of padding (and even more so class). If you align all data on 32 bit boundaries, this shouldn't be a problem, so I strongly recommend that you do so. Then the program becomes portable between compilers.

All these variables and pointers to them must be declared with volatile qualifier, otherwise the optimizer might go haywire. Things like (*(bool*)(CONFIG_ADDRESS + 0x0083)) are brittle and might break at any point, unless you add volatile.

You can place data at a fixed location in memory, but how to do so is compiler/linker-specific. And since it isn't standardized, it's always a pain to get right. With gcc-flavoured compilers it might be something like: __attribute__(section(".dataflash")) where .dataflash is your custom segment that you must reserve space for in the linker script. You'll need to take a closer look at how to do this with your specific toolchain (others use #pragmas etc instead), I'll use the __attribute__ here just to illustrate.

If this section gets downloaded together with the executable binary, or only through bootloader, is up to you to define. Linker scripts typically come with a "no init" option.

So you could do something like:

```<code>// flashdata.h

typedef struct
{
  uint32_t stuff;
  uint32_t more_stuff;
  ...
} flashdata_t;

extern volatile const flashdata_t flash_data __attribute__(section(".dataflash"));
</code>```

And then declare it as:

```<code>// flashdata.c

volatile const flashdata_t flash_data __attribute__(section(".dataflash"));
</code>```

And now you can use it as any struct, flash_data.stuff.

If you are using C, you can even split up each uint32_t chunk with union, such as typedef union { uint32_t u32; uint8_t u8 [4]; } and similar, but that isn't possible in C++, because it doesn't allow union type punning.

Body:
I'm programming bare-metal embedded, so no OS etc. on a STM32L4 (ARM Cortex M4). I have a separate page in flash, which is written by a bootloader (it is not and should not be part of my application binary, this is a must). In this page, I store configuration parameters that will be used in my application. This configuration page may change, but not during runtime, after a change I reset the processor.

How can I access this data in flash most nicely?

My definition of nice is (in this order of priority):
- support for (u)int32_t, (u)int8_t, bool, char[fixed-size]
- little overhead when compared to #define PARAM (1) or constexpr
- typesafe usage (i.e. uint8_t var = CONFIG_CHAR_ARRAY shall issue atleast a warning)
- no RAM copy
- readability of the configuration parameters while debugging (using STM32CubeIDE)

The solution shall scale for all possible 2048 bytes of the flashpage. Code generation is anyhow part of the process.

So far, I have tested two variants (I am coming from plain C but am using (potentially modern) C++ in this project). My current testcase is

    if (param) function_call();

but it should also work for other cases such as

    for(int i = 0; i < param2; i++)

define with pointer cast

#define CONF_PARAM1 (*(bool*)(CONFIG_ADDRESS + 0x0083))

Which leads to (using -Os):

8008872:    4b1b        ldr r3, [pc, #108]  ; (80088e0 <_Z16main_applicationv+0xac>)
8008874:    781b        ldrb    r3, [r3, #0]
8008876:    b10b        cbz r3, 800887c <_Z16main_applicationv+0x48>
8008878:    f7ff ff56   bl  8008728 <_Z10function_callv>

80088e0:    0801f883    .word   0x0801f883

const variable

const bool CONF_PARAM1 = *(bool*)(CONFIG_ADDRESS + 0x0083);

leading to

800887c:    4b19        ldr r3, [pc, #100]  ; (80088e4 <_Z16main_applicationv+0xb0>)
800887e:    781b        ldrb    r3, [r3, #0]
8008880:    b10b        cbz r3, 8008886 <_Z16main_applicationv+0x52>
8008882:    f000 f899   bl  8008728 <_Z10function_callv>

80088e4:    200000c0    .word   0x200000c0

I dislike option 2, as it adds a RAM copy (would not scale well for 2048 bytes of config), option 1 looks like very old c style and does not help while debugging. I struggle to find another option using the linker script, as I do not find a way to not end up with the variable being in the application's binary.

Is there any better way of doing this?

Body:
No need to re-invent the wheel - placing data in flash is a fairly common use-case in embedded systems. When dealing with such data flash, there are some important considerations:

All data must sit at the very same address, with the same type, from case to case. This means that struct is problematic because of padding (and even more so class). If you align all data on 32 bit boundaries, this shouldn't be a problem, so I strongly recommend that you do so. Then the program becomes portable between compilers.

All these variables and pointers to them must be declared with volatile qualifier, otherwise the optimizer might go haywire. Things like (*(bool*)(CONFIG_ADDRESS + 0x0083)) are brittle and might break at any point, unless you add volatile.

You can place data at a fixed location in memory, but how to do so is compiler/linker-specific. And since it isn't standardized, it's always a pain to get right. With gcc-flavoured compilers it might be something like: __attribute__(section(".dataflash")) where .dataflash is your custom segment that you must reserve space for in the linker script. You'll need to take a closer look at how to do this with your specific toolchain (others use #pragmas etc instead), I'll use the __attribute__ here just to illustrate.

If this section gets downloaded together with the executable binary, or only through bootloader, is up to you to define. Linker scripts typically come with a "no init" option.

So you could do something like:

// flashdata.h

typedef struct
{
  uint32_t stuff;
  uint32_t more_stuff;
  ...
} flashdata_t;

extern volatile const flashdata_t flash_data __attribute__(section(".dataflash"));

And then declare it as:

// flashdata.c

volatile const flashdata_t flash_data __attribute__(section(".dataflash"));

And now you can use it as any struct, flash_data.stuff.

If you are using C, you can even split up each uint32_t chunk with union, such as typedef union { uint32_t u32; uint8_t u8 [4]; } and similar, but that isn't possible in C++, because it doesn't allow union type punning.


问:
Most Efficient Way Of Clearing Cache Using ASP.NET
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

```<code>public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}
</code>```

Is this really bad? I can't see how else I am supposed to clear the cached items?

答:
Have you considered using a Cache Dependency?
Here's the MSDN explanation and a few tidbits from there:

Establishes a dependency relationship between an item stored in an ASP.NET application's Cache object and a file, cache key, an array of either, or another CacheDependency object. The CacheDependency class monitors the dependency relationships so that when any of them changes, the cached item will be automatically removed.

```<code>// Insert the cache item.
CacheDependency dep = new CacheDependency(fileName, dt);
cache.Insert("key", "value", dep);

// Check whether CacheDependency.HasChanged is true.
if (dep.HasChanged)
  Response.Write("<p>The dependency has changed.");
else Response.Write("<p>The dependency has not changed.");
</code>```

And this very enthusiastic fellow explains some more about it.

Body:
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}

Is this really bad? I can't see how else I am supposed to clear the cached items?

Body:
Have you considered using a Cache Dependency?
Here's the MSDN explanation and a few tidbits from there:

Establishes a dependency relationship between an item stored in an ASP.NET application's Cache object and a file, cache key, an array of either, or another CacheDependency object. The CacheDependency class monitors the dependency relationships so that when any of them changes, the cached item will be automatically removed.

// Insert the cache item.
CacheDependency dep = new CacheDependency(fileName, dt);
cache.Insert("key", "value", dep);

// Check whether CacheDependency.HasChanged is true.
if (dep.HasChanged)
  Response.Write("<p>The dependency has changed.");
else Response.Write("<p>The dependency has not changed.");

And this very enthusiastic fellow explains some more about it.


问:
Resize image to lowest size with minimum quality loss
I have this piece of code to resize picture:

```<code>public static void GetProductSmallThumbnail(string fileUrl, string fileName)
        {
            System.Drawing.Image.GetThumbnailImageAbort myCallback =
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            System.Drawing.Image img = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
                img = System.Drawing.Image.FromStream(fs);
                int orgwidth = img.Width;
                int orgheight = img.Height;

                int imgwidth = img.Width;
                int imgheight = img.Height;

                // if 240 is max width
                imgwidth = 240;
                imgheight = Convert.ToInt32((imgwidth * orgheight) / orgwidth);
                System.Drawing.Image myThumbnail = img.GetThumbnailImage(
                imgwidth, imgheight, myCallback, IntPtr.Zero);
                myThumbnail.Save(Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"));
            }
            finally
            {
                fs.Close();
            }

        }
</code>```

Everything works correctly but the file size is much more than expected.
For example I used this image for Input:

The resulted image has correct width and height but the size is 89 KB, but I expect this image which is 7 KB

答:
The Save function of System.Drawing.Image has an overload which accepts a format as its second parameter (see docs). To save your image in a format that is different from your original, pass the format to the save funtion:

```<code>myThumbnail.Save(
    Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"),
    ImageFormat.Jpeg);
</code>```

Body:
I have this piece of code to resize picture:

public static void GetProductSmallThumbnail(string fileUrl, string fileName)
        {
            System.Drawing.Image.GetThumbnailImageAbort myCallback =
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            System.Drawing.Image img = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
                img = System.Drawing.Image.FromStream(fs);
                int orgwidth = img.Width;
                int orgheight = img.Height;

                int imgwidth = img.Width;
                int imgheight = img.Height;

                // if 240 is max width
                imgwidth = 240;
                imgheight = Convert.ToInt32((imgwidth * orgheight) / orgwidth);
                System.Drawing.Image myThumbnail = img.GetThumbnailImage(
                imgwidth, imgheight, myCallback, IntPtr.Zero);
                myThumbnail.Save(Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"));
            }
            finally
            {
                fs.Close();
            }

        }

Everything works correctly but the file size is much more than expected.
For example I used this image for Input:

The resulted image has correct width and height but the size is 89 KB, but I expect this image which is 7 KB

Body:
The Save function of System.Drawing.Image has an overload which accepts a format as its second parameter (see docs). To save your image in a format that is different from your original, pass the format to the save funtion:

myThumbnail.Save(
    Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"),
    ImageFormat.Jpeg);


问:
Uninstall mongodb correctly and install mongodb again
Please teach me how to uninstall my mongodb in my virtualbox(ubuntu).

I tried these command and nothing was removed :

```<code>sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev
sudo apt-get purge mongodb-10gen
sudo apt-get autoremove
</code>```

It still exists.
I type mongod --version   it shows  db version v2.6.1

Update:

I want to remove it and then install it again:

I tried the following 4 commands -

```<code>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
sudo apt-get update
sudo apt-get install mongodb-org
</code>```

then
    sudo service mongod start

and type mongo  there is error:

```<code>MongoDB shell version: 2.6.4
connecting to: test
2014-09-02T21:27:10.390+0800 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111     Connection refused
2014-09-02T21:27:10.392+0800 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed
</code>```

Did I miss something?
Please help me.  Thank you!!

答:
To remove Mongo run  these commands below

```<code>sudo apt-get purge mongodb
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb
</code>```

If you have different versions of mongo already  installed, Run the command below

sudo apt-get autoremove
```

<p><strong>To install mongo safely in Ubuntu 18.04 first update all packages by running this command</strong></p>

```sudo apt update
```

<p><strong>Now install mongo</strong></p>

```sudo apt install -y mongodb
```

<p><strong>Start mongo by running command below</strong></p>

```sudo systemctl start mongodb
```

<p><strong>Now check mongodb status by running</strong></p>

```sudo systemctl status mongodb
```

It should show a status Active

I hope this works for you thanks

Body:
Please teach me how to uninstall my mongodb in my virtualbox(ubuntu).

I tried these command and nothing was removed :

sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev
sudo apt-get purge mongodb-10gen
sudo apt-get autoremove

It still exists.
I type mongod --version   it shows  db version v2.6.1

Update:

I want to remove it and then install it again:

I tried the following 4 commands -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
sudo apt-get update
sudo apt-get install mongodb-org

then
    sudo service mongod start

and type mongo  there is error:

MongoDB shell version: 2.6.4
connecting to: test
2014-09-02T21:27:10.390+0800 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111     Connection refused
2014-09-02T21:27:10.392+0800 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed

Did I miss something?
Please help me.  Thank you!!

Body:
To remove Mongo run  these commands below

sudo apt-get purge mongodb
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

If you have different versions of mongo already  installed, Run the command below

sudo apt-get autoremove

To install mongo safely in Ubuntu 18.04 first update all packages by running this command

sudo apt update

Now install mongo

sudo apt install -y mongodb

Start mongo by running command below

sudo systemctl start mongodb

Now check mongodb status by running

sudo systemctl status mongodb

It should show a status Active

I hope this works for you thanks


问:
UIView in tableViewCell crash issue
I have created a UIView in tableViewCell and set UIView contraints 5 from all side,
but when I try to change its backgroud color or getting its frame facing crash

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

```<code>class MyCell: UITableViewCell{
    @IBOutlet weak var viewCell: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

     func designCell(data:[String:Any]){
        self.viewCell.backgroundColor = UIColor.yellow //getting crash
    }
}
</code>```

答: The error you are facing means that you forgot to connect the viewCell outlet in storyboard. Open your storyboard and make sure the outlet is connected to the desired viewCell.

Title: UIView in tableViewCell crash issue

Body:
I have created a UIView in tableViewCell and set UIView contraints 5 from all side,
but when I try to change its backgroud color or getting its frame facing crash

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

class MyCell: UITableViewCell{
    @IBOutlet weak var viewCell: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

     func designCell(data:[String:Any]){
        self.viewCell.backgroundColor = UIColor.yellow //getting crash
    }
}


问:
python selenium no such element exception
Having trouble getting selenium to send keys to username field. I have tried "find_element_by_css_selector" and all the other find elements. Keep getting no such element exception.

This is the code I have so far:

```<code>import webbrowser
from selenium import webdriver

browser = webdriver.Chrome()
webbrowser.open('https://www.kraken.com/en-us/login')
browser.implicitly_wait(10)
browser.find_element_by_name('username').send_keys('your-username')
</code>```

答: Good Question.This problem is caused because Selenium didn't find the element.TO fix this you need to replace the implicity_wait with 'time.sleep(in seconds)'.This will make selenium wait for the entire website to load.Some elements of the website take more time to load.Implicity wait won't work here.</p>

Body:
Having trouble getting selenium to send keys to username field. I have tried "find_element_by_css_selector" and all the other find elements. Keep getting no such element exception.

This is the code I have so far:

import webbrowser
from selenium import webdriver

browser = webdriver.Chrome()
webbrowser.open('https://www.kraken.com/en-us/login')
browser.implicitly_wait(10)
browser.find_element_by_name('username').send_keys('your-username')


问:
`vsync` property in TabController constructor
According to this: sample code

I created my own implementation of TabController:

```<code>void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: choices.length);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        bottomNavigationBar: new Material(
          color: Colors.blue,
          child: new TabBar(
            controller: _tabController,
            isScrollable: false,
            tabs: choices.map((Choice choice) {
              return new Tab(
                text: null,
                icon: new Icon(choice.icon),
              );
            }).toList(),
          ),
        ),
        appBar: new AppBar(
          title: const Text('Swap'),
        ),
        body: new TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return new Padding(
              padding: const EdgeInsets.all(16.0),
              child: new ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
      ),
    );
  }
}
</code>```

In line: _tabController = new TabController(vsync: this, length: choices.length); I got error this message:

error: The argument type '_MyAppState' can't be assigned to the parameter type 'TickerProvider'. (argument_type_not_assignable at [swap] lib/main.dart:24)

What is wrong with my code?

答:
Simply add with TickerProviderStateMixin at the end of extends state class as follows:

```<code>class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
//...
}
</code>```

Body:
According to this: sample code

I created my own implementation of TabController:

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: choices.length);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        bottomNavigationBar: new Material(
          color: Colors.blue,
          child: new TabBar(
            controller: _tabController,
            isScrollable: false,
            tabs: choices.map((Choice choice) {
              return new Tab(
                text: null,
                icon: new Icon(choice.icon),
              );
            }).toList(),
          ),
        ),
        appBar: new AppBar(
          title: const Text('Swap'),
        ),
        body: new TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return new Padding(
              padding: const EdgeInsets.all(16.0),
              child: new ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
      ),
    );
  }
}

In line: _tabController = new TabController(vsync: this, length: choices.length); I got error this message:

error: The argument type '_MyAppState' can't be assigned to the parameter type 'TickerProvider'. (argument_type_not_assignable at [swap] lib/main.dart:24)

What is wrong with my code?

Body:
Simply add with TickerProviderStateMixin at the end of extends state class as follows:

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
//...
}


问:
Simulation veins-run has encountered a problem. Simulation terminated with exit code: -1073740940
I use Omnet++ 5.4.1 Veins 4.7.1 and Sumo 30.
My simulation works well and generates the right output
But when the simulation time runs end or I stop the simulation, it shows the following error:

simulation veins-run' has encountered a problem. finish with error
    Simulation terminated with exit code: -1073740940
  Working directory: C:/Users/AB/src/omnetpp-5.4.1/samples/veins/examples/veins
  Command line: ../../../../bin/opp_run.exe -m -u Qtenv -n .;../../src/veins --image-path=../../images -l ../../src/veins omnetpp.ini
  Environment variables:
  PATH=;C:/Users/AB/src/omnetpp-5.4.1/samples/veins/src;C:\Users\AB\src\omnetpp-5.4.1\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\mingw64\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin;;C:/Users/AB/src/omnetpp-5.4.1/ide/jre/bin/server;C:/Users/AB/src/omnetpp-5.4.1/ide/jre/bin;C:/Users/AB/src/omnetpp-5.4.1/ide/jre/lib/amd64;.;C:\Users\AB\src\omnetpp-5.4.1\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\mingw64\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\local\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin;C:\Windows\System32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin\site_perl;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin\vendor_perl;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin\core_perl;C:\Users\AB\src\omnetpp-5.4.1;
  OMNETPP_ROOT=C:/Users/AB/src/omnetpp-5.4.1/
  OMNETPP_IMAGE_PATH=C:\Users\AB\src\omnetpp-5.4.1\images

And the finish() method doesn't work, and I can't record the information and use it to draw chart.
Please help me to solve my problem.
Thanks.

答:
In your omnetpp.ini set:

```<code>debug-on-errors = true
</code>```

and start the simulation in debug mode. The debugger should show the command that causes an error. Reference: OMNeT++ Tutorial - 2.3 Debugging

Another clue: unfortunately OMNeT++ uses decimal numbers for exit code, while hex values are more valuable. The exit code -1073740940 has the hex representation: 0xc0000374. One may use the last number for looking among Microsoft Windows exception codes.

Body:
In your omnetpp.ini set:

debug-on-errors = true

and start the simulation in debug mode. The debugger should show the command that causes an error. Reference: OMNeT++ Tutorial - 2.3 Debugging

Another clue: unfortunately OMNeT++ uses decimal numbers for exit code, while hex values are more valuable. The exit code -1073740940 has the hex representation: 0xc0000374. One may use the last number for looking among Microsoft Windows exception codes.


问:
How to parse Address from Google Places GeoDataApi for Android, (address_components missing)
We use the Google Places API prediction similar as in the example app. On selection of a result we get the details for the predicted location using:

```<code>Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId);
</code>```

This works fine, my problem is that the result contains just a String as address.

When using the JS version of the API, the result contains this:

```<code>"address_components" : [
     {
        "long_name" : "522",
        "short_name" : "522",
        "types" : [ "street_number" ]
     },
     {
        "long_name" : "Overtoom",
        "short_name" : "Overtoom",
        "types" : [ "route" ]
     },
     {
        "long_name" : "Amsterdam-West",
        "short_name" : "Amsterdam-West",
        "types" : [ "sublocality_level_1", "sublocality", "political" ]
     },
     {
        "long_name" : "Amsterdam",
        "short_name" : "Amsterdam",
        "types" : [ "locality", "political" ]
     },
     {
        "long_name" : "Amsterdam",
        "short_name" : "Amsterdam",
        "types" : [ "administrative_area_level_2", "political" ]
     },
     {
        "long_name" : "Noord-Holland",
        "short_name" : "NH",
        "types" : [ "administrative_area_level_1", "political" ]
     },
     {
        "long_name" : "Nederland",
        "short_name" : "NL",
        "types" : [ "country", "political" ]
     },
     {
        "long_name" : "1054",
        "short_name" : "1054",
        "types" : [ "postal_code_prefix", "postal_code" ]
     }
  ],
</code>```

But the above information inside address_components is missing when using the API on Android.
How do I get this information on Android using the Google places API?

答: Places SDK for Android now supports ADDRESS_COMPONENTS in Field... :-)</p>

Body:
We use the Google Places API prediction similar as in the example app. On selection of a result we get the details for the predicted location using:

Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId);

This works fine, my problem is that the result contains just a String as address.

When using the JS version of the API, the result contains this:

"address_components" : [
     {
        "long_name" : "522",
        "short_name" : "522",
        "types" : [ "street_number" ]
     },
     {
        "long_name" : "Overtoom",
        "short_name" : "Overtoom",
        "types" : [ "route" ]
     },
     {
        "long_name" : "Amsterdam-West",
        "short_name" : "Amsterdam-West",
        "types" : [ "sublocality_level_1", "sublocality", "political" ]
     },
     {
        "long_name" : "Amsterdam",
        "short_name" : "Amsterdam",
        "types" : [ "locality", "political" ]
     },
     {
        "long_name" : "Amsterdam",
        "short_name" : "Amsterdam",
        "types" : [ "administrative_area_level_2", "political" ]
     },
     {
        "long_name" : "Noord-Holland",
        "short_name" : "NH",
        "types" : [ "administrative_area_level_1", "political" ]
     },
     {
        "long_name" : "Nederland",
        "short_name" : "NL",
        "types" : [ "country", "political" ]
     },
     {
        "long_name" : "1054",
        "short_name" : "1054",
        "types" : [ "postal_code_prefix", "postal_code" ]
     }
  ],

But the above information inside address_components is missing when using the API on Android.
How do I get this information on Android using the Google places API?


问:
Extract first element from multi dimensional array from pandas dataframe
I have a data frame consists of reviews column which is a multi dimensional array, I would like to extract first element as shown below,

Suppose df['Reviews'] consists of following rows

I want the output in a separate column as shown below,

Please find sample data 3 values for the column below:

df['Reviews'] =
[['Just like home', 'A Warm Welcome to Wintry Amsterdam'], ['01/03/2018', '01/01/2018']]
[['Great food and staff', 'just perfect'], ['01/06/2018', '01/04/2018']]
[['Satisfaction', 'Delicious old school restaurant'], ['01/04/2018', '01/04/2018']]

Please help

答:
I guess this should help. This worked for me.

```<code>df['Reviews']=df['Reviews'].apply(lambda c: str(c[0]).strip('[]'))
</code>```

This works fine if run once.If run again on same code, it ll further divide the text.So i suggest comment it out after using it.
Or make a new column.

P.S: You should include the code instead of screenshots so that it can be tested first.

EDIT

Looks fine to me.try once again and remember if you run it twice (incase not making separate column), it ll return none

Body:
I guess this should help. This worked for me.

df['Reviews']=df['Reviews'].apply(lambda c: str(c[0]).strip('[]'))

This works fine if run once.If run again on same code, it ll further divide the text.So i suggest comment it out after using it.
Or make a new column.

P.S: You should include the code instead of screenshots so that it can be tested first.

EDIT

Looks fine to me.try once again and remember if you run it twice (incase not making separate column), it ll return none