text:
Q: What is meant by 'have been to'? What is meant by "have been to" in the following sentence:

*

*They have already been to Paris, haven't they?

Does it mean that:

*

*They have recently visited Paris?

or

*

*They have just come back from Paris?

Thank you

A: It could mean either of those and it could also mean They have visited Paris at some point in the past.
The key significance of the present perfect is present relevance, but the exact meaning of that present relevance can vary.
In your 1., the present relevance is that their being back is seen as a continuing consequence of their returning.
In your 2., the present relevance is that their trip was recent, and is seen in the frame of recent things.
In my 3., the present relevance is that they are currently in a state of having been to Paris at some point in their past.

A: "They have already been to Paris"
The general idea that is conveyed in this sentence is that they have been to Paris at some point in the past.
However, we do not know at what point in the past they visited Paris. Therefore, both of your interpretations could have potentially happened, but the sentence "They have already been to Paris, haven't they?" does not commit itself to only one of these.
By including "already" you are also creating an air of disappointment. To me, this sentence is trying to show that they were all hoping to go to Paris together, but because they (the other people) have already been (at some unknown point in the past), they would prefer not to go again.
Saying this, the sentence could just be neutral as well, by simply talking about the fact that some people they know have been to Paris in the past.


text:
Q: How get another user data from firebase? I want when user click to admin profile, user can see the admin info.
Im using the currentUser to get the id of current user who logged in already in applications.
I'm trying to know how get the another user data.
    String currentuser = FirebaseAuth.getInstance().getCurrentUser().getUid();

    // init firebase database
    mUserDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");

    mUserDatabaseReference.child(currentuser).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            // here using Picasso for get the image url and set in ImageView
            String imageUrl = dataSnapshot.child("profile_pic").getValue().toString();
            Picasso.with(AboutCompany_for_users.this).load(imageUrl).into(companyPhoto);

            String name = dataSnapshot.child("name").getValue().toString();
            String email = dataSnapshot.child("email").getValue().toString();
            String phone = dataSnapshot.child("mobile").getValue().toString();
            String busesNumbers = dataSnapshot.child("buses_numbers").getValue().toString();
            String lineName = dataSnapshot.child("bus_line").getValue().toString();

            // here we get the data from
            companyName.setText(name);
            companyEmail.setText(email);
            companyPhone.setText(phone);
            companyBusesNumbers.setText(busesNumbers);
            companyLineName.setText(lineName);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    driversInformations.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent driversInfo = new Intent(AboutCompany_for_users.this, CompanyDrivers.class);
            startActivity(driversInfo);
        }
    });

I expect when user click on admin profile show the admin info not current user info

A: You can't query other user accounts in Firebase Authentication from client code.  You will have to either

*

*Store the other user's data in a database, and query that database.

*Call some backend code and use the Firebase Admin SDK to perform the query, and return that to the client.

Usually people choose option 1.

A: Create a Cloud Functions and use the Firebase Admin SDK.
You can get another user data by uid or email or phone number.
And you can list user each by max 1000.
If you create a Cloud Functions using node.js then code is like this.
// get another user data by uid
exports.getUser = functions.https.onCall(async (data, context) => {
  try {
    // if you want to deny unauthorized user
    // - context.auth.token.xxx is customClaims. (if you use)
    // if (context.auth || context.auth.uid || context.auth.token.xxx) {
    //   return Promise.reject("unauthorized");
    // }

    const user = await admin.auth().getUser(data.uid);
    return {
      displayName: user.displayName,
      email: user.email,
      photoURL: user.photoURL
    };
  } catch (error) {
    // If user does not exist
    if (error.code === "auth/user-not-found") {
      return {};
    }
    throw error;
  }
});

See:

*

*https://firebase.google.com/docs/functions/callable

*https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data

A: You can create a Firebase cloud functions and you can call that function from your Android app
Next, under that function, you can retrieve the data of the corresponding user and return it as a result to your Android app.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to plot grid, scatter points, and trend of one graph as separate files I am attempting to save a plot in "layers". First I want to save just the grid. Then I want to save just my scatter points. And finally I want to save just my trend line, but I can't figure out how to "turn off" my scatter points to do this. My reasoning for doing this is so that I can import each component of the graph as a layer in photoshop.
Here's my code:
FIRST PLOT GRID ONLY
fig=plt.figure()
ax1=fig.add_subplot(111)
#ax1.plot(x,p(x), linewidth=3.0, color="#daa004")
plt.ylim(top=72)
plt.ylim(bottom=60)
plt.xlim(right=2025)
plt.xlim(left=1895)
plt.grid(axis='x', alpha=0.4)
plt.grid(axis='y', alpha=0.4)
plt.savefig('MeanAnnualFallTMAX_Grid.png', transparent=True)

PLOT SCATTER ONLY
ax1.plot(x,y,'o',markersize=3,color="#daa004",label="Annual Mean Fall Maximum Temperature")
plt.axis('off')
plt.savefig('MeanAnnualFallTMAX_Scatter.png', transparent=True)

PLOT TREND ONLY (The problem)
ax1.plot(x,p(x), linewidth=3.0, color="#daa004")
plt.axis('off')
plt.savefig('MeanAnnualFallTMAX_Trend.png', transparent=True)

But this prints the scatter and the trend. Is there a way to "clear" or "turn-off" the scatter points I previously plotted?

A: if you save a reference to your line you may either

*

*Turn the points invisible
line, = ax1.plot(x,y,'o')
# ...
line.set_visible(False)

*Remove the points from the axes
line, = ax1.plot(x,y,'o')
# ...
line.remove()

A: I think for this workflow I'd at least try to save the figure as svg and open this in Inkscape. Ungrouping the results there gives access to every partof the figure.
However, it'll soon be divided into too small pieces like points or lines, but have a look - perhaps it helps.


text:
Q: React Native Testing Library: scroll FlatList to bottom I have a react-native FlatList component with onEndReached event used to load more items.
I am testing the component with react-native-testing-library. The test is as follows:

*

*Component mounted.

*Requests 10 items to mockedBackend.

*Expect FlatList to render those 10 items.

*fireEvent onEndReached to ask for next page with some more items.

*Expect FlatList to render new items.

Test was failing because FlatList was not rendering new items even thought FlatList's data property was being updated (I used act and waitFor as needed).
I managed to make the test pass when I fired onScroll event to bottom after some tries with hardcoded values.
Is there a way to make a helper to scroll to bottom taking into account proper FlatList size?
Helper to improve:
export const scrollListToBottom = (list: ReactTestInstance) => {
  // FIXME: improve to get real list size
  // After some tries these hardcoded values allowed to pass the test
  act(() => {
    fireEvent.scroll(list, {
      nativeEvent: {
        contentSize: {height: 500, width: 100},
        contentOffset: {y: 400, x: 0},
        layoutMeasurement: {height: 100, width: 100},
      }
    })
  })

  // FIXME: if onScroll works perfectly is this even needed?
  act(() => {
    fireEvent(list, 'onEndReached')
  })
}

Thank you.


text:
Q: change page background color page on click I was trying to change the background of the page color to "black" and the text color inside the card to "white" after clicking the button. When the button is clicked the color changes just for 1 second and goes back to the default color.
In the below code, will show you some parts from the main
The HTML Code:

Roboto

         <button type="submit" class="font-button"></button>

Christina Robertson (12 styles)

Then came the night of
         the first falling star.

 <button class="btn-black" id="bMode" onclick="blackMode()"></button>

The JS Code:
const changeToBlack = document.getElementById('bMode');
 const text = document.getElementsByClassName('font-text');

 changeToBlack.addEventListener('click', blackMode);

 function blackMode() {
     document.body.style.backgroundColor = "black";
     text.style.color = "white";
 }

I wrote the code to change only the background color, for the card l dont know how to go about it. So I tried to change only the text color for 1 paragraph which is not working either.

A:

let timeStamp;
const changeToBlack = document.getElementById('bMode');
const text = document.getElementById('font-text');
const oriBodyBgColor = document.body.style.backgroundColor;
const oriFontColor = text.style.color;

changeToBlack.addEventListener('click', function() {
  if (timeStamp) {
    clearTimeout(timeStamp)
  }
  document.body.style.backgroundColor = "black";
  text.style.color = "white";
  timeStamp = setTimeout(function() {
    document.body.style.backgroundColor = oriBodyBgColor;
    text.style.color = oriFontColor;
  }, 1000)
});
<!DOCTYPE html>

Roboto

      <button type="submit" class="font-button"></button>

Christina Robertson (12 styles)

Then came the night of the first falling star.

  <button class="btn-black" id="bMode">点我</button>

You could run this code in in jsfiddle. Click me


text:
Q: Need help in understanding how this particular Constraint Layout works I was going through a Udacity course on Android development and found this example of Constraintlayout (though I have shown only a part of the xml code and screen shot here). I have a hard time understanding how this is working.
xml layout file snippet:
        <ImageView
        android:id="@+id/tableHeaderImage"
        android:background="@color/colorPrimaryLight"
        android:layout_height="24dp"
        android:layout_width="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintTop_toBottomOf="@+id/textViewDepartureTime"
        app:layout_constraintHorizontal_bias="0.33" />

    <!-- COMPLETED (12) Create an ImageView for the blue table's body -->
    <ImageView
        android:id="@+id/tableImage"
        android:background="@color/colorPrimary"
        android:layout_height="0dp"
        android:layout_width="0dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintBottom_toBottomOf="@+id/textViewTerminal"/>

    <!-- COMPLETED (13) Create a TextView for each of the labels and text fields in the blue table -->
    <TextView
        android:id="@+id/textViewTerminalLabel"
        android:text="@string/terminal_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintLeft_toLeftOf="@+id/textViewTerminal"
        app:layout_constraintRight_toRightOf="@+id/textViewTerminal"

        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage" />

    <TextView
        android:id="@+id/textViewGateLabel"
        android:text="@string/gate_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintLeft_toLeftOf="@+id/textViewGate"
        app:layout_constraintRight_toRightOf="@+id/textViewGate"
        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage"
        />

    <TextView
        android:id="@+id/textViewSeatLabel"
        android:text="@string/seat_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintRight_toRightOf="@+id/textViewSeat"
        app:layout_constraintLeft_toLeftOf="@+id/textViewSeat"
        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage"
        />

    <TextView
        tools:text="@string/terminal"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:id="@+id/textViewTerminal"
        app:layout_constraintTop_toTopOf="@+id/tableImage"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        app:layout_constraintHorizontal_bias="0.0"
        android:textAlignment="center" />

    <TextView
        android:id="@+id/textViewGate"
        tools:text="@string/gate"
        android:layout_width="120dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        android:textAlignment="center"
        app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintBottom_toBottomOf="@+id/tableImage"/>

    <TextView
        android:id="@+id/textViewSeat"
        tools:text="@string/seat"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="@+id/tableImage"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        app:layout_constraintHorizontal_bias="1.0"
        android:textAlignment="center"
        android:layout_width="120dp" />

