text:
Q: Problems downloading the Stub class from server to Client - Java RMI I am having problems with running my HelloWorld Java RMI application.
I have the server, remote class and remote interface in one computer and a client and a remote interface in another. The server and registry run fine. When I try to run the client, i receive this error:
Client1 exception: java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
        java.lang.ClassNotFoundException: Remote_Stub (no security manager: RMI class loader disabled)
I noticed that if I have the Remote_Stub.class file in the same directory as the client, everything works fine. So i figured that my problem is downloading the stub from the server to the client.
I am not quite sure why this is giving me this error or not, but after doing some research I think it has something to do with security as in I dont have permission to download the file from one computer to the other (because it states "no security manager") If that is so, does anyone know how I could solve this problem? Or how I could set the permission?
Thanks!!
Micheal

A: Your server needs to set a security policy. You need a JVM property like:
-Djava.security.policy=/path/to/myserver.policy

Where myserver.policy is a file that has your server's security policies, for example:
grant {
    permission java.security.AllPermission "", "";
};

On a related note, I am not personally a huge fan of RMI because it's given me greif in the past with the way it deals with class versioning between server and clients, and the fact that it's Java specific, so limits your clients to being written in Java. If you have the flexibility to choose a different client-server technology, you should take a look at SOAP (AXIS2 is not bad) or REST services (Restlet looks pretty promising). This post may help you with pros and cons:
http://michaeldehaan.net/2008/07/17/xmlrpc-vs-rest-vs-soap-vs-all-your-rpc-options/

A: http://download.oracle.com/javase/tutorial/rmi/client.html
Take a look at that. It states clearly how you instantiate a SecurityManager in your client as the first step to make sure the stubs are downloaded.

A: You don't need stubs at all from JDK 1.5. See the class Javadoc for UnicastRemoteObject.


text:
Q: Checkbox value is true but tick is not showing - Android / Java Basically here I have three(3) checkbox list in three(3) different fragment. When I open the activity, my checkbox in the default fragment display like normal, but the one in different fragment display differently. The value of the checkbox is still true. Below is the image for the checkbox to make things clearer and also my code.
First fragment page:

Second fragment page:

Code for setting up the checkbox and its if condition
private void setCheckBox(ArrayList<DataPrefType> arrayList){
    for(int i = 0; i < arrayList.size(); i++){
        id = i + 1;
        checkBox = new CheckBox(getActivity());
        checkBox.setId(i + 1);
        checkBox.setText(arrayList.get(i).getName());
        checkBox.setPadding(10, 10, 10, 10);
        checkBox.setLayoutParams(params);
        checkBox.setGravity(Gravity.CENTER);
        checkBoxLayout.addView(checkBox);

        if(!userPreference.isEmpty() || userPreference != null){
            for(int j = 0; j < userPreference.get(0).getDataPrefTypeArrayList().size(); j++){
                int retrieveId = Integer.parseInt(userPreference.get(0).getDataPrefTypeArrayList().get(j).getId());
                if(checkBox.getId() == retrieveId)
                    checkBox.setChecked(true);
            }
        }

A: The bug with the checkboxes not showing as checked even though isChecked is true is within the animation of the draw.
I found this solution here. I am posting it here as an answer to make it easier to find and including some extra information about how to call it.
Try calling jumpDrawablesToCurrentState on the root view (or parent view of your check boxes). If specifically calling to checkBox.setChecked(true); as OP is, call this after. In this question, it would be important to call this after all checkboxes have been added to the parent view. This essentially will draw all drawables in the current state, skipping the animation process.
Example:
@Override
public void onStart() {
    View v = getView();
    if(v != null) {
        CheckBox chkYourCheckBox = (CheckBox)v.findViewById(R.id.chkYourCheckBox);
        chkYourCheckBox.setChecked(true); //sometimes this may draw fine, and other times it may not
        //***The important line:
        v.jumpDrawablesToCurrentState();
    }
}

A: You can override the Fragment's setUserVisibleHint() method and load in the checkboxes there.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser)setCheckBox();
}

This is just a workaround, and I don't think its the best way to solve it, but I haven't found anything better yet. This can lead to Null pointer exceptions.

A: I created this Kotlin extension property to deal with the problem (obviously only useful if you are writing Kotlin code, not Java)
/**
 * Set the state of a checkbox skipping animations.
 */

var CheckBox.checked: Boolean
    get() = isChecked
    set(value) {
        if(isChecked != value) {
            isChecked = value
            jumpDrawablesToCurrentState()
        }
    }

Now in my code I write checkbox_view.checked = true instead of checkbox_view.isChecked = true

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change time zone for an asp.net application I need to set default timezone for my ASP.NET to Asia/Dhaka or GMT+6 timezone. But i cannot find a way to change it globally. There is a lot of reference on Stackoverflow and rest of the web for doing this by getting timezone info and calculating correct time for each time i need a DateTime object.
But trust me, I don't want to do this in this way. So dont give me any suggestion like that. I want to set the timezone to Asia/Dhaka or GMT+6 preferably from web.config. (Similar we do in php with php.ini) So that each time i need DateTime object the time is evaluated with my timezone no matter what the timezone is for server.
Is this possible? If possible then how??
Thanks in advance for the solution :)

A: There's very easy way to do it. Simply get the current UTC time and your timezone in two different variables. Then convert UTC to your timezone in third variable and use it anywhere. Here's how you do it.
DateTime date1 = DateTime.UtcNow;

TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time");

DateTime date2 = TimeZoneInfo.ConvertTime(date1, tz);

Set your Time Zone in tz and then use "date2" anywhere.

A: I have a problem with the instruction:
TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

So... i create a personal TimeZoneInfo.
Here my code...
public static DateTime DateNow()
        {
            DateTime utcTime = DateTime.UtcNow;
            TimeZoneInfo myZone = TimeZoneInfo.CreateCustomTimeZone("COLOMBIA", new TimeSpan(-5, 0, 0), "Colombia", "Colombia");
            DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
            return custDateTime;
        }

A: You can Change TimeZone...And Get Date
 DateTime utcTime = DateTime.UtcNow;
    TimeZoneInfo myZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
    DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
    Str.Append(custDateTime.ToString());

A: Sorry there is no way in .NET to change the time zone globally.
The only way you have is to change the timezone of your server or rewrite all of your code.
The best practice is to not rely on the system time zone at all (never use DateTime.Now).
You should handle all date as Utc dates and then convert to a specific zone when displaying them to users.
Even if you manage to handle timezones in your ASP.NET application, there are still timezones on SQL Server, for example GETTIME funtion. If your application is entirely written in UTC, your SQL server function will work as well.

A: Having a similar issue (with Time zones) I ended up changing some database types from DateTime to DateTimeOffset (SQL Server).
DateTimeOffset Struct
I wrote an extension for this:
public static class Extensions
{
    public static DateTimeOffset ToCentralTime(this DateTimeOffset value)
    {
        return TimeZoneInfo.ConvertTime(value, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
    }
}

Example of use:
public class ClockPunch
{
    private DateTimeOffset dtoTimeIn;
    private DateTimeOffset? dtoTimeOut;
    public ClockPunch() { }
    public DateTimeOffset TimeIn
    {
        get { return dtoTimeIn.ToCentralTime(); }
        set { dtoTimeIn = value; }
    }
    public DateTimeOffset? TimeOut
    {
        get
        {
            DateTimeOffset? retVal = null;
            if (dtoTimeOut != null)
            {
                retVal = ((DateTimeOffset)dtoTimeOut).ToCentralTime();
            }
            return retVal;
        }
        set { dtoTimeOut = value; }
    }
}

A: Better could be to create a customTimeZone
        public static DateTime DateNow()
        {
            DateTime utcTime = DateTime.UtcNow;
            TimeZoneInfo myZone = TimeZoneInfo.CreateCustomTimeZone("INDIA", new TimeSpan(+5, +30, 0), "India", "India");
            DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
            return custDateTime;
        }


text:
Q: Extract specific number from command outout I have the following issue.
In a script, I have to execute the hdparm command on /dev/xvda1 path.
From the command output, I have to extract the MB/sec values calculated.
So, for example, if executing the command I have this output:
/dev/xvda1:
 Timing cached reads:   15900 MB in  1.99 seconds = 7986.93 MB/sec
 Timing buffered disk reads: 478 MB in  3.00 seconds = 159.09 MB/sec

I have to extract 7986.93 and 159.09.
I tried:

*

*grep -o -E '[0-9]+', but it returns to me all the six number in the output

*grep -o -E '[0-9]', but it return to me only the first character of the six values.

*grep -o -E '[0-9]+$', but the output is empty, I suppose because the number is not the last character set of outoput.

How can I achieve my purpose?

A: To get the last number, you can add a .*  in front, that will match as much as possible, eating away all the other numbers. However, to exclude that part from the output, you need GNU grep or pcregrep or sed.
grep -Po '.* \K[0-9.]+'

Or
sed -En 's/.* ([0-9.]+).*/\1/p'

A: Consider using awk to just print the fields you want rather than matching on numbers. This will work using any awk in any shell on every Unix box:
$ hdparm whatever | awk 'NF>1{print $(NF-1)}'
7986.93
159.09


text:
Q: Close popup menu when outside is clicked I have the following code
<!DOCTYPE html>

    <title>GalacticCraft</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <link rel="shortcut icon" type="image/png" href="favicon.ico">

and CSS
.popup {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    position: absolute;
    z-index: 5;
    opacity: 0.5
}
.popup-menu {
    top: 0;
    width: 700px;
    height: 99.6%;
    background-color: #fff;
    position: absolute;
    z-index: 10;
    left:calc(50% - 351px);
    border: 2px solid #808080;
        -webkit-animation: fadein 1s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 1s; /* Firefox < 16 */
        -ms-animation: fadein 1s; /* Internet Explorer */
         -o-animation: fadein 1s; /* Opera < 12.1 */
            animation: fadein 1s;
    padding-left: 20px;
}
.apply {
    width: 350px;
    height: 350px;
    position: relative;
    left: calc(50% - 185px);
}
.popup-menu p {
    color: #009AFF;
    text-align: center;
    font-size: 35px;
}
.popup-menu a {
    text-decoration: none
}
.list-staff {
    width: 350px;
    height: 350px;
    position: relative;
    left: calc(50% - 185px);
}
.close {
    position: absolute;
    top: 2px;
    right: 2px;
}
html {
    background-image: url("assets/bg.png");
    background-size: 100%;
    overflow: hidden;
    width: 100%;
    height: 100%;
}
#portal {
    bottom: 0;
    height: 550px;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    text-align: center;
    top: 0;
    width: 1000px;
}
#buttons {
  bottom:75px;
  height:200px;
  position:absolute;
  width:1000px;
}

.button {
  background-position:center;
  background-repeat:no-repeat;
  background-size:190px;
  cursor:pointer;
  display:inline-block;
  height:200px;
  transition:background-size .2s ease;
  width:200px;
}

.button:hover {background-size:200px}
.button:active {background-size:180px}

#button1 {background-image:url("assets/forums.png")}

#button2 {background-image:url("assets/store.png")}

#butt

on3 {background-image:url("assets/rules.png")}

#button4 {background-image:url("assets/staff.png")}

#button5 {background-image:url("assets/vote.png")}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

Here is a JSFiddle for that https://jsfiddle.net/vgjvzmp5/
As you can see, when you click "Click me", a popup window comes up. It's working how I'd like it to, but how would I close it when the faded background is clicked, or when the close icon in the corner is clicked? I'm using plain Javascript.

A: Here's a simple working example. You don't need to append a bunch of html on click. You can just add it directly to your html with display:none and use js to show & hide:
function show() {
    document.getElementById('popup').style.display = 'block';
}

