问:
private repo - go 1.13 - `go mod ..` failed: ping "sum.golang.org/lookup" .. verifying package .. 410 gone
I am using golang 1.13 .

I have a project that depends on a private gitlab project.

I have the ssh keys for the same.

When I try to retrieve the dependencies for a newly created module, I am getting the following error:

```<code>$ go version
go version go1.13 linux/amd64

$ go mod why
go: downloading gitlab.com/mycompany/myproject v0.0.145
verifying gitlab.com/mycompany/myproject@v0.0.145: gitlab.com/mycompany/myproject@v0.0.145: reading https://sum.golang.org/lookup/gitlab.com/mycompany/myproject@v0.0.145: 410 Gone
</code>```

I have no idea why it is trying to ping sum.golang.org/lookup since it is a private gitlab project.

My ~/.gitconfig contains the following (based on my looking up in google search for similar errors)

```<code># Enforce SSH
[url "ssh://git@github.com/"]
  insteadOf = https://github.com/
[url "ssh://git@gitlab.com/"]
        insteadOf = https://gitlab.com/
[url "ssh://git@bitbucket.org/"]
  insteadOf = https://bitbucket.org/
[url "git@gitlab.com:"]
        insteadOf = https://gitlab.com/
</code>```

The error still persists.

I would expect the package to be downloaded from my private gitlab project repository to the current project.

Is there anything I need to do in my private gitlab project repository to make it ready for 'go get' ?

The private gitlab project repository already contains the go.sum and go.mod for the project as well.

Anything that I am missing ?

edit: 1) The private repo name and the company name contains no asterisks or any other special characters. only alphabets and not even numeric characters.

答:
Basically it failed to verify private repository. However I don't like turning off checksum, but you can easily set GOSUMDB to off before trying to get module. something like this:

```<code>GOSUMDB=off go get github.com/mycompany/myproject
</code>```

ref: https://github.com/golang/go/issues/35164#issuecomment-546503518

A second and better solution is to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database. The variable is a comma-separated list of glob patterns (same syntax of Go's path.Match) of module path prefixes. For example,

```<code>export GOPRIVATE=*.corp.example.com,rsc.io/private
</code>```

Or

```<code>go env -w GOPRIVATE=github.com/mycompany/*
</code>```

Last solution you can try is to turn off such checks for all private repositories that you don't want to go public or being verified through  sum.golang.org/lookup/github.com/mycompany/...

```<code>GONOSUMDB=gitlab.com/mycompany/* go mod why
</code>```

Note that:

If you have issues fetching modules or repos over https, you may want to add the following to your ~/.gitconfig to make go get/fetch repositories using ssh instead of https

[url "ssh://git@github.com/"]
       insteadOf = https://github.com/

Body:
I am using golang 1.13 .

I have a project that depends on a private gitlab project.

I have the ssh keys for the same.

When I try to retrieve the dependencies for a newly created module, I am getting the following error:

$ go version
go version go1.13 linux/amd64

$ go mod why
go: downloading gitlab.com/mycompany/myproject v0.0.145
verifying gitlab.com/mycompany/myproject@v0.0.145: gitlab.com/mycompany/myproject@v0.0.145: reading https://sum.golang.org/lookup/gitlab.com/mycompany/myproject@v0.0.145: 410 Gone

I have no idea why it is trying to ping sum.golang.org/lookup since it is a private gitlab project.

My ~/.gitconfig contains the following (based on my looking up in google search for similar errors)

# Enforce SSH
[url "ssh://git@github.com/"]
  insteadOf = https://github.com/
[url "ssh://git@gitlab.com/"]
        insteadOf = https://gitlab.com/
[url "ssh://git@bitbucket.org/"]
  insteadOf = https://bitbucket.org/
[url "git@gitlab.com:"]
        insteadOf = https://gitlab.com/

The error still persists.

I would expect the package to be downloaded from my private gitlab project repository to the current project.

Is there anything I need to do in my private gitlab project repository to make it ready for 'go get' ?

The private gitlab project repository already contains the go.sum and go.mod for the project as well.

Anything that I am missing ?

edit: 1) The private repo name and the company name contains no asterisks or any other special characters. only alphabets and not even numeric characters.

Body:
Basically it failed to verify private repository. However I don't like turning off checksum, but you can easily set GOSUMDB to off before trying to get module. something like this:

GOSUMDB=off go get github.com/mycompany/myproject

ref: https://github.com/golang/go/issues/35164#issuecomment-546503518

