text:
Q: How can I shrink down all of these if statements? This part of the code is from a school assignment. I got it to work, but I feel like I can simplify it or at least make it look cleaner. However, I have not yet been able to do so. Any suggestions? (It is from a tic tac toe game)
if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != '-') {
    winner = board[0][0];
} else if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] != '-') {
    winner = board[1][0];
} else if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] != '-') {
    winner = board[2][0];
} else if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] != '-') {
    winner = board[0][0];
} else if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-') {
    winner = board[0][1];
} else if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] != '-') {
    winner = board[0][2];
} else if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != '-') {
    winner = board[2][0];
} else if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-') {
    winner = board[0][0];
}

A: try
 if(check(board[0][0],board[0][1],board[0][2]) &&  board[0][2]!='-')
 .....

private boolean check(a,b,c){
    return a==b && b==c;
}

also you can see a better solution here

A: Here is another way of doing it:
int[][] checks = {{0,0,0,1},{1,0,0,1},{2,0,0,1}, // horizontals
                  {0,0,1,0},{0,1,1,0},{0,2,1,0}, // verticals
                  {0,0,1,1},{2,0,-1,1}};         // diagonals
char winner = '-';
for (int[] check : checks)
    if ((winner = checkWinner(board, check[0], check[1], check[2], check[3])) != '-')
        break;

private static char checkWinner(char[][] board, int y, int x, int dy, int dx) {
    char c = board[y][x];
    return (board[y + dy][x + dx] == c && board[y + dy * 2][x + dx * 2] == c ? c : '-');
}

A: What about following approach. As I can see, you have limited number of winners: board[0][0], board[1][0], board[2][0], board[0][1], board[2][0]. You can create separate Predicate for each winnger with appropriate name.
Predicate<char[][]> isZeroOneWinner = new Predicate<char[][]>() {
    @Override
    public boolean test(char[][] board) {
        return board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-';
    }
};

I think is is better that multiple if...else.


text:
Q: Faster TMultiReadExclusiveWriteSynchronizer? Is there a faster kind of TMultiReadExclusiveWriteSynchronizer out there? FastCode perhaps?
Starting with Windows Vista, Microsoft added a Slim Reader/Writer lock. It performs much better than Delphi's TMultiReadExclusiveWriteSynchronizer. Unfortunately it only exists in Windows Vista and later, something which few customers actually have yet.
Presumably the concepts in use inside a Slim Reader/Writer lock could be redone in native Delphi code - but has anyone done it?
i have a situation where acquiring and releasing locks on a TMultiReadExclusiveWriteSynchronizer (even when there's no contention - a single thread), causes 100% overhead (the operation time doubles). i can run without locking, but then my class is no longer thread-safe.
Is there a faster TMultiReadExclusiveWriteSynchronizer?
Note: If i use a TCriticalSection i only suffer a 2% performance hit (although critical sections are known to be fast when the acquire succeeds, i.e. while it's single threaded and there's no contention). The downside of a CS is that i lose the "multiple readers" capability.
The Measurements
Using TMultiReadExclusiveWriteSynchronizer a sizable amount of time is spent inside BeginRead and EndRead:

i then ported the code to use Window's own SlimReaderWriter Lock (which some code rewrite, as it doesn't support recursive lock taking), and profiled the resutls:

*

*TMultiReadExclusiveWriteSynchronizer: 10,698 ns per iteration
10,697,772,613 ns to iterate 1,000,000 times

*SRWLock: 8,802 ns per iteration
 8,801,678,339 ns to iterate 1,000,000 times

*Omni Reader-Writer lock: 8,941 ns per iteration
 8,940,552,487 ns to iterate 1,000,000 times