And the corresponding layout is:

As we see the first ImageView (tableHeaderImage) is used for the header of the table and the second ImageView (tableImage) is used for the content of the table.
(The layout @+id/textViewDepartureTime is simply above 'tableHeaderImage' and I have not shown here for simplicity)
I can understand how Table header is formed (@+id/tableHeaderImage) clearly.
But I dont understand how content table (@+id/tableImage) is formed.
As we can see in the code the content table has 0dp width and height and three TextViews (namely @+id/textViewTerminal , @+id/textViewGate ,@+id/textViewSeat) 'somehow' 'expand' this content table beyond 0dp.
And I am not getting how this expansion of content table has taken place(Especially the vertical expansion of it).

A: You see, @+id/textViewTerminal has a height of wrap_content, which means that its height depends on the text size attribute value, which is currently @style/TextAppearance.AppCompat.Display2, in other words the text size is Regular, 45sp :
Material Design Typography Styles
The height of the @+id/tableImage is truly 0dp, but it is defined in a different way by using constraints Look at these lines of code from the tableImage XML definition:
...
app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
app:layout_constraintBottom_toBottomOf="@+id/textViewTerminal"
...

You can see very obviously that the height of the @+id/tableImage is defined by the distance from the bottom of the @+id/tableHeaderImage
to the bottom of the @+id/textViewTerminal  which is defined implicitly by the text size. Let me know if you understand it.
Asking questions is always the fastest way to learn anything.
Good luck with the course.


text:
Q: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'rowType' gettting TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be
used to index type 'rowType'.   No index signature with a parameter of type 'string' was found on
type 'rowType'.
error on this row  {rowData[key]}
import * as React from "react"

interface  rowType {
  id: number;
  name: string;
  title: string;
  completed: boolean;
}

export interface RowProps { rowData: rowType};

const Row = ({ rowData }: RowProps) => {

  return (
      <>
          {Object.keys(rowData).map((key:) =>(
              <div> {rowData[key]}</div>
          ))}
      </>
  )
}

export default Row;


text:
Q: Windows 7 / ATI CCC - Monitor limit? I have a Ati 4850 X2 and back in the days when Windows 7 was in beta, I had this running with 4 monitors (Crossfire off). Now I have come to set this up again, with a RTM version of Windows 7 and the latest ATI drivers and it seems I can only have two monitors on at one time. If I try and set the monitors up in Control Panel, it simply disables the non-primary monitor, and if I attempt to do it in CCC, I get the message "To extend the desktop, a desktop or display must be disabled."
Does anyone know why this is and/or how to fix it?
I've currently tried using the latest ATI drivers and the drivers (i think) I was using over a year ago when I had this setup.

A: Sorry to answer my own question but this was a bit odd. I installed using drivers from a while ago (not sure how old they are, found the exe lying around on my HDD) and arranged the monitors in CCC, not in Control Panel. This seemed to work fine, but the latest drivers do not work. Hopefully this might help someone in the future!


text:
Q: GAE: Why is my css not found? With this configuration I get a HTTP 500 error.
application: xxx
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /style
  static_dir: style

- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: /admin/.*
  script: google.appengine.ext.admin.application
  login: admin

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.2"

builtins:
- remote_api: on

My log says this though:
INFO     2013-04-16 12:11:28,356 server.py:561] default: "GET /style/pimp_soef.css   HTTP/1.1" 500 2168

And this is my HTML:
<link type="text/css" rel="stylesheet" href="/style/pimp_soef.css" />

What am I missing? Thanks in advance!
EDIT
What about my mainHandler? Something to do with that!?
app = webapp2.WSGIApplication([
    ('/', MainHandler),
], debug=True)

A: Try typing the URL to the css file directly into the URL bar, that'll let you be sure the problem is not with your HTML.
Your code looks correct.
My guess is that it's something else.  A typo in the filename.  Maybe you have a capital letter.  Or your directory structure is not set up so that /style can be found.  Maybe file permissions.


text:
Q: When starting the application or compiling JSP via ant, Tomcat 7 Jasper complains about superfluous or misplaced JAR file. I got below message
May 03, 2014 3:31:37 PM org.apache.jasper.compiler.TldLocationsCache
  tldScanJar INFO: At least one JAR was scanned for TLDs yet contained
  no TLDs. Enable debug logging for this logger for a complete list of
  JARs that were scanned but no TLDs were found in them. Skipping
  unneeded JARs during scanning can improve startup time and JSP
  compilation time.


text:
Q: NPM: Multiple same named prehooks Can I have multiple same named prehooks in my package.json?
For e.g (Using two pretest):
"scripts": {
    "start": "react-scripts start",
     ...
    "pretest": "eslint ignore file ...",
    "pretest": "eslint --ignore-pattern '.someFolder/*'"
  }

Is there a better/sophisticated approach, other than using && or what I am using already?
Thank you

A: Here's a module I came across earlier that might be helpful in making it easier to work with: https://www.npmjs.com/package/npm-run-all
"scripts": {
    "start": "react-scripts start",
     ...
    "pretest":"run-s pretest:*",
    "pretest:1": "eslint ignore file ...",
    "pretest:2": "eslint --ignore-pattern '.someFolder/*'"
  }


text:
Q: Renaming of multiple files via batch script I have this part of batch script which is doing following:
-Under every sub-folder it renames files: 'jpg,gif,png' to 'Poster 1', 'Poster 2', 'Poster 3' and so on... (no change on extension)
set i=0
for %%b in (*.jpg *.gif *.png) do (
  set /A i+=1
   ren "%%b" "Poster !i!%%~Xb"
  echo File "%%b" renamed to "Poster !i!%%~Xb"
)

rem PATCH to fix a bug in previous FOR command (PLEASE IGNORE: there isa bug in prev. FOR command, which renames one file twice, if there are just two image files in a folder) :
if !i! neq 0 if not exist "Poster 1.*" (
  ren "Poster !i!.*" "Poster 1.*"
  echo ...and renamed back to "Poster 1"
)

!!!!! What I need is following: !!!!!
-I need to add a requirement if there is just a one file in the folder to rename it to "Poster", as without it this script renames it to 'Poster 1'
Thank you!

A: Just a logical solution, After the do loop , you can check the value of 'i' again and if it is 1 then you can perform the rename operation once again[Rename Poster1 to Poster]. Hope this helps

A: After the patch if command:
if !i! equ 1 ren "Poster 1.*" "Poster.*"

EDIT:
If you insert previous line after the patch if command (as I said), the final code is this:
set i=0
for %%b in (*.jpg *.gif *.png) do (
   set /A i+=1
   ren "%%b" "Poster !i!%%~Xb"
   echo File "%%b" renamed to "Poster !i!%%~Xb"
)
rem PATCH to fix a bug in previous FOR command:
if !i! neq 0 if not exist "Poster 1.*" (
   ren "Poster !i!.*" "Poster 1.*"
   echo ...and renamed back to "Poster 1"
)
REM NEW COMMAND TO RENAME THE UNIQUE FILE TO "Poster":
if !i! equ 1 ren "Poster 1.*" "Poster.*"

Antonio


text:
Q: Doxygen ignores wellformed comments in makefile I try to document my build system (at moment a bunch of make files and shell scripts) with doxygen. the only helpful tip I found is:
Can doxygen be used to document makefile templates and include *.mk file interfaces?
I used πάντα ῥεῖ answer to edit my doxyfile:
FILE_PATTERNS = *.c *.cc *.cxx *.cpp *.c++ *.h *.hpp *.h++ *.md *.markdown *.mk
INPUT_FILTER = "sed -e 's|##|//!|'"
FILTER_PATTERNS =
FILTER_SOURCE_FILES = YES

but my documentation produces this:
 //!
 //! @file environment.mk
 //! @brief Environment variables and definitions for the build system
 //!
 //! Insert detailed descritpion here
 //!
 //! @date 23.11.2016
 //! @author @kgoedde
 //!

 //!
 //! @cond
 //!
 # always the project directory
 export top         = $(abspath $(shell pwd))
 export project_name    = $(notdir $(shell pwd))

 # Setting compiler and linker
 CXX = clang++
 LD  = clang++
 AR  = ar

 CXXFLAGS   = -O0 -g3 -Wall -c -fmessage-length=0 -fPIC -std=c++14 -pthread
 TCXXFLAGS  = -Wall -c -fmessage-length=0 -fPIC -std=c++14 -pthread

 LDFLAGS  = -pthread
 TLDFLAGS = -pthread

 ARFLAGS  = -rs

 # Standard include paths
 INCDIRS        = ${top}/include/thirdparty ${top}/include/main
 TINCDIRS   = ${INCDIRS} ${top}/include/test

 # Stadard library paths
 LIBDIRS    = /usr/lib64
 //!
 //! @endcond
 //!

So it used the filter but didnt process the commentar. The doxygen documentation is sparse at this point, has anyone an idea what I do wrong?
Thank you,
Kai

After the help of Arthur I learned one additional thing (for interested people): instead of
INPUT_FILTER = "sed -e 's|##|//!|'"

I set
 FILTER_PATTERNS = *.mk="sed -e 's|##|//!|'"

now it filters only *.mk files :-).
Hth,
Kai

A: Your file extension is still .mk which is not a supported extension.
As noted for FILE_PATTERNS and for INPUT_FILTER:
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.

So you need to add
EXTENSION_MAPPING = mk=c