A second and better solution is to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database. The variable is a comma-separated list of glob patterns (same syntax of Go's path.Match) of module path prefixes. For example,

export GOPRIVATE=*.corp.example.com,rsc.io/private

Or

go env -w GOPRIVATE=github.com/mycompany/*

Last solution you can try is to turn off such checks for all private repositories that you don't want to go public or being verified through  sum.golang.org/lookup/github.com/mycompany/...

GONOSUMDB=gitlab.com/mycompany/* go mod why

Note that:

If you have issues fetching modules or repos over https, you may want to add the following to your ~/.gitconfig to make go get/fetch repositories using ssh instead of https

[url "ssh://git@github.com/"]
       insteadOf = https://github.com/


来源: stackexchange

问:
ASP.NET Core 2.0 combining Cookies and Bearer Authorization for the same endpoint
I've created a new ASP.NET Core Web Application project in VS17 using the "Web Application (Model-View-Controller)" template and ".Net Framework" + "ASP.NET Core 2" as the configuration. The authentication config is set to "Individual User Accounts".

I have the following sample endpoint:

```<code>[Produces("application/json")]
[Route("api/price")]
[Authorize(Roles = "PriceViwer", AuthenticationSchemes = "Cookies,Bearer")]
public class PriceController : Controller
{

    public IActionResult Get()
    {
        return Ok(new Dictionary<string, string> { {"Galleon/Pound",
                                                   "999.999" } );
    }
}
</code>```

"Cookies,Bearer" is derived by  concatenating CookieAuthenticationDefaults.AuthenticationScheme and JwtBearerDefaults.AuthenticationScheme.

The objective is to be able to configure the authorization for the end point so that it's possible access it using both the token and cookie authentication methods.

Here is the setup I have for Authentication in my Startup.cs:

```<code>    services.AddAuthentication()
        .AddCookie(cfg => { cfg.SlidingExpiration = true;})
        .AddJwtBearer(cfg => {
            cfg.RequireHttpsMetadata = false;
            cfg.SaveToken = true;
            cfg.TokenValidationParameters = new TokenValidationParameters() {
                                                    ValidIssuer = Configuration["Tokens:Issuer"],
                                                    ValidAudience = Configuration["Tokens:Issuer"],
                                                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                                                };
        });
</code>```

So, when I try to access the endpoint using a browser, I get the 401 response with a blank html page.

Then I login and when I try to access the endpoint again, I get the same response.

Then, I try to access the endpoint by specifying the bearer token. And that returns the desired result with the 200 response.

So then, if I remove [Authorize(AuthenticationSchemes = "Cookies,Bearer")], the situation becomes the opposite - cookie authentication works and returns 200, however the same bearer token method as used above doesn't give any results and just redirect to the default AspIdentity login page.

I can see two possible problems here:

1) ASP.NET Core doesn't allow 'combined' authentication.
2) 'Cookies' is not a valid schema name. But then what is the right one to use?

Please advise. Thank you.

答:
Tested with Asp.net Core 2.2

```<code>JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddAuthentication(options =>
    {
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.Authority = "https://localhost:4991";
        options.RequireHttpsMetadata = false;
        // name of the API resource
        options.Audience = "api";
    });

services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.Authority = "https://localhost:4991";
        options.RequireHttpsMetadata = false;

        options.ClientId = "WebApp";
        options.ClientSecret = "secret";

        options.ResponseType = "code id_token";
        options.Scope.Add("api");
        options.SaveTokens = true;
    });

services.AddAuthorization(options =>
{
    // Add policies for API scope claims
     options.AddPolicy(AuthorizationConsts.ReadPolicy,
        policy => policy.RequireAssertion(context =>
            context.User.HasClaim(c =>
                ((c.Type == AuthorizationConsts.ScopeClaimType && c.Value == AuthorizationConsts.ReadScope)
                || (c.Type == AuthorizationConsts.IdentityProviderClaimType))) && context.User.Identity.IsAuthenticated
        ));
    // No need to add default policy here
});

app.UseAuthentication();
app.UseCookiePolicy();
</code>```

In the controller, add necessary Authorize attribute

```<code>[Authorize(AuthenticationSchemes = AuthorizationConsts.BearerOrCookiesAuthenticationScheme, Policy = AuthorizationConsts.ReadPolicy)]
</code>```

Here is the helper class

```<code>public class AuthorizationConsts
{
    public const string BearerOrCookiesAuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme + "," + IdentityServerAuthenticationDefaults.AuthenticationScheme;
    public const string IdentityProviderClaimType = "idp";
    public const string ScopeClaimType = "scope";
    public const string ReadPolicy = "RequireReadPolicy";
    public const string ReadScope = "data:read";
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've created a new ASP.NET Core Web Application project in VS17 using the "Web Application (Model-View-Controller)" template and ".Net Framework" + "ASP.NET Core 2" as the configuration. The authentication config is set to "Individual User Accounts".

I have the following sample endpoint:

[Produces("application/json")]
[Route("api/price")]
[Authorize(Roles = "PriceViwer", AuthenticationSchemes = "Cookies,Bearer")]
public class PriceController : Controller
{

    public IActionResult Get()
    {
        return Ok(new Dictionary<string, string> { {"Galleon/Pound",
                                                   "999.999" } );
    }
}

"Cookies,Bearer" is derived by  concatenating CookieAuthenticationDefaults.AuthenticationScheme and JwtBearerDefaults.AuthenticationScheme.

The objective is to be able to configure the authorization for the end point so that it's possible access it using both the token and cookie authentication methods.

Here is the setup I have for Authentication in my Startup.cs:

    services.AddAuthentication()
        .AddCookie(cfg => { cfg.SlidingExpiration = true;})
        .AddJwtBearer(cfg => {
            cfg.RequireHttpsMetadata = false;
            cfg.SaveToken = true;
            cfg.TokenValidationParameters = new TokenValidationParameters() {
                                                    ValidIssuer = Configuration["Tokens:Issuer"],
                                                    ValidAudience = Configuration["Tokens:Issuer"],
                                                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                                                };
        });

So, when I try to access the endpoint using a browser, I get the 401 response with a blank html page.

Then I login and when I try to access the endpoint again, I get the same response.

Then, I try to access the endpoint by specifying the bearer token. And that returns the desired result with the 200 response.

So then, if I remove [Authorize(AuthenticationSchemes = "Cookies,Bearer")], the situation becomes the opposite - cookie authentication works and returns 200, however the same bearer token method as used above doesn't give any results and just redirect to the default AspIdentity login page.

I can see two possible problems here:

1) ASP.NET Core doesn't allow 'combined' authentication.
2) 'Cookies' is not a valid schema name. But then what is the right one to use?

Please advise. Thank you.

Body:
Tested with Asp.net Core 2.2

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddAuthentication(options =>
    {
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.Authority = "https://localhost:4991";
        options.RequireHttpsMetadata = false;
        // name of the API resource
        options.Audience = "api";
    });

services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.Authority = "https://localhost:4991";
        options.RequireHttpsMetadata = false;

        options.ClientId = "WebApp";
        options.ClientSecret = "secret";

        options.ResponseType = "code id_token";
        options.Scope.Add("api");
        options.SaveTokens = true;
    });

services.AddAuthorization(options =>
{
    // Add policies for API scope claims
     options.AddPolicy(AuthorizationConsts.ReadPolicy,
        policy => policy.RequireAssertion(context =>
            context.User.HasClaim(c =>
                ((c.Type == AuthorizationConsts.ScopeClaimType && c.Value == AuthorizationConsts.ReadScope)
                || (c.Type == AuthorizationConsts.IdentityProviderClaimType))) && context.User.Identity.IsAuthenticated
        ));
    // No need to add default policy here
});

app.UseAuthentication();
app.UseCookiePolicy();

In the controller, add necessary Authorize attribute

[Authorize(AuthenticationSchemes = AuthorizationConsts.BearerOrCookiesAuthenticationScheme, Policy = AuthorizationConsts.ReadPolicy)]

Here is the helper class

public class AuthorizationConsts
{
    public const string BearerOrCookiesAuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme + "," + IdentityServerAuthenticationDefaults.AuthenticationScheme;
    public const string IdentityProviderClaimType = "idp";
    public const string ScopeClaimType = "scope";
    public const string ReadPolicy = "RequireReadPolicy";
    public const string ReadScope = "data:read";
}


问:
Pythonic way of not printing a error message up
I am trying to suppress a error/warning in my log while calling a library. Assume i have this code

```<code>        try:
            kazoo_client.start()
        except:
            pass
</code>```

This is calling a zookeeper client which throws some exception which bubble up, now i don't want the warn/error in my logs when i call kazoo_client.start() is there a way to get this suppressed when you call the client

答:
If you know the exception, try contextlib.suppress:

```<code>>>> from contextlib import suppress
>>> x = (i for i in range(10))
>>> with suppress(StopIteration):
...     for i in range(11):
...         print(next(x))

0
1
2
3
4
5
6
7
8
9
</code>```

Without suppress it throws StopIteration error at last iteration.

```<code>>>> x = (i for i in range(10))

>>> for i in range(11):
...     print(next(x))

0
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):

  File "<ipython-input-10-562798e05ad5>", line 2, in <module>
    print(next(x))

StopIteration
</code>```

Suppress is Pythonic, safe and explicit.

So in your case:

```<code>with suppress(SomeError):
    kazoo_client.start()
</code>```

EDIT:

To suppress all exceptions:

```<code>with suppress(Exception):
    kazoo_client.start()
</code>```

Body:
I am trying to suppress a error/warning in my log while calling a library. Assume i have this code

        try:
            kazoo_client.start()
        except:
            pass

This is calling a zookeeper client which throws some exception which bubble up, now i don't want the warn/error in my logs when i call kazoo_client.start() is there a way to get this suppressed when you call the client

Body:
If you know the exception, try contextlib.suppress:

>>> from contextlib import suppress
>>> x = (i for i in range(10))
>>> with suppress(StopIteration):
...     for i in range(11):
...         print(next(x))

0
1
2
3
4
5
6
7
8
9

Without suppress it throws StopIteration error at last iteration.

>>> x = (i for i in range(10))

>>> for i in range(11):
...     print(next(x))

0
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):

  File "<ipython-input-10-562798e05ad5>", line 2, in <module>
    print(next(x))

StopIteration

Suppress is Pythonic, safe and explicit.

So in your case:

with suppress(SomeError):
    kazoo_client.start()

EDIT:

To suppress all exceptions:

with suppress(Exception):
    kazoo_client.start()


问:
How do you get the name of a property using the property itself
I've run into an issue where I need to get the name of a property for logging purposes.  I'm sure there is a way to do this in VB.Net using some amalgam of reflection and lambda expressions, but I've been unsuccessful so far.

What I'm trying to do is convert this:

```<code>objAddress.AddressLine
</code>```

to this:

```<code>"AddressLine"
</code>```

答:
Using the System.Runtime.CompilerServices works wonders in this case, as of Net4.5. [See Caller Information] The optional CallerMemberName string can be used to identify what method/property called the log.

From MSDN

```<code>Private Sub DoProcessing()
    TraceMessage("Something happened.")
End Sub

Public Sub TraceMessage(message As String,
        <System.Runtime.CompilerServices.CallerMemberName> Optional memberName As String = Nothing,
        <System.Runtime.CompilerServices.CallerFilePath> Optional sourcefilePath As String = Nothing,
        <System.Runtime.CompilerServices.CallerLineNumber()> Optional sourceLineNumber As Integer = 0)

    System.Diagnostics.Trace.WriteLine("message: " & message)
    System.Diagnostics.Trace.WriteLine("member name: " & memberName)
    System.Diagnostics.Trace.WriteLine("source file path: " & sourcefilePath)
    System.Diagnostics.Trace.WriteLine("source line number: " & sourceLineNumber)
End Sub

' Sample output:
'   message: Something happened.
'   member name: DoProcessing
'   source file path: C:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoVB\CallerInfoVB\Form1.vb
'   source line number: 15
</code>```

Different implementation showing results from a Property Call

```<code>Class Foo
    Public ReadOnly Property ThisPropertyObject As Object
        Get
            LogManager.Ping
            Return Nothing
        End Get
    End Property
    Sub New()
      Dim this = ThisPropertyObject
    End Sub
End Class

Public Module LogManager
        Public Sub Ping(<CallerMemberName> Optional memberName As String = Nothing,
                        <CallerFilePath> Optional sourcefilePath As String = Nothing,
                        <CallerLineNumber> Optional sourceLineNumber As Integer = 0)
            Trace.Writeline(String.Format("[{0}]|{1}|LN:{2}] <PING>",
                                          Path.GetFileName(sourcefilePath),
                                          memberName,
                                          sourceLineNumber)
                                          )
                            )
        End Sub

End Module

'! Results from 'DebugView'
' [20692][LogTestFile.vb|ThisPropertyObject|LN:62] <PING>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've run into an issue where I need to get the name of a property for logging purposes.  I'm sure there is a way to do this in VB.Net using some amalgam of reflection and lambda expressions, but I've been unsuccessful so far.

What I'm trying to do is convert this:

objAddress.AddressLine

to this:

"AddressLine"

Body:
Using the System.Runtime.CompilerServices works wonders in this case, as of Net4.5. [See Caller Information] The optional CallerMemberName string can be used to identify what method/property called the log.

From MSDN

Private Sub DoProcessing()
    TraceMessage("Something happened.")
End Sub

Public Sub TraceMessage(message As String,
        <System.Runtime.CompilerServices.CallerMemberName> Optional memberName As String = Nothing,
        <System.Runtime.CompilerServices.CallerFilePath> Optional sourcefilePath As String = Nothing,
        <System.Runtime.CompilerServices.CallerLineNumber()> Optional sourceLineNumber As Integer = 0)

    System.Diagnostics.Trace.WriteLine("message: " & message)
    System.Diagnostics.Trace.WriteLine("member name: " & memberName)
    System.Diagnostics.Trace.WriteLine("source file path: " & sourcefilePath)
    System.Diagnostics.Trace.WriteLine("source line number: " & sourceLineNumber)
End Sub

' Sample output:
'   message: Something happened.
'   member name: DoProcessing
'   source file path: C:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoVB\CallerInfoVB\Form1.vb
'   source line number: 15

Different implementation showing results from a Property Call

Class Foo
    Public ReadOnly Property ThisPropertyObject As Object
        Get
            LogManager.Ping
            Return Nothing
        End Get
    End Property
    Sub New()
      Dim this = ThisPropertyObject
    End Sub
End Class

Public Module LogManager
        Public Sub Ping(<CallerMemberName> Optional memberName As String = Nothing,
                        <CallerFilePath> Optional sourcefilePath As String = Nothing,
                        <CallerLineNumber> Optional sourceLineNumber As Integer = 0)
            Trace.Writeline(String.Format("[{0}]|{1}|LN:{2}] <PING>",
                                          Path.GetFileName(sourcefilePath),
                                          memberName,
                                          sourceLineNumber)
                                          )
                            )
        End Sub

End Module

'! Results from 'DebugView'
' [20692][LogTestFile.vb|ThisPropertyObject|LN:62] <PING>


问:
remainders for fractions in python
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

```<code>print(1%2)
=1

print(2%4)
=2
</code>```

答:
If you split 20 donuts among 3 people, everyone gets 6 donuts and 2 donuts remain.

If you split 1 donut among 2 people, everyone gets 0 donuts and 1 donut remains.

If you split 2 donuts among 4 people, everyone gets 0 donuts and 2 donuts remain.

Title: remainders for fractions in python

Body:
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

print(1%2)
=1

print(2%4)
=2


问:
new thread is created, but doesn't run (java)
here's a little code I wrote. This next class waits for a connection and creates a new thread upon receiving one:

```<code>    ServerSocket serverSocket = null;
    ExecutorService serv = Executors.newCachedThreadPool();
    serv.execute(new UserThread());
    try {
        serverSocket = new ServerSocket(FMDataManager.getPort());
        serverSocket.setSoTimeout(0);
        while (_listening){
            System.out.println("Listening on port "+FMDataManager.getPort());
            System.out.println("Waiting for connections.");
            serv.execute(new UploadThread(serverSocket.accept()));
        }
    } catch (IOException e) {
        System.err.println("Could not listen on port: "+FMDataManager.getPort()+".");
        System.exit(-1);
    }
</code>```

as you can see i am using ServerSocket.accept() method to wait for a connection.
The thread is indeed created, but it won't run. I put a little "thread created" in its constructor and another message "starting thread" in run(), but I only got the  first message. After that it didn't do anything, I didn't even get "thread created".
Any ideas please?

I've add the implementation of the UploadThread I am trying to start, maybe It'll help

```<code>public class UploadThread extends Thread{

Socket _socket;

public UploadThread(Socket socket) {
    super("UserThread");
    _socket = socket;
}
public void run(Socket socket) {
    System.out.println("entred upload thread");
    DataOutputStream out = null;
    DataInputStream in = null;
    try {
        out = new DataOutputStream(_socket.getOutputStream());
        in = new DataInputStream(_socket.getInputStream());
        FileMessage inputMessage;
        SendFile outputMessage;
        inputMessage = (FileMessage) CommandEnum.readMessage(in);
        System.out.println("F: "+inputMessage.getCaption());
        File file = null;
        Iterator<File> itr = FMDataManager.getFiles().iterator();
        while (itr.hasNext()){
            File temp = itr.next();
            if (temp.getName().equals(inputMessage.getFile()))
                file = temp;
        }
        outputMessage = new SendFile(file);
        outputMessage.send(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            _socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}
</code>```

答:
Try serv.submit instead of serv.execute.

EDIT

Looks like UploadThread isn't overriding run() correctly. That being said, your run method declaration should look like this:

```<code>@Override
public void run(){
    //do stuff
}
</code>```

There's no need to pass socket as an argument.

Body:
here's a little code I wrote. This next class waits for a connection and creates a new thread upon receiving one:

    ServerSocket serverSocket = null;
    ExecutorService serv = Executors.newCachedThreadPool();
    serv.execute(new UserThread());
    try {
        serverSocket = new ServerSocket(FMDataManager.getPort());
        serverSocket.setSoTimeout(0);
        while (_listening){
            System.out.println("Listening on port "+FMDataManager.getPort());
            System.out.println("Waiting for connections.");
            serv.execute(new UploadThread(serverSocket.accept()));
        }
    } catch (IOException e) {
        System.err.println("Could not listen on port: "+FMDataManager.getPort()+".");
        System.exit(-1);
    }

as you can see i am using ServerSocket.accept() method to wait for a connection.
The thread is indeed created, but it won't run. I put a little "thread created" in its constructor and another message "starting thread" in run(), but I only got the  first message. After that it didn't do anything, I didn't even get "thread created".
Any ideas please?

I've add the implementation of the UploadThread I am trying to start, maybe It'll help

public class UploadThread extends Thread{

Socket _socket;

public UploadThread(Socket socket) {
    super("UserThread");
    _socket = socket;
}
public void run(Socket socket) {
    System.out.println("entred upload thread");
    DataOutputStream out = null;
    DataInputStream in = null;
    try {
        out = new DataOutputStream(_socket.getOutputStream());
        in = new DataInputStream(_socket.getInputStream());
        FileMessage inputMessage;
        SendFile outputMessage;
        inputMessage = (FileMessage) CommandEnum.readMessage(in);
        System.out.println("F: "+inputMessage.getCaption());
        File file = null;
        Iterator<File> itr = FMDataManager.getFiles().iterator();
        while (itr.hasNext()){
            File temp = itr.next();
            if (temp.getName().equals(inputMessage.getFile()))
                file = temp;
        }
        outputMessage = new SendFile(file);
        outputMessage.send(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            _socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

Body:
Try serv.submit instead of serv.execute.

EDIT

Looks like UploadThread isn't overriding run() correctly. That being said, your run method declaration should look like this:

@Override
public void run(){
    //do stuff
}

There's no need to pass socket as an argument.


问:
Azure Cognitive Services Face Android - NoClassDefFoundError
I am trying to make an app to detect face using Face API from Azure's tutorial. When I try to run the app, I get an Error:

java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/DefaultHttpClient;

at com.microsoft.projectoxford.face.rest.WebServiceRequest.(WebServiceRequest.java:67)

at com.microsoft.projectoxford.face.FaceServiceRestClient.(FaceServiceRestClient.java:99)

at com.contoso.facetutorial.MainActivity.(MainActivity.java:28)

Here is my code:

MainActivity.java

```<code>package com.contoso.facetutorial;

// <snippet_imports>
import java.io.*;
import java.lang.Object.*;
import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.view.*;
import android.graphics.*;
import android.widget.*;
import android.provider.*;
// </snippet_imports>

// <snippet_face_imports>
import com.microsoft.projectoxford.face.*;
import com.microsoft.projectoxford.face.contract.*;
// </snippet_face_imports>

public class MainActivity extends Activity {
    // <snippet_mainactivity_fields>
    // Add your Face endpoint to your environment variables.
    private final String apiEndpoint = "https://ceranfaceapi.cognitiveservices.azure.com/";
    // Add your Face subscription key to your environment variables.
    private final String subscriptionKey = "xxxx";

    private final FaceServiceClient faceServiceClient =
            new FaceServiceRestClient(apiEndpoint, subscriptionKey);

    private final int PICK_IMAGE = 1;
    private ProgressDialog detectionProgressDialog;
    // </snippet_mainactivity_fields>

    // <snippet_mainactivity_methods>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(
                        intent, "Select Picture"), PICK_IMAGE);
            }
        });

        detectionProgressDialog = new ProgressDialog(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK &&
                data != null && data.getData() != null) {
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                        getContentResolver(), uri);
                ImageView imageView = findViewById(R.id.imageView1);
                imageView.setImageBitmap(bitmap);

                // Comment out for tutorial
                detectAndFrame(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // </snippet_mainactivity_methods>
    }

    // <snippet_detection_methods>
    // Detect faces by uploading a face image.
    // Frame faces after detection.
    private void detectAndFrame(final Bitmap imageBitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        ByteArrayInputStream inputStream =
                new ByteArrayInputStream(outputStream.toByteArray());

        AsyncTask<InputStream, String, Face[]> detectTask =
                new AsyncTask<InputStream, String, Face[]>() {
                    String exceptionMessage = "";

                    @Override
                    protected Face[] doInBackground(InputStream... params) {
                        try {
                            publishProgress("Detecting...");
                            Face[] result = faceServiceClient.detect(
                                    params[0],
                                    true,         // returnFaceId
                                    false,        // returnFaceLandmarks
                                    null          // returnFaceAttributes:
                                    /* new FaceServiceClient.FaceAttributeType[] {
                                        FaceServiceClient.FaceAttributeType.Age,
                                        FaceServiceClient.FaceAttributeType.Gender }
                                    */
                            );
                            if (result == null){
                                publishProgress(
                                        "Detection Finished. Nothing detected");
                                return null;
                            }
                            publishProgress(String.format(
                                    "Detection Finished. %d face(s) detected",
                                    result.length));
                            return result;
                        } catch (Exception e) {
                            exceptionMessage = String.format(
                                    "Detection failed: %s", e.getMessage());
                            return null;
                        }
                    }

                    @Override
                    protected void onPreExecute() {
                        //TODO: show progress dialog
                        detectionProgressDialog.show();
                    }
                    @Override
                    protected void onProgressUpdate(String... progress) {
                        //TODO: update progress
                        detectionProgressDialog.setMessage(progress[0]);
                    }
                    @Override
                    protected void onPostExecute(Face[] result) {
                        //TODO: update face frames
                        detectionProgressDialog.dismiss();

                        if(!exceptionMessage.equals("")){
                            showError(exceptionMessage);
                        }
                        if (result == null) return;

                        ImageView imageView = findViewById(R.id.imageView1);
                        imageView.setImageBitmap(
                                drawFaceRectanglesOnBitmap(imageBitmap, result));
                        imageBitmap.recycle();
                    }
                };

        detectTask.execute(inputStream);
    }

    private void showError(String message) {
        new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    }})
                .create().show();
    }
    // </snippet_detection_methods>

    // <snippet_drawrectangles>
    private static Bitmap drawFaceRectanglesOnBitmap(
            Bitmap originalBitmap, Face[] faces) {
        Bitmap bitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(10);
        if (faces != null) {
            for (Face face : faces) {
                FaceRectangle faceRectangle = face.faceRectangle;
                canvas.drawRect(
                        faceRectangle.left,
                        faceRectangle.top,
                        faceRectangle.left + faceRectangle.width,
                        faceRectangle.top + faceRectangle.height,
                        paint);
            }
        }
        return bitmap;
    }
    // </snippet_drawrectangles>
}
</code>```

答:
To continue using the Apache HTTP client, apps that target Android 9 and above can add the following to their AndroidManifest.xml:

```<code><uses-library android:name="org.apache.http.legacy" android:required="false"/>
</code>```

Body:
I am trying to make an app to detect face using Face API from Azure's tutorial. When I try to run the app, I get an Error:

java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/DefaultHttpClient;

at com.microsoft.projectoxford.face.rest.WebServiceRequest.(WebServiceRequest.java:67)

at com.microsoft.projectoxford.face.FaceServiceRestClient.(FaceServiceRestClient.java:99)

at com.contoso.facetutorial.MainActivity.(MainActivity.java:28)

Here is my code:

MainActivity.java

package com.contoso.facetutorial;

// <snippet_imports>
import java.io.*;
import java.lang.Object.*;
import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.view.*;
import android.graphics.*;
import android.widget.*;
import android.provider.*;
// </snippet_imports>

// <snippet_face_imports>
import com.microsoft.projectoxford.face.*;
import com.microsoft.projectoxford.face.contract.*;
// </snippet_face_imports>

public class MainActivity extends Activity {
    // <snippet_mainactivity_fields>
    // Add your Face endpoint to your environment variables.
    private final String apiEndpoint = "https://ceranfaceapi.cognitiveservices.azure.com/";
    // Add your Face subscription key to your environment variables.
    private final String subscriptionKey = "xxxx";

    private final FaceServiceClient faceServiceClient =
            new FaceServiceRestClient(apiEndpoint, subscriptionKey);

    private final int PICK_IMAGE = 1;
    private ProgressDialog detectionProgressDialog;
    // </snippet_mainactivity_fields>

    // <snippet_mainactivity_methods>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(
                        intent, "Select Picture"), PICK_IMAGE);
            }
        });

        detectionProgressDialog = new ProgressDialog(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK &&
                data != null && data.getData() != null) {
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                        getContentResolver(), uri);
                ImageView imageView = findViewById(R.id.imageView1);
                imageView.setImageBitmap(bitmap);

                // Comment out for tutorial
                detectAndFrame(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // </snippet_mainactivity_methods>
    }

    // <snippet_detection_methods>
    // Detect faces by uploading a face image.
    // Frame faces after detection.
    private void detectAndFrame(final Bitmap imageBitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        ByteArrayInputStream inputStream =
                new ByteArrayInputStream(outputStream.toByteArray());

        AsyncTask<InputStream, String, Face[]> detectTask =
                new AsyncTask<InputStream, String, Face[]>() {
                    String exceptionMessage = "";

                    @Override
                    protected Face[] doInBackground(InputStream... params) {
                        try {
                            publishProgress("Detecting...");
                            Face[] result = faceServiceClient.detect(
                                    params[0],
                                    true,         // returnFaceId
                                    false,        // returnFaceLandmarks
                                    null          // returnFaceAttributes:
                                    /* new FaceServiceClient.FaceAttributeType[] {
                                        FaceServiceClient.FaceAttributeType.Age,
                                        FaceServiceClient.FaceAttributeType.Gender }
                                    */
                            );
                            if (result == null){
                                publishProgress(
                                        "Detection Finished. Nothing detected");
                                return null;
                            }
                            publishProgress(String.format(
                                    "Detection Finished. %d face(s) detected",
                                    result.length));
                            return result;
                        } catch (Exception e) {
                            exceptionMessage = String.format(
                                    "Detection failed: %s", e.getMessage());
                            return null;
                        }
                    }

                    @Override
                    protected void onPreExecute() {
                        //TODO: show progress dialog
                        detectionProgressDialog.show();
                    }
                    @Override
                    protected void onProgressUpdate(String... progress) {
                        //TODO: update progress
                        detectionProgressDialog.setMessage(progress[0]);
                    }
                    @Override
                    protected void onPostExecute(Face[] result) {
                        //TODO: update face frames
                        detectionProgressDialog.dismiss();

                        if(!exceptionMessage.equals("")){
                            showError(exceptionMessage);
                        }
                        if (result == null) return;

                        ImageView imageView = findViewById(R.id.imageView1);
                        imageView.setImageBitmap(
                                drawFaceRectanglesOnBitmap(imageBitmap, result));
                        imageBitmap.recycle();
                    }
                };

        detectTask.execute(inputStream);
    }

    private void showError(String message) {
        new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    }})
                .create().show();
    }
    // </snippet_detection_methods>

    // <snippet_drawrectangles>
    private static Bitmap drawFaceRectanglesOnBitmap(
            Bitmap originalBitmap, Face[] faces) {
        Bitmap bitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(10);
        if (faces != null) {
            for (Face face : faces) {
                FaceRectangle faceRectangle = face.faceRectangle;
                canvas.drawRect(
                        faceRectangle.left,
                        faceRectangle.top,
                        faceRectangle.left + faceRectangle.width,
                        faceRectangle.top + faceRectangle.height,
                        paint);
            }
        }
        return bitmap;
    }
    // </snippet_drawrectangles>
}

Body:
To continue using the Apache HTTP client, apps that target Android 9 and above can add the following to their AndroidManifest.xml:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>


问:
Codeigniter & Ajax - Console.log data returns CI's landing page in HTML
I want to console.log the result of my query using ajax, but it outputs the CI Landing page in the HTML Code.

JS:

```<code> function getRouters(data)
  {
    $.ajax({
      type: 'POST',
      url: "http://localhost/ldcm/Main_controller/getRouters",
      data: data,
      success: function (data) {
        console.log(data);
      }
    });
  }