A 17% improvement when using SRWLocks (aka Omni's spinning lock).
Now, i cannot switch the code permanantly over to use Windows Vista SRWLocks, as there are some entire enterprises of customers that are still on Windows XP.
The Slim locks are just careful use of InterlockedCompareExchange functions; but more careful than i can successfully use. I'm this far away from just stealing the 140 machine instructions involved, and have it done.
Bonus Reading

*

*Is Critical Section always faster?

*How to write fast multi-thread Delphi applications

A: TOmniMREW from OmniThreadLibrary claims to be faster and more lightweight:
OTL is an excellent threading lib, BTW.
Sample Code
TOmniReaderWriterLock = class(TInterfacedObject, IReaderWriterLock)
private
   omrewReference: Integer;
public
   { IReaderWriterLock }
   procedure BeginRead;
   procedure EndRead;
   procedure BeginWrite;
   procedure EndWrite;
end;

{ TOmniReaderWriterLock }

procedure TOmniReaderWriterLock.BeginRead;
var
  currentReference: Integer;
begin
    //Wait on writer to reset write flag so Reference.Bit0 must be 0 than increase Reference
    repeat
        currentReference := Integer(omrewReference) and not 1;
    until currentReference = Integer(InterlockedCompareExchange(Pointer(omrewReference), Pointer(Integer(currentReference) + 2), Pointer(currentReference)));
end;

procedure TOmniReaderWriterLock.EndRead;
begin
    //Decrease omrewReference
    InterlockedExchangeAdd(@omrewReference, -2);
end;

procedure TOmniReaderWriterLock.BeginWrite;
var
    currentReference: integer;
begin
    //Wait on writer to reset write flag so omrewReference.Bit0 must be 0 then set omrewReference.Bit0
    repeat
        currentReference := omrewReference and (not 1);
    until currentReference = Integer(InterlockedCompareExchange(Pointer(omrewReference), Pointer(currentReference+1), Pointer(currentReference)));

    //Now wait on all readers
    repeat
    until omrewReference = 1;
end;

procedure TOmniReaderWriterLock.EndWrite;
begin
    omrewReference := 0;
end;

A: In the end i used a compromise solution. The Omni reader-writer lock uses "slim" principles (spinning bit-manipulations). Like Window's own, it doesn't support lock escalation. I've tested it, and it doesn't seem to lockup crash or deadlock.
In the end i used a fallback situation. The most generic of generic interfaces to support "read-write" concepts:
IReaderWriterLock = interface
   ['{6C4150D0-7B13-446D-9D8E-866B66723320}']
   procedure BeginRead;
   procedure EndRead;
   procedure BeginWrite;
   procedure EndWrite;
end;

And then we decide at runtime which implementation to use. If we're on Windows Vista or new, use Window's own SlimReaderWriter, otherwise fallback to Omni version:
TReaderWriterLock = class(TObject)
public
   class function Create: IReaderWriterLock;
end;

class function TReaderWriterLock.Create: IReaderWriterLock;
begin
   if Win32MajorVersion >= 6 then //SRWLocks were introduced with Vista/Server 2008 (Windows version 6.0)
   begin
      //Use the Windows built-in Slim ReaderWriter lock
      Result := TSlimReaderWriterLock.Create;
   end
   else
   begin
      //XP and earlier fallback to Omni equivalent
      Result := TOmniReaderWriterLock.Create;
   end;
end;

Note: Any code is released into the public domain. No attribution required.

A: The Delphi TMultiReadExclusiveWriteSynchronizer is very sophisticated - it can be acquired recursively and you can update from Read to Write.
This comes with a cost, which in this case means managing a bucket of shared state per thread. As the Windows thread-local mechanics (accessible via threadvar) is too simplistic for this (not able cope with several MREWS instances) it is done in a rather inefficient way – see the RTL or JCL sources – the implementations are quite similar, sharing bad performance and update-deadlock risk.
First ensure you really need the MREWS functionality – I assume, according to proportional size of locking overhead to the workload, you will be much better off with a TCriticalSection.
If you really-really need it, go with the Delphi implementation and watch out for the possible hidden unlock in BeginWrite – see it's documentation and return value meaning.
It is possible to implement a Vista-like SRW using the Interlocked functions or inline assembly, but it's not worth the effort in most cases.

A: The JCL has a MREWS that is a different implementation which might work for you. Not sure what version of windows it requires.
http://wiki.delphi-jedi.org/wiki/JCL_Help:TJclMultiReadExclusiveWrite
http://wiki.delphi-jedi.org/index.php?title=JEDI_Code_Library

A: Try this? It can be used as a normal variable:
type myclass=class
              Lock:TOBRWLock;
              function ReadIt:Integer;
              procedure WriteIt(A:Integer);
             end;
function ReadIt:Integer;
begin;
 Lock.LockRead;
 Result:=GetVal;
 Lock.UnLockRead;
end;

There is much space for improvement and you can build from here varieties that favour read above write or just act differently depending on the need.
const ldFree    = 0;
      ldReading = 1;
      ldWriting = 2;
type TOBRWLock          = record
                 [Volatile]WritersWaiting,
                           ReadersWaiting,
                           ReadersReading,
                           Disposition    : Integer;
                           procedure LockRead;
                           procedure LockWrite;
                           procedure UnlockRead;
                           procedure UnlockWrite;
                           procedure UnReadWrite;
                           procedure UnWriteRead;
                          end;

procedure TOBRWLock.LockRead;
var SpinCnt : NativeUInt;
    I       : Integer;
begin
 SpinCnt:=0;
 TInterlocked.Increment(ReadersWaiting);
 repeat
  if (Disposition=ldReading)
     then begin
           I:=TInterlocked.Increment(ReadersReading);
           if (Disposition<>ldReading) or (I=1)(*Only 1 read reference or Disposition changed, suspicious, rather retry*)
              then begin
                    TInterlocked.Decrement(ReadersReading);
                    continue;
                   end
              else begin(*Success*)
                    TInterlocked.Decrement(ReadersWaiting);
                    break;
                   end;
          end;
  if (WritersWaiting<>0)or(Disposition<>ldFree)
     then begin
           SpinBackoff(SpinCnt);
           continue;
          end;
  if TInterlocked.CompareExchange(Disposition,ldReading,ldFree)=ldFree
     then begin
           TInterlocked.Increment(ReadersReading);
           TInterlocked.Decrement(ReadersWaiting);
           break;
          end;
  SpinBackoff(SpinCnt);
 until False;
end;

procedure TOBRWLock.LockWrite;
var SpinCnt : NativeUInt;
begin
 SpinCnt:=0;
 TInterlocked.Increment(WritersWaiting);
 repeat
  if (Disposition<>ldFree)
     then begin
           SpinBackoff(SpinCnt);
           continue;
          end;
  if TInterlocked.CompareExchange(Disposition,ldWriting,ldFree)=ldFree
     then begin
           TInterlocked.Decrement(WritersWaiting);
           break;
          end
     else SpinBackoff(SpinCnt);
 until False;
end;

procedure TOBRWLock.UnlockRead;
begin
 {$IFDEF DEBUG}
 if Disposition<>ldReading
    then raise Exception.Create('UnlockRead a lock that is not Reading');
 {$ENDIF}
 TInterlocked.Decrement(ReadersReading);
 if ReadersReading=0
    then begin;
          if TInterlocked.CompareExchange(Disposition,ldFree,ldReading)<>ldReading
             then raise Exception.Create('Impossible 310');
         end;
end;

procedure TOBRWLock.UnlockWrite;
begin
 {$IFDEF DEBUG}
 if Disposition<>ldWriting
    then raise Exception.Create('UnlockWrite a lock that is not Writing');
 {$ENDIF}
 if TInterlocked.CompareExchange(Disposition,ldFree,ldWriting)<>ldWriting
    then raise Exception.Create('Impossible 321');
end;

procedure TOBRWLock.UnReadWrite;
var SpinCnt : NativeUInt;
begin
 {$IFDEF DEBUG}
 if Disposition<>ldReading
    then raise Exception.Create('UnReadWrite a lock that is not Reading');
 {$ENDIF}
 TInterlocked.Increment(WritersWaiting);
 SpinCnt:=0;
 repeat
  if ReadersReading=1(*Only me reading*)
     then begin;
           if TInterlocked.CompareExchange(Disposition,ldWriting,ldReading)<>ldReading(*Must always succeed*)
              then raise Exception.Create('Impossible 337');
           TInterlocked.Decrement(ReadersReading);
           TInterlocked.Decrement(WritersWaiting);
           break;
          end;
  SpinBackoff(SpinCnt);
 until False;
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails add file via controller In the controller my Rails project, I would like to create a new file /public/my_files/welcome.txt with content
Welcome to my website!

(The folder my_files does not exist yet.)
How can I do that?
(Edit: I know that to make a static page, I don't need to do it via a controller. I'm actually making a dynamic page, but I'm just simplifying the example.)

A: I am not really sure what you asking about, but if you just want a static page you can do so without using the controllers
Just make a folder in the public dir (right click >> new >> folder) and make a html file in it.
Then start the rails server and point your browser to
localhost:3000/my_files/welcome.html

A:
File.open(Rails.root + '/public/my_files/welcome.txt', 'w') {|f|
  f.write("your dynamic data") }

This is the simplest way you can create a file. Ruby will automatically create the file if not present. Let me know if this fits within your requirment.


text:
Q: Showing that $(x_2 - x_1)^2 + (y_2 - y_1)^2 \leq 8$, where $x^2 + y^2 \leq 1$ Let $D^2$ be the unit disk in $\mathbb{R}^2$ and $(x_1, y_1), (x_2, y_2) \in D^2$.
I can't show that
$$(x_2 - x_1)^2 + (y_2 - y_1)^2 \leq 8.$$
Can someone give me a hint?

A: The inequality can actually be tighter... The geometric argument is straightforward:
$$
(x_2-x_1)^2+(y_2-y_1)^2
$$
is the squared distance between the two points. As these lay inside the unit disk, their distance is as most 2, therefore
$$
(x_2-x_1)^2+(y_2-y_1)^2\leq 4.
$$

A: If we apply the euclidean norm, as we have that the maximum distance between the pair of coordinates $x_1,x_2$ and $y_1,y_2$ is 2, meaning that they are at the opposite extremes of the disc, we can then show:
$$ \lVert (x_1 - x_2)^2\rVert + \lVert (y_1 - y_2)^2 \rVert \leq 2^2 + 2^2 = 8$$

A: Here's a more circuitous, but more general, argument using the triangle inequality several times and the fact that if a point lies inside the unit disk, all of its coordinates must have magnitude no greater than $1$:
\begin{align*}
(x_2 - x_1)^2 + (y_2-y_1)^2 &=\big| (x_2 - x_1)^2 + (y_2-y_1)^2\big| \\
&= \big|x_2^2 - 2x_1x_2 + x_1^2 + y_2^2 - 2y_1y_2 + y_1^2\big| \\
&= \big|(x_1^2 + y_1^2) + (x_2^2 + y_2^2) - 2(x_1x_2 + y_1y_2)\big| \\
&\leq \big|x_1^2\big| + \big|y_1^2\big| + \big|x_2^2\big| + \big|y_2^2\big| + 2\bigg(\big|x_1x_2\big| + \big|y_1y_2\big|\bigg)\\
&\leq 1 + 1 + 1 + 1 + 2(|x_1||x_2|+|y_1||y_2|)\\
&\leq 4 + 2(1 + 1)\\
&= 8
\end{align*}
(Note that this argument actually holds for any point in the unit square, not just the unit disk.)

A: By C-S $$(x_1-x_2)^2+(y_1-y_2)^2=x_1^2+y_1^2+x_2^2+y_2^2-2(x_1x_2+y_1y_2)\leq$$
$$\leq2+2\sqrt{(x_1^2+y_1^2)(x_2^2+y_2^2)}\leq4<8$$


text:
Q: IdentityServer4.Stores.ValidatingClientStore Invalid client configuration for ... client no allowed grant type specified Hi I am getting the error...
"IdentityServer4.Stores.ValidatingClientStore Invalid client configuration for ... client no allowed grant type specified"
when using a sql database context initially seeded from static data.
If I use the same static data on an AddInMemoryClients context no errors occurs and everything works fine.
Client definition...
        new Client
        {
            ClientId = "GameMvc",
            ClientName = "MGame web client",
            ClientSecrets =  { new Secret("058dddb593be4e149c19e23fd336e2ed".Sha256()) },
            AllowRememberConsent = false,
            AllowOfflineAccess = true,
            UpdateAccessTokenClaimsOnRefresh = true,
            AccessTokenLifetime = 180,
            AllowedGrantTypes = GrantTypes.Hybrid,
            RedirectUris = { "https://localhost:44330/signin-oidc" },
            PostLogoutRedirectUris = { "https://localhost:44330/signout-callback-oidc" },
            AllowedScopes =
            {
                "openid",
                "profile",
                "email",
                "address",
                "offline_access",
                "role",
            }
        }

Identity server debug output
fail: IdentityServer4.Stores.ValidatingClientStore[0]
      Invalid client configuration for client GameMvc: no allowed grant type specified
info: IdentityServer4.Events.DefaultEventService[0]
      {
        "Name": "Invalid Client Configuration",
        "Category": "Error",
        "EventType": "Error",
        "Id": 3001,
        "ClientId": "GameMvc",
        "ClientName": "MGame web client",
        "Message": "no allowed grant type specified",
        "ActivityId": "0HLUGMDSRD0QH:00000007",
        "TimeStamp": "2020-03-25T11:56:22Z",
        "ProcessId": 22768,
        "LocalIpAddress": "::1:44320",
        "RemoteIpAddress": "::1"
      }
fail: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Unknown client or not enabled: GameMvc
{
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "Raw": {
          "client_id": "GameMvc",
          "redirect_uri": "https://localhost:44330/signin-oidc",
          "response_type": "code id_token",
          "scope": "openid profile email offline_access role experience subscription_level GameApi",
          "response_mode": "form_post",
          "nonce": "637207341781609343.NzJmYjQ1ZjgtNDI1Yy00ZWY4LWE2YTItOTE0MWUwNTYwNDIwNzQ0NWJjOWEtN2FhNS00M2NlLTlhMmMtMTlkODBhMTliYjdm",
          "state": "CfDJ8H3n8sVeRBlPopiMUAsqux6eF3ZksNANFCae20YtpBRAXjP-7HUxq1--kcY8uMuiT1moapzqik0ifGaLVmBiQw2QcRcNLlJCpN50yy2uHy52-ydsbCEGigE81skOlEalX2fMbjOuVRSC5jT4FaE2DFM-wPj8ndbf_VGYQ-FG5avBp9vsSKMW_CdUaUtrbs4nsEmAn1NTZoXIPTXnzBcCKOPwSpCOalpK1i4SbpKFbvN3PAKCNw1zPi-lFM5_W3icVvD_gazWnP3X1jxp_3XzCSoKIf3bKSL6TKuix28SPJZ_-KnKJtWOAUkkTFu20Qr0DQ",
          "x-client-SKU": "ID_NETSTANDARD2_0",
          "x-client-ver": "5.5.0.0"
        }
      }
fail: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Request validation failed
info: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      {
        "SubjectId": "anonymous",
        "RequestedScopes": "",
        "Raw": {
          "client_id": "GameMvc",
          "redirect_uri": "https://localhost:44330/signin-oidc",
          "response_type": "code id_token",
          "scope": "openid profile email offline_access role experience subscription_level GameApi",
          "response_mode": "form_post",
          "nonce": "637207341781609343.NzJmYjQ1ZjgtNDI1Yy00ZWY4LWE2YTItOTE0MWUwNTYwNDIwNzQ0NWJjOWEtN2FhNS00M2NlLTlhMmMtMTlkODBhMTliYjdm",
          "state": "CfDJ8H3n8sVeRBlPopiMUAsqux6eF3ZksNANFCae20YtpBRAXjP-7HUxq1--kcY8uMuiT1moapzqik0ifGaLVmBiQw2QcRcNLlJCpN50yy2uHy52-ydsbCEGigE81skOlEalX2fMbjOuVRSC5jT4FaE2DFM-wPj8ndbf_VGYQ-FG5avBp9vsSKMW_CdUaUtrbs4nsEmAn1NTZoXIPTXnzBcCKOPwSpCOalpK1i4SbpKFbvN3PAKCNw1zPi-lFM5_W3icVvD_gazWnP3X1jxp_3XzCSoKIf3bKSL6TKuix28SPJZ_-KnKJtWOAUkkTFu20Qr0DQ",
          "x-client-SKU": "ID_NETSTANDARD2_0",
          "x-client-ver": "5.5.0.0"
        }
      }

however using the same client on in memory scenario with AddInMemoryClients it works... see the debug output below..
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      ValidatedAuthorizeRequest
      {
        "ClientId": "GameMvc",
        "ClientName": "MGame web client",
        "RedirectUri": "https://localhost:44330/signin-oidc",
        "AllowedRedirectUris": [
          "https://localhost:44330/signin-oidc"
        ],
        "SubjectId": "anonymous",
        "ResponseType": "code id_token",
        "ResponseMode": "form_post",
        "GrantType": "hybrid",
        "RequestedScopes": "openid profile email offline_access role experience subscription_level GameApi",
        "State": "CfDJ8H3n8sVeRBlPopiMUAsqux7YiGRgIGQOeT0aF9aYMv-a40lLmjS_uEZw_jMeQAgkq7wFGq8mMMekKNm8U6uFL_kruFOX_gYjhJjzRZUKG1aHE0vpcJ0i0zYqd9aTh6elus8MxkP6NaGWszjf0wXSwVNboUdq_7NAvR_b4Pyt0sMkD5LTysTQ4VePtKi-FjDarp5xlRPvQUfiYpZfcyOGi7eqSlHuiVzD83uByMBhJ3cIA6h5n5zDzzotNpwxw_QLQk4A8zN06tgTHhUYTWV-5kxYiX3N84f__eyB3K_TCY94Kbm562BZX4TtfLzJHqJAdg",
        "Nonce": "637207668423193165.NjAzZDAwM2UtMjc0Yi00ZTNiLTgyOWYtN2JhYTI5ZTkxNDBlZGJiN2FiZGEtN2ZmYy00OGFkLWE5MGItMzAzNmY3OGM1MGIx",
        "SessionId": "",
        "Raw": {
          "client_id": "GameMvc",
          "redirect_uri": "https://localhost:44330/signin-oidc",
          "response_type": "code id_token",
          "scope": "openid profile email offline_access role experience subscription_level GameApi",
          "response_mode": "form_post",
          "nonce": "637207668423193165.NjAzZDAwM2UtMjc0Yi00ZTNiLTgyOWYtN2JhYTI5ZTkxNDBlZGJiN2FiZGEtN2ZmYy00OGFkLWE5MGItMzAzNmY3OGM1MGIx",
          "state": "CfDJ8H3n8sVeRBlPopiMUAsqux7YiGRgIGQOeT0aF9aYMv-a40lLmjS_uEZw_jMeQAgkq7wFGq8mMMekKNm8U6uFL_kruFOX_gYjhJjzRZUKG1aHE0vpcJ0i0zYqd9aTh6elus8MxkP6NaGWszjf0wXSwVNboUdq_7NAvR_b4Pyt0sMkD5LTysTQ4VePtKi-FjDarp5xlRPvQUfiYpZfcyOGi7eqSlHuiVzD83uByMBhJ3cIA6h5n5zDzzotNpwxw_QLQk4A8zN06tgTHhUYTWV-5kxYiX3N84f__eyB3K_TCY94Kbm562BZX4TtfLzJHqJAdg",
          "x-client-SKU": "ID_NETSTANDARD2_0",
          "x-client-ver": "5.5.0.0"
        }
      }

I could check that the data is indeed persisted on the database..

Here below the /.well-known/openid-configuration
/ https://localhost:44320/.well-known/openid-configuration

{
  "issuer": "https://localhost:44320",
  "jwks_uri": "https://localhost:44320/.well-known/openid-configuration/jwks",
  "authorization_endpoint": "https://localhost:44320/connect/authorize",
  "token_endpoint": "https://localhost:44320/connect/token",
  "userinfo_endpoint": "https://localhost:44320/connect/userinfo",
  "end_session_endpoint": "https://localhost:44320/connect/endsession",
  "check_session_iframe": "https://localhost:44320/connect/checksession",
  "revocation_endpoint": "https://localhost:44320/connect/revocation",
  "introspection_endpoint": "https://localhost:44320/connect/introspect",
  "device_authorization_endpoint": "https://localhost:44320/connect/deviceauthorization",
  "frontchannel_logout_supported": true,
  "frontchannel_logout_session_supported": true,
  "backchannel_logout_supported": true,
  "backchannel_logout_session_supported": true,
  "scopes_supported": [
    "subscription_level",
    "experience",
    "role",
    "address",
    "phone",
    "email",
    "profile",
    "openid",
    "GameApiFullAccess",
    "GameApiReadWrite",
    "GameApiReadOnly",
    "GameApi",
    "offline_access"
  ],
  "claims_supported": [
    "subscription_level",
    "experience",
    "role",
    "address",
    "phone_number",
    "phone_number_verified",
    "email",
    "email_verified",
    "family_name",
    "given_name",
    "middle_name",
    "nickname",
    "preferred_username",
    "profile",
    "picture",
    "website",
    "gender",
    "name",
    "birthdate",
    "locale",
    "updated_at",
    "zoneinfo",
    "sub"
  ],
  "grant_types_supported": [
    "authorization_code",
    "client_credentials",
    "refresh_token",
    "implicit",
    "password",
    "urn:ietf:params:oauth:grant-type:device_code"
  ],
  "response_types_supported": [
    "code",
    "token",
    "id_token",
    "id_token token",
    "code id_token",
    "code token",
    "code id_token token"
  ],
  "response_modes_supported": [
    "form_post",
    "query",
    "fragment"
  ],
  "token_endpoint_auth_methods_supported": [
    "client_secret_basic",
    "client_secret_post"
  ],
  "id_token_signing_alg_values_supported": [
    "RS256"
  ],
  "subject_types_supported": [
    "public"
  ],
  "code_challenge_methods_supported": [
    "plain",
    "S256"
  ],
  "request_parameter_supported": true
}

A: Finally I had cached the error
The error is produced if...
builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) for ConfigurationDbContext
So the desired option for Identity Server dbContext is QueryTrackingBehavior.TrackAll
BR

A: For me, I had created a new client and there was a missing configuration in
configuration.ClientGrantTypes table.
So I inserted a new ClientGrantType:
INSERT INTO configuration.ClientGrantTypes (GrantType, ClientId) VALUES ('authorization_code', YOURCLIENTID)


text:
Q: Why do my friends get Tough Break contracts every 15 minutes and I don't? So I've had the campaign pass for a while now and I'm on about 15/26 contracts with the Tough Break campaign pass.
I get 2 contracts per week, as it says here: When do I get new Contracts on the Team Fortress Tough Break Update? but my friends who got it yesterday are getting a contract as soon as they complete the previous one, and are now on 25/26 contracts. Considering I've had the campaign pass since early December, What the hell? The contracts page is blank most the time.

A: The contract system appears to occasionally bug out and give people a bunch more contracts than they should get.
There are only supposed to be 15 (maybe 16) as of January 29, 2016 (i.e. today).
Edit: All 26 contracts should be available as of March 9 or so.

A: How many total contracts have they completed so far?
Your say your friends have only just bought their campaign pass, then they will receive new ones as they complete their current ones until they are equal with everyone else, which as Powerlord states is ~15-16 contracts as of January 29, 2016.
The contract system is built this way so that people who buy in late, or are unable to complete their contracts within a week, won't miss completing any contracts (and therefore not earning drops).
It also means that if you are lagging behind in completing your current contracts, and miss the day where you will normally be awarded the contract, you will get new ones straight after you finish them as well.


text:
Q: Bayesian estimation of Dynamic Regression with AR(1) parameters I would like to draw (Bayesian) inference in a dynamic linear regression with regression parameters following independent AR(1) processes $\beta_{t,i} = \mu_i+\beta_{t-1,i}+w_{t,i}$. However, I encounter problems with my Gibbs sampler and I do not find the mistake in my approach - every comment is highly appreciated:
1. All the computations are performed using a simulated data-set. I would like to back out the AR(1) parameters of the underlying betas.
set.seed(3010)
#   Simulate autoregressive regression parameter
simAR <- function(n,sigma,mu,rho,mu0){
    ts <- rep(mu0,n+1)
    for (i in 1:n) ts[i+1] <- mu + rho*ts[i] + rnorm(1,sd=sqrt(sigma))
    return(ts)
    }
T <- 500
rhoB    <- c(0.9,0.7)
sigmaB <- rep(0.1,2)
muB <- c(-0.3,0.3)
mu0B <- rep(0,2)
beta1 <- simAR(T-1,sigmaB[1],muB[1],rhoB[1],mu0B[1])
beta2 <- simAR(T-1,sigmaB[2],muB[2],rhoB[2],mu0B[2])
beta3 <- rep(4,T)
betatrue <- cbind(beta1,beta2,beta3)
matplot(betatrue,type="l")

2. Compute the time-series $y$ with additional noise term
sigmay <- 0.3
a   <- matrix(rnorm(ncol(betatrue)*T),nc=ncol(betatrue))
y   <- matrix(apply(a*betatrue,1,sum)+rnorm(T,sd=sqrt(sigmay)))
round(rbind(OLS=coef(lm(y~a-1)),Simulated = colMeans(betatrue),True=c(muB/(1-rhoB),4)),2)
             a1   a2   a3
OLS       -3.02 1.01 3.95
Simulated -2.93 1.01 4.00
True      -3.00 1.00 4.00

3. Time-varying regression with AR(1) dynamics
Investigating this model within a Bayesian regression framework is possible by setting
\begin{align*}y_t &= F_t \theta_t + v_t,& v_t \sim N(0, \sigma^2 _y) \\
 \theta_t &= G \theta_{t-1} + w_t, &w_t \sim N_p (0,W) \\
 \theta_0 &\sim N_p (m_0, C_0) \end{align*}
where
\begin{align*}
F_t &=\left(X_t, 0\right) \\
 \theta_t &= \left(\beta_{1,t},\beta_{2,t},\beta_{3,t},1\right) \\
 G &=  \left(\begin{matrix}
 \rho_0  & 0  & 0 & \mu_1\\
 0 &  \rho_1   & 0&\mu_2\\
 0 & 0 & \rho_3   &\mu_3\\
 0&0&0&1
 \end{matrix}\right)\\
 W  &=  \left(\begin{matrix}
 \sigma^{2}_{1} & 0 & 0 & 0 \\
  0 &  \sigma^{2} _{2} & 0 & 0\\
    0 & 0  &\sigma^{2} _{3}  & 0\\
        0 & 0 & 0 & \varepsilon \end{matrix}\right)\\
\end{align*}
The Dynamic Linear Model contains the following unknown parameters
$\Psi = \left(\sigma^{2} _{y} \sigma^{2} _{1}, \sigma^{2} _{2}, \sigma^{2} _{3}, \mu_1 , \mu_2 ,\mu_3 ,\rho_1 , \rho_2, \rho_3\right)$
I chose the following prior dependence structure:
$\pi(\Psi) = \pi(\sigma^2 _y)\pi(W)\pi(\mu_1, \mu_2 ,\mu_3)\pi(\rho_1, \rho_2,\rho_3).$
It is convenient to define inverse-Gamma priors for the volatility terms:
\begin{align*}
 \sigma^2_{y}   & \sim \mathcal{G}^{-1}\left(c_y,C_y\right) \\
 \sigma^2_{i} & \sim \mathcal{G}^{-1}\left(c_i,C_i\right)
\end{align*}
The conditional priors for the drift coefficients are chosen to be normal $\mu_i |\sigma^2 _i \sim N\left(b_0,\frac{\sigma^2_{i}}{N_0}\right).$
The AR(1) parameters ($\rho_i$) are not bounded to the stationary region by theprior choice as I set $\pi(\rho_i) \sim N(\psi_0,\tau_0) = N(0, 1)$.
4. Sampling procedure
The Gibbs sampling consists of the following steps:

*

*Start with initial guess $\Psi^0$

*Sample the states $\Theta^i $ from $\pi\left(\Theta|\Psi^i,Y\right)$

*Generate draws $\Psi^{i+1}$ from $\pi\left(\Psi|\Theta^i ,Y\right)$

Sampling the states is done via Forward Filtering Backward Sampling. Conditional on having sampled $\Theta^i$, the unknown variances $\sigma_{y}^{2}$ and $\sigma_{i}^{2}$ are computed using
$\sigma^2_{y}| \dots \sim \mathcal{G}^{-1}\left(c_y + \frac{T}{2}, C_y + \frac{1}{2}\sum\limits_{t=1}^T (y_t-(F_t \theta_t))^2\right)$ and
$\sigma^2_i| \dots \sim \mathcal{G}^{-1}\left(c_i + \frac{T+1}{2},\frac{1}{2}\sum\limits_{t=1}^T (\theta_{i,t}-(G\theta_{t-1})_i+ \frac{N_0}{2}\left(b_0 - \mu_i\right)^2+ C_i\right).$
For the unknown drifts $\mu_i$ I obtain
$p(\mu_i|\dots) \sim N\left(\frac{1}{T+N_0}\left(\sum\limits_{t=1}^T \left(\theta_{t,i}-\rho_i\theta_{t-1,i}\right)+N_0 b_0\right), \sigma^2 _i /(N_0 + T)\right)$.
The AR parameters $\rho_i$ are computed using
$\rho_i | \dots\sim N\left(\psi_j^T,\tau_j ^T\right)$
with $\tau_j ^T := \left(\frac{1}{\sigma_i ^2}\sum\limits_{t=1}^T {\theta_{t-1} ^i} ^2 +\frac{1}{\tau^2}\right)^{-1}$ and $\psi_j^T := \left(\tau_j ^T\right)^{-1} \left[\frac{1}{\sigma_i ^2 }\sum\limits_{t=1}^T \left(\theta_t ^i - \mu_i\right)\theta_{t-1} ^i + \frac{1}{\tau ^2} \psi\right]$.
5. Simulation
The R Code (using the DLM package) is constructed as follows (and in large parts borrowed from this excellent Book (code provided on home page).
library(dlm)

p       <- 4            # State dimension
m       <- ncol(y)
T       <- nrow(y)
B       <- function(phi.init,Mu.init,tot=p) diag(c(phi.init,rep(1,p-length(phi.init))))+ cbind(matrix(0,nc=p-1,nr=p),c(Mu.init,0))

a2       <- cbind(a,0)
psi0       <- 0
tau0       <- 1
shapeY     <- 2
rateY      <- 0.1
shapeTheta <- 2
rateTheta  <- 0.1
Mu0          <- 0
N0       <- 10

######MCMC - Initialization############################

burn        <- 10000
MC      <- 10000 + burn
gibbsTheta  <- array(NA, dim=c(MC,T+1,p))
gibbsPsi    <- matrix(NA, nrow=MC, ncol=p-1)
gibbsV  <- matrix(NA, nrow=MC, ncol=m)
gibbsW  <- matrix(NA, nrow=MC, ncol=p-1)
gibbsMu <- matrix(NA, nrow=MC, ncol=p-1)

tiny        <- 1e-12

phi.init    <- rnorm(p-1,mean=psi0,sd=tau0)
V.init  <- 1/rgamma(1,shapeY,rateY)
W.init  <- 1/rgamma(1,shapeTheta,rateTheta)
Mu.init     <- rnorm(p-1,mean=0,sd=W.init/N0)
mod         <- dlm(m0=c(rep(0,p-1),rep(1,1)),
            C0=diag(c(rep(1e01,p-1),tiny)),
            FF=matrix(1,nrow=1,ncol=p),
            JFF=matrix(1,nc=p,nr=1),
            V= var(residuals(lm(y~a2-1))),
            GG=B(phi.init,Mu.init),
            W=diag(c(rep(W.init,p-1),tiny)),X=a2)

######Gibbs Sampling###################################

for (i in 1:MC){
    if(i%%100==0){ cat('# Iteration', i,'- V:     ',round(median(gibbsV[1:i],na.rm=TRUE),3),'\n'); flush.console()}
    # generate the states by FFBS
        modFilt         <- dlmFilter(y, mod, simplify=TRUE)
        theta       <- dlmBSample(modFilt)
        gibbsTheta[i,,]     <- theta
    # generate the W_j
        theta.center    <- theta[-1,] - t(mod$GG %*% t(theta[-(T+1),]))
  SStheta  <- apply((theta.center)^2, 2,sum)
  phiTheta   <- rep(NA,p-1)
  for(j in 1:(p-1)){phiTheta[j]<-rgamma(1, shape=shapeTheta+(T+1)/2, rate=rateTheta+SStheta[j]/2+N0/2*(Mu.init[j]-Mu0)^2)}
  gibbsW[i,]   <- 1 / phiTheta
  mod$W        <- diag(c(gibbsW[i,],tiny))
    # generate the Mu_j
        MuMean <- rep(NA,p-1)
        for(j in 1:(p-1)) MuMean[j] <- 1/(T+N0)*(N0*Mu0+sum(theta[-1,j]-mod$GG[j,j]*theta[-T,j]))
  MuVar  <- gibbsW[i,]/(T+N0)
  for(j in 1:(p-1)) {Mu.init[j] <- rnorm(1,mean=MuMean[j],sd=sqrt(MuVar[j]))}
  gibbsMu[i,] <- Mu.init
  mod$GG     <- B(phi.init,gibbsMu[i,])
    # generate the V_i
        y.center    <- rep(NA,T)
        for(t in 1:T) y.center[t] <- y[t] - mod$X[t,]%*%theta[t+1,]
  SSy  <- sum(y.center^2)
  gibbsV[i,] <- 1/rgamma(m, shape=shapeY+T/2, rate=rateY+SSy/2)
  mod$V  <- gibbsV[i,]
    # generate the AR parameters psi_1, psi_2
        phi.init    <- rep(NA,p-1)
        for (j in 1:(p-1)){
             tau <- 1/(1/tau0 + 1/gibbsW[i,j] * crossprod(theta[-1,j]))
             psi <- tau * (1/gibbsW[i,j] * sum((theta[-1,j]-gibbsMu[i,j])*theta[-T,j]) + psi0/tau0)
             phi.init[j] <- rnorm(1, psi, sd=sqrt(tau))
        }
        gibbsPsi[i,] <- phi.init
        mod$GG       <- B(gibbsPsi[i,],gibbsMu[i,])
  }

6. Cleaning, Thining and evaluation
After the simulation steps I obtain the following output for the states (I obtain every 5th observation to reduce autocorrelation in the sample).
 # Remove burn-in phase + Thin-out
    thinfactor <- 5
    thin <- function(dat,fact=thinfactor) as.matrix(dat)[seq(from=1,to=nrow(as.matrix(dat)),by=fact),]

    gibbsW  <- thin(gibbsW[-(1:burn),])
    gibbsMu     <- thin(gibbsMu[-(1:burn),])
    gibbsPsi    <- thin(gibbsPsi[-(1:burn),])
    gibbsTheta  <- gibbsTheta[seq(from=burn+1,to=MC-burn,by=thinfactor),,]
    gibbsV  <- thin(gibbsV[-(1:burn),])

# Theta (state)
    postmeanTheta   <- apply(gibbsTheta,c(2,3),function(x) mean(x,na.rm=TRUE))
    postquantileTheta <- apply(gibbsTheta,c(2,3),function(x)quantile(x,c(0.05,0.95),na.rm=TRUE))
    par(mar = c(2, 4, 1, 1) + 0.1, cex = 0.6, mfrow=c(1,3))

    for(j in 1:3){
        ytmp   <- postmeanTheta[-(1:5),j]
        y01 <- postquantileTheta[1,-(1:5),j]
        y09 <- postquantileTheta[2,-(1:5),j]
        plot(ytmp,type="l",ylim=range(ytmp,y01,y09),main=paste('Posterior distribution of Theta',j))
        lines(y01,col="grey")
        lines(y09,col="grey")
        lines(betatrue[,j],col='red')
    }

Apparently, the posterior distribution is not really capturing what I aimed at. The plot shows the posterior draws of the states and should (at least this is what I expect) be somewhat comparable to the 'true' states which are plotted in red. Why isn't this the case?

*

*Are there too much parameters? (I doubt so)

*Is there an error in my Gibbs sampler derivations (I can provide the full calculations if needed, but the computations do not seem odd to me)

*Is there an implementation issue?

*Is this whole simulation study not suited to test whether my code works?


text:
Q: vis.js timeline how to check if there is currently an appointment Is there an event or something similar that triggers when an item starts ?

Well, basically what I want is an event (or something else that works) that will trigger when the red line crosses, in this example, 10:00am.

A: Well, the red line is just the current time. You can have a time interval fired each, let's say, 3 seconds and check if you have any item of the timeline crossing the line. Like this pseudocode:
var timeline = ... // This is the timeline object

setInterval(function() {
    var now = new Date(); // This is the current position of the timeline
    for (var d in timeline.itemsData._data) {
         if (d.start <= now && d.end >= now) { // this means the red line is crossing this item
             // do something...
         }
    }
}, 3); // each 3 seconds

The code is not complete. But there's the main idea.

A: Oh, I forgot to close this question.
There sadly is no API for this, but a simple timeout will do.
setTimeout(function () {
   //do stuff on appointment begin
   setTimeout(function () {
       //do something when finished
   }, end - Date.now());
}, start - now);

Ps. you'll have to do this for each appointment.


text:
Q: How do I share an ASP.NET web forms site through visual studio online or azure? Please bear with me as I've never used .NET to do team development but how do I share the code for an ASP.NET web forms site (not MVC or web forms application) through visual studio online?  I've figured it out how to do it through a web forms application but I'm not familiar with how to code in a web forms application, and I can't put a web forms site into the team explorer solutions because it's not a project.  With this assignment we are also tasked to use azure for deployment of the website and hosting databases.  Any information with how to regulate team development of a web forms site would be much appreciated.

A: Web Sites have been deprecated since 2010. You should upgrade to a Web application. The technology is the same. Your only difference is that your code behind is all compiled into the same DLL so your pages need unique names so that they do not collide.
Once you have upgraded your automated build woul create the necessary output.


text:
Q: Diode circuit analysis with constant voltage drop model
For this circuit I have to find the V_out/V_in ratio and my problem lies on one instance and that is ,
if V1 is negative (for the case  V1< Diode on Voltage) all the current flows through the diode and diode acts like constant voltage source which in turn causes some current flow through R_1. My question is ,Why Diode On voltage is the only cause for the current flow through R_1 ? Does  V_1 not have any role on causing current flow through R_1 since V1 is in magnitude greater than Diode_On voltage?

A:
My question is ,Why Diode On voltage is the only cause for the current
flow through R_1 ?

If you are modeling the forward conduction of the diode as a constant voltage then there is also a constant voltage across R1. With a constant voltage across R1, due to ohm's law the current through R1 is constant.

Does V_1 not have any role on causing current flow through R_1 since
V1 is in magnitude greater than Diode_On voltage?

All V1 does when it alters is change the current through D1 but, while ever the voltage is constant across the diode (forward conduction) the current through R1 is fixed by the diode forward voltage.


text:
Q: Find by class name doesn't work in jQuery I need to get the value of the info class after the submit button is clicked.
I have the following HTML which is made of many table rows (here displayed two)

   Name1
   Info Text 1
   <input type="submit" class="button" value="Submit">

   Name2
   Info Text 2
   <input type="submit" class="button" value="Submit">

I want to get the value of the info class - Info Text in this example.
I try to select it using the following jQuery selector:
$(this).parent().siblings().find(".info").text();

But it gives me blank window when I try to alert the result.
But when I use next() it works:
$(this).parent().siblings().next().text();


text:
Q: Awswrangler, KeyError while trying to apply partition_filter. Key actually exists when importing dataframe I am trying to load a pd.DataFrame, reading it form a parquet file in aws.
I am applying partition_filter to get only certain data from the df that corresponds to the conditions I want. In this particular case, the df column, df['source'] must be equal to the crawler_name string variable.
I apply the s3.read_parquete in the following way:
def read_aws_parquet(aws_uri: str, crawler_name: str, year: str, month: str, day:Optional[str], columns: list = ['url', 'crawl_timestamp', 'source']) -> pd.DataFrame:

    my_filter = lambda x: True if x["source"] == crawler_name else False
    # my_filter = lambda x: x["source"] == crawler_name
    logger.warning(f'{aws_uri} is a valid url')
    return wr.s3.read_parquet(
        path=aws_uri,
        path_suffix=".snappy.parquet",
        use_threads=True,
        columns=columns,  # 'deactivated_timestamp' must be added later
        partition_filter=my_filter,
        dataset=True
        # pyarrow_additional_kwargs={"filters": [('source', '=', crawler_name)]}
    )

If I don't apply the partition_filter I receive a complete dataframe that contains the crawler_name several times in the column 'source'. In that way, I verified this value existed.
but if I apply the filter, I get the following error
File "/Users/administrator/Library/Caches/pypoetry/virtualenvs/pf-11294-manual-review-of-the-tracking-url-MC2_y5HC-py3.10/lib/python3.10/site-packages/awswrangler/s3/_read_parquet.py", line 749, in read_parquet
    paths = _apply_partition_filter(path_root=path_root, paths=paths, filter_func=partition_filter)
  File "/Users/administrator/Library/Caches/pypoetry/virtualenvs/pf-11294-manual-review-of-the-tracking-url-MC2_y5HC-py3.10/lib/python3.10/site-packages/awswrangler/s3/_read.py", line 88, in _apply_partition_filter
    return [p for p in paths if filter_func(_extract_partitions_from_path(path_root=path_root, path=p)) is True]
  File "/Users/administrator/Library/Caches/pypoetry/virtualenvs/pf-11294-manual-review-of-the-tracking-url-MC2_y5HC-py3.10/lib/python3.10/site-packages/awswrangler/s3/_read.py", line 88, in <listcomp>
    return [p for p in paths if filter_func(_extract_partitions_from_path(path_root=path_root, path=p)) is True]
  File "<input>", line 19, in <lambda>
KeyError: 'source'

What is wrong with my partition filter?


text:
Q: how to pass json from two query in single array $sql = "SELECT user_registration.user_id, user_registration.full_name, user_registration.username, user_profile.profile_picture FROM user_registration LEFT JOIN user_profile ON user_registration.user_id = user_profile.user_id ";
    $result = $con->query($sql);

    if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
            $outaa[] = $row;

            $f_user_id = $row['user_id'];

        $sql1 = "SELECT status FROM user_follower WHERE (from_user_id = '$f_user_id' AND to_user_id = '$user_id' ) OR (from_user_id = '$user_id' AND to_user_id = '$f_user_id' )";

        $result1 = $con->query($sql1);
        if ($result1->num_rows > 0) {
        while($row1 = $result1->fetch_assoc()) {

            $outaa[] = $row1;
        }
        }
        else {
            $outaa[] =  "No";
        }

    }
    }
   $out = array_merge(array('result'=>'true','reason'=>'Data Fetching Succesfully','user_suggested_data' => $outaa));

i wanted to pass in single array.
Ans like :
"user_suggested_data": {
        "0": {
            "user_id": "121",
            "full_name": "Ankit Shah",
            "username": "shah_ankit39",
            "profile_picture": null,
            "status": 0
        },
        "1": {
            "user_id": "122",
            "full_name": "pooja",
            "username": "pooja25",
            "profile_picture": null,
            "status": 0
        },
        "2": {
            "user_id": "123",
            "full_name": "swapnil",
            "username": "swapnil25",
            "profile_picture": null,
            "status": 0
        },
}

A: You can achieve this by improving your SQL query to:
  SELECT
    user_registration.user_id,
    user_registration.full_name,
    user_registration.username,
    user_profile.profile_picture,
    user_follower.status
  FROM
    user_registration LEFT JOIN user_profile USING(user_id)
  WHERE
    (user_follower.to_user_id = '$user_id'
      AND user_follower.from_user_id = user_registration.user_id)
    OR (user_follower.from_user_id = '$user_id'
      AND user_follower.to_user_id = user_registration.user_id)"

store it as a string in $sql variable and finally, perform the query:
$result = $con->query($sql);


text:
Q: Populating an entire column with same value returned from a CASE statement I am trying to populate a column with the same result value from a resulting CASE statement through the entire s_date/part_no grouping.
We have tried multiple different routes to get recursion to work for what we're needing, but with no luck.  The calculations are extremely tricky, and we know SQL isn't the best for recursion, so we're trying to find an alternate route to go for the time being to meet the customer needs and time crunch.
SELECT
        s_date,
        part_no,
        i_group,
        s_level,
        p_category,
        qty_filled,
        qty_total,
        relief_amt,
        extreme_amt,
        curr_mth_note,
        CASE
            WHEN curr_mth_note IS NOT NULL
                 AND i_group = '1'
                 AND s_level = '80' THEN qty_filled
            ELSE NULL
        END AS g1s1_filled
        FROM
        (
            SELECT
                t1.s_date,
                t1.part_no,
                t1.i_group,
                t1.s_level,
                t1.p_category,
                t1.qty_filled,
                t1.qty_total,
                mv.relief_amt,
                mv.extreme_amt,
                mv.curr_mth_note,
            FROM
                multi_table mv,
                t_table t1
            WHERE
                t1.part_no = mv.part_no
                AND mv.part_no = 'xxxx'
                AND t1.s_date = mv.s_date
                AND t1.s_date = '201805'
            GROUP BY
                t1.s_date,
                t1.i_group,
                t1.s_level,
                t1.part_no,
                t1.p_category,
                t1.qty_filled,
                t1.qty_total,
                mv.relief_amt,
                mv.extreme_amt,
                mv.curr_mth_note,
            ORDER BY
                t1.s_date,
                t1.i_group,
                t1.s_level DESC
        )
ORDER BY
    s_date,
    part_no,
    i_group,
    DECODE(s_level, '80', 1, '100', 2, 'Late', 3)

The current output for the above looks like this:

What I'm trying/hoping to get is the entire g1s1_filled column to show the same 67 amount where i_group = '1' and s_level = '80' for all available date/part combos.
So for that column to show this:
G1S1_FILLED
67
67
67
67
67

I've researched how to try to use a where instead of when, with no luck.
 There will be multiple other columns built out like this, to where I can eventually do calculations as well.

A: You could use a conditional analytic minimum in the SELECT clause. I don't have your data, so I will illustrate with a similar query on the SCOTT.EMP table - suppose I want to fill NEWCOL with the salary of one particular employee. I would do it like this:
select empno, ename, sal, job, deptno,
       min(case when empno = 7499 and ename = 'ALLEN' then sal end) over () as newcol
from   scott.emp;

     EMPNO ENAME             SAL JOB           DEPTNO     NEWCOL
---------- ---------- ---------- --------- ---------- ----------
      7369 SMITH             800 CLERK             20       1600
      7499 ALLEN            1600 SALESMAN          30       1600
      7521 WARD             1250 SALESMAN          30       1600
      7566 JONES            2975 MANAGER           20       1600
      7654 MARTIN           1250 SALESMAN          30       1600
      7698 BLAKE            2850 MANAGER           30       1600
      7782 CLARK            2450 MANAGER           10       1600
      7788 SCOTT            3000 ANALYST           20       1600
      7839 KING             5000 PRESIDENT         10       1600
      7844 TURNER           1500 SALESMAN          30       1600
      7876 ADAMS            1100 CLERK             20       1600
      7900 JAMES             950 CLERK             30       1600
      7902 FORD             3000 ANALYST           20       1600
      7934 MILLER           1300 CLERK             10       1600

If (in your problem) there is only one row with the "special" combination of values in I_GROUP and S_LEVEL, then you can use (conditional, analytic) MIN or MAX or even AVG or SUM - they will all be equal to the single value, 67 in your case. If there is more than one such value, then you will need to make a choice: do you want the MIN, the MAX, the AVG, or perhaps something else. In any case, you can still use the same idea.

A: I think you want a window function:
    SUM(CASE WHEN curr_mth_note IS NOT NULL AND i_group = '1' AND
                  s_level = '80'
             THEN qty_filled
        END) OVER (PARTITION BY s_date, part_no)  AS g1s1_filled

A: instead of case statement, write a subquery for it
(select qty_filled
  from t_Table
  where
    i_group = '1' and
    s_level = '80' and
    rownum = 1
) as g1s1_filled

A: You can remove the CASE expression and move your whole query (excepted the ORDER BY clause) to a CTE. Then you can self-JOIN it to append the relevant g1s1_filled to each row.
NB : you have to be careful when defining the self-join conditions ; I provided a suggestion below, you might need to refine it.
Query :
WITH cte AS (
    SELECT
        s_date,
        part_no,
        i_group,
        s_level,
        p_category,
        qty_filled,
        qty_total,
        relief_amt,
        extreme_amt,
        curr_mth_note
        FROM
        (
            SELECT
                t1.s_date,
                t1.part_no,
                t1.i_group,
                t1.s_level,
                t1.p_category,
                t1.qty_filled,
                t1.qty_total,
                mv.relief_amt,
                mv.extreme_amt,
                mv.curr_mth_note,
            FROM
                multi_table mv,
                t_table t1
            WHERE
                t1.part_no = mv.part_no
                AND mv.part_no = 'xxxx'
                AND t1.s_date = mv.s_date
                AND t1.s_date = '201805'
            GROUP BY
                t1.s_date,
                t1.i_group,
                t1.s_level,
                t1.part_no,
                t1.p_category,
                t1.qty_filled,
                t1.qty_total,
                mv.relief_amt,
                mv.extreme_amt,
                mv.curr_mth_note,
            ORDER BY
                t1.s_date,
                t1.i_group,
                t1.s_level DESC
        )
)
SELECT a.*, b.qty_filled as g1s1_filled
FROM
    cte AS a
    INNER JOIN cte as b
        ON  b.s_date = a.s_date
        AND b.part_no = a.part_no
        AND b.i_group = '1'
        AND b.s_level = '80'
        AND b.curr_mth_note IS NOT NULL
ORDER BY
    a.s_date,
    a.part_no,
    a.i_group,
    DECODE(a.s_level, '80', 1, '100', 2, 'Late', 3)


text:
Q: Field synchronization in Play! Controllers Consider a situation when we have a Controller with 2 action methods that use same controller field. This field should be lazily initialized.
public class SomeController extends Controller {
    private static volatile Resource resource;

    private static Resource getResource() {
        if (resource == null) {
            synchronized (SomeController.class) {
                if (resource == null) {
                    resource = new Resource();
                }
            }
        }

        return resource;
    }

    public static void action1() {
        getResource().doSomeAction();
    }

    public static void action2() {
        getResource().doSomeAnotherAction();
    }

}

What are better ways of synchronizing common resources using Play Framework? Consider that resource should be lazy initialized.
Thanks,
Adrian

A: There is no difference with lazy-loaded class(field) in Play or in others servlet containers (tomcat etc) which use regular servlets. Your code with double-check-locking should works fine. But I suggest you to avoid double-check-locking (even it's not broken), simply make your method synchronized.


text:
Q: Programmatic check for img src in React I have a page with many customer logos on it in a table. One table cell tries to get the logo like this:
<TableCell className={classNames(classes.urlDealCell, classes.dealCell)}>
    {this.getLogo(deal.CompanyWebsite)}
</TableCell>

getLogo is:
getLogo = url => {
  const source = `https://logo.clearbit.com/${url}`;
  return ;
};

80% of the time, the logo comes back fine, and if there is no deal.CompanyWebsite, I can provide a default logo. But I need to handle another edge case:
If the request to the img source fails with a URL like this:
https://logo.clearbit.com/absoluteGarbage, can I somehow check this in React and fallback to the default logo?
Must I try a GET request to the src URL for each logo before trying to assign the src attribute of the img? If so, this would double the number of image requests, which would suck for larger page result sets.

A:   {e.target.onerror = null; e.target.src="image_path_here"}}/>

When an image fails to load, onError gets called. Use this function to do your logic

A: Use the onError attribute:
 event.target.src=defaultUrl} />