text:
Q: Get string and its length from file I have a file in which I have the maximum length of the string on the first line and the string itself on the second line.
It is an educational task so I can't use the <string> library.
I did this:
ifstream input;
input.open("input.txt");
int n;
input >> n;
char* str = new char[n];
input.getline(str, n); // This is the thing i want to get rid of.
input.getline(str, n);

And it works, but I have to call getline() twice, because after I get the length with input >> n; there is still a '\n' char after it on that line, and to go to the second line of the file I have to call getline(), that is the only solution that I came up with. Any help will be much appreciated!

A: Thanks everyone, cin.ignore() did it for me. Now the code is better in my opninon.
input >> n;
cout << n << endl;
char* str = new char[n];
input.ignore();
input.getline(str, n);


text:
Q: one of two parameters mandatory I'm trying to make a solid PowerShell function with parameters.
Now the problem is I don't get the ParameterSetNames to work.
What I want to get is that

*

*computername OR ipaddress is always mandatory

*computername or ipaddress has to be set but not both at the same time (If possible )

*if adminuser or adminpassword are given the other one is mandatory

I tried a lot of diffrent settings but keeps failing
this was my last attempt
CmdletBinding(DefaultParameterSetName="IpAddress")]
[CmdletBinding()]
Param
(
     # computername: Name of the host you want to connect to.
     [Parameter(Mandatory=$true,ParameterSetName="ComputerName", Position=0)]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddress")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameCredentials", Position=0)]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddressCredentials")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddressUser")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameUser", Position=0)]
     [String]$computername,

     # ipAddress: Ip Address of the host you want to connect to.
     [Parameter(Mandatory=$false,ParameterSetName="ComputerName")]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddress", Position=0)]
     [Parameter(Mandatory=$false,ParameterSetName="ComputerNameCredentials")]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressCredentials", Position=0)]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressUser", Position=0)]
     [Parameter(Mandatory=$false,ParameterSetName="ComputerNameUser")]
     [switch]
     [String]$ipAddress,

     # credentials: PowerShell credentials use to connect to the host.
     [Parameter(Mandatory=$false,ParameterSetName="ComputerName")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddress")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameCredentials")]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressCredentials")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddressUser")]
     [Parameter(Mandatory=$false,ParameterSetName="ComputerNameUser")]
     [PSCredential]$credentials,

     # adminUser: Username to use to connect to the host.
     [Parameter(Mandatory=$false,ParameterSetName="ComputerName")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddress")]
     [Parameter(Mandatory=$false,ParameterSetName="ComputerNameCredentials")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddressCredentials")]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressUser")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameUser")]
     [String]$adminUser,

     # adminPassword: Password to use to connect to the host.
     [Parameter(Mandatory=$false,ParameterSetName="ComputerName")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddress")]
     [Parameter(Mandatory=$false,ParameterSetName="ComputerNameCredentials")]
     [Parameter(Mandatory=$false,ParameterSetName="IpAddressCredentials")]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressUser")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameUser")]
     [String]$adminPassword
)

A: this is my solution
thanks to briantist
[CmdletBinding(DefaultParameterSetName="ComputerName")]
Param
(
     # computername: Name of the host you want to connect to.
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameCred", Position=0)]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNamePlain", Position=0)]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerName", Position=0)]
     [String]$computername,
     # ipAddress: Ip Address of the host you want to connect to.
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressCred", Position=0)]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressPlain", Position=0)]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddress", Position=0)]
     [String]$ipAddress,

     # credentials: PowerShell credentials use to connect to the host.
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNameCred")]
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressCred")]
     [PSCredential]$credentials,

     # adminUser: Username to use to connect to the host.
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressPlain")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNamePlain")]
     [String]$adminUser,

     # adminPassword: Password to use to connect to the host.
     [Parameter(Mandatory=$true,ParameterSetName="IpAddressPlain")]
     [Parameter(Mandatory=$true,ParameterSetName="ComputerNamePlain")]
     [String]$adminPassword,

     # writeLog: Boolean that enables or disables log-writing.
     [Parameter(Mandatory=$false)]
     [Boolean]$writeLog=$true
)

A: Hm, I think you have too many parameter sets. Also not sure why you have separate user/password parameters and a PSCredential parameter. You should really just use the PSCredential. But I'll assume you need this for some reason (please consider changing it).
4 parameter sets:

*

*ComputerNameCred

*ComputerNamePlain

*IpAddressCred

*IpAddressPlain

function Thing {
    [CmdletBinding(DefaultParameterSetName="ComputerNameCred")]
    Param
    (
         # computername: Name of the host you want to connect to.
         [Parameter(Mandatory=$true,ParameterSetName="ComputerNameCred", Position=0)]
         [Parameter(Mandatory=$true,ParameterSetName="ComputerNamePlain", Position=0)]
         [String]$computername,

         # ipAddress: Ip Address of the host you want to connect to.
         [Parameter(Mandatory=$true,ParameterSetName="IpAddressCred", Position=0)]
         [Parameter(Mandatory=$true,ParameterSetName="IpAddressPlain", Position=0)]
         [String]$ipAddress,

         # credentials: PowerShell credentials use to connect to the host.
         [Parameter(Mandatory=$true,ParameterSetName="ComputerNameCred")]
         [Parameter(Mandatory=$true,ParameterSetName="IpAddressCred")]
         [PSCredential]$credentials,

         # adminUser: Username to use to connect to the host.
         [Parameter(Mandatory=$true,ParameterSetName="IpAddressPlain")]
         [Parameter(Mandatory=$true,ParameterSetName="ComputerNamePlain")]
         [String]$adminUser,

         # adminPassword: Password to use to connect to the host.
         [Parameter(Mandatory=$true,ParameterSetName="IpAddressPlain")]
         [Parameter(Mandatory=$true,ParameterSetName="ComputerNamePlain")]
         [String]$adminPassword
    )
}

Get-Help Thing # use this to make sure your parameter sets are as they should be.

I also removed [switch] from your IP address parameter; not sure why that was there. You may want to consider using [System.Net.IPAddress] for that parameter instead of [String]. It will still accept strings (they will be cast), but it automatically validates the parameter since the cast will fail if it's not a valid IP.


text:
Q: Best Approach - Writing Records to Oracle from Excel with VBA w/ Multiple End Users I have develop an application in Excel w/ VBA that has a user form that collects data from the end user and inserts that data into a table in Oracle 11g.  I have to distribute this file to 10 - 15 users.  I am currently connecting with my personal credentials via the code, and everything works as designed.
What kind of configuration do I need to set up so I can remove my Username and Password from the connection string and have all the end users still be able to connect?  All of them connect to this data source already on a regular basis.  So, they have the Oracle Client installed and have tnsnames.ora files, etc.  I just don't know how to productionalize the app so it can be distributed?  The working code is as follows:
    Public Sub SubmitSupplytoOracle(sYear As Integer, sWeek As Integer, sArea As String, sCrew As String, sSuper As String, _
                                    sTECOH As Integer, sTECUG As Integer, sContOH As Integer, sContUG As Integer)

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sqlInsert As String
    Dim sCurrUser As String
    Dim sConnString As String
    Dim recordsAffected As Long
    'Dim wsTest As Worksheet
    'Dim sqlSelect As String

    'Set wsTest = ActiveWorkbook.Worksheets("Test") 'have to create a new worksheet called 'Test' to use this
    sCurrUser = CreateObject("WScript.Network").UserName
    sConnString = "User ID=xxxxxx;Password=yyyyyy;Data Source=ZZZZ;Provider=OraOLEDB.Oracle"

    sqlInsert = "INSERT INTO POTW_MH_Supply (" & _
                    "MHSupplyID," & _
                    "SupplyYear," & _
                    "ISO_Week," & _
                    "Service_Area," & _
                    "CrewHQ," & _
                    "Supervisor_Last_Name," & _
                    "TEC_OH_MHs," & _
                    "TEC_UG_MHs," & _
                    "Cont_OH_MHs," & _
                    "Cont_UG_MHs," & _
                    "Insert_UserName)" & _
                    " VALUES(" & _
                        "seq_POTWMHSupply.NEXTVAL," & _
                        sYear & "," & _
                        sWeek & "," & _
                        "'" & sArea & "'," & _
                        "'" & sCrew & "'," & _
                        "'" & sSuper & "'," & _
                        sTECOH & "," & _
                        sTECUG & "," & _
                        sContOH & "," & _
                        sContUG & "," & _
                        "'" & sCurrUser & "'" & _
                        ")"

    'sqlSelect = "SELECT * FROM STJOF.POTW_MH_Supply"

    Set cn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    cn.Open sConnString
    cn.CommandTimeout = 60

    cn.BeginTrans
    cn.Execute sqlInsert, recordsAffected
    cn.CommitTrans

    Debug.Print recordsAffected

    If recordsAffected = 1 Then
        MsgBox "Your submittal of Supply Man Hours was successful"
    Else
        MsgBox "Your submittal might not have been recorded succesfully for some reason. Please try again"
    End If

    'Might use this later if I need to return some values from this table.
    'rs.Open sqlSelect, cn
    'wsTest.Range("B3").CopyFromRecordset rs

    cn.Close

    'Cleanup objects
    Set cn = Nothing
    Set rs = Nothing
    sConnString = ""

    End Sub

A: Consider having each user save a YAML file to a designated, secured location that holds their database credentials and have Excel parse the configuration file into a collection of key/value pairs to complete connection string.
YAML
database_connection:
 provider : OraOLEDB.Oracle
 database : ZZZZ
 user     : xxxxxx
 password : yyyyyy

VBA
YAML Parser Function
Function ParseYAML(strFile) As Collection
    Dim myFile As String, textline As String, oneline As String
    Dim dataArray As Variant, data As Variant, key As Variant
    Dim dbColl As Collection
    Dim line As Integer, sizeArray As Integer

    Set dbColl = New Collection

    ' OPEN YAML FILE
    Open strFile For Input As #1

    ' LOOP THROUGH LINES
    Do Until EOF(1)
        Line Input #1, textline

        oneline = Replace(textline, " ", "")
        dataArray = Split(oneline, ":", 2)
        sizeArray = UBound(dataArray, 1) - LBound(dataArray, 1) + 1

        ' POPULATE KEY/VALUE PAIR
        If Not textline = "" And Not sizeArray = 0 Then
            data = dataArray(1)
            key = dataArray(0)

            If Right(key, 1) <> ":" Then
                dbColl.Add data, key
            End If
        End If
    Loop
    Close #1

    Set ParseYAML = dbColl