function hide() {
    document.getElementById('popup').style.display = 'none';
}

https://jsfiddle.net/vgjvzmp5/3/

A: You should use stopPropagation() .
Preview availabe in codepen !


text:
Q: How to Open a PDF in an Android-Unity3D App? I'm developing an Android app in Unity3D to be used in classrooms, it has buttons to display some webs and videos related to the current lesson, but now I would like to have a button that open the default-pdf-viewer in the Android Tablet and loads a PDF file that I have in a folder in my project assets.
The thing is I have been trying a lot of code from different people from StackOverflow posts and Unity community Threads, but nothing works for me.
I have already tried:
Unity Answers 1
Unity Answers 2
Unity Answers 3
My minimum android  API level is set 22 (in relation to this reddit post)
Here's my code so far:
IEnumerator openPDF() {
     var path = "jar:file://" + Application.dataPath + "!/assets/test.pdf";
     var savePath = Application.persistentDataPath;

     WWW www = new WWW(path);
     yield return www;
     var error = www.error;

     byte[] bytes = www.bytes;
     var result = "File size : "+bytes.Length;

     try{
         System.IO.File.WriteAllBytes(savePath+"/test.pdf", bytes);
         error = "No Errors so far";
     }catch(Exception ex){
         error = ex.Message;
     }

     Application.OpenURL(savePath+"/test.pdf");
}

When I print the www.error string I get a "404 not Found".
Here's what I get when I print the path variable: jar:file:///data/[MY APP PACKAGE NAME]/base.apk!/assets/test.pdf

A: If your app target level API 24 or more, you need to use FileProvide API, otherwise you get FileUriExposedException, as described here.
To interact with FileProvider from С# code, you need to know how to interact with AndroidJavaClass and AndroidJavaObject to work with Java libraries (namely android.support.v4).
Also you need to know how to declares a content provider component by adding the <provider> attribute to your AndroidManifest.xml in your project and some more points that are listed here.
In the answer of this post you can find a solution to the problem, but stumble upon the following troubles:

1) The android.support.v4 library is no longer available on the path
  "AndroidSDK/extras/android/support/v4/android-support-v4.jar", since now it is part of another library.
2) You can find this library in some archives on the Internet, but
  when you download them you will find that the res folder in
  Plugins/Android is no longer supported and you need to create a .aar binary file in which you need to put AndroidManifest.xml and
  android.support.v4 library.
3) When specifying the attribute <provider> in AndroidManifest.xml,
  you need to additionally specify <meta-data> in which to specify the
  path, where in your .aar archive the provider_paths.xml file is
  located, otherwise your application will crash at startup.

You can try to go this long way yourself, or download my asset, which already has all the necessary code for working with the android.support.v4 library via AndroidJavaClass and AndroidJavaObject, and which is also able to rewrite package name in AndroidManifest.xml and providers_paths.xml when you will change it in the project settings. A demo is also included there.
Link on github:
https://github.com/Mihail5412/Unity-Android-Files-Opener

A: Ok, finally I got the solution!
As you can read here Android permissions changed in Nougat (v.7) so that's why I wasnt able to open the pdf, the sistem was blocking it.
The solution was simple, I just lowered the target API level to 23 (Android 6.0 'Marshmallow').
Here's my code if someone is interested:
void openPDF(){
  string namePDF = "test";
  TextAsset pdfTem = Resources.Load("PDFs/"+namePDF, typeof(TextAsset)) as TextAsset;
  System.IO.File.WriteAllBytes(Application.persistentDataPath + "/"+namePDF+".pdf", pdfTem.bytes);
  Application.OpenURL(Application.persistentDataPath+"/"+namePDF+".pdf");
    }


text:
Q: Typing required props indirectly received from composite, cloned React parent I originally had a composite component which returned something like:
  return (
    <canvas>
      {children}
    </canvas>
  );

In order to be able to pass down certain props to its children, I changed it to:
  // CompositeComponent
  return (
    <canvas>
      {React.cloneElement(children as React.ReactElement, {
        prop1_forAllChildren: someData
      })}
    </canvas>
  );

My problem comes when passing a child to the component, since the child component call does not include prop1_forAllChildren...
  <CompositeComponent>
    // Error here: prop1 is "missing" but required in type 'ChildProps'
    <ChildComponent
      prop2_childSpecificProp={someOtherData}
    />
  </CompositeComponent>

...despite the child receiving both prop1_forAllChildren (indirectly, down from CompositeComponent) and prop2_childSpecificProp (directly from ChildComponent call).
const ChildComponent = ( props: ChildProps ) => {
    // props.prop1_forAllChildren is used here.
    // props.prop2_childSpecificProp is used here.
    // ...
}

The component does work, but I am forced to define the type ChildProps as if prop1 were an optional argument, which it isn't as it is always required inside ChildComponent.
interface ChildProps {
    prop1_forAllChildren?: prop1Type; // note the "?"
    prop2_childSpecificProp: prop2Type;
}

What would be the correct way of typing or/and calling this component while keeping prop1_forAllChildren as a required argument?
edit: would just calling the component with an empty/null prop1 be a better solution?
  <CompositeComponent>
    <ChildComponent
      prop2_childSpecificProp={someOtherData}
      prop1_forAllChildren={null}
    />
  </CompositeComponent>


text:
Q: The -ls command listing weird command in ubuntu 16.04 Lady and Gentlemen,
When I want to list out something inside the directory, I do this command ls
Then I got the following weird command:
root@venus:~# ls
udo journalctl -u postgresql

The screenshot of the output
What is the meaning of the output? Can anyone explain? My expectation is that, it should list out all directories inside the home directory but instead I got that weird command.
Thank you!

A: How could such a thing happen?
root@venus:~# ls
udo journalctl -u postgresql

This looks like a single file, named udo journalctl -u postgresql.
My guess is that you will find the content of this file is either s or empty.
root@venus:~# cat udo\ journalctl\ -u\ postgresql

And that this was caused by some permutation of s>udo rather than sudo.

A: Check with pwd and ls -la when file was created. Check contents of the file. It looks like file created by script but also check the directory path and contents before removing such file.


text:
Q: Cursor issue with Stored Procedure In the below oracle sql package body, I receive a "SQL Statement ignored" error and cannot determine the cause. Please see the SELECT statement of the dborLoans_cursor in the PROCEDURE updateLoansInLdcTab in the statement below:
create or replace
PACKAGE body PK_DBORUFT_SYNC AS
PROCEDURE mainProg(v_beginDate DATE, v_endDate DATE) IS
BEGIN
    updateLoansInLdcTab(v_beginDate,v_endDate);
END mainProg;

FUNCTION searchForLdcToUpdate(v_beginDate DATE, v_endDate DATE) RETURN type_ref_cursor IS
    v_ldcLoan type_ref_cursor;
BEGIN
    DBMS_OUTPUT.ENABLE(1000000);
     OPEN v_ldcLoan FOR
        SELECT loan_id
        FROM ldc.ldc_rel_tab
        WHERE loan_id NOT IN
                (SELECT loan_id
                 FROM dbor.vw_ldc_data dbor
                 WHERE dbor.closing_agent     IS NOT NULL
                             AND dbor.closing_agent_phone IS NOT NULL
                             AND dbor.lock_expiration_date > sysdate)
                     AND TO_CHAR(request_date, 'MM/DD/YYYY') >= v_beginDate
                     AND TO_CHAR(request_date, 'MM/DD/YYYY') <= v_endDate;

    RETURN v_ldcLoan;
END searchForLdcToUpdate;

PROCEDURE updateLoansInLdcTab(v_beginDate DATE, v_endDate DATE) is
TYPE dborLdcData IS TABLE OF dbor.vw_ldc_data%ROWTYPE;
v_ldcLoan_type_rec type_ref_cursor;
    v_ldcLoanCursor_type ldcLoanCursor_type;
dborReference           dborLdcData;
v_LDC_LOANID            VARCHAR2(10);
    v_LOAN_ID                           VARCHAR2(10);
v_BANKLINE                          VARCHAR2(20);
    v_CHANNEL                           VARCHAR2(20);
    v_PROPERTY_TYPE                 VARCHAR2(10);
    v_STATE                                 VARCHAR2(2);
    v_STREET_NAME                   VARCHAR2(64);
    v_FIRST_NAME                        VARCHAR2(64);
    v_LAST_NAME                         VARCHAR2(64);
    v_CLOSING_AGENT                 VARCHAR2(50);
    v_CLOSING_AGENT_PHONE   VARCHAR2(15);
v_REGION_CODE           VARCHAR2(20);
v_CLPP_FLAG             VARCHAR2(1);
v_INSTRUMENT_NAME       VARCHAR2(30);
v_BROKER_OFFICER        VARCHAR2(30);
v_COST_CENTER           VARCHAR2(10);
v_PREPARED_BY           VARCHAR2(30);
v_BUYPRICE              NUMBER(9,4);
v_SRP                   NUMBER(8,3);
v_TOTAL_BUYPRICE        NUMBER(9,4);
v_TOTAL_SRP             NUMBER(8,3);
v_BRANCH_NAME                   VARCHAR2(30);
v_LOCK_EFFECTIVEDATE    DATE;
dbor_count              NUMBER;

    CURSOR dborLoans_cursor IS
        SELECT P.loan_id,
                 P.property_type,
                 P.state,
                 P.street_name,
                 P.close_date,
                 P.loan_purpose,
                 P.borrower_last_name,
                 P.borrower_first_name,
                 P.closing_agent,
               P.closing_agent_phone,
                 P.region_code,
                 P.clpp,
                 P.instrument_name,
                 P.broker_officer,
               P.lock_effective_date,
                 P.channel,
                 NVL(P.buyprice, 0) buyPrice
         FROM dbor.vw_ldc_data P
                    LEFT JOIN dbor.wlnprogram W
                             ON upper(P.instrument_name) = W.ln_pgm
                    LEFT JOIN
                         (SELECT A.loan_id FROM ldc.ldc_rel_tab A WHERE A.ldc_status='LDC_PENDING'
                         ) pend ON pend.loan_id = p.loan_id
                    LEFT JOIN
                        (SELECT DISTINCT A.loan_id
                         FROM ldc.ldc_rel_tab A, ldc.ldc_request_rel_tab B
                         WHERE A.ldc_status   IN ('LDC_PENDING', 'DISBURSED','COMPLETE','RECON_PENDING','SUBMITTED','DISBURSEPAYOFF','VOIDREQUEST','FUNDS_REQUESTED')
                                    AND A.ldc_id          = B.ldc_id
                                    AND (B.funding_reason = 'DL Payoff' OR B.funding_reason   ='Original Disbursement')
                        ) disbursed ON disbursed.loan_Id = p.loan_id
                    LEFT JOIN
                        (SELECT name, phone, agent_id, street1, city, zip, state FROM dbor.WCLOS_AGNT) wagnt
                            ON wagnt.agent_id=p.loan_id
                    LEFT JOIN
                        (SELECT loan,
                                        company_name,
                                        phone_phn,
                                        street,
                                        city,
                                        zip_code,
                                        state
                            FROM DBOR.WLOAN_PARTY
                            WHERE type='4'
                         ) wloan ON wloan.loan   =p.loan_id
            WHERE P.closing_agent     IS NOT NULL
                        AND p.loan_id not in (SELECT loan_id FROM ldc.ldc_rel_tab)
                        AND P.closing_agent_phone IS NOT NULL
                        AND P.lock_expiration_date > sysdate ;

  v_dborLdcData dbor.vw_ldc_data%ROWTYPE;

BEGIN
    DBMS_OUTPUT.ENABLE(1000000);

    dborReference := dborLdcData();
    v_ldcLoanCursor_type := searchForLdcToUpdate(v_beginDate, v_endDate);
    dbor_count := 0;