JSFiddle: https://jsfiddle.net/g1wubsLm/1/


text:
Q: Code not working for Pivot Data Set having Rows>65536 My purpose is to create a Pivot Table and further a Pivot Chart out of the Dump data (A1:AE170000) I have. I've attached my code below, which works perfectly fine if I reduce my data to around 60-65k rows, but not otherwise.
It throws Runtime error 13 : Type Mismatch at the line I am setting up my Pivot Cache (PTCache).
Private Sub OptionButton3_Click()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    ThisWorkbook.Sheets("Data").Activate

    Dim PTCache As PivotCache
    Dim PT As PivotTable
    'Setting range as my entire data set
    Dim PTRange As Range
    Set PTRange = Range("A1", Range("A1").End(xlToRight).End(xlDown))
    'Adding a new worksheet for Pivot Table and Chart
    Dim ws As Worksheet
    Set ws = Sheets.Add
    ws.Name = "All"
    PTRange.Select
    ThisWorkbook.Sheets("All").Activate
    'Runtime error 13:Type Mismatch at this line while setting PTCache
    Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PTRange)
    Set PT = ActiveSheet.PivotTables.Add(PTCache, Range("A1"), "All")
    With PT
        .PivotFields("Name").Orientation = xlPageField
        .PivotFields("Rate").Orientation = xlDataField
        .PivotFields("Date").Orientation = xlRowField
    End With
    PT.PivotSelect ("")

    Charts.Add
    ActiveChart.Location where:=xlLocationAsObject, Name:=PT.Parent.Name
    ActiveChart.ChartType = xlLine
    ActiveChart.Parent.Top = Range("I7").Top
    ActiveChart.Parent.Left = Range("I7").Left

    Range("A2").Select
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