End Function

Current Macro
Public Sub SubmitSupplytoOracle(...)
    Dim dbCreds As Collection
    ...

    Set dbCreds = ParseYAML("C:\Path\To\OracleConnectionDetails.yml")

    sConnString = "Provider=" & dbCreds("provider") & _
                  ";Data Source=" & dbCreds("database") & _
                  ";User ID=" & dbCreds("user") & _
                  ";Password=" & dbCreds("password") & ";"

    ...

End Sub


text:
Q: Parsing bson.M with mgo in Golang I am looking to parse specific values out of MongoDB diagnostic commands using the mgo connector. I can loop through the bson.M{} response, but I'm unsure how to actually pull out specific nested values within the map and store them as a value. Here is the code I have thus far:
    //Connect to mongo shell
session, err := mgo.Dial("localhost")
if err != nil {
    panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)

//Get connPoolStats
connResult := bson.M{}
if err := session.DB("admin").Run("connPoolStats", &connResult); err != nil {
    panic(err)
} else {
    for key, value := range connResult {
        fmt.Println(key, value)
}

The output is:
totalRefreshing 0
hosts map[]
replicaSets map[]
numClientConnections 0
totalInUse 0
totalAvailable 0
totalCreated 0
numAScopedConnections 0
pools map[]
ok 1

I would like to pull out numClientConnections, totalInUse, available, etc and store them in variables-- as well as pull out values from the nested maps within pools map[] Do I need to convert to json to do this or use something other than bson.M?


text:
Q: Split string with two delimiters and convert type I have a PL/pgSQL function like this (thanks to the guy who made this possible):
 CREATE OR REPLACE FUNCTION public.split_string(text, text)
    RETURNS SETOF text
    LANGUAGE plpgsql
    AS $function$
    DECLARE
      pos int;
      delim_length int := length($2);
    BEGIN
      WHILE $1 <> ''
      LOOP
        pos := strpos($1,$2);
        IF pos > 0 THEN
          RETURN NEXT substring($1 FROM 1 FOR pos - 1);
          $1 := substring($1 FROM pos + delim_length);
        ELSE
          RETURN NEXT $1;
          EXIT;
        END IF;
      END LOOP;
      RETURN;
    END;
    $function$

It splits a string with a delimiter. Like this:
select * from split_string('3.584731 60.739211,3.590472 60.738030,3.592740 60.736220', ' ');

"3.584731"
"60.739211,3.590472"
"60.738030,3.592740"
"60.736220"

How can I save the results in a temp_array or temp_table. So I can get the the results in temp_x and split up these points again. Like:
"3.584731"
"60.739211"
"3.590472"
"60.738030"
"3.592740"
"60.736220"

and return the values as double precision. And all of this should be done in the function.

A: If you need the intermediary step:
SELECT unnest(string_to_array(a, ' '))::float8
       -- or do something else with the derived table
FROM   unnest(string_to_array('3.584731 60.739211,3.590472 60.738030', ',')) a;

This is more verbose than regexp_split_to_table(), but may still be faster because regular expressions are typically more expensive. (Test with EXPLAIN ANALYZE.)
I first split at ',', and next at ' ' - the reversed sequence of what you describe seems more adequate.
If need be, you can wrap this into a PL/pgSQL function:
CREATE OR REPLACE FUNCTION public.split_string(_str text
                                             , _delim1 text = ','
                                             , _delim2 text = ' ')
  RETURNS SETOF float8 AS
$func$
BEGIN
   RETURN QUERY
   SELECT unnest(string_to_array(a, _delim2))::float8
          -- or do something else with the derived table from step 1
   FROM   unnest(string_to_array(_str, _delim1)) a;
END
$func$ LANGUAGE plpgsql IMMUTABLE;

Or just an SQL function:
CREATE OR REPLACE FUNCTION public.split_string(_str text
                                             , _delim1 text = ','
                                             , _delim2 text = ' ')
  RETURNS SETOF float8 AS
$func$
   SELECT unnest(string_to_array(a, _delim2))::float8
   FROM   unnest(string_to_array(_str, _delim1)) a
$func$ LANGUAGE sql IMMUTABLE;

Make it IMMUTABLE to allow performance optimization and other uses.
Call (using the provided defaults for _delim1 and _delim2):
SELECT * FROM split_string('3.584731 60.739211,3.590472 60.738030');

Or:
SELECT * FROM split_string('3.584731 60.739211,3.590472 60.738030', ',', ' ');

Fastest
For top performance, combine translate() with unnest(string_to_array(...)):
SELECT unnest(
          string_to_array(
             translate('3.584731 60.739211,3.590472 60.738030', ' ', ',')
           , ','
          )
       )::float8

A: You do not need special functions, use built-in regexp_split_to_table:
SELECT *
  FROM regexp_split_to_table(
        '3.584731 60.739211,3.590472 60.738030,3.592740 60.736220',
        '[, ]') s;

EDIT:
I don't see why you wish to stick with PL/pgSQL function if there's a built-in one.
Anyway, consider this example:
WITH s AS
(
    SELECT ' ,'::text sep,
           '3.584731 60.739211,3.590472 60.738030,3.592740 60.736220'::text str
 )
SELECT sep, left(sep,1), right(sep,-1),
       str,
       translate(str, right(sep,-1), left(sep,1))
  FROM s;

This means, that you can:

*

*do similar transformations before you call your function or

*integrate this code inside, but this will mean you'll need to introduce at least one extra variable, unless you feel comfortable replacing all $1 into translate($1, right($2,-1), left($2,1)) throughout the code. Obviously, plain $2 should be changed to left($2,1).

A: If I understand to your questions well, you can do:
-- store context to temp table
CREATE TEMP TABLE foo AS SELECT v::double precision FROM split_string('...') g(v);

-- store context to ARRAY
SELECT ARRAY(SELECT v::double precision FROM split_string('....') g(v))


text:
Q: Catching Exception in Controller NonFatal Assume I have the following controller method:
def getAllRules() = AuthAction("View" on "Rules").async {
   Metrics.measureTime("getAllRules", category = Category) {
     ruleService.getAllRules.map({
       case Nil => NoContent
       case rules => Ok(Json.toJson(rules.toViewRules))
     }).recover {
       case e: Exception => handlerError(s"Failure occurred on getAllRules, ex: ${e.getMessage}", "getAllRules")
     }
   }
}

when handleError is:
def handlerError(err: String, occurredOn: String): Result = {
    Metrics.errorsCounter(occurredOn).increment()
    logger.error(err)
    InternalServerError(Json.toJson(Json.obj("error" -> err)))
}

I understood that catching all exceptions is a mistake, and I should catch only NonFatal Exceptions.
I wanted to ask:

*

*What is a Fatal Exception? How can occur? VirtualMachineError, InterruptedException, LinkageError, ControlThrowable

*Why it's not good to catch all exceptions, but only NonFatal?

*In the case of Fatal Exception - how its need to be handled?, code-example would be great with an explanation

*Just to make sure - If the controller will not catch any Exception, in k8s & docker env, the Pod will be failed with status Error and make a Restart - Right?

A:
What is a Fatal Exception? How can occur? VirtualMachineError, InterruptedException, LinkageError, ControlThrowable

Basically, you can conisider fatal errors - those which you can not handle properly. E.g. VirtualMachineError or any another java.lang.Error identifies problems occured in JVM internals, which you can't do much with: like AbstractMethodError - identifies that somehow was invoked method without implementation, which means that the issue in bytecode.
Or famous OutOfMemmoryError - usually recommended to not handle, because it might lead to heap corrution or another problems. Let them just crash an app.

Why it's not good to catch all exceptions, but only NonFatal?
Because, suing case NonFatal(e) => you avoiding possible problems describe before.
In the case of Fatal Exception - how its need to be handled?,
code-example would be great with an explanation

You should not catch them - fatal errors your friends and will make troubleshooting easier. Let them crash the app. It is correct approach.

Just to make sure - If the controller will not catch any Exception, in
k8s & docker env, the Pod will be failed with status Error and make a
Restart - Right?

Yes, but make sure you have some circuit breaker logic - don't re-start app endless time, if it is does not help. E.g. in case with AbstractMethodError - problems with binaries and only way to fix it - re-build or fix dependencies, but restating will only consume resources, without result.

A: I think that looking at the apply method of NonFatal is the best to understand it:
def apply(t: Throwable): Boolean = t match {
  // VirtualMachineError includes OutOfMemoryError and other fatal errors
  case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
  case _ => true
}

From Scaladoc:

Extractor of non-fatal Throwables. Will not match fatal errors like VirtualMachineError (for example, OutOfMemoryError and StackOverflowError, subclasses of VirtualMachineError), ThreadDeath, LinkageError, InterruptedException, ControlThrowable.

Let's deep dive into each of the exceptions above:

*

*VirtualMachineError: Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.

*ThreadDeath: An application should catch instances of this class only if it must clean up after being terminated asynchronously.  If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.

*InterruptedException: Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.

*LinkageError: Subclasses of {@code LinkageError} indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.

*ControlThrowable: A parent class for throwable objects intended for flow control. Instances of ControlThrowable should not normally be caught.
As you can see, all exceptions are exceptions that the process cannot recover from. Therefore, it is the best to let those exceptions bubble, and terminate the process.
The usage should be(from the NonFatal page I attached):
try {
  // dangerous stuff
} catch {
  case NonFatal(e) => log.error(e, "Something not that bad.")
 // or
  case e if NonFatal(e) => log.error(e, "Something not that bad.")
}


text:
Q: bash: echo in and also out of program damn I'm getting sick of these titles.
I was getting:
(standard_in) 1: syntax error
(standard_in) 1: illegal character: S
(standard_in) 1: syntax error
(standard_in) 1: syntax error

types of errors.
I was convinced that this has to be caused by an unbalanced echo, or something, but I have 100s in my script so its hard to debug. so I made a function to debug the output:
#!/bin/bash
myecho ()
{
        echo -e $1;
        if [ $? != 0 ]
        then
                dev=$(ps | awk '{print $2}')
                dev="/dev/$dev" # get the... whatever /dev/pts/2 is
                echo "echo -e \x22last echo failed:\\x60\\x27$1\\x27\\x60\x22 > $dev" | sh # format to escape the string so I can see it
                exit 2;
        fi

}

and then I would change all the "echo -e"'s to "myecho". to debug. It didn't work. I'm wondering if this is possible, or even a possible problem, and if so how I can debug with a debug function.


text:
Q: Does windows 2016 support Lotus Notes Client 8.5.3? I want to install Lotus Notes Client 8.5.3 on windows 2016. I am not sure whether 8.5.3 version is compatible with windows 2016.
Does windows 2016 support Lotus Notes Client 8.5.3? Any help would be appreciated.

A: Notes 9 was introduced in 2013. So 8.5.3 was not even supported anymore at all when Windows 2016 came out 4 years ago.
So: No, Notes 8.5.3 is not supported on Windows 2016... it is not supported on ANY Platform anymore.... You might probably use a software version a little younger than 10 years...

A: I suggest using Notes 9.  I believe the client 8.5.3 can be installed and run, but what will it be connecting to?  To read local databases, it should be OK, if the db's are also of the same version.


text:
Q: Navigating to the definitions of `defun` and `defmacro` with slime/swank Emacs version: 26.3

Slime version: 2.26.1

I start up Emacs.
I open up a simple .lisp file.
(defun testfn (x y)
  (+ x y))

(defmacro testmc (form)
  form
  `(list 1 2 3))

I place my cursor over the symbol defun and issue the keyboard-command M-. (slime-edit-definition).
This should bring me to the definition of defun.
But it doesn't.
It brings me here:

I place my cursor over the symbol defmacro and issue the keyboard-command M-. (slime-edit-definition).
This should bring me to the definition of defmacro.
But it doesn't.
It brings me here:

Why does it do this & how do I fix this

A: Notice there is a warning in the REPL when trying to find the source of DEFUN:

WARNING: inconsistent 2 form-number-translations

You can replicate it yourself in the REPL:
CL-USER> (let ((slynk::*buffer-package* (find-package :cl))
               (slynk::*buffer-readtable* *readtable*))
          (slynk:find-definitions-for-emacs "DEFUN"))
WARNING: inconsistent 2 form-number-translations
(("(DEFMACRO DEFUN)"
  (:LOCATION (:FILE "/home/chris/data/src/sbcl/src/code/macros.lisp")
   (:POSITION 4140)
   (:SNIPPET "(setq doc nil)
    (let* (;; stuff shared between LAMBDA and INLINE-LAMBDA and NAMED-LAMBDA
           (lambda-guts `(,@decls (block ,(fun-name-block-name name) ,@forms)))
           (lambda `(lambda ,lambda-list ,@lambda-guts))
           (named-lambda `("))))

To find where the warning comes from, you could do as I did first and do a textual search on the repository, or you could use the following alternate method that works better, namely invoke the debugger on warnings:
(handler-bind ((warning (lambda (c) (invoke-debugger c))))
  (let ((slynk::*buffer-package* (find-package :cl))
        (slynk::*buffer-readtable* *readtable*))
    (slynk:find-definitions-for-emacs "DEFUN")))

This comes from SLYNK-SBCL::FORM-NUMBER-POSITION, and the interesting value in the debugger is the source location obtained from SBCL:
#<SB-INTROSPECT:DEFINITION-SOURCE {10369C50F3}>
--------------------
The object is a STRUCTURE-OBJECT of type SB-INTROSPECT:DEFINITION-SOURCE.
PATHNAME: #P"SYS:SRC;CODE;MACROS.LISP"
FORM-PATH: (5)
FORM-NUMBER: 89
CHARACTER-OFFSET: 3917
FILE-WRITE-DATE: 3825178034
PLIST: NIL
DESCRIPTION: NIL

It says the source is the fifth toplevel form in the file (which corresponds to the character offset), and from here, the FORM-NUMBER is the 89th form in a depth-first search walk of the form (this comes from the structure's docstring).
But, if I recompile the function FORM-NUMBER-POSITION with DEBUG set to 3, the toplevel form read at this position,  TLF is NIL:
 1: (SLYNK-SBCL::FORM-NUMBER-POSITION #S(SB-INTROSPECT:DEFINITION-SOURCE :PATHNAME #P"SYS:SRC;CODE;MACROS.LISP" :FORM-PATH (5) :FORM-NUMBER 89 :CHARACTER-OFFSET 3917 :FILE-WRITE-DATE 3825178034 :PLIST NIL..
      Locals:
        DEFINITION-SOURCE = #S(SB-INTROSPECT:DEFINITION-SOURCE :PATHNAME #P"SYS:SRC;CODE;MACROS.LISP" :FORM-PATH (5) :FORM-NUMBER 89 :CHARACTER-OFFSET 3917 :FILE-WRITE-DATE 3825178034 :PLIST NIL :DESCRIPTION NIL)
        FORM-NUMBER = 89
        PATH-TABLE = #((0 0))
        POS-MAP = #<HASH-TABLE :TEST EQ :COUNT 126 {103B227EA3}>
        POS-MAP#1 = #<HASH-TABLE :TEST EQ :COUNT 126 {103B227EA3}>
        STREAM = #<SB-IMPL::STRING-INPUT-STREAM {7F3E0350D953}>
        TLF = NIL
        TLF#1 = NIL
        TLF-NUMBER = 5

In read-source-form, you can see that the form is being read inside a (ignore-errors (read ...)) form, which returns NIL in case of error. I tried calling (read ...) only but this somehow did not invoke the debugger, so I did the same thing as above and explicitly invoked it on any condition.
There is an error, namely that the package "SB-XC" does not exist, which is expected since, if I am not mistaken, this is a package that only exists during the compilation of SBCL itself.
I think you should contact the SBCL SLY developers and file a bug for this directly, they would certainly have a better idea of how to fix the behaviour (feel free to link to your question in addition to giving the usual details of the bug report).

A: I'm seeing pretty much what you're seeing.
Defun (line 280 of defboot.lisp) is a macro, which is defined in terms of defun-expander (line 230 of defboot.lisp) which is what you're seeing.
Whereas, defmacro takes you directly to its definition (line 15 of defmacro.lisp) which is what you're seeing.
It seems to be doing useful things.
I defined a new function 'addmore'
(defun addmore (x y z)
  (testfn x (testfn y z)))

I compiled it all, and M-. on 'addmore' takes me to the definition of testfn.
So I think it's all working.


text:
Q: VBA Error 1004 when Copy Pasting Values and Formatting from one Sheet to Another I'm trying to copy the content and formatting of Rec1 to Rec2. However, I keep getting error 1004 and a message saying that Excel does not have enough memory to execute the task.
Please note that there are other macros in the worksheet

Private Sub CommandButton3_Click()

Dim Source As Worksheet
Dim Target As Worksheet

Set Source = ThisWorkbook.Worksheets("Rec1")
Set Target = ThisWorkbook.Worksheets("Rec2")

Target.Cells.Clear

Source.Cells.Copy

Target.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

A: Instead of copying the entire sheet, just copy the UsedRange.
Souce.UsedRange.Copy

You could also clear the target's used range:
Target.UsedRange.Clear


text:
Q: Class and class keyword in Java I am a little bit confused. Java has some reflection methods to call on Class<T> objects.
But I wonder what is the interconnection between Class<T> class and class keyword in java.
Class<T> is just class that uses to represent class itself (methods, fields, annotations) as an object, because everything in java is an object. class keyword is used on language level syntax to represent an entity.
When class loader loads class into memory permgen( I know that ther is no such memory area now) ,but to represent class as an object we need an object, so in this case Class<T> comes into play.
Am I correct ? Please explain how does it works ?

A: In short: in "imperative" context the property SomeClass.class is an instance of Class<SomeClass>. The type Class<SomeClass> represents the SomeClass class as an object (reflection).


text:
Q: Do gathering skills Stack? I'm playing Story Mode, in it Myself and Raquna have the Mine skill and i am wondering if the effects stack since or if it's only beneficial to have 1 character specialize in a gathering skill.
NOTE: i do not want to know if/when characters leave the party as if the skills do not stack i can assume the party will change

A: If you're playing story mode, the party will never change. Gathering skills do stack, but putting gathering skills on the main party is a waste of skill points on expert, as you can gather once per day anyway without any skills in Untold. If you're playing on any of the easier difficulties though, feel free to put points into gathering skills, the extra money and better equipment may help. You can gather anything and everything without any gathering skills, but it is faster with gathering skills, as you can get more materials per trip/day.


text:
Q: What is the most elegant way to implement a business rule relating to a child collection in LINQ? I have two tables in my database:
Wiki
    WikiId
    ...

WikiUser
    WikiUserId (PK)
    WikiId
    UserId
    IsOwner
    ...

These tables have a one (Wiki) to Many (WikiUser) relationship.
How would I implement the following business rule in my LINQ entity classes:

"A Wiki must have exactly one owner?"

I've tried updating the tables as follows:
Wiki
    WikiId (PK)
    OwnerId (FK to WikiUser)
    ...

WikiUser
    WikiUserId (PK)
    WikiId
    UserId
    ...

This enforces the constraint, but if I remove the owner's WikiUser record from the Wiki's WikiUser collection, I recieve an ugly SqlException.  This seems like it would be difficult to catch and handle in the UI.
Is there a way to perform this check before the SqlException is generated?  A better way to structure my database?  A way to catch and translate the SqlException to something more useful?
Edit: I would prefer to keep the validation rules within the LINQ entity classes if possible.
Edit 2:  Some more details about my specific situation.
In my application, the user should be able to remove users from the Wiki.  They should be able to remove any user, except the user who is currently flagged as the "owner" of the Wiki (a Wiki must have exactly one owner at all times).
In my control logic, I'd like to use something like this:
wiki.WikiUsers.Remove(wikiUser);
mRepository.Save();

And have any broken rules transferred to the UI layer.
What I DON'T want to have to do is this:
if(wikiUser.WikiUserId != wiki.OwnerId) {
    wiki.WikiUsers.Remove(wikiUser);
    mRepository.Save();
}
else {
    //Handle errors.
}

I also don't particularly want to move the code to my repository (because there is nothing to indicate not to use the native Remove functions), so I also DON'T want code like this:
mRepository.RemoveWikiUser(wiki, wikiUser)
mRepository.Save();

This WOULD be acceptable:
try {
    wiki.WikiUsers.Remove(wikiUser);
    mRepository.Save();
}
catch(ValidationException ve) {
    //Display ve.Message
}

But this catches too many errors:
try {
    wiki.WikiUsers.Remove(wikiUser);
    mRepository.Save();
}
catch(SqlException se) {
    //Display se.Message
}

I would also PREFER NOT to explicitly call a business rule check (although it may become necessary):
wiki.WIkiUsers.Remove(wikiUser);
if(wiki.CheckRules()) {
    mRepository.Save();
}
else {
   //Display broken rules
}

A: This question has too many dependencies to answer well—the biggest of which is where you plan on enforcing business rules overall. In order of preference, you have to ask: Do you have a business rule layer? If not, do you have an independent data access layer? If not, are you using a data provider model? If not, then you're looking at enforcing this kind of thing (or handling the SqlException) wherever you're handling the configuration UI.
For something like a wiki, you probably don't need a hugely complex business rule engine simply because your problem domain is pretty well constrained already. Also, this sounds like the kind of rule that pretty much never changes so isolating it in a formal rules layer is a bit of overkill. As such, you're probably best off putting this kind of constraint in the data layer or data provider.
If you're using Linq to Sql, for example, you could mirror what you've done in SQL Server by making the OwnerId property in your model be a non-nullable property tied by a relationship to the WikiUser table. That'd enforce that the OwnerId property is populated (because it is non-nullable) and give you the unique constraint you are looking for.


text:
Q: JSON to a Java collection I got JSON like
{
"items":[
{
"id":15
,"name":"abc"
}
,{
"id":16
,"name":"xyz%"
}
,{
"id":17
,"name":"qwerty"
}
,{
"id":18
,"name":"rudloph"
}
,{
"id":19
,"name":"jane"
}
,{
"id":20
,"name":"doe"
}
]
}

I have class which is like:
public class Foo {
    public String id;
    public String name;
}

And I want to convert this JSON into List<Foo>. How can i do this? Right now I am doing like:
List<Foo> fooList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(json);
JSONArray araray = jsonObject.getJSONArray("items");
for(int i =0 ; i < araray.length();i++){
    Foo dto = new Foo();
    dto.setId(Long.valueOf((String) araray.getJSONObject(i).get("id")));
    dto.setName((String) araray.getJSONObject(i).get("name"));
    fooList.add(dto);
}

PS: Cannot change JSON. Jackson or Gson. Please let me know with code example.

A: i think you need to use the java json api and you need bind it manually

A: If you use gson, you may use TypeToken to load the json string into a custom Foo object.
List<Foo> objects = gson.fromJson(source, new TypeToken<List<Foo>>(){}.getType());

source can be String or BufferedReader.

A: You are having the wrong model for the JSON String. actually the list of Foo is inside another Model. Simply write another class like
public class Item {

    List<Foo> items;

    public Item() {
    }

   // getter setter
}

Now you can use com.fasterxml.jackson.databind.ObjectMapper like this
ObjectMapper mapper = new ObjectMapper();
Item item = mapper.readValue(json, Item.class);

for(Foo foo : item.getItems()) {
            ...
}

A: Try this with GSON.
Gson gson = new Gson();
Map<String, List<Foo>> objects = gson.fromJson(source,
    new TypeToken<Map<String, List<Foo>>>(){}.getType());
List<Foo> list = objects.get("items");


text:
Q: dismiss AlertDialog inside adapter when application closed Everytime the AlertDialog is showing and the application is closed or destroyed I get this error in the logcat has leaked window. I know that using onDestroy() method below removes that error but that only works if the AlertDialog is inside the activity. However in my case I'm using the AlertDialog inside the adapter which is shown on the code below
@Override
public void onDestroy(){
    super.onDestroy();
    if(alertDialog != null && alertDialog.isShowing()) {
        alertDialog.cancel();
    }
}

Logcat Error.
Activity com.test.example.MovieList has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{1ed0b473 V.E..... R.......
    0,0-1080,543} that was originally added here at android.view.ViewRootImpl.<init>
        (ViewRootImpl.java:363)

Adapter
    public class MyAdapter extends RecyclerView.Adapter <MyAdapter.ViewHolder>{

        private List<Movies> moviesList;
        private Context mContext;
        AlertDialog alertDialog;

    public MyAdapter (Context context, List<Movies> list) {
            mContext = context;
            moviesList= list;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            mContext = parent.getContext();
            View view = View.inflate(parent.getContext(), R.layout.movies, null);
            return new ViewHolder(view);
        }

    @Override
        public void onBindViewHolder(final ViewHolder holder, int viewType) {
        final Movies movies = moviesList.get(holder.getAdapterPosition());
        final String id = movies.getId()

        holder.title.setText(movies.getTitle());

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
             AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle);
                builder.setTitle(R.string.dialog_title);

                builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                         moviesList.remove(holder.getAdapterPosition());
                         DBHelper db = new DBHelper (mContext);
                         db.deleteMovie(movie);
                         notifyDataSetChanged();
                         db.close();
                         dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                  }
                });

                alertDialog = builder.create();
                alertDialog.show();
                return false;
            }
        });
    }

       @Override
        public int getItemCount() {
            return (moviesList != null? moviesList.size():0);
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            TextView title;

            ViewHolder(View itemView) {
                super(itemView);
                title = (TextView) itemView.findViewById(R.id.movie_title);
            }

        }
    }