$('#generateRes').click(function () {
   var data = userDetailsObj.data.homesize.id + userDetailsObj.data.floors.id + userDetailsObj.data.internetPlan.id + userDetailsObj.data.devices.id;
   console.log(data);
   if(data) {
      getRouters(data);
   } else{

   }
});
</code>```

Controller:

```<code>public function getRouters(){
                $data = $_POST['data'];
                $this->load->model('Query_Model');
                $data = $this->Query_Model->getRouters($data);

                echo json_encode($data);
        }
</code>```

Model:

```<code>public function getRouters($data)
        {
            $this->db->select('*');
            $this->db->where('id', $data);
            $q = $this->db->get('selection');
            $response = $q->result_array();
            return $response;
        }
</code>```

Is it supposed to print that way? Or did i miss a configuration part in config?

答:
As I assume your .htaccess code not working. Second, you need to update your controller code. Update below code:

.htaccess

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /ldcm/
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

</IfModule>
</code>```

Controller

```<code>   public function getRouters()
   {
         $this->load->model('Query_Model');
         $data = $_POST;
         $result = $this->Query_Model->getRouters($data);
         echo json_encode($result);
         exit();
    }
</code>```

As you mentioned in comment you are getting errot Unidentified index: data. it means data parameter is not reciveing in POST request. Verify your POST request what you are getting. And replace $data = $_POST; with $data = $_POST['parameter'];