A: From PivotCaches.Create Method (Excel) (my emphasis):

<blah><blah> ... When passing as a range, it is recommended to either use a string to specify the workbook, worksheet, and cell range, or set up a named range and pass the name as a string. Passing a Range object may cause "type mismatch" errors unexpectedly.

Just set up a string var to the external address of the Data worksheet's Range.CurrentRegion property radiating out from A1 and use that.
Option Explicit

Private Sub OptionButton3_Click()
    'Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim PT As PivotTable, PTCache As PivotCache
    Dim PTRange As Range, ws As Worksheet, strRNG As String

    strRNG = ThisWorkbook.Worksheets("Data").Cells(1, 1).CurrentRegion.Address(external:=True)

    With Worksheets.Add(after:=Sheets(Sheets.Count))
        .Name = "All"
        Set PTCache = .Parent.PivotCaches.Create(xlDatabase, strRNG)
        Set PT = .PivotTables.Add(PTCache, .Range("A1"), "All")
        With PT
            .PivotFields("Name").Orientation = xlPageField
            .PivotFields("Rate").Orientation = xlDataField
            .PivotFields("Date").Orientation = xlRowField
        End With
        PT.PivotSelect ("")
    End With

    'all the chart stuff here

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub


text:
Q: Add to interest group using Mailchimp API v3 I'm using this MailChimp api v3 wrapper https://github.com/drewm/mailchimp-api/tree/api-v3
Using the example I can add an email to my list but cannot add it to one of my interest groups.
This is the example code:
$MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');
    $result = $MailChimp->post('lists/b1234346/members', array(
                'email_address'     => 'davy@example.com',
                'status'            => 'subscribed',
                'merge_fields'      => array('FNAME'=>'Davy', 'LNAME'=>'Jones'),
                'interests'         => array( '2s3a384h' => true )
                ));