A: I have one (may be) possible solution.
Replace
AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle);

With
AlertDialog.Builder builder = new AlertDialog.Builder(mContext.getApplicationContext(), R.style.AppCompatAlertDialogStyle);

Note : Replace your Activity's context with the Application context. Cause your activity might have reference in alert-dialog which is causing this leak.

A: You can setup callback using interface, will notify your activity.
Your adapter
    public class MyAdapter extends RecyclerView.Adapter <MyAdapter.ViewHolder>{

        private List<Movies> moviesList;
        private Context mContext;
        AlertDialog alertDialog;
        private AdapterCallback callback;

    public MyAdapter (Context context, List<Movies> list, AdapterCallback callback) {
            mContext = context;
            moviesList= list;
           this.callback=callback;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            mContext = parent.getContext();
            View view = View.inflate(parent.getContext(), R.layout.movies, null);
            return new ViewHolder(view);
        }

    @Override
        public void onBindViewHolder(final ViewHolder holder, int viewType) {
        final Movies movies = moviesList.get(holder.getAdapterPosition());
        final String id = movies.getId()

        holder.title.setText(movies.getTitle());

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {

               if(this.callback!=null)
                     callback.onButtonLongPress(holder.getAdapterPosition())
                return false;
            }
        });
    }

       @Override
        public int getItemCount() {
            return (moviesList != null? moviesList.size():0);
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            TextView title;

            ViewHolder(View itemView) {
                super(itemView);
                title = (TextView) itemView.findViewById(R.id.movie_title);
            }

        }

  public interface AdapterCallback{
   void onButtonLongPress(int position);
 }
    }