Body:
I want to console.log the result of my query using ajax, but it outputs the CI Landing page in the HTML Code.

JS:

 function getRouters(data)
  {
    $.ajax({
      type: 'POST',
      url: "http://localhost/ldcm/Main_controller/getRouters",
      data: data,
      success: function (data) {
        console.log(data);
      }
    });
  }

$('#generateRes').click(function () {
   var data = userDetailsObj.data.homesize.id + userDetailsObj.data.floors.id + userDetailsObj.data.internetPlan.id + userDetailsObj.data.devices.id;
   console.log(data);
   if(data) {
      getRouters(data);
   } else{

   }
});

Controller:

public function getRouters(){
                $data = $_POST['data'];
                $this->load->model('Query_Model');
                $data = $this->Query_Model->getRouters($data);

                echo json_encode($data);
        }

Model:

public function getRouters($data)
        {
            $this->db->select('*');
            $this->db->where('id', $data);
            $q = $this->db->get('selection');
            $response = $q->result_array();
            return $response;
        }

Is it supposed to print that way? Or did i miss a configuration part in config?

Body:
As I assume your .htaccess code not working. Second, you need to update your controller code. Update below code:

.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /ldcm/
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

</IfModule>

Controller

   public function getRouters()
   {
         $this->load->model('Query_Model');
         $data = $_POST;
         $result = $this->Query_Model->getRouters($data);
         echo json_encode($result);
         exit();
    }