print_r($result);

My understanding is the key in that array entry for interests is the ID of the group. I created a group in MailChimp, which has a group title and group names.
I can see an id when I hover over the group title edit button, and also the group name edit button. If I hover over the "0 subscribers" for a group name I can see that same id and a group_id. I've tried both values and I get this error:

Array ( [type] =>
  http://kb.mailchimp.com/api/error-docs/400-invalid-resource [title] =>
  Invalid Resource [status] => 400 [detail] => Invalid interest ID:
  '39561'. [instance] => 12c1ab46-a0b5-4014-8107-08cfa97a9a94 )

I've googled and still can't find the answer. Any help?

A: You can get the Id of the specific interest option not the group id, by going to the playground
Then you navigate to your list and group:

When you click on the name of the interest option it will show the option meta data, including it's id:

A: Interests are (can be? must be?) grouped under interest-categories, but you only need the ID of the interest itself, not the ID of the interest-category when setting it for the user.
Your error may be from using the interest-category ID instead of the specific interest ID.

A: A quick and dirty way to capture all of the Interest IDs...
$MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');
    $result = $MailChimp->post('lists/b1234346/members', array(
                'email_address'     => 'davy@example.com',
                'status'            => 'subscribed',
                'merge_fields'      => array('FNAME'=>'Davy', 'LNAME'=>'Jones')
                ));