**Your Activity**

    public MyActivity extends Activity implement MyAdapter.AdapterCallback{
    ...

    void onButtonLongPress(final int position){

            AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle);
                builder.setTitle(R.string.dialog_title);

                builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                         moviesList.remove(holder.getAdapterPosition());
                         DBHelper db = new DBHelper (mContext);
                         db.deleteMovie(movie);
                         notifyDataSetChanged();
                         db.close();
                         dialog.dismiss();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                  }
                });

                alertDialog = builder.create();
                alertDialog.show();

            }
}


text:
Q: Execute multiple .sql scripts using c# i want to run a script that calls multiple *.sql scripts
i have multiple server in lots off sub office
will need error control on script if the *.sql crashes
also like to use a config file so i can edit for each site
ta
Gerard
here some source code i have found
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sqlConnectionString = "Data Source=TECHSUP4\\SQLEXPRESS;Initial Catalog=TESTCU;Integrated Security=True";
            FileInfo file = new FileInfo("C:\\Database\\Scripts\\test.sql");
            string script = file.OpenText().ReadToEnd();
            SqlConnection conn = new SqlConnection(sqlConnectionString);
            Server server = new Server(new ServerConnection(conn));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
    }
}

A: How about using powershell to run that?

$cmd = get-content "C:\temp\CombinedScripts.sql"
   foreach ($svr in get-content "C:\temp\ServerList.txt")
    {
       $con = "server=$svr;database=master;Integrated Security=sspi"
       $da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $con)
       $dt = new-object System.Data.DataTable
       $da.fill($dt) | out-null
       $svr
       $dt | format-table
     }

A: If one of the lines in your test.sql file encounters a problem, the code you've posted will throw an exception and leave the database in an unknown state.
I personally would parse each SQL statement out of the file and execute it one statement at a time.  Around each execution, I would wrap an exception handler that logs the exception and the line that caused it.  Depending on exactly what you're trying to do, you may be able to continue executing statements or you may want to terminate execution there.
It should be noted that it really depends what's in "test.sql".  If its simple one-line commands that are autonomous from one another, you should be able to execute them one at a time as I've described.  If its string of commands that create variables, execute stored procedures and so on, this may not be the correct approach.  In this case, you may want to move more logic into the .sql file to do what needs to be done.

A: if your server is MS SQL Server 2005 or higher you could use sqlcmd utility to run your sql statements. It can also act as a scripting language and run a set of sql statements as a script.

The sqlcmd utility lets you enter
  Transact-SQL statements, system
  procedures, and script files at the
  command prompt, in Query Editor in
  SQLCMD mode, in a Windows script file
  or in an operating system (Cmd.exe)
  job step of a SQL Server Agent job.
  This utility uses OLE DB to execute
  Transact-SQL batches.

the rest is here: sqlcmd Utility


text:
Q: video not stopping when closing modal in bootstrap modal I tried with many solutions but not worked. I am new please help me with below codes:

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
    Open modal
</button>