As you mentioned in comment you are getting errot Unidentified index: data. it means data parameter is not reciveing in POST request. Verify your POST request what you are getting. And replace $data = $_POST; with $data = $_POST['parameter'];


问:
Why are multiple media queries not working?
Trying to get multiple media queries to work on mobile but it only recognizes the first one and the second one does nothing. Please help and thanks.

It won't let me post without writing more text so just ignore this haha.

Again: It won't let me post without writing more text so just ignore this haha.

link to application

/* Medium sized screen */

@media all and (max-width: 1300px) {
  #left {
    width: 300px;
  }
  #right {
    width: calc(100% - 300px);
  }
  /* Filters */
  .filters {
    right: 100%;
    width: 100%;
    background-color: #F7F7F7;
    transition: right 1s;
    position: absolute;
    z-index: 1;
    top: 50px;
    height: calc(100% - 50px);
  }
  .filters .close {
    display: block;
    position: absolute;
    font-size: 30px;
    right: 0;
  }
  .filters.show {
    right: 0;
  }
  .filtersIcon {
    display: flex;
  }
  /* Drink list */
  .totalDrinks {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .drinkList {
    width: 100%;
  }
}

/* Small screens */

@media all and (max-width: 900px) {
  #right {
    left: 100%
  }
  #left {
    width: 100%;
    position: absolute;
  }
  .drinkItem {
    min-height: 280px;
  }
}```
</div>
</div>
</p>

<p><strong>EDIT</strong>
I found the issue, I forgot to add this in the header</p>

```<meta name="viewport" content="width=device-width, initial-scale=1.0">
```

答:
You need to write mobile first media queries. Kindle see the ref: mobile first media queries

```<code>/*
  ##Device = Desktops
  ##Screen = 1281px to higher resolution desktops
*/

@media (min-width: 1281px) {

  //CSS

}

/*
  ##Device = Laptops, Desktops
  ##Screen = B/w 1025px to 1280px
*/

@media (min-width: 1025px) and (max-width: 1280px) {

  //CSS

}

/*
  ##Device = Tablets, Ipads (portrait)
  ##Screen = B/w 768px to 1024px
*/

@media (min-width: 768px) and (max-width: 1024px) {

  //CSS

}

/*
  ##Device = Tablets, Ipads (landscape)
  ##Screen = B/w 768px to 1024px
*/