print_r($result);

Your print_r after not specifying the "interests" key in the post should provide you with an interests array with the IDs telling you they are all marked as false.
["interests"]=> array(7) { ["258ad948a1"]=> bool(false) ["8e30162ec8"]=> bool(false) ["f2f79df229"]=> bool(false) ["b4e2f6effc"]=> bool(false) ["4fb0927fef"]=> bool(false) ["f2d1e06470"]=> bool(false) ["9f6c7c4db2"]=> bool(false) }


text:
Q: How to change fb:registration tag visibility from inside getLoginStatus() function This is how I've set up my login/registration flow. On the index.html page there is a link. Once it is clicked you are sent to a second page where your login status is checked and the fb login/registration box is shown if you're not registered or logged in.
What I've done is made the tag invisible on the page until after the login status is checked? Once it's checked I want it to become visible if the user isn't logged in or registered, but it's not becoming visible.
What is the best way to hide the visibility of the register/login box until login status is checked. I don't want to use facebooks login() function because I don't want a pop up window. I want to use the XFBML tag. Below is my code:
<!DOCTYPE html>

<fb:registration
  fields="name,birthday,gender,location,email"
  redirect-uri="http://spilot.koding.com/signedRequest.php" width="530">
</fb:registration>

A: This was the solution that worked for me. I decided to use the registration plugin instead. I put the iframe in a div and set the div's visibility to "hidden", then in the init code where it checks log in status, I call a function that uses document.getElementById().style.visibility ="visible" to grab the div and change its visibility. Make sure everything that needs quotes around it has them, that was one of my original mistakes.
<!DOCTYPE html>

//put iframe inside a div and set the div's visibility to hidden.


text:
Q: How can I make the react-bootstrap Navbar stay fixed="top" and have sidebar under it I learn ReactJs and the react-bootstrap NavBar. I wanted to have a fixed="top" NavBar so it is always visible. So the content is scrolled under it!
The two problems i have here in my CodeSanbox is that the side-bare that the NavBar menu opens is under the NavBar.
I think I know why it's because of the fixed="top" property on the NavBar. I have tried to understand how it works and it looks like I have to calculate the NavBar height and set that as top margin for the side-bare. Any better idea or if I'm wrong here please advice?
My other problem is the size of the 3-strip icon Hamburger menu. How can I change it to be bigger? I read the docs and I see no information for this?

A: For the .side-drawer, you can adjust the top property (e.g., top: 146px) or you can add some padding to the sidebar element so that it makes space for the header.
.side-drawer {
  padding-top: 160px;
}

As for the hamburger button dimensions, I recommend resizing .navbar-toggler-icon
.navbar-dark .navbar-toggler-icon {
  height: 100px;
  width: 100px;
}


text:
Q: Android - Change the Activity State using another Thread is Not Working MyThread class is used to change the value of the myValue attribute in ActivityTwo Class.
public class MyThread implements Runnable {

    private ActivityTwo activity;

    public MyThread(ActivityTwo activity) {
        this.activity = activity;
    }

    @Override
    public void run() {
          while(true){
            activity.setValue(2);
         }
    }
}

ActivityTwo is an AppCompatActivity activity which runs as the main Thread.
public class ActivityTwo extends AppCompatActivity {

    private MyThread myThread;
    private Button startLogBtn;
    private int myValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);

         startLogBtn = findViewById(R.id.startLogBtn);
        myThread = new MyThread(this);

        startLogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(myThread).start();
            }
        });
   }

   public void setValue(int value){
       this.myValue= value;

   }

}

When I Click the startLogButton it goes to a white screen and then restart the app. What should I do? I have no idea what has gone wrong.
Thanks in advance.

A: The issue was I have violated the rule "Do not access the Android UI toolkit from outside the UI thread".
ref : https://developer.android.com/guide/components/processes-and-threads
As a solution I found that I can use thread communication using message passing.
ref : Communication between UI thread and other threads using handler


text:
Q: Does using msysgit lead to repository corruption? While stumbling through the chromium code documentation, I came across this post:
http://code.google.com/p/chromium/wiki/UsingGit#Windows

If you are using msysgit, you are
  asking for trouble. Using both msysgit
  (including TortoiseGit) and cygwin's
  version of git is a path to lead to
  repository corruption so it's safer to
  stick with the cygwin's version. So if
  you still have msysgit in your PATH,
  you are on your own.

Does this really happen?  What causes the corruption?

A: It depends when the warning was written, but further down the paragraph it suggests:

Be sure to turn off git's crlf munging:

git config --global core.autocrlf false

My guess it that it's a combination of line-ending conversion problems and msysgit not being stable when that bit of documentation was written. However, having myself only ever used git-svn to do an import from SVN to Git, and not two-way collaboration, it's possible that the warning is still valid.

A: I saw msysgit corrupt two Chromium checkouts in early 2009.  I think that's roughly when this caveat was written.  It seemed that git-svn support was immature at that point in time.  I've avoided msysgit since then -- a real shame, because it's 4x-5x faster.  Maybe things are better now?


text:
Q: How to update all your ubuntu-make packages? Currently you can't update packages with umake. Here's a link to the closed github issue How to update installed software?#122. As mentionned you only need to remove the package and reinstall it like this.
umake --remove <type> <package> && umake <type> <package>

For example, if you know that idea shoul be reinstalled, type:
umake --remove ide idea && umake ide idea

So I was lookong for a solution to update all my umake packages.

A: Assuming you have choosed default installation path, all packages are installed in $HOME/.local/share/umake/
So you can list them and update them like this:
for path in $(ls -d $HOME/.local/share/umake/**/*/); do
    package=$(basename ${path});
    type=$(basename $(dirname ${path}));
    echo "Reinstalling ${package} of ${type}";
    umake --remove $type $package && umake $type $package;
done


text:
Q: AWS CDK - role and policy creation How can I translate this CloudFormation to CDK (JavaScript or Java)? I was trying to do it, but this is the first time that I work with CDK and I'm not sure how to do it.
FargateTaskExecutionServiceRole:
Type: AWS::IAM::Role
Properties:
  AssumeRolePolicyDocument:
    Statement:
    - Effect: Allow
      Principal:
        Service:
          - ecs-tasks.amazonaws.com
      Action:
        - sts:AssumeRole
  Policies:
    - PolicyName: AmazonECSTaskExecutionRolePolicy
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Action:
            - 'ecr:GetAuthorizationToken'
            - 'ecr:BatchCheckLayerAvailability'
            - 'ecr:GetDownloadUrlForLayer'
            - 'ecr:BatchGetImage'
            - 'logs:CreateLogStream'
            - 'logs:PutLogEvents'
          Resource: '*'

A: You should refer to API reference document to get a clear picture. There are examples for such use cases.
However, since you have already asked here and my hands has been itchy to provide you with an answer, so here goes the TypeScript implementation of just the IAM part:
import {
   ManagedPolicy,
   Role,
   ServicePrincipal,
   PolicyStatement,
   Effect
} from '@aws-cdk/aws-iam';

....
....

const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com')
});

// Add a policy to a Role
ecsFargateServiceRole.addToPolicy(
  new PolicyStatement({
    effect: Effect.ALLOW,
    resources: ['*'],
    actions: [
      'ecr:GetAuthorizationToken',
      'ecr:BatchCheckLayerAvailability',
      'ecr:GetDownloadUrlForLayer',
      'ecr:BatchGetImage',
      'logs:CreateLogStream',
      'logs:PutLogEvents'
    ]
  })
);

// Add a managed policy to a role you can use
ecsFargateServiceRole.addManagedPolicy(
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
);

....
....

UPDATE:
When you are adding an AWS managed policy to a role, you can get the managed policy as a reference by its name or by its ARN. The important part is that if an AWS Managed policy is used as above by its name or ARN, then you will not need to use the policy statement explicitly. From my answer above, you can use the managed policy approach rather than using the policy statement.
An easy way to define the role now would be:
const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com'),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
  ]
});

Note that I have excluded the constructor for the Construct for brevity.
UPDATE: (from comments)
With version 2 of CDK you have to add service-role/ to managed policy. So it looks like this:
ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy')


text:
Q: Android service error handling What is best way for services error handling?
For example, I have service which get some information from Internt, I want show to user some dialog with message when connectivity is bad. Or if I have some Util class for parse HTML that used by my service and exception occures in this Util class. How to show dialog? As I know DialogBuilder needs some Activity context, but Service context is wrong for this. Right?
Thanks.

A: Have you considered using a notification?  You can set a brief message and icon on the task bar, and the user has the option of clicking it, where you can open up a dialog with more details or they can just clear it.  You can also clear it within the service if connectivity gets better.


text:
Q: c# testing a generic exception I'm writing integration test for a repository class that operates on a MySQL database.
I want to test the fact that inserting the same record two times throw an exception, I'm using xUnit
    [Fact]
    public void Insert_SamePaymentTwoTimes_ThrowInvalidOperationException()
    {
        Payment payment;
        using (var transaction = new TransactionScope())
        {
            int? id = 0;
            id = paymentRepository.Insert(testPayment);
            payment = paymentRepository.GetById(id);

            Assert.Throws<MySql.Data.MySqlClient.MySqlException>(() => paymentRepository.Insert(payment));
        }
    }

The test works fine but I want my tests to be as generic as possibile, if later my PaymentRepository writes to let's say MSSQL the test will fail.
I came up with this solution :
Change Insert() function so it throw a generic system exception:
using (var conn = GetOpenConnection())
{
   try
   {
       paymentId = conn.Insert(paymentData);
   }
   catch (MySqlException ex)
   {
       throw new InvalidOperationException(ex.Message);
   }
}

and catch that exception on my test:
    [Fact]
    public void Insert_SamePaymentTwoTimes_ThrowInvalidOperationException()
    {
        Payment payment;
        using (var transaction = new TransactionScope())
        {
            int? id = 0;
            id = paymentRepository.Insert(testPayment);
            payment = paymentRepository.GetById(id);

            Assert.Throws<InvalidOperationException>(() => paymentRepository.Insert(payment));
        }
    }

Are there any alternatives to this approach ? I was thinking of maybe implement a custom DbException in order to be as generic as possibile.


text:
Q: How to acquire a file path using objective c I want a function which just returns the full file path of a file selected in finder.
I am currently have this function:
+ (NSString*)choosePathWindow:(NSString*)title buttonTitle:(NSString*)buttonTitle allowDir:(BOOL)dir allowFile:(BOOL)file{
    [NSApp activateIgnoringOtherApps:YES];

    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel setLevel:NSFloatingWindowLevel];
    [openPanel setAllowsMultipleSelection:NO];
    [openPanel setCanChooseDirectories:dir];
    [openPanel setCanCreateDirectories:dir];
    [openPanel setCanChooseFiles:file];
    [openPanel setMessage:title];
    [openPanel setPrompt:buttonTitle];

    NSString* fileName = nil;
    if ([openPanel runModal] == NSModalResponseOK)
    {
        for( NSURL* URL in [openPanel URLs])
        {
            fileName = [URL path];
        }
    }
    [openPanel close];
    return fileName;
}

But this usually behaves awfully and stutters into view and often hangs after choosing a file (I have an i7-7700k and 16GB ddr4) and always hangs when clicking cancel. I also believe that this may be to do with external network mounts I have. But any other software such as PHPStorm or Chrome work fine with the same window.
Is there a better way to do this?