WHILE dborLoans_cursor%FOUND LOOP
  FETCH dborLoans_cursor INTO v_dborLdcData;
  dbor_count := dbor_count + 1;
        v_LOAN_ID := v_dborLdcData.LOAN_ID;
        v_PROPERTY_TYPE := v_dborLdcData.property_type;
        v_STATE := v_dborLdcData.state;
        v_STREET_NAME := v_dborLdcData.street_name;

        v_LAST_NAME  := v_dborLdcData.borrower_last_name;
  v_FIRST_NAME := v_dborLdcData.borrower_first_name;
        v_CLOSING_AGENT  := v_dborLdcData.closing_agent;
        v_CLOSING_AGENT_PHONE := v_dborLdcData.closing_agent_phone;

        v_CLPP_FLAG := v_dborLdcData.clpp;
        v_INSTRUMENT_NAME := v_dborLdcData.INSTRUMENT_NAME;
        v_BROKER_OFFICER := v_dborLdcData.BROKER_OFFICER;
        v_CHANNEL := v_dborLdcData.CHANNEL;
        EXECUTE IMMEDIATE 'SELECT region_code FROM dbor.Branch WHERE branch_name = '||v_dborLdcData.CHANNEL INTO v_REGION_CODE;
        EXECUTE IMMEDIATE 'SELECT cost_center FROM ldc.REF_BANKLINE_REL WHERE channel = '||v_dborLdcData.CHANNEL INTO v_COST_CENTER;
        EXECUTE IMMEDIATE 'SELECT bankline FROM ldc.REF_BANKLINE_REL WHERE channel = '||v_dborLdcData.CHANNEL INTO v_BANKLINE;
        v_LOCK_EFFECTIVEDATE := v_dborLdcData.lock_effective_date;
        v_BUYPRICE := v_dborLdcData.buyPrice;

        LOOP
    FETCH v_ldcLoan_type_rec INTO v_LDC_LOANID;
            EXECUTE IMMEDIATE
    'update ldc.ldc_rel_tabtest
    set loan_id = ' ||''''|| v_LOAN_ID||''''||
        ',bankline = ' ||''''||  v_BANKLINE||''''||
            ',channel = ' ||''''||v_CHANNEL||''''||
            ',PROPERTY_TYPE= ' ||''''||v_PROPERTY_TYPE||''''||
            ',STATE = ' ||''''||v_STATE||''''||
            ',STREET_NAME = ' ||''''||v_STREET_NAME||''''||
            ',BORROWER_NAME = ' ||''''||v_LAST_NAME||','||''''||v_FIRST_NAME||''''||
            ',CLOSING_AGENT = ' ||''''||v_CLOSING_AGENT||''''||
            ',CLOSING_AGENT_PHONE = ' ||''''||v_CLOSING_AGENT_PHONE||''''||
                ',REGION_CODE = ' ||''''||v_REGION_CODE||''''||
                ',CLPP_FLAG = ' ||''''||v_CLPP_FLAG||''''||
                ',INSTRUMENT_NAME = ' ||''''||v_INSTRUMENT_NAME||''''||
                ',BROKER_OFFICER = ' ||''''||v_BROKER_OFFICER||''''||
                ',COST_CENTER = ' ||''''||v_COST_CENTER||''''||
                ',BUYPRICE = ' ||v_BUYPRICE ||
    ' where loan_id = ' ||v_LDC_LOANID;
        END LOOP;
    END LOOP;
EXCEPTION
    WHEN OTHERS
      THEN
        DBMS_OUTPUT.PUT_LINE(SQLERRM);
END updateLoansInLdcTab;
END PK_DBORUFT_SYNC;

A: After quick glance at this (without running it), I would have though there are errors on the lines below as you have not put quotes around the value which is being concatenated in:
EXECUTE IMMEDIATE 'SELECT region_code FROM dbor.Branch WHERE branch_name = '||v_dborLdcData.CHANNEL INTO v_REGION_CODE;
EXECUTE IMMEDIATE 'SELECT cost_center FROM ldc.REF_BANKLINE_REL WHERE channel = '||v_dborLdcData.CHANNEL INTO v_COST_CENTER;
EXECUTE IMMEDIATE 'SELECT bankline FROM ldc.REF_BANKLINE_REL WHERE channel = '||v_dborLdcData.CHANNEL INTO v_BANKLINE;

However, from the comments above you seem to have gotten it working.
The bigger problem in this code is why are you using execute immediate at all?  You don't need to, and worse you have created non scalable code as the three execute immediate statements above and the big update are not using bind variables.  In PLSQL if you avoid using execute_immediate, you don't need to worry about binds at all, PLSQL does it all for you automagically.
Try converting the execute immediate select into something like:
select region_code
into v_region_code
from dbor.branch
where branch_name = v_dborLdcData.CHANNEL;

That will work find and fix the bind variable problem.  Then do the same to the update:
update ldc.ldc_rel_tabtest
set loan_id = v_LOAN_ID
    bankline = v_bank_line
    ...
    ...
where loan_id = v_LDC_LOANID;

The code will be simpler, easier to find errors in the SQL and more scalable.

A: Problem was due to missing grant on DBOR.WLOAN_PARTY.


text:
Q: All I get is a blank page when I visit localhost:9080 I have been using udacity.com to learn to program but I ran into some problem with my code(python). The application is post to allow to put down the day you were born and when you push submit it's post to say "Thanks That's a totally valid day!". It's not doing it. The application just restarts again. Can some tell me why the is statement is not working and how to fix it.
import webapp2
form="""

    <form>
        What is your birthday?

        Month<input type="type" name="month">
        Day<input type="type" name="day">
        Year<input type="type" name="year">

%(error)s

        <input type="submit">
    </form>

"""
class MainPage(webapp2.RequestHandler):
    def write_form(self, error=""):
        self.response.out.write(form % {"error": error} )
    def get(self):
        self.write_form()

        def post(self):
            user_month = valid_month(self.request.get('month'))
            user_day = valid_day(self.request.get('day'))
            user_year = valid_year(self.request.get('year'))

            if not (user_month and user_month and user_year):
                self.write_form("That doesn't look valid to me, friend.")
            else:
                self.response.out.write("Thanks! That's a totally valid day!")

app = webapp2.WSGIApplication([('/',MainPage)], debug=True)

A: That fragment has a syntax error. If you're watching the terminal/console, you'll notice Python complain about the else (which is missing a trailing :). Watching the console, and understanding what it's saying, is key if you want to make progress.
With that fixed, you'll see the form. Then, when you trying posting, you'll get a "405 Method not allowed" because the post method is over-indented.

A: Add method="post" to your form tag just above the text "What is your birthday?". You are using post method to post data to the form but the button submit doesn't know that you are using post as the tag  does not have method="post" in it.
Also check my answer on one of your other related post here. python post and get commands


text:
Q: How to push a website to bitbucket I have website already developed locally that I want to share with other developers.
I have created an account on Bitbucket and looking for a way to push and make my website available to others.
Any idea? Sorry I'm quite new in this. I am using

Cygwin Terminal on Windows 7

. Thanks

A: Give a look to this tutorial:
https://confluence.atlassian.com/display/BITBUCKET/Import+code+from+an+existing+project
The basic code is:
cd /path/to/my/repo
git remote add origin ssh://git@bitbucket.org/your_git_path.git
git push -u origin master


text:
Q: Search equality in a certain field with AWK I am trying to get the name out of /etc/passwd using awk to search only in the 5th field of every row, and then to cut some part of that line and print it out.
This is what I wrote but it doesn't seems to work:
for iter in "$@";
do cat /etc/passwd | awk -F ":" '$5==$iter' | cut -d":" -f6;
done;

concerning the delimiter syntax, everything should be fine I guess?
so my problem is in the $5==$iter, I assume.
How can I change that $5==$iter to - if the 5th field of that row contains my $iter var, then cut and so on..
Sorry for the ignorance, I am a beginner :)
Thanks in advance.

A: See How do I use shell variables in an awk script?
-v should be used to pass shell variables into awk. Also, there's no reason to use either cat or cut here:
for iter in "$@"; do
  awk -F: -v iter="$iter" '$5==iter { print $6 }' </etc/passwd
done

A: As Charles Duffy commented, your code would be more efficient if it didn't need to read /etc/passwd every pass.  And while this particular loop probably doesn't need to be optimized (after all, /etc/passwd is typically not that long and most OS's would cache the file anyway after the first read), it would be interesting to see an awk script read the file only once.
That said, here's another implementation where awk is only invoked once:
printf "%s\n" "$@" | awk -F: '
  NR == FNR { etc_passwd[ $5 ] = $6;  next }
            { print $0 , etc_passwd[ $0 ]   }
' /etc/passwd  /dev/stdin

The NR == FNR condition is an idiom that  causes its associated command only to be executed for the first file in the list of files that follows the awk script (that is, for the reading of /etc/passwd).

A: You can also do everything in bash, example:
#!/bin/bash

declare -A passwd               # declare a associative array

# build the associative array "passwd" with the
# 5th field as a "key" and 6th field as "value"
while IFS=$':\n' read -a line; do      # emulate awk to extract fields
    [[ -n "${line[4]}" ]]  || continue # avoid blank "keys"
    passwd["${line[4]}"]=${line[5]}    # in bash, arrays starting in "0"
done < /etc/passwd

for iter in "$@"; do
    if [ ${passwd[$iter] + 'x'} ]; then
        echo ${passwd[$iter]}
    fi
done

(This version doesn't get into accout múltiples values for 5th field)
here is a better version that can handle blank values as well, ike./script.sh '':
while IFS=$':\n' read -a line; do
    for iter in "$@"; do
        if [ "$iter" == "${line[4]}" ]; then
            echo ${line[5]}
            continue
        fi
    done
done < /etc/passwd

A pure awk solution could be:
#!/usr/bin/awk -f

BEGIN {
    FS = ":"
    for ( i = 1; i < ARGC; i++ ) {
        args[ARGV[i]] = 1
        delete ARGV[i]
    }
    ARGV[1] = "/etc/passwd"
}
($5 in args) { print $6 }

and you could call as ./script.awk -f 'param1' 'param2'.


text: Q: Windows Server Task Scheduler -> trigger on an event(triggered by stored procedure) could i schedule a task triggered by an event, and this event would be stored procedure..so I want to trigger it after successfully executing of a stored procedure. Can this be done and how? Many Thanks


text:
Q: How to debug ERR_SSL_PROTOCOL_ERROR / SSL_ERROR_RX_RECORD_TOO_LONG? I've written simple Java HTTPS server.
Creating server socket:
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(
    getCertificateKeyStore().getIterator().toInputStream(),
    getCertificateKeyStorePassword().toCharArray()
);

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, getCertificateKeyPassword().toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(keyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(km, tm, null);
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
return sslServerSocketFactory.createServerSocket(port);

Generating certificate:
final SystemConsole systemConsole = new SystemConsole();
systemConsole.writeLine("apt install -y certbot");
systemConsole.writeLine(
    "certbot certonly " + (
        "--standalone " +
        "--non-interactive " +
        "--agree-tos " +
        "--email " + email + " " +
        "--domains " + new JoinStrings(domainNames, ' ')
    )
);
System.out.println(systemConsole.read());
final Directory storage = getCommonDataStorage();
final Directory letsEncryptLiveDir = Directory.getExisting("/etc/letsencrypt/live");
final Directory letsEncryptKeysDir = letsEncryptLiveDir.getNotNull(letsEncryptLiveDir.getKeys().getFirst());
storage.removeIfExists("certificate.jks");
systemConsole.writeLine("cd " + letsEncryptKeysDir.absolutePath);
systemConsole.writeLine("openssl pkcs12 -export -out keystore.pkcs12 -in fullchain.pem -inkey privkey.pem -password pass:ilovejava");
System.out.println(systemConsole.read());
systemConsole.write("keytool -importkeystore"); {
    systemConsole.write(" -srckeystore keystore.pkcs12");
    systemConsole.write(" -srcstoretype PKCS12");
    systemConsole.write(" -destkeystore " + storage.absolutePath + "/certificate.jks");
    systemConsole.write(" -storepass " + keyStorePassword);
    systemConsole.write(" -keypass " + keyPassword);
    systemConsole.write(" -srcstorepass ilovejava");
    systemConsole.writeLine();
}
System.out.println(systemConsole.read());
systemConsole.writeLine("rm keystore.pkcs12");
return storage.read("certificate.jks");

And it used to work well until yesterday. Then it SUDDENLY stopped working.
In Chrome: ERR_SSL_PROTOCOL_ERROR
In Firefox: SSL_ERROR_RX_RECORD_TOO_LONG
In Edge: strangely still works.
Another strange thing: Chrome say my SSL certificate is actually OK:

Moreover! Chrome also establish connection, send request and receive response (at least its headers):

And it looks like it does it over SECURE socket connection (because there are no other way to connect). And handshake is actually occur (as I can see in server logs).
But still, I get that SSL related errors. How can I debug what EXACTLY goes wrong?
UPDATE: Tried openssl s_client -connect <my_domain>:443. Getting this:
CONNECTED(00000003)
depth=2 O = Digital Signature Trust Co., CN = DST Root CA X3
verify return:1
depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
verify return:1
depth=0 CN = stage.bd-polpharma.com.ua
verify return:1
---
Certificate chain
 0 s:/CN=stage.bd-polpharma.com.ua
   i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
 1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
   i:/O=Digital Signature Trust Co./CN=DST Root CA X3
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIFaTCCBFGgAwIBAgISBB3XbH/2SQ6Ai1WXqKyLIDJjMA0GCSqGSIb3DQEBCwUA
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xOTA0MjUwNzQ3NDlaFw0x
OTA3MjQwNzQ3NDlaMCQxIjAgBgNVBAMTGXN0YWdlLmJkLXBvbHBoYXJtYS5jb20u
dWEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDF0iM/tA0qu644/RUv
m3uGA6RjbPihNnXQW2qy2RAALJhCprXDoVpMGzxIrZs/XvXvcRTa7ps9+zPJCCRN
dUxnydm0rk5H5Orvt2gWMCT/Ln42OyHHjDuYFo3kY9U8xHrkY+x2r4uHBv1GDkQ/
HZrmHRk6fy0yeaMKx6j8y2H8BvG3Hwj7p73sW2umUxnuoP4dbRSTBZqTk6dGNjuN
lWonCFandADcIa2fwzVkBUUDo4NegxB1SuVsu7mGegzmyxCLQhIo8NtSDeCuEN6N
MV8YVenP3CMsHpHAbx1Ly8FbLpmIOUTmDAE4OkNQJTmHEJ2s+ZVT8WNlfhh+rUSf
fUqrAgMBAAGjggJtMIICaTAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYB
BQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFItV0gKguULL
OGG03Q4KJXJnL58uMB8GA1UdIwQYMBaAFKhKamMEfd265tE5t6ZFZe/zqOyhMG8G
CCsGAQUFBwEBBGMwYTAuBggrBgEFBQcwAYYiaHR0cDovL29jc3AuaW50LXgzLmxl
dHNlbmNyeXB0Lm9yZzAvBggrBgEFBQcwAoYjaHR0cDovL2NlcnQuaW50LXgzLmxl
dHNlbmNyeXB0Lm9yZy8wJAYDVR0RBB0wG4IZc3RhZ2UuYmQtcG9scGhhcm1hLmNv
bS51YTBMBgNVHSAERTBDMAgGBmeBDAECATA3BgsrBgEEAYLfEwEBATAoMCYGCCsG
AQUFBwIBFhpodHRwOi8vY3BzLmxldHNlbmNyeXB0Lm9yZzCCAQMGCisGAQQB1nkC
BAIEgfQEgfEA7wB2AG9Tdqwx8DEZ2JkApFEV/3cVHBHZAsEAKQaNsgiaN9kTAAAB
alOt8a4AAAQDAEcwRQIhAPRmn7ySWOg2bwY90b1q6HxEYyv/APvH2R6a+lwljXJ1
AiAHxeuBUoveypoA5kUueihWe8HjdOuIF0JDbqvCks2itwB1ACk8UZZUyDlluqpQ
/FgH1Ldvv1h6KXLcpMMM9OVFR/R4AAABalOt8OEAAAQDAEYwRAIgT6LbDXae36hY
WFCNA7uybp95ta2ql0iVq0spxttOawECIBbu9Z/oBRAlrGhiMshL9Gqq4ok8OciR
6NmOsH3nXqtlMA0GCSqGSIb3DQEBCwUAA4IBAQAJYXoBWnhdLITZxL0I5s/IrerC
ychitXGqxXY8yJd+HxikJnz+tw6QU+De/aZFdu7/zyZID0X/f59bSE6C2EJZXccP
NQB0Qi7XcMUddMLiHT5vXhQ+KIqctbQyUNokxz8blB6rEi2zDhoHgfvFHQP4ErWG
pJYXLDTMYMT1kdF4ciyiauKLMxPc6i1Mn0Ob0CYLtBl9suLEBrw5RS9ZSlVNXwFN
rl6Vrrvs6H5ntMffBC4zqHELhwTx/uFoh50XzYH7LeLKoGdl5UwRLiPMAJ/zPnDy
BqdhRghbHcTXbbM1qiuO90juZzazUh6rOtK4hDZ97jraacMC1EiaaLdTCYSE
-----END CERTIFICATE-----
subject=/CN=stage.bd-polpharma.com.ua
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 3069 bytes and written 302 bytes
Verification: OK
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: AC9F77EB2B148C44D053707331C431BE1EA40944B6FB2C67FF3B7F4D9B8B00F8
    Session-ID-ctx:
    Master-Key: AC4B43FE48F138613B55D5E42E39998A5A9500E86B7B154D177D3E98B3DC2A03D5CC344052DE2310B8C1CE91BD487AA5
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1556186839
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
    Extended master secret: yes

UPDATE: Tried getDefaultAlgorithm(), "PKIX", "TLSv1.2", "TLSv1.3" with all possible combinations. Didn't help.

A: After 3 days of trying every possible thing and asking every possible person, I found that I can downgrade Java version from 11 to 10 (OpenJDK or Oracle JDK doesn't matter). And it solves the problem.
But still, why? And how to deal with it on later Java? By the way, Oracle JDK 12 still has this... bug? I'm not sure how to call it. It can't be that SSL is broken in Java 11+. I think, I'm doing something wrong, but I still don't know what.


text:
Q: Describing shapes independent of a co-ordinate system? Idea
Let's try to express objects in terms of their line elements and line element vector rather than the co-ordinate system. Let the object be a line in three dimensions:
Line

At the origin we have:
$$ d \vec s|_{(0,0,0)} =  dx \hat i + dy \hat j + dz \hat k $$
$$ d \vec s|_{(a,a,a)} = dx \hat i + dy \hat j + dz \hat k  $$
Hence the equation of this line in terms of it's line element vector is:
$$ d \vec s|_{(0,0,0)} = d \vec s|_{(a,a,a)}   $$
This can be easily the equation of a line in $n$ dimensions passing through the origin!
Hence, the equation of a line is:
$$ d \vec s|_{\vec r} = d \vec s|_{\vec r + \vec \epsilon}$$
Shell
To find the equation of the surface of a unit sphere:
Let the co-ordinate system be:
$$ d \vec s |_{\theta,\phi} = d \theta \hat \theta  + sin \theta d \phi \hat \phi  $$
$$ d \vec s |_{\theta+ \epsilon ,\phi } = d \theta \hat \theta  + sin (\theta  +\epsilon )d \phi \hat \phi  $$
Then the inner product of both line elements are:
$$d \vec s |_{\theta,\phi}  \cdot d \vec s |_{\theta + \epsilon,\phi } = d \theta^2  + sin(\theta) sin(\epsilon + \theta ) d \phi^2 $$
$$ = d \theta^2  + sin^2 (\theta) cos(\epsilon) d \phi^2 + cos(\theta)sin(\epsilon) d \phi^2 $$
Keeping $1$'st order terms in $\epsilon$:
$$ = d \theta^2  + sin^2 (\theta) d \phi^2 + cos(\theta) \epsilon d \phi^2 $$
But this is nothing more than:
$$ = |d \vec s |_{\theta,\phi}|^2 + (\lim_{\epsilon \to 0} \frac{d \vec s |_{\theta + \epsilon,\phi} - d \vec s |_{\theta,\phi}}{\epsilon}) \cdot ( \epsilon  \hat \phi d \phi)  $$
Hence, the general equation of a shell is (?):
$$ \lim_{\epsilon \to 0} \frac{d \vec s |_{\theta,\phi, \dots, \kappa}  \cdot d \vec s |_{\theta +\epsilon,\phi,\dots, \kappa } - |d \vec s |_{\theta,\phi, \dots, \kappa}^2}{\epsilon} = (\lim_{\epsilon \to 0} \frac{d \vec s |_{\theta +\epsilon,\phi,\dots, \kappa } - d \vec s |_{\theta ,\phi,\dots, \kappa }}{\epsilon}) \cdot ( \hat \phi d \phi) $$
This is the same as:
$$ (\lim_{\epsilon \to 0} \frac{d \vec s |_{\theta +\epsilon,\phi,\dots, \kappa } - d \vec s |_{\theta ,\phi,\dots, \kappa }}{\epsilon}) \cdot (d \vec s|_{\theta +\epsilon,\phi,\dots, \kappa } - (  \hat \phi d \phi ))= 0  $$
where $d \vec s |_{\theta +\epsilon,\phi,\dots, \kappa } - (  \hat \phi  d \phi)) \neq \vec 0  $
Verification of shell in different coordinate system:
The equation of a unit shell in $3$-D is:
$$ x^2 + y^2 + z^2 = 1 $$
$$\implies dz =-\frac{x dx + ydy}{\sqrt{x^2 + y^2 -1}}$$
Hence, the line element is:
$$ ds|_{(x,y,z)} = dx \hat i + dy \hat j -\frac{x dx + ydy}{\sqrt{x^2 + y^2 -1}} \hat k  $$
Similarily, the line element at a different point is:
$$ ds|_{(x+ \epsilon,y,z)} = dx \hat i + dy \hat j -(\frac{x dx + ydy}{\sqrt{(x + \epsilon)^2 + y^2 -1}} + \frac{ \epsilon dx }{\sqrt{(x+ \epsilon)^2 + y^2 -1}}) \hat k   $$
Expanding to first order in $\epsilon$ we get:
$$ ds|_{(x+ \epsilon,y,z)} = dx \hat i + dy \hat j -(\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}}- \frac{ \epsilon x (x dx + ydy)}{{(x^2 + y^2 -1)}^{3/2}} + \frac{ \epsilon dx }{\sqrt{(x)^2 + y^2 -1}}) \hat k $$
Simplifying a bit we get:
$$ ds|_{(x+ \epsilon,y,z)} = dx \hat i + dy \hat j -(\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}}- \frac{ \epsilon x (x dx + ydy)}{{(x^2 + y^2 -1)}^{3/2}} + \frac{ \epsilon {(x^2 + y^2 -1)}dx }{{(x^2 + y^2 -1)}^{3/2}}) \hat k $$
Further simplyfying:
$$ ds|_{(x+ \epsilon,y,z)} = dx \hat i + dy \hat j -(\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}}- \frac{ \epsilon  ( xydy)}{{(y^2 -1)}^{3/2}} + \frac{ \epsilon {( y^2 -1)}dx }{{(x^2 + y^2 -1)}^{3/2}}) \hat k $$
Hence,
$$ ds|_{(x+ \epsilon,y,z)} \cdot  ds|_{(x,y,z)} = dx^2 + dy^2 +(\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}}) (\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}}- \frac{ \epsilon  ( xydy)}{{(x^2 + y^2 -1)}^{3/2}} + \frac{ \epsilon {( y^2 -1)}dx }{{(x^2 + y^2 -1)}^{3/2}})  $$
Hence,
$$ ds|_{(x+ \epsilon,y,z)} \cdot  ds|_{(x,y,z)} = dx^2 + dy^2 +(\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}})^2  -(\frac{x dx + ydy}{\sqrt{(x )^2 + y^2 -1}}) (\frac{ \epsilon  ( xydy)}{{(x^2 + y^2 -1)}^{3/2}} + \frac{ \epsilon {( y^2 -1)}dx }{{(x^2 + y^2 -1)}^{3/2}})  $$
Which is equal to:
$$ = |d \vec s |_{\theta,\phi}|^2 + (\lim_{\epsilon \to 0} \frac{d \vec s |_{x + \epsilon,y,z} - d \vec s |_{x,y,z}}{\epsilon}) \cdot ( \epsilon  \hat k d k)  $$
Questions
What is the subbranch of differential geometry known as? (studying shapes in this fashion?)
Is the general equation of a shell correct? (If not, please show the correct expression?) How to show uniqueness of solutions? Will this idea work if one  thinks of it as an embedding in a higher Euclidean dimension? (If yes, why wont it work without that)? Can any shape be expressed in terms of line element (I think the answer should be yes but I'm not sure how to prove it)?


text:
Q: How do I center UILabel TEXT horizontally? Now I've seen a lot of examples that teach you either how to center the UILabel Text in the middle of the screen, but that's not what I'm asking for. I'm asking on how to make sure that the text of UILabel remains half way between the left and right bounds of the screen and All I have to do is make adjustments Vertically. I have the following:
self.aboutMee = [[UILabel alloc] initWithFrame:CGRectMake(0, 400, 120, self.view.bounds.size.width)];
            self.aboutMee.text = @"About Me";
            self.aboutMee.textAlignment = NSTextAlignmentCenter;
            self.aboutMee.backgroundColor = [UIColor clearColor];
            self.aboutMee.font = [UIFont fontWithName:@"Helvetica" size:14];
            [self.aboutMee setTextColor:[UIColor colorWithRed:0.0/255.0 green:140.0/255.0 blue:199.0/255.0 alpha:1.0]];
            [self.aboutMee setFont:[UIFont fontWithName:@"HelveticaNeueLTStd-ThCn" size:35]];
            [self.scrollView addSubview:self.aboutMee];

Now I've tried to make the entire label 320 in width and then just center the text, but that doesn't work. Any ideas?

A: You should set frame correctly:   CGRectMake(pos.x, pos.y, width, height)
self.aboutMee = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        self.aboutMee.text = @"About Me";
        self.aboutMee.textAlignment = NSTextAlignmentCenter;
        self.aboutMee.backgroundColor = [UIColor clearColor];
        self.aboutMee.font = [UIFont fontWithName:@"Helvetica" size:14];
        [self.aboutMee setTextColor:[UIColor colorWithRed:0.0/255.0 green:140.0/255.0 blue:199.0/255.0 alpha:1.0]];
        [self.aboutMee setFont:[UIFont fontWithName:@"HelveticaNeueLTStd-ThCn" size:35]];
        [self.scrollView addSubview:self.aboutMee];


text:
Q: How to start rpcbind automatically at boot on Ubuntu 14.04 server? I have been unsuccessfully trying to configure my Ubuntu 14.04 server to start rpcbind on boot.
RPCbind is installed and works fine if I start it manually with
service rpcbind start
I have added the symlinks to the runlevel directories automatically using the command
update-rc.d rpcbind defaults
For the record, I tried other variations of the previous command, such as update-rc.d rpcbind start 2345 and update-rc.d rpcbind enable 2345. None of them created the symlinks, only update-rc.d rpcbind defaults did.
Now, in my default runlevel, there is a symlink that looks like this:
S20rpcbind -> ../init.d/rpcbind

Even with this, when I reboot the server, rpcbind does not start automatically.
Any help to make this work will be appreciated! Thanks.

A: I finally found one way to do it that works. I simply added the command service rpcbind start inside the  /etc/rc.local script.
I don't know if this is the proper way to do it, but it works.

A: Like Neo_999 says you can add stuff to your /etc/rc.local and for already declared services this works well.
For things without a service-declaration, you can fake it through GNU screen:
sudo -u $USER -- screen -d -m $EXECUTABLE
This let's you spawn a pre-detached screen-session with an arbitrary $EXECUTABLE running as $USER.
Hacky as heck, but it does work and saves you the trouble of writing init-scripts.


text:
Q: Imagine having a broken radio transmitter, and I need to make it work by building a solenoid with an inductance of 100 uH. How can I do it? This is a problem made by my professor.
Imagine having to repair a radio in a rural area, without any high-tech instruments, and I need to build a solenoid with an inductance of 100uH, a cross-section area of 1.00 cm2 and a lenght of 3.00cm.
Do I need to find the number of turns and their diameter, explaining also the type of material I would use?
I found some formulas, such as L  = [d2 n2] / [18d + 40l] , or this L = u0 * (n2/l) * S . What's the difference between them?
https://www.electricaltechnology.org/2014/03/inductance-air-core-inductor-calculator.html (This is the link to the first formula, while the second one was found in my physics' course book).
I know that I have to find the number of turns and their diameter, the only thing I don't know is which formula do I have to use.


text:
Q: Prolog removing all variables and duplicates I need a query, which will remove me all variables and duplicates from list.
Example:
?- L = [1,2,3,X,Y,3,2], my_awesome_predicate(L, Res).

Then, Res should be: [1,2,3].
I don't care about order (it could be [2,3,1], [3,2,1] or whatever).
Unfortunately, I have a task in which I have to care about efficiency, so my main question is - can it be done faster? Currently, I have the following code:
remove_variables([], []).
remove_variables([H|List], Res):- var(H), !, remove_variables(List, Res).
remove_variables([H|List], [H|Res]):- remove_variables(List, Res).

my_awesome_predicate([], []).
my_awesome_predicate(List, Res):-
  sort(List, Sorted),
  remove_variables(Sorted, Res).

A: If you are using SWI then you can improve a little further with this code:
my_awesome_predicate(List, Res):-
  sort(List, MRes),
  remove_variables(MRes, Res).

remove_variables([Var|Tail], NTail):-
  var(Var),
  !,
  remove_variables(Tail, NTail).
remove_variables(Res, Res).

as it seems that SWI's sort will leave unbounded variables first (don't know if this behavior is a standard among other prolog's), so you can stop removing variables once you find the first non-variable.
Reading a bit SWI's documentation, it's stated that:
4.7.1 Standard Order of Terms

Comparison and  unification of arbitrary  terms.   Terms are ordered  in
the so called ``standard order''.  This order is defined as follows:

 1. Variables < Numbers < Atoms < Strings < Compound Terms

so it seems safe to stop removing elements when you find the first non-variable...

A: awesome([],[]).
awesome([H|T],R):- var(H), !, awesome(T,R).
awesome([H|T],R):- awesome(T,[H],R).

awesome([],R,R).
awesome([H|T],A,R):- memberchk(H,A) -> awesome(T,A,R) ; awesome(T,[H|A],R).

Something like this? Theoretically it is quadratic, but your lists are very short and this code is very simple, so might get optimized by the compiler better.
If you append your resulting lists, better change it to work with difference lists, putting the output directly into the resulting list being built:
awesome([],Z,Z).
awesome([H|T],R,Z):- var(H), !, awesome(T,R,Z).
awesome([H|T],R,Z):- R=[H|Y], awesome(T,[H],Y,Z).

awesome([],_,Z,Z).
awesome([H|T],A,R,Z):- memberchk(H,A) -> awesome(T,A,R,Z)
                                      ;  R=[H|Y], awesome(T,[H|A],Y,Z).

memberchk/2 of course weeds out variables as well as duplicates.

A: This is an old question but for the reference there is another nice and short solution using setof.
my_awesome_predicate(L, Res) :-
    setof(X, (member(X, L), ground(X)), Res).

Res contains the solution without variables with the terms ordered by their first appearance.
?- my_awesome_predicate([1,2,3,X,Y,3,2], Res).
Res = [1, 2, 3].


text:
Q: How do I access the user's password from LDAP in a LdapUserDetailsMapper using spring security? We are using spring security in our web application based on spring MVC.
We are doing authentication using LDAP module of spring security which is working properly. Now I need to get the user password from LDAP for saving in the database.
For this I am using this in my code.
    public class PersonContextMapper implements UserDetailsContextMapper {

    public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<GrantedAuthority> authorities) {
    Person.Essence p = new Person.Essence(ctx);

    p.setUsername(username);
    p.setAuthorities(authorities);

        Object passwordValue = ctx.getObjectAttribute("userPassword");

    return p.createUserDetails();

    }

    public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
    Assert.isInstanceOf(Person.class, user, "UserDetails must be a Person instance");

    Person p = (Person) user;
    p.populateContext(ctx);
    }
}

But I am not getting the any value for the password. Its always null.
Please help.
PS. My authentication is successful. It means password entered in the login form is matches properly with the password stored in the LDAP.

A: It might be that the authentication state of the connection does not have permission to read the value of the userPassword attribute. Most often, applications issue a BIND request to the directory server, including appropriate controls as necessary. The password is included in the BIND request and the directory server changes the authentication state of the connection upon successful completion of the BIND request. In any case, the value of the userPassword attribute is encrypted or hashed more often than not, and applications have no need to read the value.


text:
Q: Precision / Recall for multi-label classification using torchmetrics Is there a function or a set of arguments that I can use in order to calculate Precision and Recall for a multi-label problem?
Note that with multi-label I mean that each sample can be classified into more than one class.
The following is not returning what I would expect:
import torch
from torchmetrics import Precision
target = torch.tensor([
    [0, 0, 1, 1, 0],  # Sample 1 belongs to class 2 and 3 (zero-indexed)
    [0, 0, 1, 0, 0], # Sample 2 belongs to class 2 (zero-indexed)
])
preds = torch.tensor([
    [0, 0, 0, 0, 0],  # Sample 1 predicted to belong to no class
    [0, 0, 0, 0, 0], # Sample 2 predicted to belong to no class
])
metric = Precision(num_classes=5, mdmc_average="samplewise")
print(metric(preds, target))

It returns: tensor(0.7000), but it should be 0% since there are no True Positives.


text:
Q: Why does hibernate remove data from association table? I have following relation in my program:
@Entity
@Table(name = "student")
public class Student extends Person {
    private Map<Document, DocumentInfo> documents =
       new HashMap<Document, DocumentInfo>();
    ...
    @OneToMany
    @JoinTable(name = "student_documents",
            joinColumns = @JoinColumn(name = "student"),
            inverseJoinColumns = @JoinColumn(name = "document_info"))
    @MapKeyJoinColumn(name = "document")
    public Map<Document, DocumentInfo> getDocuments() {
        return documents;
    }
    ...
}

When I save student with his documents information all seems good..
When I read him from database all seems good too, but when I try to read it one more time I have NullPointerException. I did some research and found that during the first invocation of student.getDocuments() hibernate deletes records from table student_documents:
Hibernate: select document0_.id as id2_0_, document0_.title as title2_0_ from document document0_ where document0_.id=?
Hibernate: select document0_.id as id2_0_, document0_.title as title2_0_ from document document0_ where document0_.id=?
Hibernate: delete from student_documents where student=?

What I've done wrong?
Thanks
my test code looks like:
    Student student = new Student();
    student.setFirstName("123");
    studentService.add(student);
    Student student2 = studentService.read(student.getId());
    assertFalse(student2.getDocuments().size() == 0); // here it all occurs

service method:
public Student add(Student student) {
    for (Document document : documentRepository.findAll()) {
        DocumentInfo documentInfo = new DocumentInfo(false, "");
        documentInfoRepository.save(documentInfo);
        student.getDocuments().put(document, documentInfo);
    }
    return studentRepository.save(student);
}

A: Seems like I just found the issue. Can't check it now in my old project, but it's very similar to problems related to this hibernate bug.


text:
Q: How to use the signal QMovie::frameChanged(int frameNumber) to emit a signal? I want to use the frameChanged(int) to emit a signal when the currentFrameNumber is equal to the frameCount, my QT version is 4.7.4
QObject::connect(movie,SIGNAL(frameChanged(int)),movie,SLOT(stop()));
QMovieChild.cpp:
class QMovieChild:public QMovie
{

signals:
void newSignal();
public slots:
    void onFrameChanged(int frameNumber){
        if(frameNumber == this->frameCount()-2)
            emit newSignal();
}
};

Monster.cpp:
void Monster::Vanishment()
{
QMovieChild *movie = new QMovieChild();
movie->setFileName("./pikaqiu.gif");
QSize size = this->getLabelPointer()->size();
movie->setScaledSize(size);
this->getLabelPointer()->setMovie(movie);
QMovie::connect(movie,SIGNAL(newSignal()),movie,SLOT(deleteLater()));
QMovie::connect(movie,SIGNAL(frameChanged(int)),movie,SLOT(onFrameChanged(int)));
movie->start();
}

A: To create a signal the class should inherit from QObject, if the class you use is QWidget, it is also valid since it inherits from QObject.
#ifndef QMOVIECHILD_H
#define QMOVIECHILD_H

#include <QMovie>

class QMovieChild : public QMovie
{
    Q_OBJECT
public:
    QMovieChild(QObject * parent = 0):QMovie(parent){
        connect(this, SIGNAL(frameChanged(int)), this, SLOT(onFrameChanged(int)));
    }

signals:
    void newSignal();
private slots:
    void onFrameChanged(int frameNumber){
        if(frameNumber == frameCount()-1){
            emit newSignal();
            //stop();
        }
    }

};

#endif // QMOVIECHILD_H

Use:
QMovieChild *movie = new QMovieChild;
movie->setFileName("./pikaqiu.gif");
QMovie::connect(movie,SIGNAL(newSignal()),movie,SLOT(deleteLater()));
QSize size = getLabelPointer()->size();
movie->setScaledSize(size);
getLabelPointer()->setMovie(movie);
movie->start();


text:
Q: How to get number of values >= x across multiple columns I'm trying to count the number of times a value is greater than "x" across all my columns. There have been lots of examples that show this using the column names, but my column names are long and I'm trying to use the column numbers. Essentially I want sum of: the number of times each column has a value greater than 5 for each month. Here is a sample dataframe
# Create a, b, c, d variables
a <- c("06-25-20 08:00:00 AM","06-25-20 08:15:00 AM",
       "06-25-20 08:30:00 AM","06-25-20 08:45:00 AM",
       "07-25-20 08:45:00 AM", "07-25-20 08:45:00 AM",
       "08-25-20 08:45:00 AM", "08-25-20 08:45:00 AM",
       "09-25-20 08:45:00 AM","09-25-20 08:45:00 AM")
b <- c(4,5,8, "NA", 4,5,"NA",7,7,6)
c <- c(6,10,8, "NA", 8,5,"NA",8,7,2)
# Join the variables to create a data frame
df <- data.frame(a,b,c)
df$a = as.POSIXlt(df$a, format="%m-%d-%y%H:%M:%S", tz = 'EST')

Here is some sample code
Proportion_over_five = df %>% pivot_longer(-c(a)) %>%
  mutate(month = lubridate::month(a), year = lubridate::year(a)) %>%
  group_by(month, year, name) %>%
  summarise(count = sum(df[,2:3]>5))

When I use that code it gives me the wrong answers. I think it says 13 times for each column and each month.
I've also tried this code
Proportion_over_five = df %>% pivot_longer(-c(a)) %>%
  mutate(month = lubridate::month(a), year = lubridate::year(a)) %>%
  group_by(month, year, name) %>%
apply(X=df,2,FUN=function(x) length(which(df[,2:3] >= 20)))

and I get the error message
Error in `-.POSIXt`(left) : unary '-' is not defined for "POSIXt" objects

so with this sample data frame the result should look like
month  year  a  b
06     2020  2  3
07     2020  1  2
08     2020  1  1
09     2020  2  1

A: Do you want this?
df %>%
  mutate(month = lubridate::month(a), year = lubridate::year(a)) %>%
  group_by(month, year) %>%
  summarise(across(.cols = 2:3, ~ sum(. > 5)), .groups = 'drop')

# A tibble: 4 x 4
  month  year     b     c
  <dbl> <dbl> <int> <int>
1     6  2020     2     3
2     7  2020     0     1
3     8  2020     2     2
4     9  2020     2     1


text:
Q: Why 'Cannot read property 'x' of undefined' is not evaluated to false? I have encountered the error 'Cannot read property 'x' of undefined' multiple times, and I know that I can manage to work around it by doing the famous
if (foo && foo.bar)

But the question is WHY ? Why do we need to check that object exists to test that his properties are defined or not ? Wouldn't be easier for everyone (approximately, we can safely exclude the guys building JavaScript engines) to test only the target property, and the JavaScript engine do the 'foo &&' behind the scenes ?
Many tears were shed, and more nights were spent sleepless debugging this error, so why the JS engine implementors chose to do it this way ? Is it a part of the specification of ECMAScript (Spec website)? Is it to laugh at newbies ? Is it a conspiration from StackOverflow to make more people visiting their website and ask the same question over and over ?
Ok, it is a part of the ECMAScript specs : The Reference Specification Type (Normally. I am not that expert in reading formal, suit-and-tie-wearing-man-toned documents, but it should be it).
It is a language construct, but why can't they make it easier for the miserable developers using it ?
This question is about learning more about how JavaScript works, so it would be nice if you can explain things in depth.
And for the sake of the completeness of the question, a working example : jsfiddle.net/vr6bgwop/

A: Let's look at some semi-related constructs of the language:

*

*Accessing an object's property which doesn't exist (e.g. var foo = {}; foo.a) results in undefined

*Passing less (or more) arguments than the function expects is legal; accessing a parameter that wasn't passed results in undefined

*Doing math operations on non-numbers results in NaN, which propagates through the computation (spot the object: a * b - c ^ d, you can't can you?)

And so forth. One can argue that the following all of the examples above should throw an error. Yet they don't, and it's not to save CPU cycles or memory, it's because of how the language works, and a history of fuck-ups. That last one is really, really important.
It's how the language works: Objects and primitives
But let's talk about your example. Why even throw an error?
Contrary to popular belief, not everything in JS is an object: Most things can be turned into an object (see another answer of mine if you're interested), but there are two very important primitives which cannot, namely null and undefined.
Let's look at that for a bit: If you could say that null and undefined can be turned into objects, then there'd be no problem accessing their properties, right?
Well, languages like Ruby do that. In Ruby, truly everything is an object, so you can do this: nil.nil? (see example). Trying to access a non-existing property (or slot? was that how they called it?) raises an exception like it does on any other objects (why are they raising exceptions!? can't they just return undefined?)
But most other languages don't. Famously, null values and friends are there to represent that which is nothing, Not an Object in languages which are familiar with that concept. In Java and C# the NullReferenceException is famous. In C++ it's worse: de-referencing a null causes a segfault! Imagine debugging that!
Therefore, considering the history of the language and its having both objects and primitives, it makes sense to throw an error if you can't treat a primitive like an object.
Imagine that world
Let's say that you're correct: The distinction is stupid, it should be implemented. You raise a bug report, TC39 (the ones in charge of specifying javascript) agree, it's implemented everywhere. Content, you go to your favourite editor, write this smack in the middle of things:
foo.bar.baz = 4

And for some reason, something else in a pretty unrelated part of your system which gets passed foo.bar.baz in some obscure fashion throws weird errors, about false not having a toFixed function.
wtf? How did this happen? How do you approach debugging it?
After several hours of debugging and working your way back through the call stack, you smack your forehead in disbelief. "I'm an idiot", you say to yourself, "how could I have forgotten to initialize foo.bar?"
That's why I also personally think that NaN propagation is a disaster.
But why did you get so worked up?
But finally, let's clear something out of the way: Why did this error cause you hours of debugging? Since this is an exception, it clearly shows you the line and column it happened in, and you obviously know this rule, so the distance from error to finding the right spot is nearly instantaneous. That's the point you should work on, language idiosyncrasies aside.
Aside: Where it is in the spec
You were close to where this behaviour is specified. Luckily for you (and sadly for me...) I've read a lot of that formal, suit-and-tie-wearing-man-toned document, and knew how to find this.
Searching for Property Accessors, you get to the Evaluation section. Note step 7 of the first algo, and step 4 of the second:

Let bv be RequireObjectCoercible(baseValue).

In the RequireObjectCoercible table, we see that undefined and null throw a TypeError.

A: Imagine the overhead of checking all parents of z in a.b.c.d....x.y.z, every time you need to access z.
That's why you explicitly have to check for missing properties, yourself. There is no way to automatically check it without significantly increasing memory / CPU usage.

That said, if you were to automatically return, for example, undefined if one of the parents isn't set, then you'd have no way of knowing whether z is undefined, or if one of it's parents is.
How would you then make sure it's parents are properly set? By manually checking each parent.

A:
Wouldn't be easier for everyone (approximately, we can safely exclude
  the guys building JavaScript engines) to test only the target
  property, and the JavaScript engine do the 'foo &&' behind the scenes
  ?

Of course they could. And it would be much slower due to the extra tests required, also in all the cases where the developer bloody well knows that foo cannot be null:
foo = { bar: (i == 50) };
if(foo.bar) {...}

Developer laziness is never an excuse for slowing down a language. In your case, you are evaluating 2 conditions: whether foo is even set, and if it is, whether its property bar is set. If you test 2 conditions, you write both conditions.

A: Javascript don't allows you to access non-existing properties equal all programming languages. It's a feature that forces you to develop with good practices. There are a lot of methods to avoid your problem in an if statement, for example initialize objects with null or undefined values:
 var foo = {
      bar: null,
      beer: undefined
 }

 if(foo.beer) {
      // you'll never notice with an undefined error, so undefined is the value!
 }

And please, don't be conspiranoic.


text:
Q: Azure user-assigned managed service identity not working from within Azure VM I have a VM in a scale set which has a user-assigned MSI attached to it. This MSI has read access to a specific key vault, set-up in its access policy tab.
From within a VM I need to access the key vault. az CLI is installed on the VM. When trying to log-in I'm getting the following error:
> az login --identity -u /subscriptions/subscriptionId/resourcegroups/group/providers/Microsoft.ManagedIdentity/userAssignedIdentities/name
No access was configured for the VM, hence no subscriptions were found

When I login interactively with az login and enter the displayed code at https://microsoft.com/devicelogin it works great...
However, the point of using MSI is to have it work without interaction...
Did somebody else have this problem?

A: Az login --identity is for accessing Azure Resource Manager. This enables you to perform control-plane/management operations over Key Vault. This is the equivalent of getting a token for https://management.azure.com/
Key Vault access policies enable data-plane access to the Vault. For this, you'll need a token for https://vault.azure.net
Check out the following tutorials:
Linux: https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-linux-vm-access-nonaad
Windows: https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-nonaad


text:
Q: Can't inflate the menu I am going to inflate a menu in my first Activity.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

The R.menu.main:

<item
    android:id="@+id/action_serach"
    android:title="Search"
    android:orderInCategory="100"
    android:icon="@drawable/ic_search"
    app:showAsAction="ifRoom" />

It doesn't work, but it inflates the another XML file named R.menu.menu_home.
The R.menu.menu_home:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_star"
android:title="Search"
android:orderInCategory="100"
android:icon="@drawable/ic_star_half"
app:showAsAction="ifRoom"
     />
</menu>

But in my second Activity, it works, whether it's R.menu.main or  R.menu.menu_home.
  why?

A: I think the problem is that you have to Override the class method, so add @Override before.
Here you can get more info about the Override annotation.

A: I have solve this problem.It's because i  replace the framelayout with a fragment in the activity and the onCreateOptionsMenu() method is in the fragment.

A: Use this code.
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.main, menu);
     return true;
 }


text:
Q: Android VideoView or SurfaceView to play videos? which one should I use to weigh less in the device system and battery, the VideoView or the SurfaceView ?
Thanks

A: VideoView uses a SurfaceView. In your areas of concern, they are equal.


text:
Q: Unity - Gameobject look at mouse I've ran into a problem.
The basic setup I have right now, two objects: my camera, and my player object.
The player moves via Transform on WASD, and is supposed to rotate on mouse
movement.
The camera is top down (At a slight "3ps" style angle, which keeps the player object centre to the camera's perspective, and rotates according to the players rotation.
This is the players movement script:
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public int playerSpeed = 8;  //players movement speed

    void Update () {
        if (Input.GetKey ("w"))
        {
            transform.Translate (Vector3.forward * Time.deltaTime * playerSpeed); //move forward
        }
        if (Input.GetKey ("s"))
        {
            transform.Translate (Vector3.back * Time.deltaTime * playerSpeed); //move backwards
        }
        if (Input.GetKey ("a"))
        {
            transform.Translate (Vector3.left * Time.deltaTime * playerSpeed); //move left
        }
        if (Input.GetKey ("d"))
        {
            transform.Translate (Vector3.right * Time.deltaTime * playerSpeed); //move right
        }
    }
}

This is the players rotation script:
using UnityEngine;
using System.Collections;

public class mouseLook : MonoBehaviour {
    private Vector3 inputRotation;
    private Vector3 mousePlacement;
    private Vector3 screenCentre;

    void Update () {
        FindCrap();
        transform.rotation = Quaternion.LookRotation(inputRotation);
    }

    void FindCrap () {
        screenCentre = new Vector3(Screen.width * 0.5f,0,Screen.height * 0.5f);
        mousePlacement = Input.mousePosition;
        mousePlacement.z = mousePlacement.y;
        mousePlacement.y = 0;
        inputRotation = mousePlacement - screenCentre;
    }
}

The result of everything I have shown is it rotates, but it doesn't rotate true to where the mouse physically is.
While I draw circles with the mouse, it will do full rotations, but not consistently point to where the mouse is. I'm not sure as to why.
The desired result is for the camera (child of player object) to follow the players movement and rotation, while the player moves with its movement script, and rotates to point true to where the mouse is.
Anyone got any ideas? Thanks in advance.
Edit: if it helps, the current rotation works like this.
drawing large circles with the mouse around the player gives a slower rotation, than extremely tight circles around the player.

A: I'm not sure If I understand what you are trying to do. If you are trying to do something similar to the game "Dead Nation", then I would suggest something like this:
MouseLook.cs
void Update()
{
    Vector3 mouse = Input.mousePosition;
    Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3(
                                                        mouse.x,
                                                        mouse.y,
                                                        player.transform.position.y));
    Vector3 forward = mouseWorld - player.transform.position;
    player.transform.rotation = Quaternion.LookRotation(forward, Vector3.up);
}

If you want the camera to move and rotate along with the player then just make the camera a child of the player object.

A: a sollution that worked for me but its in 2D
also dont make the camera a child of the player but use a slurping script as shown in this video.
https://www.youtube.com/watch?v=MFQhpwc6cKE&t=3s&ab_channel=Brackeys
public Camera cam;
Transform my;

void Awake()
{
    cam = Camera.main;
    my = GetComponent<Transform>();
}

void Update()
{
    // Distance from camera to object.  We need this to get the proper calculation.
    float camDis = cam.transform.position.y - my.position.y;

    // Get the mouse position in world space. Using camDis for the Z axis.
    Vector3 mouse = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camDis));

    float AngleRad = Mathf.Atan2(mouse.y - my.position.y, mouse.x - my.position.x);
    float angle = (180 / Mathf.PI) * AngleRad;

    my.rotation = Quaternion.Euler(0, 0, angle);
}


text:
Q: In CrafterCMS, how can I publish a content through an API? I'm trying to write a bash script that would publish a list of files already present in crafter.
Is there an API to do that? And I suppose you need to be logged in first.
Thank you

A: Try using the Bulk Publish API, like this:
POST /api/1/services/api/1/deployment/bulk-golive.json?site={siteName}&path={path}&environment={env}
You will need to be logged in, so login and save the cookie to use when calling this API.

A: Adding to sumerz response you could use this to log in
curl -i -b cookies.txt -H "Content-Type:application/x-www-form-urlencoded" -H "Accept:application/json, text/plain, */*"  -c cookies.txt -X POST -d "username=admin&password=admin" http://localhost:8080/studio/api/1/services/api/1/user/login.json

then you could use -b and -c to make curl aware of a session.


text:
Q: restar items entre tablas en django python Hola soy nuevo en esto y tengo la siguiente pregunta: ¿como puedo descontar items de las siguientes tablas? restar cantidad a EntregaItem desde la tabla DevolucionItem.
Modelos Entrega y EntregaItem
class Entrega(models.Model):
   creador = models.CharField(max_length=30, blank=True)
   fecha_entrega = models.DateField(default=datetime.now)
   contrato = models.ForeignKey('contrato.Contrato', on_delete=models.CASCADE,
              related_name='contratoentrega')

class EntregaItem(models.Model):
   entrega = models.ForeignKey(Entrega, on_delete=models.CASCADE, null=True)
   item = models.ForeignKey('equipos.Equipos', on_delete=models.SET_NULL, null=True)
   codigo = models.CharField(max_length=50, default='-')
   cantidad = models.IntegerField(default=0)

Modelo Devolucion y DevolucionItem
class Devolucion(models.Model):
   creador = models.CharField(max_length=30, blank=True)
   fecha_devol = models.DateTimeField(default=datetime.now)
   contrato = models.ForeignKey('contrato.Contrato', on_delete=models.CASCADE,
              related_name='contratodevol')
   dias_arriendo = models.IntegerField(default=0)

class DevolucionItem(models.Model):
   devolucion = models.ForeignKey(Devolucion, on_delete=models.CASCADE, null=True)
   item = models.ForeignKey('equipos.Equipos', on_delete=models.SET_NULL, null=True)
   codigo = models.CharField(max_length=50, default='-')
   cantidad = models.IntegerField(default=0)

Lo estoy tratando de hacer de la siguiente forma y no me resulta.
class DevolucionCreate(CreateView):
   def get_success_url(self):
       id_itemdevolucion = DevolucionItem.objects.\
                           filter(devolucion__contrato_id=self.contrato_id)
       for x in id_itemdevolucion:
           cant_entr = EntregaItem.objects.filter(id=x.item_id)
           for z in cant_entr:
               resta = z.cantidad - x.cantidad
               update = EntregaItem.objects.values('cantidad').\
                        filter(id=x.item_id).update(cantidad=resta)
    return reverse_lazy('devolucion:devolucion-list')

Espero me puedan ayudar, llevo varios días con esto :-/ (al parecer no se como hacer los querysets correctos para filtar y llegar a los campos.
Agrego la vista:
class DevolucionCreate(CreateView):
def get_success_url(self):
    id_itemdevolucion = DevolucionItem.objects.\
        filter(devolucion__contrato_id=self.contrato_id)
    for x in id_itemdevolucion:
        cant_entr = EntregaItem.objects.filter(id=x.item_id)
        for z in cant_entr:
            resta = z.cantidad - x.cantidad
            update = EntregaItem.objects.values('cantidad').\
                filter(id=x.item_id).update(cantidad=resta)
    return reverse_lazy('devolucion:devolucion-list')

Esta seria la vista que se envian los datos a traves de ajax
class DevolucionCreate(SuccessMessageMixin, CreateView):
    model = Devolucion
    form_class = DevolucionForm
    template_name = 'devolucion/devolucion_form.html'

    def get_success_url(self):
        success_message = 'devolucion creada correctamente'
        messages.success(self.request, (success_message))
        return reverse_lazy('devolucion:devolucion-list')

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):

        data = {}
        try:
            action = request.POST['action']

            if action == 'search_equipos':
                data = []
                equipos = Equipos.objects.filter(codigo__icontains=request.POST['term'])[0:20]

                for i in equipos:
                    item = i.toJSON()
                    item['text'] = i.codigo  # valores Select2
                    data.append(item)

            elif action == 'add':
                devolucion = json.loads(request.POST['listado'])
                devol = Devolucion()
                devol.nombre_empresa_id = devolucion['nombre_empresa']
                devol.n_contrato_id = devolucion['n_contrato']  # no se esta enviando este dato
                devol.servicio_id = devolucion['servicio']
                devol.fecha_devol = devolucion['fecha_devol']
                devol.numero_guia = devolucion['numero_guia']
                devol.save()
                for i in devolucion['equipos']:
                    items = DevolucionItem()
                    items.devolucion_id = devol.id
                    items.item_id = i['id']
                    items.codigo = i['codigo']
                    items.cantidad = int(i['cantidad'])
                    items.save()

            else:
                data['error'] = 'No ha ingresado nada'
        except Exception as e:
            data['error'] = str(e)
        # messages.success(request, 'Listado creado correctamente')
        return JsonResponse(data, safe=False)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['action'] = 'add'
        context['det'] = []
        return context

A: Para hacerlo, en el bucle for de tu vista debe ser así:
for i in devolucion['equipos']:
    items = DevolucionItem()
    items.devolucion_id = devol.id
    items.item_id = i['id']
    items.codigo = i['codigo']
    items.cantidad = int(i['cantidad'])
    items.save()

    # Hacemos la operacion
    entrega_item = EntregaItem.objects.get(item_id = items.item.id)
    entrega_item.cantidad = abs(entrega_item.cantidad - items.cantidad)
    entrega_item.save()

La única manera en que se "relacionan" por así decirlo, el modelo DevolucionItem y el modelo EntregaItem, es atraves del modelo Equipos, asi que atraves de el es la única manera de obtener la instancia del modelo EntregaItem indicada (o eso espero xD, ya que no adjuntaste el modelo Equipos).
Por otra parte al momento de crear la instancia del modelo DevolucionItem, puedes hacerlo asi:
items = DevolucionItem(
    devolucion_id = devol.id,
    item_id = i['id'],
    codigo = i['codigo'],
    cantidad = int(i['cantidad'])
)

Es mucho mas simple, ademas de que se crea la instancia y ya se inicialisan todos los atributos de una.
Espero haberte ayudado.


text:
Q: Show on a window (awt/swing) what I system.out.prinlt() I have a void method that prints some stuff. Can (swing)TextField be filled with the content of my print, somehow? Or should I use something different?
if my method prints:
Hello
how
are
you?

I would like to show on the window, exactly that. Thank you.
private class ButtonListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        label.setText(instance.voidMethodThatPrints());
    }
}

It does not work cause setText takes a string, so I was trying to ask you if there's a faster way to make it work.

A: What's wrong with textArea.append(text)? Call it with appropriate arguments and get what you need.

A: You can use System.setOut(PrintWriter pw) to redirect the standard output. However you'll have to write some additional logic to make it go to a text area (since there's no setOut(JTextArea jt) method).
Edit: This approach is not recommended for your situation. The correct approach in your case would be to redesign your code, such as suggested by I-LOVE-2-REVIVE in the comments.


text:
Q: Json Path sum functions for List of List I am using JSON path to do something similar to this:
I have copied the JSON path example, but modified the price field to represent price Year-over-Year (number to array).
{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": [ 1, 2, 3 ]
      },
      {
        "category" :"fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": [ 1, 2, 3 ]
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": [ 1, 2, 3 ]
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": [ 1, 2, 3 ]
      }
    ],
    "bicycle": {
      "color": "red",
      "price": [ 1, 2, 3 ]
    }
  },
  "expensive": 10
}

What I want to find is the year over year total price for all the books.
I can get a Array of Array (lets say res) using: $.store.book[*].price
Output:
[
   [ 1, 2, 3 ],
   [ 1, 2, 3 ],
   [ 1, 2, 3 ],
   [ 1, 2, 3 ]
]

I want to further reduce this output (by sum) to:
[4, 8, 12] // Sum up nth element of each array.
           // (res[0][0] + res[1][0] + res[2][0] + res[3][0] = 4 ... and so on)

Is there a way to achieve this using jsonpath (preferred)/any other JavaScript syntax ?

A:

let data = [
  [ 1, 7, 3 ],
  [ 2, 6, 3 ],
  [ 3, 5, 3 ],
  [ 4, 4, 3 ]
]

let result = data[0].map((_, colIndex) => data.map(row => row[colIndex]))
                    .map(value => value.reduce((acc, value) => acc + value, 0))

console.log(result)   // [ 10, 22, 12 ]

The first map transposes rows and columns, the second map sums up what after the transpose are the rows.

A:

const data = {
  "store": {
    "book": [{
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": [1, 2, 3]
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": [1, 2, 3]
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": [1, 2, 3]
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": [1, 2, 3]
      }
    ]
  }
}

const prices = []

data.store.book.forEach(book => {
  book.price.forEach((price, index) => {
    if (!prices[index]) prices[index] = 0;
    prices[index] += price;
  })
})

console.log(prices)

A: You can use some .map() and Array.prototype.reduce() paired with comma operator.

const a = { "store": { "book": [{ "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": [1, 2, 3] }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": [1, 2, 3] }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": [1, 2, 3] }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": [1, 2, 3] } ], "bicycle": { "color": "red", "price": [1, 2, 3] } }, "expensive": 10 }.store.book

console.log(a.map(x=>x.price).reduce((x,y)=>(y.map((i,z)=>x[z]+=y[z]),x)))

A: You can sum each of the columns in the matrix by mapping the first row columns to a reduction of each of their subsequent rows.

const data = {"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":[1,2,3]},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":[1,2,3]},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":[1,2,3]},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":[1,2,3]}],"bicycle":{"color":"red","price":[1,2,3]}},"expensive":10};

const sumColumns = (matrix) =>
  matrix[0].map((_, col) =>
    matrix.reduce((acc, data, row) => acc + data[col], 0));

const bookPrices = data.store.book.map(({ price }) => price);

const priceSums = sumColumns(bookPrices);

console.log(priceSums); // [ 4, 8, 12 ]
.as-console-wrapper { top: 0; max-height: 100% !important; }


text:
Q: How can I abstract this repeating pattern in ASP.NET MVC 5? In my templates I've got these repeating blocks of content which I want to abstract to a single component:

Normally I would use a razor partial view for this, and pass it some variables. However in this case that would mean passing big chunks of html as variables, which doesn't seem wise.
I've found this article: http://www.growingwiththeweb.com/2012/09/custom-helper-for-surrounding-block-in.html, which explains how to create block helpers. It's a little closer to what I'm trying to do, but it still requires me to define the html as a string, which is not what I want (as the amount of html is sizeable enough for it to become unmaintainable).
From what I understand I can't use layouts for this either, because the components occur multiple times on one page. So my question is: how can I abstract the pattern above to a single reusable component, which I can reuse on a page, which accepts multiple areas of html and accepts variables?

A: So what works for me is using a razor @helper. The code below goes in your App_Code, where you create the file YourComponentName.cshtml. In that file use the following markup:
@using System.Web.Mvc;

@helper Render(
  ViewContext context,
  string title = "Default title",
  Func<object, object> header = null,
  Func<object, object> content = null,
  Func<object, object> footer = null
)
{

@title

    @if (header != null) { @header.DynamicInvoke(context); }

    @if (content != null) { @content.DynamicInvoke(context); }

    @if (footer != null) { @footer.DynamicInvoke(context); }

}

Then you can use the component in your templates with:
  @YourComponentName.Render(
    ViewContext,
    title: "Title",
    header: @
Markup for the header
,
    content: @
The content
,
    footer: @
Markup for the footer

  )


text:
Q: Finding Shortest Paths of weighted graph using stacks I will be given some kind of this graph as in the picture below. I've searched some algorithms but it seams as if it is something impossible for me to figure them out. In fact using Floyd–Warshall algorithm it is kinda of possible, but unfortunately I'm only allowed to use stacks (instead of matrices). I also looked for Dijkstra's algorithm but I could not get the relationship with my problem.
Clearly my aim is to get all shortest paths from one point to another one. As I mentioned I will just output the solution from my stack in a vector string. I guess I have to visit each node and what I am most afraid is of getting stacked in a loop or even loosing the track during the search.
Also note that this is not a directed graph. If  Dijkstra's algorithm is applicable here I would be very grateful if anyone of you would guide me and I would really appreciate any help, suggestion, idea or even a vision for not getting stacked in a loop or loosing the track while searching.
Thanks in advance.

A: If you just want to have values of all shortest paths from some chosen node to all other nodes you will be fine with Dijkstra algorithm -- it is basically augmented BFS. Once you get the idea behind BFS you should not have any problems with understanding Dijkstra. Actually it is much easier to implement BFS with a single queue than with arrays.
Is it some formal (school?) requirement that you have to use stacks. If so it is rather strange... But you can still emulate -- in totally inefficient way -- a queue with two stacks.
(btw. DFS uses stack)
If you want to have all all shortest paths from all nodes to all other nodes, you can just run Dijkstra from each node or you can try Bellman-Ford which is bit faster, but a little bit harder to grasp.
If you want just a shortest path from a single node to some other node, (bit augmented) bidirectional BFS will be the best choice.
If you have Silverlight plugin, you can try this little application in 50% written by me:
http://grzesiaka.home.pl/GraphTutor/ you will find there a presentation step-by-step of algorithms you are interested in (with data structures and pseudo-code). Hopefully it helps you!


text:
Q: (cocos2d sneaky input) when setting joystick position with touchLocation, sprite won't move i want to let user choose where the joystick should be. i.e., when user touch at one location, the joystick will appear there and ready to use and will remove when finger released.
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if ([self getChildByTag:kTagJoyStick] == nil) {
        [self addJoystickWithPosition:[Helper locationFromTouches:touches]];
    }

}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if ([self getChildByTag:kTagJoyStick] != nil) {
        [self removeChildByTag:kTagJoyStick cleanup:YES];
    }

}
-(void) ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self ccTouchesEnded:touches withEvent:event];
}

(do nothing in ccTouchesMoved method)
the update methods for joystick is:
-(void) sneakyUpdate {

    if ([self getChildByTag:kTagJoyStick] != nil) {
        if (joystick.velocity.x < 0) {
            [self controlLeft];
        }
        else if (joystick.velocity.x > 0) {
            [self controlRight];
        }
        else {
            [self controlStop];
        }

    }
    else {
        [self controlStop];
    }

}

but the result is, the joystick will appear and auto remove. but my sprite won't move. ( i set the break point, the sneakyUpdate method did get called. but the joystick.velocity is always 0. (and the thumbSprite didn't follow our finger.
please help me.
update:
and it turns out that i have to use 2 fingers (one for touch once and let the joystick show up, move my finger away, and then use another finger to control the joystick)

A: I'm not 100% sure, but I think you should use ccTouchBegan instead ccTouchesBegan, because sneakyJoystick classes use ccTouchBegan/Moved/Ended/Cancelled. Also, there are for a single touch, that is what you want.
I hope it works!

A: It looks like the problem is in your joystick class.  Every joystick implementation I've seen uses the ccTouchesBegan method to activate the joystick, then in the ccTouchesMoved method, it makes sure its activated before using it.  The problem I am seeing is that you create and add the joystick AFTER the touches began method, meaning your joystick never 'activates'. One way of bypassing this is to do all of the joystick's ccTouchesBegan functions in the method that creates the joystick, and 'activate' it from there by passing a reference to the touch that will be using it.


text:
Q: Shell script search for a literal dollar sign next to a variable name When searching through code, I'm trying to write a regular expression that needs to search for a literal dollar sign immediately preceding a variable.
$ cat file1
a
b
c
$c1
$c2
d
$c-falaffel
$f

I want a grep expression that, when passed "c", returns:
$c1
$c2
$c-falaffel

What I have so far:
mode="c"
grep "\\$${mode}" file1

But the shell keeps interpreting $$ as asking for the pid.  How in hell do you search an expression that is defined in a variable with a literal dollar sign in front??
Oh, and it has to be good in POSIX-compliant shells (it needs to run on the busybox shell), so bashisms are not acceptable.

A: you've got one too many backslashes
$ mode="c"
$ grep "\$$mode" file1
$c1
$c2
$c-falaffel
$

tested in bash 4.2.20, ksh 93u+, and zsh 5.0.5

A: This might be close to what you need:
awk -v RS= -v var="$mode" 'sub(".*if [$]" var "_mode","")' "$0"

or maybe this:
awk -v RS= -v var="$mode" 'match($0,"if [$]" var "_mode"){print substr($0,RSTART)}' "$0"

Once you post some input and output we'll have a better idea.

A: Very similar to Ed Morton's answer: you have to build the string.
search_string='$'
search_string="${search_string}$mode"
grep "$search_string" file1


text:
Q: Animation UIImage shortcut? Hey guys first question posted!
I just started with Obj-C and I am doing my first animation. My animation consist of 60 images of 2 seconds but I am finding a bit tedious to state every single image within my code.
 self.backgroundImageView.animationImages = [NSArray alloc] initWithObjects:
    [UIImage imageNamed:@"CB00001"],
    [UIImage imageNamed:@"CB00002"],
    [UIImage imageNamed:@"CB00003"],
    [UIImage imageNamed:@"CB00004"],
    [UIImage imageNamed:@"CB00005"],
    [UIImage imageNamed:@"CB00006"],
    [UIImage imageNamed:@"CB00007"],
    [UIImage imageNamed:@"CB00008"],
    [UIImage imageNamed:@"CB00009"],
    [UIImage imageNamed:@"CB00010"],
    ....
    [UIImage imageNamed:@"CB00060"],

Is there any shortcut for this?!?!?

A: for (NSInteger i = 1; i < 61; i++) {
    NSString *imageName = [NSString stringWithFormat:@"CB%05ld", (long)i];
    //init your image with the name here.
    //...
}

Format integer with %ld and 05 means the width of the format string is 5, if length less than 5, insert leading 0.

A: NSMutableArray *array = [NSMutableArray new];
for (int a = 1; a <= 60; a++) {
    [array addObject:[UIImage imageNamed:[NSString stringWithFormat:@"CB%05i", a]]];
}

self.backgroundImageView.animationImages = array;