@media (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {

  //CSS

}

/*
  ##Device = Low Resolution Tablets, Mobiles (Landscape)
  ##Screen = B/w 481px to 767px
*/

@media (min-width: 481px) and (max-width: 767px) {

  //CSS

}

/*
  ##Device = Most of the Smartphones Mobiles (Portrait)
  ##Screen = B/w 320px to 479px
*/

@media (min-width: 320px) and (max-width: 480px) {

  //CSS

}
</code>```

link

Body:
Trying to get multiple media queries to work on mobile but it only recognizes the first one and the second one does nothing. Please help and thanks.

It won't let me post without writing more text so just ignore this haha.

Again: It won't let me post without writing more text so just ignore this haha.

link to application

/* Medium sized screen */

@media all and (max-width: 1300px) {
  #left {
    width: 300px;
  }
  #right {
    width: calc(100% - 300px);
  }
  /* Filters */
  .filters {
    right: 100%;
    width: 100%;
    background-color: #F7F7F7;
    transition: right 1s;
    position: absolute;
    z-index: 1;
    top: 50px;
    height: calc(100% - 50px);
  }
  .filters .close {
    display: block;
    position: absolute;
    font-size: 30px;
    right: 0;
  }
  .filters.show {
    right: 0;
  }
  .filtersIcon {
    display: flex;
  }
  /* Drink list */
  .totalDrinks {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .drinkList {
    width: 100%;
  }
}

/* Small screens */

@media all and (max-width: 900px) {
  #right {
    left: 100%
  }
  #left {
    width: 100%;
    position: absolute;
  }
  .drinkItem {
    min-height: 280px;
  }
}

EDIT
I found the issue, I forgot to add this in the header

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Body:
You need to write mobile first media queries. Kindle see the ref: mobile first media queries

/*
  ##Device = Desktops
  ##Screen = 1281px to higher resolution desktops
*/

@media (min-width: 1281px) {

  //CSS

}

/*
  ##Device = Laptops, Desktops
  ##Screen = B/w 1025px to 1280px
*/

@media (min-width: 1025px) and (max-width: 1280px) {

  //CSS

}

/*
  ##Device = Tablets, Ipads (portrait)
  ##Screen = B/w 768px to 1024px
*/

@media (min-width: 768px) and (max-width: 1024px) {

  //CSS

}

/*
  ##Device = Tablets, Ipads (landscape)
  ##Screen = B/w 768px to 1024px
*/

@media (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {

  //CSS

}

/*
  ##Device = Low Resolution Tablets, Mobiles (Landscape)
  ##Screen = B/w 481px to 767px
*/

@media (min-width: 481px) and (max-width: 767px) {

  //CSS

}

/*
  ##Device = Most of the Smartphones Mobiles (Portrait)
  ##Screen = B/w 320px to 479px
*/

@media (min-width: 320px) and (max-width: 480px) {

  //CSS

}

link


问:
ld: library not found for -lssl
I installed crystal with homebrew brew install crystal-lang. I was able to compile and run a "Hello World!" program, but when I try to compile the example http server (with one slight modification) I get an error.

HTTP server:

```<code>require "http/server"

port = 3000

server = HTTP::Server.new(port) do |context|
  context.response.content_type = "text/plain"
  context.response.print "Hello world! The time is #{Time.now}"
end

puts "listening on http://localhost:" + port.to_s
puts "listening on http://localhost:#{port}"
server.listen
</code>```

Error:

```<code>$ crystal server.cr                                                                                ~/sw/crystal/Lied-Today
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Error: execution of command failed with code: 1: `cc -o "/Users/Matt/.cache/crystal/crystal-run-server.tmp" "${@}"  -rdynamic  -lz `command -v pkg-config > /dev/null && pkg-config --libs libssl || printf %s '-lssl -lcrypto'` `command -v pkg-config > /dev/null && pkg-config --libs libcrypto || printf %s '-lcrypto'` -lpcre -lgc -lpthread /usr/local/Cellar/crystal-lang/0.21.1_1/src/ext/libcrystal.a -levent -liconv -ldl -L/usr/lib -L/usr/local/lib`
</code>```

I've tried the following:

Adding export LIBRARY_PATH="$LIBRARY_PATH:/usr/local/lib" to ~/.zshrc.

and

```<code>$ xcode-select --install
$ xcode-select --switch /Library/Developer/CommandLineTools
</code>```

答:
I had to add LIBRARY_PATH to fix this.</p>

```<code>export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/
</code>```

Title: ld: library not found for -lssl

Body:
I installed crystal with homebrew brew install crystal-lang. I was able to compile and run a "Hello World!" program, but when I try to compile the example http server (with one slight modification) I get an error.

HTTP server:

require "http/server"

port = 3000

server = HTTP::Server.new(port) do |context|
  context.response.content_type = "text/plain"
  context.response.print "Hello world! The time is #{Time.now}"
end

puts "listening on http://localhost:" + port.to_s
puts "listening on http://localhost:#{port}"
server.listen

Error:

$ crystal server.cr                                                                                ~/sw/crystal/Lied-Today
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Error: execution of command failed with code: 1: `cc -o "/Users/Matt/.cache/crystal/crystal-run-server.tmp" "${@}"  -rdynamic  -lz `command -v pkg-config > /dev/null && pkg-config --libs libssl || printf %s '-lssl -lcrypto'` `command -v pkg-config > /dev/null && pkg-config --libs libcrypto || printf %s '-lcrypto'` -lpcre -lgc -lpthread /usr/local/Cellar/crystal-lang/0.21.1_1/src/ext/libcrystal.a -levent -liconv -ldl -L/usr/lib -L/usr/local/lib`

I've tried the following:

Adding export LIBRARY_PATH="$LIBRARY_PATH:/usr/local/lib" to ~/.zshrc.

and

$ xcode-select --install
$ xcode-select --switch /Library/Developer/CommandLineTools

Body:
I had to add LIBRARY_PATH to fix this.

export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/


问:
Showing checked checkboxes with Vue.js
I am very new to vue, just need to change some code to make it work, and havent played much with vue.
Can you please help.

I have a form with multiple checkboxes, just need to display checked checkboxes from array.

```<code> <script>
    const sites = {"BN-C":"Brisbane Central","ML-C":"Melbourne Central","AMB-C":"Amberley Central","PEA-C":"Pearce Central"};
    let enabledSites = [];
    let selectedSites = ["BN-C","ML-C"];

    Vue.component('site_assignment', {
        data() {
            return {
                sites: sites,
                enabledSites : [],
                selectedSites: selectedSites,
            }
        },
        template: `
            <div class="form-group">
                <div class="row form-group" v-for="(key,val) in sites">
                    <div class="col-sm-1"></div>
                     <div class="col-sm-1">
                        <label for="site_assignment" class="control-label">@{{ key }}</label>
                    </div>
                    <div class="col-sm-2">
                        <input type="checkbox" :id="val" :value="val" v-model="enabledSites" @change="check()" v-bind:checked="selected">
                    </div>
                </div>
            </div>`,
        methods:{
            check(){
                enabledSites = this.enabledSites;
            },
        },
        computed: {
            selected(){
                return true;
            }
        }
    });

    new Vue({
        el: '#site_assignment',
    })
</script>
</code>```

I tried using v-bind but thats not working.
My sites object is having all sites and the selectedSites have items which should get checked.

enabledSites gets updated when you check/uncheck items and this is then used by other script.

So BN-C and ML-C shoudl be checked.

答:
new Vue({
  el: '#app',
  data: {
    sites: {
      "BN-C": "Brisbane Central",
      "ML-C": "Melbourne Central",
      "AMB-C": "Amberley Central",
      "PEA-C": "Pearce Central"
    },
    enabledSites: ["BN-C", "ML-C"]
  },
  methods: {
    check() {
      console.log(this.enabledSites);
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue"></script>

<div id="app">
  <div class="form-group">
      <div class="row form-group" v-for="(key,val) in sites" :key="key">
        <div class="col-sm-1"></div>
        <div class="col-sm-1">
          <label for="site_assignment" class="control-label">@{{ key }}</label>
        </div>
        <div class="col-sm-2">
          <input type="checkbox" :id="val" :value="val" v-model="enabledSites" @change="check()">
        </div>
      </div>
    </div>
</div></code>```

If are using v-model, checked wont work in the checkbox. You have to handle that manually.
Here the link that might help you  In Vue, v-binding is not working on the "checked" property for Bootstrap Toggle Checkboxes?

Title: Showing checked checkboxes with Vue.js

Body:
I am very new to vue, just need to change some code to make it work, and havent played much with vue.
Can you please help.

I have a form with multiple checkboxes, just need to display checked checkboxes from array.

I tried using v-bind but thats not working.
My sites object is having all sites and the selectedSites have items which should get checked.

enabledSites gets updated when you check/uncheck items and this is then used by other script.

So BN-C and ML-C shoudl be checked.

Body:
new Vue({
  el: '#app',
  data: {
    sites: {
      "BN-C": "Brisbane Central",
      "ML-C": "Melbourne Central",
      "AMB-C": "Amberley Central",
      "PEA-C": "Pearce Central"
    },
    enabledSites: ["BN-C", "ML-C"]
  },
  methods: {
    check() {
      console.log(this.enabledSites);
    }
  }
})

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div class="form-group">
      <div class="row form-group" v-for="(key,val) in sites" :key="key">
        <div class="col-sm-1"></div>
        <div class="col-sm-1">
          <label for="site_assignment" class="control-label">@{{ key }}</label>
        </div>
        <div class="col-sm-2">
          <input type="checkbox" :id="val" :value="val" v-model="enabledSites" @change="check()">
        </div>
      </div>
    </div>
</div>

If are using v-model, checked wont work in the checkbox. You have to handle that manually.
Here the link that might help you  In Vue, v-binding is not working on the "checked" property for Bootstrap Toggle Checkboxes?


问:
Restarting service after changing System Time .NET
I have the following code in my sample program.
Here I am printing the DateTime.Now every 1 second.
Now inbetween if I change the system time to another timezone still the DateTime.Now is taking old value only.
Why is this the case? When I restart the service the new DateTime is reflected. Can someone please explain this? I am changing the timezone of the System manually from Windows Date Time UI while the program is running.</p>

```<code>class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine(DateTime.Now);
                Thread.Sleep(1000);
            }
            Console.ReadLine();
        }
    }
</code>```

答:
The code for the timezone is cached: https://learn.microsoft.com/en-us/dotnet/api/system.timezone.currenttimezone?view=netframework-4.8#notes-to-callers

Local time zone data is cached after CurrentTimeZone is first used to retrieve time zone information. If the system's local time zone subsequently changes, the CurrentTimeZone property does not reflect this change. If you need to handle time zone changes while your application is running, use the TimeZoneInfo class and call its ClearCachedData() method.

Body:
I have the following code in my sample program.
Here I am printing the DateTime.Now every 1 second.
Now inbetween if I change the system time to another timezone still the DateTime.Now is taking old value only.
Why is this the case? When I restart the service the new DateTime is reflected. Can someone please explain this? I am changing the timezone of the System manually from Windows Date Time UI while the program is running.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine(DateTime.Now);
                Thread.Sleep(1000);
            }
            Console.ReadLine();
        }
    }


问:
VBA Hiding Columns and Rows using Cell Reference
I would like to hide certain columns and rows based on inputs into certain cells, to make the code easily editable.

Furthermore, if the reference cell/range is empty, then I would like to continue the code without hiding any rows or columns.