A: The code looks fine. Try calling your function from main thread; modal dialogs need this and usually don't enforce it themselves. In any case the Powebox (the thing that runs NSOpenPanel in sandbox) is a bit of a beast. Also you might get different results with debug build launched directly from Xcode (not so good) and release build launched from Finder.
To test NSOpenPanel: Try running your App under a guest account to eliminate all stuff that's cluttering the sandbox .

A: My code:
(actually in production:)
-(void)OpenIt {
    NSOpenPanel* panel = [NSOpenPanel openPanel];

    // This method displays the panel and returns immediately.
    // The completion handler is called when the user selects an
    // item or cancels the panel.

    [panel setTitle: "title...."];
    NSString *title = NSLocalizedString(@"CHOOSE_FILE", @"");
    [panel setMessage: title];

    [panel beginWithCompletionHandler:^(NSInteger result){
        if (result == NSFileHandlingPanelOKButton) {
            NSURL*  theDoc = [[panel URLs] objectAtIndex:0];
            NSLog(@"%@", theDoc);
            // Open  the document using url
            [self openUsingURL: theDoc];
        }
    }];
}


text:
Q: How to find an OSGi bundle providing a specific capability (JavaEL 5.0) I am using Felix implementation of OSGi.
I have a plugin I wrote which uses hibernate-validator:
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>8.0.0.Final</version>
</dependency>

I use the bnd-process goal of the biz.aQute.bnd:bnd-maven-plugin plugin to package that bundle.
When opening the MANIFEST.MF generated, I find the following entry:
Require-Capability: osgi.extender;filter:="(&(osgi.extender=osgi.compone
 nt)(version>=1.5.0)(!(version>=2.0.0)))",osgi.contract;osgi.contract=Ja
 vaEL;filter:="(&(osgi.contract=JavaEL)(version=5.0.0))",osgi.ee;filter:
 ="(&(osgi.ee=JavaSE)(version=17))"

Notice the osgi.contract;osgi.contract=JavaEL;filter:="(&(osgi.contract=JavaEL)(version=5.0.0))" part.
Now if I look at https://docs.osgi.org/reference/portable-java-contracts.html#jakarta-ee-contracts, I only find either Jakarta Expression Language in version 5.0 or JavaEL in version 3.0. There is no such JavaEL in 5.0 version.
I found the "hard way" that I need to add:
<dependency>
  <groupId>jakarta.el</groupId>
  <artifactId>jakarta.el-api</artifactId>
  <version>5.0.0</version>
</dependency>

to my pom.xml and ,jakarta.el;version="5.0.0" to my Private-Package bnd configuration of the bnd-maven-plugin, but I wonder whether there is an easier way.
Now what is annoying me is that my core application has the Jakarta Expression Language version 5.0 as its available capability, but not JavaEL 5.0, so I need to declare that dependency in each of my plugins (some of which I do not even control the development flow).
Hence my questions:

*

*Is this a bug in the capability resolution engine in the
bnd-maven-plugin after the infamous javax renaming into
jakarta?

*Is there any way I can avoid my plugins to explicitly
import jakarta-el when my core application has the capability, but
with a different name?

*Or am I doing something wrong somehow?


text:
Q: Python; enforce two functions implement the same interface? I want to do something, for functions, not classes, like
def function_A(param1, param2 = "default_param_2")

def function_B(__signature of A__)

So that whenever I change the interface of A, this is automatically updated in B. Is there a notion of an "abstract base interface" for functions or a mechanism to do this?

A: Not sure how useful this is but decorators may give you a least part of what you are looking for.  Consider:
from functools import wraps

def abi(f):
    @wraps(f) #preserves name/doc of wrapped function
    def function_A(param1, param2='param2'):
        print(param1, param2)
    return function_A

@abi
def function_B(*args, **kw):
    "I'm function_B but I'm REALLY function_A.  Look there for params."
    pass

Defining *args and **kw for function_B makes it flexible for function_A to change its signature.  Any parameters passed into function_B will be mapped to function_A's following the normal rules; too many args, multiple values for argument, etc. will raise TypeErrors.
If you change the signature of function_A, any calls to function_B that still match can be called successfully (assuming the module has been reloaded).  The rest will fail obviously and you'll need to update the calls to function_B.
Hope this helps!  YMMV.

A: I would not do this at runtime, and you cannot change the signature automatically but you can definitely test that in your testing suite using the inspect module.
For instance:
import inspect

def foo(bar, baz=42, **kwargs):
    pass

for param in inspect.signature(foo).parameters.values():
    print('%s is %s' % (param.name, param.kind))

This will print:
bar is POSITIONAL_OR_KEYWORD
baz is POSITIONAL_OR_KEYWORD
kwargs is VAR_KEYWORD

You can use this to compare the signature of functions in your test suite. Check out the inspect module for other things you can introspect.

A: Under Python 3 you can easily get the signature:
>>> from inspect import signature
>>> def A(a, b='default'):
...    pass
>>> sig=signature(A)
>>> print(sig)
(a, b='default')

Problem is, there is not much you can do with that without being really hacky.
You can compare a function's signature to another:
def A(a, b='default'):
    pass

def B(a, b='something else'):
    if signature(A) != signature(B):
        print('Yo, need to update me!')
    else:
        print('all good in B land')

But you cannot dynamically update B to match A.


text:
Q: Access Apex:SelectList values from JQuery I'm having following code to access the selected values of a picklist. But i'm getting 'undefined' as the value whenever i read from JS. Here is the code

Picklist 1

                <apex:selectList size="1" value="{!loadPicklist1}" styleClass="slds-select" id="1_id">
                    <apex:selectOptions value="{!loadPicklistValues}" />
                    <apex:actionSupport event="onchange"  action="{!loadAnotherItems}"/>
                </apex:selectList>

And here is my JQuery code to access the value. The button id related to the event is buttonId.
j$('#buttonId').on('click',function(e){
    //debugger;
    var 1Type = j$('#1_id').val();

    alert(1Type);

});

Please help to identify why I'm getting undefined even though I pick a value here.

A: Visualforce element's id are auto-generated, So to access them in jQuery one of the easier method is to use ends with selector.
In your example, you can refer access the selected value as follows:
j$("select[id$='1_id']").val();

Refer this blog for details more details and with different approach - VisualForce Element Ids in jQuery selectors.


text:
Q: Docker:'Not able to pull image' I accidentally deleted image locally in private repository while trying to update it ,
whenever i try to run this command :
docker pull clex-docker-dev-local.de/dba/cs.xyz_ddl_master:latest
Unsupported docker v1 repository request for 'clex-docker-dev-local'
I already tried
Login for the repository 'clex-docker-dev-local`' was successful for me


text:
Q: Strong params on a hash or array In rails I did this in a model:
  def update_user_ex(*attrs)
    user.assign_attributes(*attrs)
    # .............

where attrs is an  array with of a hash(es), for simplicity let's say it's a single hash.
How can I do this in Rails 4? "permit" doesn't work on a hash or array.

A: It's possible to use strong parameters outside of controllers per the documentation at https://github.com/rails/strong_parameters
Example:
def update_user_ex(*attrs)
  params = ActionController::Parameters.new(attrs)
  user.assign_attributes(params.permit(:name, :email, :something_else))

A: Permit do work on arrays in rails 4. But array need to be last parameter.
params.require(:test).permit(:name,:rollno, question_ids:[])

The below example give error as array is not last parameter.
params.require(:test).permit(question_ids:[], :rollno)


text:
Q: Duplicating each column of a csv and changing values of every column cell based on a condition in python I am a new user to everything especially python and pandas. I have a .csv file with more than 1000 columns and around 250 rows. The values of the rows are either 0 and 1 or empty cells. An example of the csv file is given below:
  ID       col1   col2    col3  col4 .  . ............... col1000
  1          1     0              1                         1
  2          0              1     1
  3                1              0                         0
  .
  .
  .
  .
 250         0     1              0                         0

There are two things that i want to do:
First, i want to duplicate all 1000 columns (except ID column) with same cell values and the column names as the original columns and then place each copied column next to the original column in the following order:
col1      col1     col2     col2    col3    col3     col4     col4 ...... col1000      col1000

Second, i want to replace the values in the cells based on on the following conditions:
If there is 1 in the original cell, The value in the copied column should remain 1 and if there is 0 in the original column cell then the value of the copied column should be changed to -1. If the original cell is empty then the value of original cell and the copied cell should be filled with 0 values.
The output csv file will be:
  ID     col1    col1   col2   col2   col3    col3   col4   col4 . ........... col1000   col1000
  1        1       1      0     -1      0       0      1      1                    1        1
  2        0      -1      0      0      1       1      1      1                    0        0
  3        0       0      1      1      0       0      0     -1                    0       -1
  .
  .
  .
  .
 250       0      -1     1       1      0       0      0     -1                    0       -1

I am not able to solve it and really appreciate if someone could help me out; Thanks...

A: You can try this to see if it works.
import pandas as pd
import numpy as np

Starting Data
df = pd.DataFrame({'col1':[1,0,np.NaN,np.NaN,1],'col2':[1,0,np.NaN,np.NaN,1],'col3':[1,0,np.NaN,np.NaN,1]})

First make a copy of the original df.
df_copy = df.copy()

Then replace the values in the copy based on criteria above.
columns =  df_copy.columns
df_copy[columns] = np.where(df_copy[columns]==0,-1,df_copy[columns])

Then fill the blank values with 0.
df_copy = df_copy.fillna(0)

Add a column count for sorting.
df.loc['total'] = np.arange(len(df.columns))
df_copy.loc['total'] = np.arange(len(df_copy.columns))

Then concatenate the two df's together
new_df = pd.concat([df,df_copy],axis=1)

Sort the columns using the column count row, then drop the row from the new df
new_df = new_df.sort_values(by='total',axis=1)
new_df = new_df.loc[~new_df.index.isin(['total'])]

A: You can use this (similar approach as other answer with use of pandas built-in functions to replace):
df2 = df.copy().replace(0,-1).fillna(0).drop(['ID'],1)
df = pd.concat([df.fillna(0),df2],1)

output and sample input (for a different input sample, but the comparison of columns are apparent):
input:
     ID  col1  col2  col3  col4  col1000
0     1     1     0     1   1.0      NaN
1     2     0     1     1   NaN      NaN
2     3     1     0     0   NaN      NaN
250   250     0     1     0   0.0      NaN

output:
    ID  col1  col2  col3  col4 ... col1000  col1  col2  col3  col4 ... col1000
0    1     1     0     1   1.0      0.0     1    -1     1   1.0      0.0
1    2     0     1     1   0.0      0.0    -1     1     1   0.0      0.0
2    3     1     0     0   0.0      0.0     1    -1    -1   0.0      0.0
...
250  250     0     1     0   0.0      0.0    -1     1    -1  -1.0      0.0

A: You can do the following steps, the trick is to use column index to getting the correct column sequences:
# create copied data and concat into original
df2 = pd.concat([df, df.replace(0,-1).fillna(0).drop('ID', axis=1)], 1)

# since column names are same, we need to use index
cols = [x for x in df2.columns if x != 'ID']
cols = dict(enumerate(cols))

# get correct index for column names
cols_index = [x[0] for x in sorted(cols.items(), key=lambda x: x[1])]

# fix column names
idcol = df2[['ID']]
df2 = df2.drop('ID', 1).iloc[:,cols_index]

# add the ID column
df2 = pd.concat([idcol, df2], 1).fillna(0)

print(df2)

   ID  col1  col1  col2  col2  col3  col3
0   1   1.0   1.0   1.0   1.0   1.0   1.0
1   2   0.0   0.0   0.0   0.0   0.0   0.0
2   3   NaN  -1.0   NaN  -1.0   NaN  -1.0
3   4   NaN  -1.0   NaN  -1.0   NaN  -1.0
4   5   1.0   1.0   1.0   1.0   1.0   1.0

Sample Data