Modal Heading

                <button type="button" class="close" data-bs-dismiss="modal">×</button>

Some text to enable scrolling..

as I mentioned I tried many tips but for me it doesn't work, would you please fix my example. thank you.


text:
Q: Problem with detail activity screen loading. It keeps on loading without stopping I have a problem with my detail activity layout screen. The details in the screen are showing but the screen loading does not stop after that. I need help to stop my screen loading after the details in the screen has been shown.
The main layout activity loads for a certain amount of time and it works fine but the detail activity layout keeps on loading without stopping.

DetailsFragment.java
public class DetailsFragment extends Fragment {

    private static final String LOG_TAG = DetailsFragment.class.getSimpleName();
    private static final String ARG_NEWS = "arg_news";
    private static final String SAVE_NEWS = "save_news";
    private static final String SAVE_FAVORITE_NEWS = "save_favorite_news";
    private static final String SAVE_FAVORITE_SORT = "save_favorite_sort";
    private static final String SAVE_FULLY_LOADED = "save_fully_loaded";
    private static final String SAVE_SHARE_MENU_VISIBILITY = "save_share_menu_visibility";

    private final ResponseReceiver mReceiver = new ResponseReceiver();
    private Context mContext;
    private News mNews;
    private ShareActionProvider mShareActionProvider;
    private MenuItem mShareMenuItem;
    private ImageView mPosterImageView;
    private OnLoadingFragmentListener mLoadingListener;
    private boolean mIsFavoriteNews;
    private boolean mIsFavoriteSort;
    private boolean mIsFullyLoaded;
    private boolean mIsShareMenuItemVisible;

    public DetailsFragment() {
        // Required empty public constructor
    }

    // Create new Fragment instance
    public static DetailsFragment newInstance(News newsSelected) {
        DetailsFragment fragment = new DetailsFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_NEWS, newsSelected);
        fragment.setArguments(args);
        return fragment;
    }

    public static DetailsFragment newInstance() {
        DetailsFragment fragment = new DetailsFragment();
        return fragment;
    }

    // Listener to handle star button clicks. This button adds and remove news from
    // content provider
    private final View.OnClickListener mStarButtonOnClickListener = new View.OnClickListener() {
        public void onClick(View view) {

            // Can't save it to favorites db if news poster is not ready yet
            if (mPosterImageView != null && !Utils.hasImage(mPosterImageView)) {
                Toast.makeText(mContext, R.string.please_wait_poster_download,
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (mIsFavoriteNews) {
                if (removeFavoriteNews(mNews) > 0) {
                    Toast.makeText(mContext, R.string.success_remove_favorites, Toast
                            .LENGTH_SHORT)
                            .show();
                    ((ImageButton) view).setImageResource(R.drawable.ic_star_border);

                    // Delete poster image stored in internal storage
                    Utils.deleteFileFromInternalStorage(mContext, mNews.getTitle());

                    mIsFavoriteNews = false;
                } else {
                    Toast.makeText(mContext, R.string.fail_remove_favorites,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                if (addFavoriteNews(mNews) != null) {
                    Toast.makeText(mContext, R.string.success_add_favorites, Toast
                            .LENGTH_SHORT).show();
                    ((ImageButton) view).setImageResource(R.drawable.ic_star);

                    // Save poster image to internal storage
                    Bitmap posterBitmap = Utils.getBitmapFromImageView(mPosterImageView);
                    Utils.saveBitmapToInternalStorage(mContext, posterBitmap, mNews.getTitle());

                    mIsFavoriteNews = true;
                } else {
                    Toast.makeText(mContext, R.string.fail_add_favorites, Toast
                            .LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnLoadingFragmentListener) {
            mLoadingListener = (OnLoadingFragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnLoadingInteractionListener");
        }

        mContext = context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mLoadingListener = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mNews = getArguments().getParcelable(ARG_NEWS);
            mIsFavoriteNews = isFavoriteNews(mContext, mNews);
            mIsFavoriteSort = Utils.isFavoriteSort(mContext);
        }

        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.details_menu, menu);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        mShareMenuItem = menu.findItem(R.id.menu_item_share);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider
                (mShareMenuItem);

        setShareMenuItemAction();
        super.onPrepareOptionsMenu(menu);
    }

    private void setShareMenuItemAction() {
        if (mNews != null ) {
            //String videoKey = mNews.getVideos()[0].getKey();
            if (mShareActionProvider != null
                    && mShareMenuItem != null) {
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");

                mShareActionProvider.setShareIntent(shareIntent);
                mShareMenuItem.setVisible(true);
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(SAVE_NEWS, mNews);
        outState.putBoolean(SAVE_FAVORITE_NEWS, mIsFavoriteNews);
        outState.putBoolean(SAVE_FAVORITE_SORT, mIsFavoriteSort);
        outState.putBoolean(SAVE_FULLY_LOADED, mIsFullyLoaded);
        outState.putBoolean(SAVE_SHARE_MENU_VISIBILITY, mIsShareMenuItemVisible);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mNews == null) {
            return null;
        }

        // Restore objects value
        if (savedInstanceState != null) {
            mNews = savedInstanceState.getParcelable(SAVE_NEWS);
            mIsFavoriteNews = savedInstanceState.getBoolean(SAVE_FAVORITE_NEWS);
            mIsFavoriteSort = savedInstanceState.getBoolean(SAVE_FAVORITE_SORT);
            mIsFullyLoaded = savedInstanceState.getBoolean(SAVE_FULLY_LOADED);
            mIsShareMenuItemVisible = savedInstanceState.getBoolean(SAVE_SHARE_MENU_VISIBILITY);
        }

        View view = inflater.inflate(R.layout.fragment_details, container, false);

        mPosterImageView = (ImageView) view.findViewById(R.id.news_img);

        Glide.with(mContext).load(mNews.getImageUri())
                .dontAnimate().into(mPosterImageView);

        TextView titleView = (TextView) view.findViewById(R.id.title_content);
        titleView.setText(mNews.getTitle());

        TextView publishDateView = (TextView) view.findViewById(R.id.publish_date_content);
        String date = Utils.formatDateForLocale(mNews.getPublishedDate());
        publishDateView.setText(date);

        TextView author = (TextView) view.findViewById(R.id.author_name);
        author.setText(mNews.getAuthor());

        TextView descriptionView = (TextView) view.findViewById(R.id.description_content);

        TextView fullNewsUrl = (TextView) view.findViewById(R.id.news_full);
        fullNewsUrl.setText(mNews.getFullNewsUrl());

        // In portuguese, some news does not contain overview data. In that case, displays
        // default text: @string/overview_not_available
        if (!TextUtils.isEmpty(mNews.getDescription())) {
            descriptionView.setText(mNews.getDescription());
        }

        ImageButton starButton = (ImageButton) view.findViewById(R.id.star_button);
        starButton.setOnClickListener(mStarButtonOnClickListener);

        if (mIsFavoriteNews) {
            starButton.setImageResource(R.drawable.ic_star);
        } else {
            starButton.setImageResource(R.drawable.ic_star_border);
        }

        starButton.setVisibility(View.VISIBLE);

        FrameLayout detailFrame = (FrameLayout) view.findViewById(R.id.detail_frame);
        detailFrame.setVisibility(View.VISIBLE);

        return view;
    }

    // Method that adds a News to content provider
    private Uri addFavoriteNews(News news) {

        Uri newsReturnUri = null;
        try {
            ContentValues newsContentValues = createNewsValues(news);
            newsReturnUri = mContext.getContentResolver().insert(FavoriteNewsContract
                    .NewsEntry
                    .CONTENT_URI, newsContentValues);

        } catch (SQLException e) {
            Log.d(LOG_TAG, "SQLException while adding news to Favorite db");
            e.printStackTrace();
        }

        return newsReturnUri;
    }

    // Method that removes a News from content provider
    private int removeFavoriteNews(News news) {

        int newsRemoved = mContext.getContentResolver().delete(FavoriteNewsContract
                        .NewsEntry.CONTENT_URI,
                FavoriteNewsContract
                        .NewsEntry._ID + " = ?", new String[]{news.getTitle()});

        return newsRemoved;
    }

    // Create news content values
    private ContentValues createNewsValues(News news) {
        ContentValues newsContentValues = new ContentValues();
//        newsContentValues.put(FavoriteNewsContract.NewsEntry._ID, Integer.parseInt(news
//                .getId()));
        newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_TITLE, news.getTitle());
        newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_PUBLISH_DATE, news
                .getPublishedDate());
        newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_AUTHOR, news
                .getAuthor());
        newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_DESCRIPTION, news
                .getDescription());
        newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_FULL_NEWS_URL, news
                .getFullNewsUrl());
        newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_IMG_URL, news
                .getImageUri()
                .toString());
        return newsContentValues;
    }

    // Method that query content provider and checks whether is a Favorite news or not
    private boolean isFavoriteNews(Context ctx, News news) {
        String newsID = news.getTitle();
        Cursor cursor = ctx.getContentResolver().query(FavoriteNewsContract.NewsEntry
                        .CONTENT_URI, null,
                FavoriteNewsContract.NewsEntry._ID + " = " + newsID, null, null);
        if (cursor != null && cursor.moveToNext()) {
            int newsIdColumnIndex = cursor.getColumnIndex(FavoriteNewsContract.NewsEntry._ID);
            if (TextUtils.equals(newsID, cursor.getString(newsIdColumnIndex))) {
                return true;
            }
        }

        if (cursor != null) {
            cursor.close();
        }

        return false;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mNews != null) {
            if (mReceiver != null) {
                LocalBroadcastManager.getInstance(mContext)
                        .registerReceiver(mReceiver, new IntentFilter(Constants
                                .ACTION_EXTRA_INFO_RESULT));
            }
            if (!mIsFullyLoaded && !mIsFavoriteSort) {
                Intent intent = new Intent(mContext, NewsIntentService.class);
                intent.setAction(Constants.ACTION_EXTRA_INFO_REQUEST);
                intent.putExtra(NewsIntentService.EXTRA_INFO_NEWS_ID, mNews.getTitle());
                mContext.startService(intent);

                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingDisplay(true, true);
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mReceiver != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
        }
    }

    // BroadcastReceiver for network call
    public class ResponseReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || intent.getAction() == null) {
                return;
            }

            if (intent.getAction().equals(Constants.ACTION_EXTRA_INFO_RESULT)) {

                setShareMenuItemAction();
            } else {
                Toast.makeText(mContext, R.string.toast_failed_to_retrieve_data,
                        Toast.LENGTH_SHORT).show();
            }

            if (mLoadingListener != null) {
                mLoadingListener.onLoadingDisplay(true, false);
            }

            mIsFullyLoaded = true;
        }
    }
}