Columns to Hide: based on cells C8:D8

Rows to Hide: based on cells C9:D9

This is where the logical fest should take place

```<code>

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value
</code>```

Current Code

```<code>Option Explicit

Private Sub CommandButton1_Click()

Dim MyFolder As String, MyFile As String
Dim StartTime As Double
Dim MinutesElapsed As String
Dim Filename As String
Dim Cell As String
Dim Counter As Long

If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

MsgBox "Enter Tab Name"
Exit Sub

End If

With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a Folder"
If .Show = True Then
MyFolder = .SelectedItems(1)

End If

If .SelectedItems.Count = 0 Then Exit Sub
Err.Clear
End With

Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

MyFile = Dir(MyFolder & "\", vbReadOnly)

StartTime = Timer

Do While MyFile <> ""
DoEvents
On Error GoTo 0

Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
 Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
' Set a reference to the settings sheet

Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source

' Gather the report sheet's name

reportSheetName = settingsSheet.Range("C7").Value ' good

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

Set reportSheet = Sheets(reportSheetName)

Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

Set targetRowsRange = reportSheet.Range(reportRowsAddr)

targetColumnsRange.EntireColumn.Hidden = True
targetRowsRange.EntireRow.Hidden = True

With reportSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1 '.FitToPagesTall = 1
End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

reportSheet.Select
reportSheet.PageSetup.Orientation = xlLandscape

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

ThisWorkbook.Path & "\" & Cell, _

Quality:=xlQualityStandard, IncludeDocProperties:=True, _

IgnorePrintAreas:=True, OpenAfterPublish:=False

Counter = Counter + 1

0

Workbooks(MyFile).Close SaveChanges:=False

MyFile = Dir

Loop

'turns settings back on

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub
</code>```

答:
Replace "" with """" :</p>

```<code>TEST1 = "(" & """" & ThisWorkbook.Sheets("Sheet1").Range("C8").Value & ThisWorkbook.Sheets("Sheet1")
.Range("D8").Value & """" & ")"
</code>```

Body:
I would like to hide certain columns and rows based on inputs into certain cells, to make the code easily editable.

Furthermore, if the reference cell/range is empty, then I would like to continue the code without hiding any rows or columns.

Columns to Hide: based on cells C8:D8

Rows to Hide: based on cells C9:D9

This is where the logical fest should take place

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

Current Code

Option Explicit

Private Sub CommandButton1_Click()

Dim MyFolder As String, MyFile As String
Dim StartTime As Double
Dim MinutesElapsed As String
Dim Filename As String
Dim Cell As String
Dim Counter As Long

If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

MsgBox "Enter Tab Name"
Exit Sub

End If

With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a Folder"
If .Show = True Then
MyFolder = .SelectedItems(1)

End If

If .SelectedItems.Count = 0 Then Exit Sub
Err.Clear
End With

Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

MyFile = Dir(MyFolder & "\", vbReadOnly)

StartTime = Timer

Do While MyFile <> ""
DoEvents
On Error GoTo 0

Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
 Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
' Set a reference to the settings sheet

Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source

' Gather the report sheet's name

reportSheetName = settingsSheet.Range("C7").Value ' good

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

Set reportSheet = Sheets(reportSheetName)

Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

Set targetRowsRange = reportSheet.Range(reportRowsAddr)

targetColumnsRange.EntireColumn.Hidden = True
targetRowsRange.EntireRow.Hidden = True

With reportSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1 '.FitToPagesTall = 1
End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

reportSheet.Select
reportSheet.PageSetup.Orientation = xlLandscape

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

ThisWorkbook.Path & "\" & Cell, _

Quality:=xlQualityStandard, IncludeDocProperties:=True, _

IgnorePrintAreas:=True, OpenAfterPublish:=False

Counter = Counter + 1

0

Workbooks(MyFile).Close SaveChanges:=False

MyFile = Dir

Loop

'turns settings back on

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub

Body:
Replace "" with """" :

TEST1 = "(" & """" & ThisWorkbook.Sheets("Sheet1").Range("C8").Value & ThisWorkbook.Sheets("Sheet1")
.Range("D8").Value & """" & ")"


问:
How to modify program to run until a certain key is entered
What is the best way to terminate this by entering a specific keyword or letter? Ideally want the program to terminate by entering a key followed by enter</p>

```<code>class NestedLoopTable {
    private int start;
    private int end;

    public NestedLoopTable() {
    }

    public NestedLoopTable(int aStart, int aEnd) {
        super();
        start = aStart;
        end = aEnd;
    }

    public void printTable() {
        // looping through the number of rows to print the table
        for (int i = start; i <= end - start + 1; i++) {
            for (int j = start; j <= i; j++)
                System.out.print(j + " ");
            System.out.println();
        }
    }
}
</code>```

```<code>import java.util.Scanner;

public class NestedLoopTableApp {
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter start and end");
        int start = sc.nextInt();
        int end = sc.nextInt();

        NestedLoopTable np = new NestedLoopTable(start, end);
        np.printTable();
        sc.close();
    }
}
</code>```

答: The best way to terminate the program when a specific key was entered would be to check for the key entered, and if it matches the key that will be entered when the program terminates, then run System.exit(0)

Body:
What is the best way to terminate this by entering a specific keyword or letter? Ideally want the program to terminate by entering a key followed by enter

class NestedLoopTable {
    private int start;
    private int end;

    public NestedLoopTable() {
    }

    public NestedLoopTable(int aStart, int aEnd) {
        super();
        start = aStart;
        end = aEnd;
    }

    public void printTable() {
        // looping through the number of rows to print the table
        for (int i = start; i <= end - start + 1; i++) {
            for (int j = start; j <= i; j++)
                System.out.print(j + " ");
            System.out.println();
        }
    }
}

import java.util.Scanner;

public class NestedLoopTableApp {
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter start and end");
        int start = sc.nextInt();
        int end = sc.nextInt();

        NestedLoopTable np = new NestedLoopTable(start, end);
        np.printTable();
        sc.close();
    }
}


问:
change expiration auth cookie dynamically .net core identity
I have .NET Core 3.1 Web API app with .NET Core Identity.
In Startup.cs I have the following code:

```<code>services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromHours(2);
});
</code>```

But for some users I have different value of expiration time.

Can I overwrite expiration time of auth cookie dynamically? And if yes, what's the best way to do it? Maybe there is an option in SignInManager<...> or UserManager<...> that allow to overwrite this value?

答:
The Cookies for Identity is AspNetCore.Identity.Application, and its ExpireTimeSpan is set by HandleSignInAsync.

You can use cookie's OnSigningIn event to dynamically set expire time for specific user :