df = pd.DataFrame({'ID': list(range(1,6)),
                   'col1':[1,0,np.NaN,np.NaN,1],
                   'col2':[1,0,np.NaN,np.NaN,1],
                   'col3':[1,0,np.NaN,np.NaN,1]})


text:
Q: How to sort an array while keeping the order of the index row matching the sorted row? Easiest way is to show you through excel:
Unsorted:

Sorted:

This example is with excel, but I would need to do the same thing in matlab with thousands of entries (with 2 rows if possible).
Here is my code so far:
%At are random numbers between 0 and 2, 6000 entries.

    [sorted]=sort(At);
    max=sorted(end);
    min=sorted(1);
%need the position of the min and max

But this is only 1 row that's being sorted and it has no numbers in the second row, and no index. How would I add one and keep it following my first row?
Thank you!

A: I don't have access to Matlab, but try
[sorted, I] = sort(At);

Where I will be a corresponding vector of indices of At. See the Matlab Documentation for details.

A: You have a couple of options here. For the simple case where you just need the indices, the fourth form of sort listed in the docs already does this for you:
[sorted, indices] = sort(At);

In this case, At(indices) is the same as sorted.
If your "indices" are actually another distinct array, you can use sortrows:
toSort = [At(:) some_other_array(:)];
sorted = sortrows(toSort);

In this case sorted(:, 1) will be the sorted array from the first example and sorted(:, 2) will be the other array sorted according to At.
sortrows accepts a second parameter which tells you the column to sort by. This can be a single column or a list of columns, like in Excel. It can also provide a second output argument, the indices, just like regular sort.


text:
Q: Define expected parameters for a controller action in Rails I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:
def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.
It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.
Does this exist? :)

A: Actually, stumbled across this article: http://rails.nuvvo.com/lesson/6376-action-controller-verification
The method is called verify and you can specify things like parameters to expect. :)

A: Try this code:
before_filter :check_params

private
def check_params
    needed_params=[:links]
    needed_params.each do |x|
        render :text=>"Missing param #{x}", :status=>400
        return
    end

end
Put this code at the end of your class. It will work for every action. Also, you want to return an error code 400 (Bad Request), not an error 404 (File Not Found).

A: I dont recall functionality existing that allows you to do that. You could use this instead at the top of your action:
params[:links] ||= []


text:
Q: Undefined variable: db_selected in C:\wamp\www\demo.php on line 14 Im just learning about linking databases and php. I have a database called forms1 that i created with a table named "demo" in the "demo" table i have two forms, ID and input1. when I test my demo.php i get the following error,
Notice: Undefined variable: db_selected in C:\wamp\www\demo.php on line 13
Call Stack
Time    Memory  Function    Location
1   0.0006  250416  {main}( )   ..\demo.php:0
can't useforms1:
Here is my php

    <?php
      define('DB_NAME', 'forms1');
      define('DB_USER', 'root');
      define('DB_PASSWORD', '');
      define('DB_HOST', 'localhost');

      $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

      if (!$link) {
  die('Could not connect: ' . mysql_error());
  }
  $db_seleccted = mysql_select_db(DB_NAME, $link);
      if (!$db_selected) {
  die('can\'t use' . DB_NAME . ': ' . mysql_error());
  }
     echo 'Connected Successfully';
      mysql_close();
    ?>

Does anyone have an idea what may be the problem?

A: You spelled your variable incorrectly:
$db_seleccted = mysql_select_db(DB_NAME, $link); <-- HERE

Notice the double "c". Easy fix:
$db_selected = mysql_select_db(DB_NAME, $link);


text:
Q: handling exceptions in service fabric I have an a controller method in my api calling a service which throws a custom exception.
customException :
    public class DematerialisationException : Exception
{
    private static readonly string DefaultMessage = "An error occurred during dematerialisation.";

    public DematerialisationException() : base(DefaultMessage)
    { }

    public DematerialisationException(string message) : base(message)
    { }

    public DematerialisationException(Exception inner) : base (DefaultMessage, inner)
    { }

    public DematerialisationException(string message, Exception inner) : base (message, inner)
    { }
}

the method called in the service directly throws the exception :
public async Task<LiasseDetails> CreateLiasseAsync(LiasseCreate liasseData) =>
throw new DematerialisationException();

then the caller :

I would have expected ex3 to be hit instead it's ex2 as you can see in the screenshot. the innerException is in the correct type, so why is the wrong breakpoint hit? What did I do wrong?
thanks

A: In the variable watcher, you can see that a ServiceException is thrown when getting the value of InnerException, this happened because the exception object could not be serialized.
So try to add the attribute [Serializable()] to DematerialisationException class :
[Serializable()]
 public class DematerialisationException : Exception
{
    private static readonly string DefaultMessage = "An error occurred during dematerialisation.";

    public DematerialisationException() : base(DefaultMessage)
    { }

    public DematerialisationException(string message) : base(message)
    { }

    public DematerialisationException(Exception inner) : base (DefaultMessage, inner)
    { }

    public DematerialisationException(string message, Exception inner) : base (message, inner)
    { }
}


text:
Q: Parsing arabic/chinese/japanese rss feeds with java I'm writing a rss feed parser with java and I've encountered a problem while parsing feed that have arabic/chinese/japanese characters. Example feed
When I print them I just get sets of question marks "?????? ?? ????? ??".
They end up in my database (mysql, connected by hibernate, has utf8 set as encoding) also like that.
This the part of the code that is responsible for getting the title from a feed:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(url.openStream());
doc.getDocumentElement().normalize();

Node channelNode = doc.getElementsByTagName("channel").item(0);

NodeList channelList = channelNode.getChildNodes();

for (int i = 0; i < channelList.getLength(); i++) {
    Node element = channelList.item(i);

    String name = element.getNodeName();

    if (name.equalsIgnoreCase("title")) {
     rssName = element.getTextContent();
     break;
    }
}

How to get the proper characters into the database ?
When I copy them from the feed and insert manulally into the db its ok.
Thanx
UPDATE:
Putting additional lines in my hibernate config fixed the issue:
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>

A: You need to change the MySQL JDBC URL in Hibernate configuration to include the following params:
jdbc:mysql://hostname:3306/db_name?useUnicode=yes&characterEncoding=UTF-8
Otherwise the MySQL JDBC driver will use the client platform default encoding.
Your DB encoding is totally fine since manual insert works apparently fine. XML is usually by default parsed as UTF-8, so that part is fine as well (unless explicitly otherwise specified in the XML declaration header which is likely not the case since that would be a mistake of the RSS feed server).

A: You need to ensure that the character encoding of the database is compatible with such characters. Most likely by configuring it to be UTF-8.
If the database character encoding can not handle a character, it gets converted to ?.
Most databases will have an overall default encoding and then allow per table and per column overrides.
You will also need to ensure that you are parsing in incoming stream correctly (i.e. as UTF-8 or whatever encoding it specifies).

A: It's clearly an encoding problem.
You should try to decode the RSS stream using the UTF-8 charset.


text:
Q: How to fix: Error code: 1241. Operand should contain 1 comun(s)? I'd like to return one row in my function, but I get this error code.

Error code: 1241. Operand should contain 1 column(s)?

I have these tables:
airport
airport_id,
city,
country,
name,
phonenumber

and
route
route_number,
start_date,
finish_date,
time,
start_airport_id,
finish_airport_id

I want to write a function that I give in its parameters start_country, finish_country and date and I want to return one row.
So this is my code:
FUNCTION `search`(start_country varchar(50), finish_country varchar(50), dat date)
RETURNS varchar(255) DETERMINISTIC
BEGIN
    DECLARE start_id, finish_id varchar(50);

    if (start_country is null ) or (finish_country is null) or (dat is null) then
        return 'Parameters are required.';
    end if;

    SELECT airport_id INTO start_id FROM airport where country=start_country;
    SELECT airport_id INTO finish_id FROM airport where country=finish_country;

    if (start_id is null) or (finish_id is null) then
        return 'There is no such country.';
    else
        RETURN (SELECT * FROM route
                WHERE start_airport_id=start_id
                AND  finish_airport_id=finish_id
                AND start_date=dat );

     end if;
END

I write to select
search('Hungary', 'France', '2019-03-08')

and I'd like to get:
route_number | start_date | finish_date | time |start_airprot_id| finish_airport_id
AI1000         2019-03-08    2019-03-08   3hours        1                2

But I get Error Code: 1241. Operand should contain 1 column(s)


text:
Q: BibTeX delete final dot I have a LaTeX document at the end of which I included a bibliography and a sitography.
I used the bibtopic package and the code of the sitography is:
\documentclass[12pt,oneside,a4paper]{book}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% START OF PREAMBLE
\usepackage{fancyhdr}
\pagestyle{fancy}
\setlength{\headwidth}{\textwidth}

\usepackage{microtype}
\usepackage[utf8]{inputenc}
%\usepackage[latin1]{inputenc}
\usepackage{lipsum}
\usepackage{makeidx}
\makeindex

\usepackage{float}
\usepackage{url}
\urlstyle{same}

\usepackage{listings}
%\usepackage{color}
\usepackage{amsmath}
\usepackage[dvips]{graphicx}
\usepackage{boxedminipage}
\usepackage{verbatim}
\usepackage{moreverb}
\usepackage[subfigure]{tocloft}
\usepackage{subfigure}
\usepackage[colorlinks=true,linkcolor=black,urlcolor=black,citecolor=black]{hyperref}

\usepackage{bibtopic}
\usepackage{lmodern}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{spverbatim}

\newcommand{\rfc}{\mbox{RFC 2544}}
%\renewcommand{\cftloftitlefont}{\Large\bfseries}

\begin{document}

\frontmatter
\titlepage
\newpage

% Index
\fancyhead[RO]{\scriptsize Indice}
\fancyhead[LO]{}
\tableofcontents
\newpage

%%% Sitography
\bibliographystyle{unsrt}

\backmatter

\renewcommand{\chapter}{%
  \cleardoublepage\phantomsection
  \addcontentsline{toc}{chapter}{Sitography}
}
\fancyhf{}
\thispagestyle{sitography}

\chapter{}
\renewcommand\bibname{}
\begin{btSect}{websites}
\btPrintAll
\end{btSect}

\newpage

\end{document}

The bib file is:
% Thesis sitography

@Misc{iperf,
    title = {Iperf},
    howpublished = {\url{https://iperf.fr/}},
}

@Misc{iptraffic,
    title = {{IP Traffic}},
    howpublished = {\url{http://www.zti-communications.com/iptraffic/}},
}

@Misc{rfc1242website,
    title = {{RFC} 1242},
    howpublished = {\url{http://www.ietf.org/rfc/rfc1242.txt}},
}

The output of the sitography is:

[10] Iperf. https://iperf.fr/.
[11] IP Traffic. http://www.zti-communications.com/iptraffic/.
[12] RFC 1242. http://www.ietf.org/rfc/rfc1242.txt.

I'd like to delete (or change with another symbol) the final dot after the site address and, if possible, also the dot after the title of the site.

A: You need to edit your .bst file (which is the file that defines the bibliography style). In your case, it is the unsrt.bst. I suggest you to copy unsrt.bst from the latex installation directory to your current .tex project directory. Then you can edit it without ruining the whole TeX system.
What you should do inside unsrt.bst is to look for a fin.entry, like this:
FUNCTION {fin.entry}
{ add.period$
  write$
  newline$
}

and then remove the add.period$, resulting in:
FUNCTION {fin.entry}
{
  write$
  newline$
}

Save the file and test it. The final dot should be gone.
PS: This trick does also work for other .bst files which use a final dot.


text:
Q: Mac ABRecord setValue forProperty error When I use AddressBook like this :
ABAddressBook *ab = [ABAddressBook addressBook];
ABPerson *person = [[ABPerson alloc]init];
[person setValue:lastName forProperty:kABLastNameProperty];
[ab addRecord:person];
[ab save];

I got error :
`Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: '-[__NSCFString count]: unrecognized selector sent to instance 0x1001448a0'`

What does setValue:forProperty do

A: It looks like the problem is in
-[__NSCFString count]

The setValue:forProperty sets value for a property. It looks like the problem might be your lastName object that you are trying to set.