DetailsActivity.java
public class DetailsActivity extends AppCompatActivity implements OnLoadingFragmentListener {

    private static final String LOG_TAG = DetailsActivity.class.getSimpleName();

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

        if (savedInstanceState == null) {
            Intent intent = getIntent();
            if (intent != null && intent.hasExtra(Constants.EXTRA_NEWS)) {
                News news = intent
                        .getParcelableExtra(Constants.EXTRA_NEWS);

                DetailsFragment detailsFragment = DetailsFragment.newInstance(news);
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.details_fragment_container, detailsFragment).commit();
            } else {
                Log.d(LOG_TAG, "Something went wrong. Intent doesn't have Constants.EXTRA_NEWS" +
                        " extra. Finishing DetailsActivity.");
                finish();
            }
        }
    }

    @Override
    public void onLoadingDisplay(boolean fromDetails, boolean display) {
        Fragment loadingFragment = getSupportFragmentManager()
                .findFragmentByTag(LoadingFragment.FRAGMENT_TAG);
        if (display && loadingFragment == null) {
            loadingFragment = LoadingFragment.newInstance();
            if (fromDetails) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.details_fragment_container,
                                loadingFragment, LoadingFragment.FRAGMENT_TAG).commit();
            } else {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.news_fragment_container,
                                loadingFragment, LoadingFragment.FRAGMENT_TAG).commit();
            }
        } else if (!display && loadingFragment != null) {
            getSupportFragmentManager().beginTransaction()
                    .remove(loadingFragment).commit();
        }
    }
}

LoadingFragment.xml
public class LoadingFragment extends Fragment {

    public static final String FRAGMENT_TAG = LoadingFragment.class.getSimpleName();
    private static final String LOG_TAG = LoadingFragment.class.getSimpleName();

    public LoadingFragment() {
        // Required empty public constructor
    }

    public static LoadingFragment newInstance() {
        LoadingFragment fragment = new LoadingFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_loading, container, false);
        return view;
    }
}

fragment_loading.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/semiTransparentBlack"
    android:clickable="true"
    tools:context=".ui.LoadingFragment">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center" />
</FrameLayout>

A: use onDestroy
@Override
public void onDestroy() {
    super.onDestroy();
    mLoadingListener = null;
}

and also you should remove ResponseReceiver
    if (mLoadingListener != null) {
            mLoadingListener.onLoadingDisplay(true, false);
        }

A: Most likely you need to change the loading View (ProgressBar?) visibility to INVISIBLE or GONE at the appropriate time, probably when loading is complete.
If the loading View is contained in some kind of dialog, then you would need to dismiss it at the appropriate time.


text:
Q: Foreach loop not printing first form I am updating the code of my search page, for some reason if you search any users for example there are three users with the name "Peter" and if you search for them the first Peter prints only the inputs:
  <input type="hidden" name="chatting_with" value="userexample"/><input type="hidden" name="chatting_logusr" value="userexample"/><input id="prponclick" class="openchatmsgdevices" type="submit" value="Enviar un mensaje" />

But the rest print correctly with the form:
<form target="u-n" method="POST" action="open_new_chat_with_user"><input type="hidden" name="chatting_with" value="userexample"/><input type="hidden" name="chatting_logusr" value="userexample"/><input id="prponclick" class="openchatmsgdevices" type="submit" value="Enviar un mensaje" /></form>

Heres the full code:
<?php
session_start();
include("../DD/ddd.php");
$logged_user = $_SESSION['valid_user'];
if(!$logged_user){return false;}
$query = "SELECT searched_for FROM searches WHERE `user` = '$logged_user' ORDER BY id_search DESC LIMIT 1";
$run_query = $all_conn->query($query);
$rows_searches = $all_conn->query($query)->fetch();
$searched_for = $rows_searches['searched_for'];
$no_allowed_spaces = preg_replace('/\s/', '', $searched_for);

$query_info = "SELECT * FROM user_info WHERE nombre LIKE '%".$searched_for."%' OR `user` LIKE '%".$searched_for."%'";
echo '
';
if(strlen($searched_for) >= 1)
{echo '

'.$searched_for.'

'.
'

#

'.$no_allowed_spaces.'

';}

foreach($all_conn->query($query_info) as $got_users){
if(strlen($searched_for) == 0){echo '

Buscar algo....

'; return false;}

echo '

<form target="u-n" method="POST" action="open_new_chat_with_user"><input type="hidden" name="chatting_with" value="'.$got_users['user'].'"/><input type="hidden" name="chatting_logusr"
value="'.$logged_user.'"/><input id="prponclick" class="openchatmsgdevices" type="submit" value="Enviar un mensaje" />
</form>

 <input type="button" value="Visitar árbol"/>

'.

'

'.$got_users['nombre'].'

';

}

echo '

';
echo '
';

?>


text:
Q: How can I sort dates in increasing or decreasing order (date format - Monday 4th September 2017) in selenium? I tried running below code:
List<Date> listDates = new ArrayList<Date>();

List<WebElement> elementList= driver.findElements(By.xpath(".//[@id='pricedTransactionDiv']/div"));

SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE dd'th' MMMM yyyy");

for(WebElement we:elementList)
{

    listDates.add(dateFormatter.parse(we.getText()));

}

test.log(LogStatus.INFO,"Results before applying sorting: "+listDates);

System.out.println("Results before applying sorting: "+listDates);

ArrayList<Date> sortedList = new ArrayList<>();
for(Date s:listDates){

    sortedList.add(s);

}

Collections.sort(sortedList);

test.log(LogStatus.INFO,"Results after applying sorting: "+ sortedList);

System.out.println("Results after applying sorting: "+sortedList);

But it didn't work.
I don't really know where I am going wrong. Any idea?

A:
Sorts the specified list according to the order induced by the specified comparator.

Your need to modify the below line:
Collections.sort(sortedList);

Instead, use below line of code:
Collections.sort(sortedList, new Comparator<Date>(){

    @Override
    public int compare(Date o1, Date o2) {
        return o1.compareTo(o2);
     }
});

A: Answer:
List<Date> obtainedList = new ArrayList<Date>();

String date;

List<WebElement> elementList=
 driver.findElements(By.xpath(prop.getProperty(Xpath)));

for(WebElement we:elementList){
    date=we.getText();

    //Get the date out from "Thursday 8th March 2018"
    int Date = Integer.parseInt(date.replaceAll("^\\D*(\\d+).*", "$1"));
    SimpleDateFormat dateFormatter
            = new SimpleDateFormat("EEE dd"+"'"+getDayOfMonthSuffix(Date)+"'"+ " MMMM yyyy");
    Date Date1=dateFormatter.parse(date);
    obtainedList.add(Date1);
}

test.log(LogStatus.INFO,"Results before applying "+"'"+Condition+"'"+" sorting: "+obtainedList);

ArrayList<Date> sortedList = new ArrayList<>();

for(Date s:obtainedList){
    sortedList.add(s);
}

Collections.sort(sortedList, new Comparator<Date>(){
    @Override
    public int compare(Date o1, Date o2) {
        return o1.compareTo(o2);
    }
});

if(Condition.equals("Newest to oldest")){

    Collections.reverse(sortedList);
}

test.log(LogStatus.INFO,"Results after applying sorting: "+sortedList);

//Ordinal Indicator

//Suffix of date('th','st','nd'......)

public static String getDayOfMonthSuffix(int n) {

    checkArgument(n >= 1 && n <= 31, "illegal day of month: " + n);

        if (n >= 11 && n <= 13) {

            return "th";
        }

        switch (n % 10) {

            case 1:  return "st";

            case 2:  return "nd";

            case 3:  return "rd";

            default: return "th";

        }

    }

It worked for me. Thanks all for your input and time. I appreciate it.


text:
Q: Serialize interface as JsonResult I'm trying to write a .NET Core API that returns a list of objects. The following class is being used for sending responses:
class AnimalResponse {
    public IAnimal Animal { get; set; }
}

There is an empty interface:
interface IAnimal {

}

There are also 2 classes that implement this interface:
class Cat : IAnimal {
    public string CatProperty { get; set; }
}

class Dog : IAnimal {
    public string DogProperty { get; set; }
}

As you can see, the Animal property of AnimalResponse class can contain either a Cat or a Dog class object. This is how I send response:
var response = new AnimalResponse() {
    Animal = new Cat() {
         CatProperty = "Cat Property Value"
    }
};
return JsonResult(response);

For some reason CatProperty gets missing from an API response after serialization. API returns the following json: {Animal:{}}.
So, how do I make it include all the class-specific properties?
Note: I'm using Microsoft.AspNetCore.Mvc.JsonResult, not Newtonsoft.Json.

A: 1 install NewtonsoftJson
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
2 Configure Services
services.AddControllersWithViews().AddNewtonsoftJson();

A: Serialization of derived types works only if the variable type is object.
In other words, everything will work if you redefine your AnimalResponse:
class AnimalResponse {
    public object Animal { get; set; }
}

You lose a bit of type safety, but you can get around that like so:
class AnimalResponse {
    public AnimalResponse(IAnimal animal) { Animal = animal; }
    public object Animal { get; }
}

This works because System.Text.Json has a special case for object.
(There are a few articles out there that explain why and how to work with this, but unfortunately, it was a while ago since I found the one that actually made it clear for me.)

A: If you read also here Why are interfaces not [Serializable]? interfaces are not serializable because they define a contract and not a data.
They are a way to define a behaviour for the class.
By the way you should be able to make it serializable by implementing the ISerializable interface.
EDIT: Consider using a base Class instead of an Interface if you only need to serialize data. If you need  to have both maybe a better solution is to have a base Class and an Interface and implement both.
UPDATE: Base class must implement the ISerializable interface.