```<code>services.ConfigureApplicationCookie(opt => {
    opt.Events.OnSigningIn = async (signinContext) => {

        // you can use the pricipal to query claims
        var email = signinContext.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
        if ("xxxx@hotmail.com".Equals(email))
        {
            // set the expiration time according to claims dynamically
            signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddSeconds(100);
            signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
        }
        else
        {
            signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddMinutes(60);
            signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
        }

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

Body:
I have .NET Core 3.1 Web API app with .NET Core Identity.
In Startup.cs I have the following code:

services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromHours(2);
});

But for some users I have different value of expiration time.

Can I overwrite expiration time of auth cookie dynamically? And if yes, what's the best way to do it? Maybe there is an option in SignInManager<...> or UserManager<...> that allow to overwrite this value?

Body:
The Cookies for Identity is AspNetCore.Identity.Application, and its ExpireTimeSpan is set by HandleSignInAsync.

You can use cookie's OnSigningIn event to dynamically set expire time for specific user :

services.ConfigureApplicationCookie(opt => {
    opt.Events.OnSigningIn = async (signinContext) => {

        // you can use the pricipal to query claims
        var email = signinContext.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
        if ("xxxx@hotmail.com".Equals(email))
        {
            // set the expiration time according to claims dynamically
            signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddSeconds(100);
            signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
        }
        else
        {
            signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddMinutes(60);
            signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
        }

    };
});


问:
Trying to get property of non-object from blade view in laravel
I try to display my pagination data to database ...My pagination data was from json that i already decode .....i was able to pass to my pagination data to view but not able to display in table
....
This is my error from blade view

Trying to get property of non-object

my result pagination

```<code>  LengthAwarePaginator {#4177 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#4169 ▼
        #items: array:1 [▼
          "data" => array:852 [▼
            0 => {#624 ▶}
            1 => {#623 ▶}
            2 => {#628 ▼
              +"ID": "cust1"
              +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
              +"NICK_NAME": "CUST1"
              +"PWD_INVALID_HIT": "0"
              +"PWD_CREATE_DT": "2019/07/22 15:57:15"
              +"INSTITUTION_ID": "C01"
              +"ACL_ID": "L04"
              +"LOGIN_DT": "2019/07/22 15:57:15"
              +"LOGIN_STS_ID": "N"
              +"STS_ID": "C08"
              +"TYPE_ID": "U00"
              +"UPD_ID": "sufyzasukor"
              +"UPD_DT": "2019/07/22 15:57:15"
              +"EMAIL_ID": "cust1@gmail.com"
              +"PHONE_NO_ID": "0"
              +"HP_ID": "0                        "
              +"CRT_DATE_DELETED": null
              +"irel__com_access_level": {#621 …9}
              +"irel__com_user_types": {#630 …5}
              +"irel__com_status": {#631 …5}
            }
}
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}
</code>```

My controller

```<code>public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());

         $total = count($content) ;
         $collection = new \Illuminate\Support\Collection($content);
         $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}
</code>```

my blade table that i want to display

```<code>    <tbody>
             @foreach($paginationRecord as $i=>$user)
              @php
              $currentRecordno = 1;

              @endphp

              <tr>

       <td>{{ $user->ID }}</td>
       <td>{{ $user->NICK_NAME }}</td>
       <td>{{ $user->PWD_INVALID_HIT }}</td>

        </tr>
@endforeach
</code>```

dd($user)

```<code>array:852 [▼
  0 => array:20 [▶]
  1 => array:20 [▶]
  2 => array:20 [▼
    "ID" => "cust1"
    "PWD" => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
    "NICK_NAME" => "CUST1"
    "PWD_INVALID_HIT" => "0"
    "PWD_CREATE_DT" => "2019/07/22 15:57:15"
    "INSTITUTION_ID" => "C01"
    "ACL_ID" => "L04"
    "LOGIN_DT" => "2019/07/22 15:57:15"
    "LOGIN_STS_ID" => "N"
    "STS_ID" => "C08"
    "TYPE_ID" => "U00"
    "UPD_ID" => "sufyzasukor"
    "UPD_DT" => "2019/07/22 15:57:15"
    "EMAIL_ID" => "cust1@gmail.com"
    "PHONE_NO_ID" => "0"
    "HP_ID" => "0                        "
    "CRT_DATE_DELETED" => null
    "irel__com_access_level" => array:9 [ …9]
    "irel__com_user_types" => array:5 [ …5]
    "irel__com_status" => array:5 [ …5]
</code>```

How do i display data in table

答:
You are trying to access a array as a object . That's why the error . Try this .</p>

```<code><tbody>
             @foreach($paginationRecord as $i=>$user)
              @php
                 $currentRecordno = 1;
              @endphp

              <tr>
                <td>{{ $user['ID'] }}</td>
                <td>{{ $user['NICK_NAME'] }}</td>
                <td>{{ $user['PWD_INVALID_HIT'] }}</td>
             </tr>
             @endforeach
</code>```

Body:
I try to display my pagination data to database ...My pagination data was from json that i already decode .....i was able to pass to my pagination data to view but not able to display in table
....
This is my error from blade view

Trying to get property of non-object

my result pagination

  LengthAwarePaginator {#4177 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#4169 ▼
        #items: array:1 [▼
          "data" => array:852 [▼
            0 => {#624 ▶}
            1 => {#623 ▶}
            2 => {#628 ▼
              +"ID": "cust1"
              +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
              +"NICK_NAME": "CUST1"
              +"PWD_INVALID_HIT": "0"
              +"PWD_CREATE_DT": "2019/07/22 15:57:15"
              +"INSTITUTION_ID": "C01"
              +"ACL_ID": "L04"
              +"LOGIN_DT": "2019/07/22 15:57:15"
              +"LOGIN_STS_ID": "N"
              +"STS_ID": "C08"
              +"TYPE_ID": "U00"
              +"UPD_ID": "sufyzasukor"
              +"UPD_DT": "2019/07/22 15:57:15"
              +"EMAIL_ID": "cust1@gmail.com"
              +"PHONE_NO_ID": "0"
              +"HP_ID": "0                        "
              +"CRT_DATE_DELETED": null
              +"irel__com_access_level": {#621 …9}
              +"irel__com_user_types": {#630 …5}
              +"irel__com_status": {#631 …5}
            }
}
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

My controller

public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());

         $total = count($content) ;
         $collection = new \Illuminate\Support\Collection($content);
         $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}

my blade table that i want to display

             @foreach($paginationRecord as $i=>$user)
              @php
              $currentRecordno = 1;

              @endphp

       {{ $user->ID }}
       {{ $user->NICK_NAME }}
       {{ $user->PWD_INVALID_HIT }}

@endforeach

dd($user)

array:852 [▼
  0 => array:20 [▶]
  1 => array:20 [▶]
  2 => array:20 [▼
    "ID" => "cust1"
    "PWD" => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
    "NICK_NAME" => "CUST1"
    "PWD_INVALID_HIT" => "0"
    "PWD_CREATE_DT" => "2019/07/22 15:57:15"
    "INSTITUTION_ID" => "C01"
    "ACL_ID" => "L04"
    "LOGIN_DT" => "2019/07/22 15:57:15"
    "LOGIN_STS_ID" => "N"
    "STS_ID" => "C08"
    "TYPE_ID" => "U00"
    "UPD_ID" => "sufyzasukor"
    "UPD_DT" => "2019/07/22 15:57:15"
    "EMAIL_ID" => "cust1@gmail.com"
    "PHONE_NO_ID" => "0"
    "HP_ID" => "0                        "
    "CRT_DATE_DELETED" => null
    "irel__com_access_level" => array:9 [ …9]
    "irel__com_user_types" => array:5 [ …5]
    "irel__com_status" => array:5 [ …5]

How do i display data in table

Body:
You are trying to access a array as a object . That's why the error . Try this .

<tbody>
             @foreach($paginationRecord as $i=>$user)
              @php
                 $currentRecordno = 1;
              @endphp

              <tr>
                <td>{{ $user['ID'] }}</td>
                <td>{{ $user['NICK_NAME'] }}</td>
                <td>{{ $user['PWD_INVALID_HIT'] }}</td>
             </tr>
             @endforeach


问:
Office 365 Management API: Filter using StartTime and EndTime does not work
I am trying to fetch the audit logs of SharePoint tenant for a certain time period (suppose for half an hour today earlier) but if use startTime and endTime filter it doesn't work. It always shows me content from around 24 hours ago which is not useful. Isn't this API useless if any filter does not work?

Sample URL I have used in the script:

"https://manage.office.com/api/v1.0/$tenant/activity/feed/subscriptions/content?contentType=Audit.SharePoint&startTime=2020-02-12T23:00&endTime=2020-02-12T23:15"

No matter what timestamp I put data is always around 24 hours before. Did anybody encounter it before? Is there any resolution for that? Please help.

答: Okay looks like you can only get logs older than 24 hours. If you put a timestamp less than 24 hours old, it just provides you the latest log, and ignores the timestamp.</p>


问:
Remove Brackets from all the filenames in Linux
I have a string that remove the brackets from the filename.

$ find . -name "*.mkv" -exec rename 's/[\)\(]//g' {} \;

I have managed to make a statement that removes all the () in the filename of a directory, but whenever I run into a directory like for example amazing.(2018) It shows an error that:

No directory can be found.

Please provide any alternative I need this to work, and I want it to be recursive.

答:
Ensure that you run "find" with the "-depth" parameter,
therefore leafs are renamed first,
i.e., a directory name is changed
only after all files and directories inside it are renamed.

Otherwise, if you first change the name of a directory,
files and directories inside it are no longer accessible
(they are not in the list that "find" built at the beginning).


问:
Angular Different package.json Per Environment?
I have no clue if this is possible and hoping someone can shed some light if it is. Right now I have a production environment, testing environment, and QA environment. Each environment has different code snapshots and one of them being the package.json holding different version numbers of packages. We build our environments using Jenkins builds where we simply do npm install and then ng build --prod <- example environment

Is there any way to have a specific package.json per environment, so that when the environment is defined in ng build, it will pick up that package.json and install those dependencies?

I appreciate any type of feedback as to whether this is possible or not, and hopefully example of what can be done.

答:
Instead of trying to fix this from npm side, A good git strategy will help you better.

Perhaps, create two git branches with two package.json and from Jenkins side pull the branch according to environment.

So for example if you have two branch called prod (having prod package.json) and dev (having dev package.json)

You can clone the repo and switch to prod branch for prod env.

Same for dev.