text:
Q: How to get Fee Payer of a transaction? from TransactionResponse object I am trying to make a small public script to fetch the initial minter of a token or a list of tokens.
The easiest way is to fetch the transaction that matches with the correct program id and get the fee payer because, in 99.99% of the cases, the fee payer is the minter itself.
I am trying to get the fee payer from a TransactionResponse object.
I can see that transaction.transaction.message.accountKeys[0] gives the fee payer but I couldn't find any resource to verify that the first account in accountKeys array is always the fee payer.
Is this way safe? If not, is there any other convenient way to fetch the fee payer of a transaction?

A: The payer is always the first account referenced, and the first signature is by the fee payer.
Here's a reference in the message code:
In the `Message` structure, the first account is always the fee-payer,

Excerpted from https://github.com/solana-labs/solana/blob/c419845cfeb1c7ab9ca959de66e90b9dacbc25b7/sdk/program/src/message/legacy.rs#L90
You can follow along the (slightly complicated) logic in JS: https://github.com/solana-labs/solana/blob/c419845cfeb1c7ab9ca959de66e90b9dacbc25b7/web3.js/src/transaction.ts#L415


text:
Q: bash: different behaviour of script and in terminal (loop over files) I'm trying to loop over files with having different searching conditions based on the folder which I used with a case statement.
basically it's:
#!/bin/bash
case folder in
  "Testordner")
     search_filename=*_0_*.txt
      ;;
  "Ordner2")
     search_filename=*_65_*fg*.txt
     ;;
  *)
     ;;
esac
for files in $search_filename; do
  echo $files
done

I had expected to get a list of the files fitting to the search criterium in the last echo. Instead I get the search criterium itself.
For testing I tried F="*.txt";for files in $F;do echo $files;done directly in the bash (which worked and I got a list of files) and in the same script (which got me the output *.txt
Already tried different variable expansion stuff (e.g. $(..) ((..)) ${..}, which all did not work.)
Why is that and how can I get around?
Would be great to find help.
Best wishes
Caro

using Ubuntu 22.04LTS, KDE/plasma desktop; bash v5.1.16(1). Terminal: konsole v21.12.3

A: In Bash, and with nullglob disabled (generally the default), a glob pattern will evaluate/expand to itself in the case of no matches (e.g., *.txt evaluates to the literal string *.txt).  With nullglob enabled (often preferable for scripts), a glob pattern evaluates/expands to an empty string in the case of no matches.
If your script is run from different directories, your globs will expand differently (unless, of course, the same filenames exist in each of those directories).
For example:
user@host:~ 0 $ touch {a,b,c}.log
user@host:~ 0 $ ls -l
total 0
-rw-------  1 user  staff  0 Jul 25 10:27 a.log
-rw-------  1 user  staff  0 Jul 25 10:27 b.log
-rw-------  1 user  staff  0 Jul 25 10:27 c.log
user@host:~ 0 $ shopt nullglob
nullglob        off
user@host:~ 1 $ echo *.log
a.log b.log c.log
user@host:~ 0 $ echo *.bak
*.bak
user@host:~ 0 $ shopt -s nullglob
user@host:~ 0 $ shopt nullglob
nullglob        on
user@host:~ 0 $ echo *.log
a.log b.log c.log
user@host:~ 0 $ echo *.bak

user@host:~ 0 $

On an unrelated note...  Perhaps consider habitualizing intentional quoting, at least whenever appropriate; e.g., echo "$files", as opposed to echo $files to improve command-line safety and whitespace handling.
If interested, use of arrays may also be desirable; e.g.,
#!/bin/bash -e

export PATH=/bin:/sbin:/usr/bin:/usr/sbin
shopt -s nullglob

declare -a files=()
case "$1" in
    'logs')
        files=(*.log)
        ;;
    'baks')
        files=(*.bak)
        ;;
    *)
        echo 'invalid argument' 1>&2
        exit 1
        ;;
esac

for f in "${files[@]}"; do
    echo "$f"
done

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to draw object values into a listview in android How do I draw the values from objects that I construct with a dialog and put them into a listview.
For instance; I have an object called
digitalControlObject(int, int, bool, bool).

Now when the user constructs these objects via a dialog box with corresponding input UI to (int, int, bool, bool)
I want to take those objects and add them to a listview - which will then fill in four rows for that object with the corresponding (int, int, bool, bool)
For instance
Row one would be like this:
Table Row |Pin Number |Pin Type |Pin Status |Pin Mode
------------------------------------------------------
Row 1     | 13        | 0       | ON        | ON

So; for instance, whenever I hit a button that is next to the listview; the dialog box will appear and allow for me to construct another digitalControlObject... then when I submit that dialog box it should append another row in alignment with that data set.
EDIT:
So I tried this as code:
    package com.example.ioiocontroller;

import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;

public class digitalFragment extends Fragment {
    ArrayList<digitalControlObject> digitalList;
    ListView digitalListView;
    View digitalFragmentView;
    ArrayAdapter listAdapter;
    Button addDigital;
    Button removeDigital;
    public digitalFragment() {
        // TODO Auto-generated constructor stub
    }

    public View onCreateView(LayoutInflater viewInflation, ViewGroup container,
            Bundle SavedInstantState) {

        digitalFragmentView = viewInflation.inflate(
                R.layout.digitalfragment_page, container, false);

        addDigital = (Button) digitalFragmentView
                .findViewById(R.id.digitalAddition);
        removeDigital = (Button) digitalFragmentView
                .findViewById(R.id.digitalRemoval);
        digitalListView = (ListView) digitalFragmentView
                .findViewById(R.id.digitalListView);

        // ADDITION CLICK METHOD FOR DIGITAL IO
        addDigital.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                    listAdapter = new ArrayAdapter(getActivity(), R.layout.digitallistview_layout);
                    digitalListView.setAdapter(listAdapter);
                    digitalList.add(new digitalControlObject(0, true, true, 0));

                    listAdapter.notifyDataSetChanged();
                // create and pass the digitalControlObject to the main activity

            }
        });

        // REMOVAL CLICK METHOD FOR DIGITAL IO
        removeDigital.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        return digitalFragmentView;
    }

    public ListView getDigitalListView() {
        return digitalListView;
    }

    public void setDigitalListView(ListView digitalListView) {
        this.digitalListView = digitalListView;
    }

    public View getDigitalFragmentView() {
        return digitalFragmentView;
    }

    public void setDigitalFragmentView(View digitalFragmentView) {
        this.digitalFragmentView = digitalFragmentView;
    }

}

However when I compile and run and hit the button for the onclick view I get a nullpointer error?
EDIT 2:
Even with those changes it doesn't work; here's my most recent code ... I still get a nullpointer
public View onCreateView(LayoutInflater viewInflation, ViewGroup container,
            Bundle SavedInstantState) {

        digitalFragmentView = viewInflation.inflate(
                R.layout.digitalfragment_page, container, false);

        addDigital = (Button) digitalFragmentView
                .findViewById(R.id.digitalAddition);
        removeDigital = (Button) digitalFragmentView
                .findViewById(R.id.digitalRemoval);
        digitalListView = (ListView) digitalFragmentView
                .findViewById(R.id.digitalListView);
        listAdapter = new ArrayAdapter(getActivity(), R.id.digitalListView);
        digitalListView.setAdapter(listAdapter);

        // ADDITION CLICK METHOD FOR DIGITAL IO
        addDigital.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                digitalList.add(new digitalControlObject(0, true, true, 0));

                listAdapter.notifyDataSetChanged();
                // create and pass the digitalControlObject to the main activity

            }
        });

        // REMOVAL CLICK METHOD FOR DIGITAL IO
        removeDigital.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        return digitalFragmentView;
    }

EDIT 3:
With this latest code I get an instantaneous crash
    package com.example.ioiocontroller;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class digitalFragment extends Fragment {
    ArrayList<String> digitalList;
    ListView digitalListView;
    View digitalFragmentView;
    Button addDigital;
    Button removeDigital;

    public digitalFragment() {
        // TODO Auto-generated constructor stub
    }

    public View onCreateView(LayoutInflater viewInflation, ViewGroup container,
            Bundle SavedInstantState) {

        digitalFragmentView = viewInflation.inflate(
                R.layout.digitalfragment_page, container, false);

        addDigital = (Button) digitalFragmentView
                .findViewById(R.id.digitalAddition);
        removeDigital = (Button) digitalFragmentView
                .findViewById(R.id.digitalRemoval);
        digitalListView = (ListView) digitalFragmentView
                .findViewById(R.id.digitalListView);
        final MyAdapter adapter = new MyAdapter(getActivity(), R.id.title, digitalList);
        digitalListView.setAdapter(adapter);;

        // ADDITION CLICK METHOD FOR DIGITAL IO
        addDigital.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                digitalList.add("TEST");

                adapter.notifyDataSetChanged();
                // create and pass the digitalControlObject to the main activity

            }
        });

        // REMOVAL CLICK METHOD FOR DIGITAL IO
        removeDigital.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        return digitalFragmentView;
    }

    public ListView getDigitalListView() {
        return digitalListView;
    }

    public void setDigitalListView(ListView digitalListView) {
        this.digitalListView = digitalListView;
    }

    public View getDigitalFragmentView() {
        return digitalFragmentView;
    }

    public void setDigitalFragmentView(View digitalFragmentView) {
        this.digitalFragmentView = digitalFragmentView;
    }
//////////////////////////////////////////////////////////////////////////////////
    public class MyAdapter extends ArrayAdapter<String> {

        private Context context;

        public MyAdapter (Context context, int textViewResourceId, List<String> items) {
            super(context, textViewResourceId, items);
            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.item_row, null);
            }

            String item = getItem(position);
            if (item!= null) {
                TextView itemView = (TextView) view.findViewById(R.id.title);
                if (itemView != null) {
                    itemView.setText("Item: " + item + " in position " + position);
                }
             }

            return view;
        }
    }

}

Here is the logcat:
02-27 12:58:10.173: E/Trace(9958): error opening trace file: No such file or directory (2)
02-27 12:58:10.173: D/jdwp(9958): sendBufferedRequest : len=0x4B
02-27 12:58:10.190: D/dalvikvm(9958): open_cached_dex_file : /data/app/com.example.ioiocontroller-1.apk /data/dalvik-cache/data@app@com.example.ioiocontroller-1.apk@classes.dex
02-27 12:58:10.193: D/ActivityThread(9958): BIND_APPLICATION handled : 0 / AppBindData{appInfo=ApplicationInfo{417cecb8 com.example.ioiocontroller}}
02-27 12:58:10.262: D/dalvikvm(9958): GC_FOR_ALLOC freed 54K, 11% free 6279K/7027K, paused 19ms, total 19ms
02-27 12:58:10.268: I/dalvikvm-heap(9958): Grow heap (frag case) to 7.678MB for 1536016-byte allocation
02-27 12:58:10.289: D/dalvikvm(9958): GC_FOR_ALLOC freed 1K, 10% free 7778K/8567K, paused 20ms, total 20ms
02-27 12:58:10.310: D/dalvikvm(9958): GC_CONCURRENT freed <1K, 10% free 7778K/8567K, paused 2ms+2ms, total 21ms
02-27 12:58:10.337: D/ActivityThread(9958): ACT-AM_ON_RESUME_CALLED ActivityRecord{417d02e0 token=android.os.BinderProxy@417cfaa8 {com.example.ioiocontroller/com.example.ioiocontroller.MainActivity}}
02-27 12:58:10.344: D/ActivityThread(9958): ACT-LAUNCH_ACTIVITY handled : 0 / ActivityRecord{417d02e0 token=android.os.BinderProxy@417cfaa8 {com.example.ioiocontroller/com.example.ioiocontroller.MainActivity}}
02-27 12:58:10.365: D/AbsListView(9958): checkAbsListViewlLogProperty get invalid command
02-27 12:58:10.366: D/AndroidRuntime(9958): Shutting down VM
02-27 12:58:10.366: W/dalvikvm(9958): threadid=1: thread exiting with uncaught exception (group=0x411b7908)
02-27 12:58:10.370: E/AndroidRuntime(9958): FATAL EXCEPTION: main
02-27 12:58:10.370: E/AndroidRuntime(9958): java.lang.NullPointerException
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.widget.ListView.setAdapter(ListView.java:466)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at com.example.ioiocontroller.digitalFragment.onCreateView(digitalFragment.java:41)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.View.measure(View.java:15264)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.View.measure(View.java:15264)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.View.measure(View.java:15264)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2163)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.View.measure(View.java:15264)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2131)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1435)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4650)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.Choreographer.doCallbacks(Choreographer.java:567)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.Choreographer.doFrame(Choreographer.java:536)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.os.Handler.handleCallback(Handler.java:615)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.os.Looper.loop(Looper.java:153)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at android.app.ActivityThread.main(ActivityThread.java:4987)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at java.lang.reflect.Method.invokeNative(Native Method)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at java.lang.reflect.Method.invoke(Method.java:511)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
02-27 12:58:10.370: E/AndroidRuntime(9958):     at dalvik.system.NativeStart.main(Native Method)

A: You should create a ListView with a custom row layout with four TextViews where you can put the data. Some examples here and here. On this way you can create something like this:

Then you just have to keep adding data to your ListAdapter to add new rows to the ListView

Responding to your edited answer, without Logcat is a guess, I think the problem is here:
listAdapter = new ArrayAdapter(getActivity(), R.layout.digitallistview_layout);

The best way to test this is creating a simple adapter with a row_layout.xml for each row in the ListView:
public class MyAdapter extends ArrayAdapter<String> {

    private Context context;

    public MyAdapter (Context context, int textViewResourceId, List<String> items) {
        super(context, textViewResourceId, items);
        this.context = context;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.item_row, null);
        }

        String item = getItem(position);
        if (item!= null) {
            TextView itemView = (TextView) view.findViewById(R.id.title);
            if (itemView != null) {
                itemView.setText("Item: " + item + " in position " + position);
            }
         }

        return view;
    }
}

This will be your xml item_row.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/title"/>

</LinearLayout>

So to use this:
digitalList.add(new digitalControlObject(0, true, true, 0));

MyAdapter adapter = new MyAdapter(getActivity(), R.id.title, digitalList);
digitalListView.setAdapter(adapter);

And this digitalList has to be inside your digitalfragment_page layout because is the one you are inflating in your Fragment

A: You need to define a layout with textviews required along with layout with listview. And for the updating of the list automatically, you should give onclicklistener to come to same page using intent
 public class showList extends Activity{

            @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.showlist);
            ListView myListView = (ListView) findViewById(R.id.listView);
            ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
                HashMap<String, String> hashMap = new HashMap<String, String>();
                int field1 = //value from dialog
                int field2 = //value from dialog
                boolean flag1 = //value from dialog
                boolean flag2 = //value from dialog
                hashMap.put("FIELD1", field1+"" );
                hashMap.put("FIELD2", field2+"" );
                hashMap.put("FLAG1", flag1+"" );
                hashMap.put("FLAG2", flag2+"" );
                arrayList.add(hashMap);
            ListAdapter listAdapter = new SimpleAdapter(showList.this, arrayList, R.layout.mylayout, new String[]{"FIELD1","FIELD2","FLAG1","FLAG2"},new int[]{R.id.textviewforfield1,R.id.textviewforfield2,R.id.textviewforflag1,R.id.textviewforflag2} );
            myListView.setAdapter(listAdapter);
        }
    }


text:
Q: Object condition in multiple places/repeated code (DRY) This is a fundamental application design question I've struggled with and flip-flopped on for years. We have a legacy webapp that doesn't really have a solid ORM, if that tidbit might influence your answer. To abstract my question let's say we have a class Car, and a corresponding table in our database named car. Car has a few properties: color, weight, year, maxspeed    These properties directly correspond to columns in the db table.
In our application, we define the car as "classic old" if year is < 1960 and color = black. And in many places within our app knowing whether the car is "classic old" is extremely important (maybe we're running a very illogical insurance agency which gives steep discounts and other perks to cars which are "classic old").
All over our application, we do things like:
--list all classic old cars
--give the current user a discount if their car is classic old
--list all classic old cars with max speed > 100 miles per hour
--email the current user if their car is classic old and weights more than 1000 pounds
What is the best way to go about this? We have a legacy application that does this in some places:
getOldClassicCars()

select * where year < 1960 and color = black

and in other places:
cararray = getAllCars();

for each car in cararray
      if car.year < 1960 and car.color = black
               oldcararray = car.add()

The point being that this very important, fundamental piece of our application – is the car classic old – is "hardcoded" as year < 1960 and color = black in many places. Sometimes in SQL, sometimes in application code, etc. Obviously that is not good, but as we've refactored things I'm not sure we're refactoring things the best way we can.

A: Well, you are stuck with the fundamental problem that

*

*you cant run your code on the database

*you want to be able to use the database's selection functionality on this criteria.

*you want the calculation of "classic old" to be defined in a single place (preferably code)

Lets enumerate the solutions
1: Put the calculation in a sproc and always use the sproc to retrieve cars.
The problem here is if you create a new car in code, its class status is undefined, so you haven't really solved the 'not in two places' problem.
2: Get the DB to run your calc via an assembly. for example you can get mssql to run functions from a .net assembly which you can also use in your code base to perform the same calculation.
Problem, its hard work. Plus essentially its still in two places, you have to keep the db up to date and ensure that the table is accessed correctly
3: Persist the calculated value on the DB, but perform the calc in the code
Problem, if the calculation changes the DB values will be incorrect and need updating.
3 seems to be the best option, as we will know when the calculation changes and be able to take some action to resolve the situation.
However, it might be best, given the fundamental nature of this calculation, to make that 'out of dateness' implicit in the way we structure the code.
Instead of simply persisting car.IsClassic we could add a CarStatusReport object with a datetime property. We then generate a CarStatusReport(2017) which evaluates all the cars at that point in time and saves that data in a separate table.
Our business logic is then no longer, "Is this car a classic?" but "What does the latest CarStatusReport say the status of this car is?"
You Business Logic will then reside in a single CarStatusReportGenerator service and any other logic accessing the IsClassic calculation, will be forced to acknowledge the ephemeral nature of the stored info.

A: No optimal solution here. But, one good point will be to move all the business logic into the one place. If you can't (when you make methods or functions calculating some property, for example isOld()) then hide all those inconsistencies under the hood, so implementation users (conceptually) will never notice DRY violation from outside.


text:
Q: What is the purpose of the choke in this circuit? I'm looking into modding an old battery charger, but I want to understand exactly how it works before I start. What is the purpose of the choke in this circuit?

Some people at my work have suggested the choke should be on the output of the bridge rectifier not the input - but it was obviously manufactured this way for a reason. Why would you want a choke on the AC side of a bridge rectifier?

A: Pretty sure that is there to limit the current into a largely discharged battery.
Basically it adds reactance in series with the (almost) voltage source that is the transformer so as to ensure the current does not rise to silly levels if the battery is very flat.
Another approach to the same thing that you also see in battery chargers is a transformer designed with a magnetic shunt thereby raising the leakage inductance (to largely the same effect).
Somewhat crude, not great for the power factor, but cheap and VERY robust and reliable.

A: Thus the purpose of L (depends on value)  could be to limit current in the diodes by ΔI=VΔt/L in time domain.     The diodes are often driven very hot on a heatsink.
In the frequency domain I(f)=V/(Rs+DCR+ESR+jXL(f)) but only for the duty cycle when the diodes are conducting.
Rs= Diode resistance above 0.8V
DCR= inductor DC resistance
ESR= battery ~= 5V/CCA
Transformer output impedance is low limited by mutual coupling and winding resistance.
L1 impedance Z(f)= DCR + jωL
When diode bridge BR1 is conducting just before peak AC voltage, they are also very low Resistance, Rs (which inverse to diode power rating).
The battery ESR can be even lower in the mΩ (which is inverse with Ah capacity when charged)
The battery CCA rating determines its ESR.
An automotive high current charger shown without the transformer but 16Vp


text:
Q: Update Asp.net form using stored procedures and c# i am new on visual studio trying to update my web form using store procedure and c#  i have some problems in my code
C# code
protected void Btn_update_Click(object sender, EventArgs e)
{
        SqlConnection conn = new SqlConnection(@"Data Source=mac\SQLEXPRESS;initial K Catalog=outlines_db;integrated Security=True");
        SqlCommand cmd = new SqlCommand("update_outlines", conn);
        cmd.CommandText = "update_outlines";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@title", txt_title.Text);
        cmd.Parameters.AddWithValue("@code", txt_code.Text);
        cmd.Parameters.AddWithValue("@instructor", txt_instructor.Text);
        cmd.Parameters.AddWithValue("@credit", txt_credits.Text);
        cmd.Parameters.AddWithValue("@topic1", txt_topic1.Text);
        cmd.Parameters.AddWithValue("@topic2", txt_topic2.Text);
        cmd.Parameters.AddWithValue("@topic3", txt_topic3.Text);
        cmd.Parameters.AddWithValue("@topic4", txt_topic4.Text);
        cmd.Parameters.AddWithValue("@topic5", txt_topic5.Text);
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        Response.Redirect("Grid_update.aspx");
}

Stored procedures
ALTER PROCEDURE update_outlines
    -- Add the parameters for the stored procedure here
        (
    @title varchar(100),
    @code varchar(100),
    @instructor varchar(100),
    @credit varchar(100),
    @topic1 varchar(200),
    @topic2 varchar(200),
    @topic3 varchar(200),
    @topic4 varchar(200),
    @topic5 varchar(200)

    )

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    UPDATE outline
    SET

    [course_title]= @title,
        [instructor]=@instructor,
        [credit] =@credit,
        [topic1]=@topic1,
        [topic2]=@topic2,
        [topic3]=@topic3,
        [topic4]=@topic4,
        [topic5]=@topic5
        WHERE
        [course_code]= @code

END
GO


text:
Q: php-mysql for MySQL-server (case sensitive) I don't know how but it seems there are two different versions of mysql probably from different yum repositories :
yum list | grep  mysql
MySQL-server.x86_64                        5.5.9-1.linux2.6            installed
mysql-server.x86_64                        5.1.47-1.2.amzn1            amzn

I need to install php-mysql which is available only for the version that is not installed (5.1.47-1.2.amzn1), if I run yum install php-mysql there is a conflict with the other MySQL-server (5.5.9-1.linux2.6)..
yum install php-mysql
.
.
.
Transaction Check Error:
  file /usr/share/mysql/charsets/cp1251.xml from install of mysql-libs-5.1.47-1.2.amzn1.x86_64 conflicts with file from package MySQL-server-5.5.9-1.linux2.6.x86_64

As the current MySQL-server with uppercase letters is currently installed and used in production I can't uninstall it and install the other version wehre the php-mysql package is compatible.
How can I install php-mysql for the MySQL-server (5.5.9-1.linux2.6) ? why there are two versions of mysql-servers ?
Any help will be appreciated..

A: I just had a similar problem when trying to install geoip-devel (GeoIP-devel version 1.4.5 in repo extras, geoip-devel version 1.4.6 in repo rpmforge). Mine was solved by excluding the rpmforge:
yum install --disablerepo=rpmforge GeoIP-devel

I guess your problem is with several repos supplying different versions, maybe you can use yum downgrade (possibly with the --disablerepo option)?


text:
Q: npm postbuild script gives error in renaming file I have made a node script for npm postbuild that does simple task to rename the file in build folder after build is generated in a react app.
here is the file postbuild.js
let fs = require("fs");
let path = require("path");

const oldJSPath = path.join(__dirname, "build", "static", "js", "*.js");
const newJSPath = path.join(__dirname, "build", "static", "js", "bundle.js");

const oldCSSPath = path.join(__dirname, "build", "static", "css", "*.css");
const newCSSPath = path.join(__dirname, "build", "static", "css", "bundle.css");

fs.renameSync(oldJSPath, newJSPath);
fs.renameSync(oldCSSPath, newCSSPath);

Now the problem is that I keep getting error:
ENOENT: no such file or directory, rename C:\Users\HDL\Documents\demo-redux-app\build\static\js\*.js' -> 'C:\Users\HDL\Documents\demo-redux-app\build\static\js\bundle.js
Even though file and directory does exist in the build directory
structure of build dir:
-build
  -static
    -css
      *.css
    -js
      *.js

    -media
      *.png, jpg etc

Don't Know if this is essential but here is package.json :
{
  "name": "demo-redux-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-redux": "^5.0.7",
    "react-scripts": "1.1.4",
    "redux": "^4.0.0",
    "redux-promise-middleware": "^5.1.1",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "postbuild": "node postbuild.js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

A: Node.js fs doesn't support wildcards.
If the intention is to match the first file among *.js and rename it to bundle.js, this can be done with globs:
const globby = require('globby');

const newJSPath = path.join(__dirname, "build", "static", "js", "bundle.js");
const oldJSWildcardPath = path.join(__dirname, "build", "static", "js", "*.js");
const [oldJSPath] = globby.sync(oldJSWildcardPath);
if (oldJSPath) {
  fs.renameSync(oldJSPath, newJSPath);
}
...

Or with regexps:
const newJSPath = path.join(__dirname, "build", "static", "js", "bundle.js");
const oldJSDirPath = path.join(__dirname, "build", "static", "js");
const [oldJSPath] = fs.readdirSync(oldJSDirPath).filter(filename => /.js$/.test(filename));
if (oldJSPath) {
  fs.renameSync(oldJSPath, newJSPath);
}
...


text:
Q: How to enforce MUI styling, if it is being overwritten by a global setting? I am working on a React Component, something like a Quiz, that will be inserted into a client's webpage. I obviously don't have any say in their website's stylesheet and can't do anything about it, it is what it is. So I am wondering if there is a way to enforce the Material UI on MUI components?
Examples:

This is my development build.

And this is inside the production build, on my client's website. They have a  global setting, that is overwriting this one. Specifically they are targeting input[type="email"], which is causing me troubles.
So I am asking here if there is a way for it to enforce MUI styling.

A: Add a className props to your Material UI inputs let's say className="email-input" then create a css file add that className and to add to it the height, width and other styles you want, just like how you would do styling in normal html file then import it in your react component file.
When you add your project to your client's site the css file will be loaded after their site's css, so your styles will override theirs.


text:
Q: How do I connect a react frontend and express backend? So here is my issue in a pickle: btw I had some trouble finding out how to do this through google and I did try using StackOverflow but couldn't find the exact answer
So I have a ReactJS website where I use

yarn start

to run and it launches on localhost:3000
I want it to launch on localhost:3000 while an express server also launches on that server, aka start the react server up in express.js.
It seems like every tutorial I've found, most are outdated, and the remaining ones are guides to turn react into a static website and THEN use express. I would like to keep react on the server-side for advantage of react-router
Edit1: So basically when I have an expressjs server
THE DATABASE DETAILS HAVE BEEN REMOVED, THAT LINE ISNT AN ERROR

const express = require('express'); var app = express();
var mysql = require('mysql'); var connection =
  mysql.createConnection({   host     :
   database : 'main' });
connection.connect()
app.post('/users', function(req, res) {   var user = req.body;
    res.end('Success'); })
app.listen(3000, function(){  console.log('Express sever is listening
  on port 3000') })
//connection.end()

I also start the create-react-app server with yarn start and it launches on localhost:3000 but this expressjs server overrides that.
So I want to connect the two to be able to send post requests

A: I just recently worked on a sample repo that implements this strategy. There are a few ways this can be done, but the simplest way to do this will be to start the express server as a second server that will run on a different port, ie. 3001. You can then use concurrently to launch both the react server (I am assuming webpack) and the express API server in a single command.
Here is a tutorial that shows how this can be set up. You should pay attention to the section in this tutorial about proxying requests from the client (browser) through the webpack server. There are some considerations to think about with regards to CORS configuration if you do not proxy requests through the webpack server.
Here is my proof of concept repo where I implemented just what you are looking for:  react client, and express server. It can be run via concurrently or with docker (compose).

A: You can change the port on which express is listening:
var server = app.listen(3001, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)

Change 3001 to any valid port number


text:
Q: @font-face not finding fonts in folder I am trying to get @font-face to work within a sub domain located in the folder public_html/evansopen. I have the site http://coryfitzpatrick.com/evansopen/ running. I want to put fontsquirrel files in evansopen/fonts but they wont load when I dont have them in the same location as the styles.css and index.php (The public_html/evansopen folder). It is running fine this way currently, but I like to keep my file structure clean.
I can get images to load from /evansopen/images/putting_green_footer.gif folder with no problem like this
#footer {
    background-image: url(images/putting_green_footer.gif); background-repeat: repeat;
}

Why can I not get @font-face to direct to evansopen/fonts/ like so?
@font-face {
    font-family: 'nexa_lightregular';
        src: url('fonts/nexa_light-webfont.eot');
        src: url('fonts/nexa_light-webfont.eot?#iefix') format('embedded-opentype'),
             url('fonts/nexa_light-webfont.woff') format('woff'),
             url('fonts/nexa_light-webfont.ttf') format('truetype'),
             url('fonts/nexa_light-webfont.svg#nexa_lightregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

I have researched this quite a bit. Im sorry if this is a redundant post.

A: Example to using fontface
Your CSS file (domain.com/path/custom-font.css)
font-family: 'nexa_lightregular';
      src: url('fonts/nexa_light-webfont.eot');
      src: url('fonts/nexa_light-webfont.eot?#iefix') format('embedded-opentype'),
           url('fonts/nexa_light-webfont.woff') format('woff'),
           url('fonts/nexa_light-webfont.ttf') format('truetype'),
           url('fonts/nexa_light-webfont.svg#nexa_lightregular') format('svg');
font-weight: normal;
font-style: normal;

Your font files have to upload in

domain.com/path/fonts/nexa_light-webfont.ttf

for example
PS : It's about where is your css file, so make a /fonts/ folder in same CSS file path.
EX: domain.com/mycss.css -> domain.com/fonts/myfont.ttf


text:
Q: "No property" error while declaring superclass for Spring Data repositories I have a simple webapp that uses few spring components - Spring Boot, MVC and  Spring Data for persistence management (everything is written in Groovy build up with Gradle).
I am trying to add some common logic for all repositories as it is described in the documentation. I created the following artifacts:
GenericObjectRepository which is an interface defining my common method:
@NoRepositoryBean
interface GenericObjectRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
    String sharedCustomMethod(String name)
}

GenericObjectRepositoryImpl implementing above interface:
class GenericObjectRepositoryImpl<T, ID extends Serializable>
        extends SimpleJpaRepository<T, ID> implements GenericObjectRepository<T, ID> {

    EntityManager entityManager

    GenericObjectRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
        super(domainClass, entityManager)

        this.entityManager = entityManager;
    }

    @Override
    String sharedCustomMethod(String name) {
        "Hello ${name}"
    }
}

and finally the repository (with some random data-specific method)
@Repository
interface MarketingClientRepository extends GenericObjectRepository<MarketingClient, Long> {
    List<MarketingClient> findByLastName(String lastName);
}

The problem is that everytime I start the application, and Spring tries to instantinate MarketingClientRepository, i get the following Exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'marketingClientRepository': Invocation of init method failed;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
...
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type MarketingClient!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
...

It seems to me that Spring Data is trying to parse my method (sharedCustomMethod), extracting the shared part and tries to apply all the magic it does to every other Repository interface method (tries to access shared property on my business object - which obviously does not exist).
Thanks in advance,
EDIT 1:
I added the FactoryBean as it is said in step 3, but I failed to compile it. I don't know if it's something wrong with generics (I admit that this construction is quite complicated for me). The class code is as follows:
class GenericRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
        extends JpaRepositoryFactoryBean<R, T, I> {

    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        new GenericRepositoryFactoryBean(entityManager)
    }

    private static class GenericRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

        private EntityManager entityManager

        GenericRepositoryFactory(EntityManager entityManager) {
            super(entityManager)

            this.entityManager = entityManager
        }

        protected Object getTargetRepository(RepositoryMetadata metadata) {
            new GenericObjectRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager)
        }

        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            GenericObjectRepository.class
        }
    }
}

The compiler says:
/.../GenericRepositoryFactoryBean.groovy: 14: unable to resolve class T
 @ line 14, column 60.
   yBean<R extends JpaRepository<T, I>, T,
                                 ^

/.../GenericRepositoryFactoryBean.groovy: 14: unable to resolve class I
 @ line 14, column 63.
   an<R extends JpaRepository<T, I>, T, I e
                                 ^

2 errors

A: You basically miss step 3 in the steps required to make this work described in the reference documentation.
As the process is rather awkward, I've filed a ticket to simplify this process.


text:
Q: How to test dynamic pages using cucumber in Ruby on Rails I want to test page which has some header, text that comes from database. I want to write cucumber test to test such pages to see of the headings, text is correct as expected.
E.g: On a page I have a section to display chart. This chart has header which is coming from database. I want to test a case to check if the header text is displayed properly as expected or not.

A: Here are two approaches to this

*

*Put what you expect in the test database first then test that your application show things correctly

*Don't worry about the details of what is being displayed and just test that there is a visible placeholder for your content.
If your chart is complex and requires a lot of data then the first approach might be too difficult, so use the second approach. If the second approach doesn't provide sufficient testing for you, consider using other test tools, and other tests to proof your chart is correct e.g. your unit tests, your chart libraries unit tests etc.


text:
Q: Get email size in CakePHP My application uses a corporate SMTP server with an email size limit of 20mb. I have emails failing with error "[SocketException] SMTP Error: 552 4.3.1 Message size exceeds fixed maximum message size" when the attachments total 14.92mb.
Currently my code loops through the attached files and tallies the file size using PHP filesize() and then compares it against the hard-coded limit of 20mb. It's supposed to run separate code to tell the user if the files are too big, however, in the above example it's still less than the limit and it's generating an ugly error instead.
Is there a way I can measure the total size of the email, attachments and all? The corporate messaging team is pushing back saying that the email must be over 20mb and I would like to properly test this.
I am using CakePHP 2.3's EmailComponent. Here is a simplified version of the code:
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail('smtp');
...

$totalAttachmentsSize = 0;
$attachments = array();
//loop array with files to be attached
foreach ($files as $file) {
$totalAttachmentsSize += filesize($file['path']);
$attachments[$file['name']] = $file['path'];
}

//compare attachments size to constant defined in bootstrap.php
if ($totalAttachmentsSize < MAX_EMAIL_SIZE) {
    $email->send();
}
else {
    //handle
}

A: Attachments are being base64 encoded, which will require some more bytes, also joining them together requires a few bytes for additional headers and stuff.
To get the exact size, check the return value of CakeEmail::send(), it will contain the rendered headers and message body. Use the the DebugTransport if you don't want to actually send the mail.
$email->transport('Debug');
$contents = $email->send();

$data = $contents['headers'] . "\r\n\r\n"
      . $contents['message'] . "\r\n\r\n\r\n.";

debug(strlen($data));

This should give you the exact number of bytes of the mail as it's being sent by the SMTP transport.


text:
Q: how to use GO TO in COBOL I have the following code snippet in one of my COBOL program.
IF  FIRST < SECOND
   MOVE FIRST TO WS
END-IF.
MOVE SECOND TO WS.
MOVE WS TO RESULT.

I need to use GO TO inside the IF block to jump to the last statement (MOVE WS TO RESULT).
IF  FIRST < SECOND
   MOVE FIRST TO WS
   GO TO <last line.(MOVE WS to RESULT)>
END-IF.
MOVE SECOND TO WS.
MOVE WS TO RESULT.

in other word, i need to skip "MOVE SECOND TO WS.".
what is the simplest way to jump to a specific line in cobol?
I read somewhere that this is possible by defining a PARAGRAPH, but don't know how to define it.
It might seems very simple but I'm newbie to COBOL programming.
Thanks.
----------------* UPDATE *----------
based on @lawerence solution, is this correct?
IF  FIRST < SECOND
     MOVE FIRST TO WS
     GO TO C10-END.
  END-IF.

  MOVE SECOND TO WS.

C10-END.
MOVE WS TO RESULT.

i just moved back the last statement to be in first level.

A: GOTO can do what you're looking for, but IF/ELSE would be more direct.  You want MOVE SECOND TO WS  to run iff the IF block does not, correct?
IF  FIRST < SECOND
    MOVE FIRST TO WS
ELSE
    MOVE SECOND TO WS
END-IF.
MOVE WS TO RESULT.

I hope I got the syntax right, I have never used COBOL and just tried to work off your snippet and this example http://www.fluffycat.com/COBOL/If-and-End-If/.  There probably will be situations in the future where you need GOTO, but it A) should be avoided when another control structure will work and B) I haven't the slightest idea how its done
to be honest, COBOL looks pretty miserable lol.  ive never seen a language so verbose.  good luck with everytihng

EDIT

Mostly for joe...
Cant this all be better done with a min function?  I'm sure the syntax is wrong, but:
Move Function Min(FIRST, SECOND) to RESULT

A: OMFSM!  It is not 1974, why are you writing Cobol like that?  This:
IF  FIRST < SECOND
   MOVE FIRST TO WS
END-IF.
MOVE SECOND TO WS.
MOVE WS TO RESULT.

Has a number of problems:

*

*It uses periods to delimit scope, that is nearly three decades deprecated.

*It isn't using ELSE

*It is trying to use GO TO.

May I suggest the following as the way to approach it since 1985:
If FIRST < SECOND
  Move FIRST to WS
Else
  Move SECOND to WS
End-IF
Move WS to RESULT

But really, the code should simply read:
If FIRST < SECOND
  Move FIRST to RESULT
Else
  Move SECOND to RESULT
End-If

Unless the intermediate result is needed in WS.  Cobol 66 and 74 used GOTO and periods because they lacked modern control structures.  I realize you are a 'newbie', but you should suggest to whoever is teaching you that they really need to upgrade their skills.

A: jon_darkstar is right when it comes to improving the logic, however if you want to see how GO TO works here goes:
  IF  FIRST < SECOND
     MOVE FIRST TO WS
     GO TO C10-RESULT.
  END-IF.

  MOVE SECOND TO WS.

C10-RESULT.
  MOVE WS TO RESULT.

C10-RESULT. starts a paragraph and has to be a unique name in your code SECTION.  By convention it should also start with the same prefix as the enclosing section.  Therefore this example assumes that your code SECTION is something like C00-MAIN-PROCESS SECTION.

A: A new non-Answer has brought this silly question to light.
ELSE in the IF is the 100% obvious answer. It is deeply odd that GO TO has to be used whereas ELSE may not be used.
Another way, surprised it didn't come up:
MOVE SECOND TO WS
IF  FIRST LESS THAN SECOND
   MOVE FIRST TO WS
END-IF
MOVE WS TO RESULT

No ELSE, no GO TO. Extra MOVE executed when FIRST is less than second, though.
To include a GO TO is simple, but stupid. Add a GO TO. A GO TO has to go somewhere (unless using ALTER ... TO PROCEED TO ..., which everyone hopes you weren't), so make a label at the point you want it to arrive, and add the name of that label to the GO TO.
A label is a user-defined word. If referenced (as in this case) it must be unique within a SECTION, if you use SECTIONs, which you don't need to, otherwise unique within the program and whether referenced or not it may not be the same name as something else (like a data-definition or the internal name of a file).
A label is a procedure-name. A procedure-name should terminate with a period/full-stop and the procedure itself should also terminate with a period/full-stop.
What about the MOVE FUNCTION MIN ( ... ) ... as a solution?
Well, it works. If other staff at your site are not used to it, you will not be thanked for using it (without prior discussion, anyway).
What does it do? Well, in Enterprise COBOL, the compiler generates an extra little area, copies the first argument to that area, tests against the second argument, copies the copy of the first argument, or the second argument, whichever is relevant, to the result.
Vs the ELSE, that is an extra storage area defined, an extra instruction for addressability of that, and an extra Assembler move (MVC) plus the lack of ready recognition.
Better for programmers new to COBOL, used to a multitude of functions in other languages? Not really, as they will be soundly beaten if they don't write programs that can be understood (at 2am) by the rest of the staff.
IF FUNCTION MIN(VAR1 VAR2 VAR3 VAR4 VAR5) = 17

It's another downside of FUNCTION. You see, you can do that. Then, at 2am, when the program has crashed 32 lines later, after VAR1 and VAR3 have been changed, are you going to be able to find the result of that IF in the core dump? Maybe, maybe not. Depends if any other functions, and of what type, have been used. At 2am, you don't want that. Not at all.
On the upside, it is less typing. For those who type, rather than use the editor.

A: In our shop, we'd use the example provided by Bill Woodger.  However, we do use periods as scope-terminators.  COBOL should be structured and use the KISS principle, just like any other language.  This:

MOVE SECOND TO WS.
IF FIRST LESS THAN SECOND
    MOVE FIRST TO WS.
MOVE WS TO RESULT.

Note that this only works if we are assured that SECOND and FIRST have numeric values, or that WS is a PIC X() string, not a numeric PIC 9().
This is by far the easiest to read.  No ELSE or GO TO required.


text:
Q: Could not resolve com.paypal.sdk:paypal-android-sdk:2.15.3 Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.paypal.sdk:paypal-android-sdk:2.15.3

A: You may need to add
buildscript {
    repositories {
        mavenCentral()

    }
}

at the top of your build.gradle file


text:
Q: Probability for random rotations of the orthogonal vectors frame Let $\{A\}$ be the frame of $3$ orthogonal unit vectors $i,j,k$. The frame is rotating freely in 3D space. Origin of the frame - point $(0,0,0)$ - is fixed and endpoints of vectors are always on  the surface of the unit sphere. The movement of the frame is  random so probability of setting the frame in particular localization is the same for all possible orientations.
Question:

What is probability that
  the distance of at least one of the endpoints of vectors
  $i,j,k$ from $Oxy$ plane is less than $d$ ($0<d<1$),
  for example $d$ can be set $=0.5$.
  Opposite event would be if all endpoints of vectors
  $i,j,k$ are distanced greater than $d$ (maybe this event is simpler for consideration).

Discussion:
If we would like to calculate probability for only a single rotating vector ( for example $i$) the calculations could be based simply on describing areas  of the sphere surfaces  assigned to events $E_i$ when $d_i < d$ or $\bar{E_i}$ when $d_i \geq{d}$. But here we have $3$ vectors constrained in the way characteristic for columns of rotation matrix.
What would be the best strategy for solution of this problem ? What kind of representation of the frame should be taken (Euler angles or axis-angle representation of rotation matrix or maybe  quaternions  ?
It is rather certain that for some values of $d$ for example $d= 0.9$ probability would be equal to $1$, for $d$ near to $0$ for example $d= 0.1$ would be rather small.. between these two values function of probability for defined event would be,  can we assume ?, monotonic...
So we have two possible cases of events with every endpoint of one of the vectors $i,j,k$, but they are not independent ones but constrained in a geometrical way. How to use these geometrical constraints in the solution?

A: I'm going to compute the "opposite" probability because it is easier.

Let $\Omega$ be the probability that all $i, j, k$ are at a distance $> d$ from the plane $Oxy$.
Let $x,y,z$ be the orthogonal unit vectors for the canonical frame.
Let $R \in SO(3)$ be the rotational matrix that bring $x,y,z$ to $i,j,k$.
For any unit vector $n$, let $B(n)$ be the set of unit vectors at an angle smaller than $\theta = \cos^{-1}(d)$ to $n$. i.e.
$$B(n) = \big\{ m \in S^2 : \angle(m,n) < \theta \big\} = \big\{ m \in S^2 : m\cdot n > d \big\}
$$
For any unit vector $n = Rm\in S^2$, the condition that $n$ is at a distance $> d$ to the plane $Oxy$ is equivalent to
$$\begin{align}
n \in B(z) \cup B(-z)
\iff & n \in B(z) \lor n \in B(-z)\\
\iff & m \in B(R^{-1}z) \lor  m \in B(R^{-1}(-z)) \iff m \in B(R^{-1}z) \lor -m \in B(R^{-1}z)\\
\iff & R^{-1}z \in B(m) \cup B(-m)
\end{align}$$
So the condition that all $i = Rx, j = Ry, k = Rz$ are at a distance $> d$ to the plane $Oxy$ is equivalent to
$$R^{-1}z \in ( B(x)\cup B(-x) )\cap (B(y) \cup B(-y)) \cap (B(z)\cup B(-z))$$
Using symmetry and taking expectation over $R$, we find
$$\begin{align}\Omega
&= \frac{1}{4\pi}
\verb/Area/(( B(x)\cup B(-x) )\cap (B(y) \cup B(-y)) \cap (B(z)\cup B(-z))\\
&= \frac{2}{\pi}\verb/Area/(B(x)\cap B(y) \cap B(z))
\end{align}$$
Let $T = B(x) \cap B(y) \cap B(z)$.

*

*For $d > \frac{1}{\sqrt{3}}$, $T = \emptyset$ and  $\Omega = 0$.

*For $d < \frac{1}{\sqrt{3}}$, $T$ forms a spherical triangle with vertices at
$$A = (\sqrt{1-2d^2}, d, d),\quad B = (d,\sqrt{1-2d^2},d)\quad\text{ and }\quad C = (d,d,\sqrt{1-2d^2})$$
The vertices are joined by three small circular arcs with

*

*length $\ell = \sqrt{1-d^2}\left[\frac{\pi}{2} - 2\sin^{-1}\left(\frac{d}{\sqrt{1-d^2}}\right)\right]$.

*geodesic curvature $k_g = \frac{d}{\sqrt{1-d^2}}$.

Let $\varphi_A, \varphi_B, \varphi_C$ be the external angles at $A, B, C$ respectively. By symmetry, they are equal to each other.
Imagine we walk along $\partial T$ in positive orientation.
At vertex $A$, the tangent vector changes from
$\displaystyle\;\frac{1}{\sqrt{1-d^2}}(d,0,-\sqrt{1-2d^2})$ to
$\displaystyle\;\frac{1}{\sqrt{1-d^2}}(-d,\sqrt{1-2d^2},0)$. This implies
$$\varphi_A = \varphi_B = \varphi_C = \cos^{-1}\left(\frac{-d^2}{1-d^2}\right) = \pi - \cos^{-1}\left(\frac{d^2}{1-d^2}\right)$$
Apply Gauss-Bonnet formula, we find
$$\begin{align}
\Omega = \frac{2}{\pi}\verb/Area/(T)
&=
\frac{2}{\pi}\left[2\pi - (\varphi_A + \varphi_B + \varphi_C + 3 k_g \ell)\right]\\
&= \frac{2}{\pi}\left[
3\cos^{-1}\left(\frac{d^2}{1-d^2}\right) +
6d \sin^{-1}\left(\frac{d}{\sqrt{1-d^2}}\right)
-\frac{\pi}{2}(2+3d)
\right]
\end{align}
$$


text:
Q: How to generate powersets with a maximum size in C#? I am trying to generate all powersets from a given list within a limit of given maximum size. I've found some great answers for how to generate powersets in general and admire the solution using bitmaps found here All Possible Combinations of a list of Values or here Computing Powersets in C#.
Is there a way to generate sets with a maximum size of 'maxSize' numbers in one set? E.g. my input is {1, 2, 3, 4, 5, 6}, but I only want results with 3 or less items. Is it possible to do within the one command? I have found a solution where I iterate over all items of the result, but this is quite inefficient for large inputs with smaller maxSize.

A: It's easy with recursion:
static public IEnumerable<List<int>> FindAllCombos(List<int> list, int maxSize, int minIndex = 0)
{
    yield return new List<int>();
    if (maxSize > 0)
        for (int i = minIndex; i < list.Count; i++)
            foreach (var set in FindAllCombos(list, maxSize - 1, i + 1))
            {
                set.Add(list[i]);
                yield return set;
            }
}

Note that the elements of the output sets will here be in the reverse order.


text:
Q: 'gulp-babel' not working in node js version 4 I am getting error, when require gulp-babel in my gulp file, to use es6 syntax in my js files.
/home/logakrishnan/Documents/project/node_modules/@babel/core/lib/transformation/file/file.js:77
  constructor(options, {
                       ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/logakrishnan/Documents/project/node_modules/@babel/core/lib/index.js:153:36)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

Node version: v4.4.7

A: You will have to upgrade your Node.js version. (Node 4 is from 2016, a relative eternity in JavaScript terms.)
At the time of writing, Babel requires Node 6.9 or newer.


text:
Q: strlen of a char array is greater than its size. How to avoid? I defined an array:
char arr[1480];
Now, from a file, I read exactly 1480 chars and put into arr (by doing arr[i]=c).
I know 1480 chars because I use a while loop to read one char ar a time (istream.get()) and stop when the incrementing index = 1480.
However, after that, I do strlen(array) and it returns 1512. How come? This only happens in some occasions, but not in all occasions, even though every time I read from file, I always read up to 1480 chars.
My doubt is one char might occupy more than 1 unit (units returned by strlen(arr)).
If so, how can I fix this?
Thanks
PS: I asked a problem earlier about my pointer gets garbaged, and this is the cause when I have a buffer (arr) of length > 1480.

A: The array size must include the string terminator. Since you read exactly the size of the array then you can't (and don't) add the string terminator. The strlen function, and all other string functions, uses the string terminator character to find the end of the string. If it's not there it will continue until it finds it.
If you may have no more than 1480 characters in the string, you should have an array of size 1481, with the last being the string terminator '\0'.

A: Try to write in this way ? Just a little sample
char arr[1481]=0x00; //define all the array with string terminator
memcpy(arr,BufCopyFrom, 1480); //BufCopyFrom is the Buffer being copied and specified to copy 1480 bytes.

Hope it helps.


text:
Q: Escaping \ in regular expressions in Ruby I was parsing a file and some lines of the file ended with "\". I wanted to use gsub to find and replace it. I tried '\' and /\/ and neither one correctly matched "\".
I ended up getting around it by using a combination of chop and strip but it left me thinking how would I do this if I ever need to again?

A: You need to escape the escape sign as well. So this should work:
/\\/

A: Passing a string to gsub that will then be compiled to a regex:
"abc\def".gsub("\\", "")
=> "abcdef"

Or just providing the regex directly:
"abc\def".gsub(/\\/, "")
=> "abcdef"


text:
Q: SQL Server full join query - get results only once I want to show results like below:
Date      InvoiceNo  SalesAmount   Date     PaymentType  CheckNo  ReceivedAmount
================================================================================
03-28-2018  C2803       1253.25    Null         Null      Null      Null
03-30-2018  C3001       563.80     Null         Null      Null      Null
04-02-2018  C0205       2311.66    04-02-2018   Check     1253      1816.25
Null        Null        Null       04-05-2018   Check     3565      2311.66
04-06-2018  C0601       560.00     04-06-2018   Check     5231      230.00
04-06-2018  C0602       280.00     Null         Null      Null      Null
04-08-2018  C0805       153.66     04-08-2018   Check     6523      330.00
Null        Null        Null       04-08-2018   Check     6524      280.00

The invoice may be issued multiple times a day, and the collection may occur several times a day.
The problem with my query is that when two invoices are generated per day and only one collection is collected, the collection results are duplicated twice.
How to display each result only once?

Query:
select
    S.Date as SDate, S.InvoiceNo, S.SalesAmount, P.Date as PDate,
    P.PaymentType, P.CheckNo, P.ReceivedAmount
from
    SalesHistory S
full outer join
    PaidHistory P ON P.Date = S.Date
where
    S.CustCode = '1701' or P.CustCode = '1701'
order by
    isnull(S.Date, P.Date)

A: You can add a ROW_NUMBER and join on it:
select
  S.Date as SDate, S.InvoiceNo, S.SalesAmount, P.Date as PDate, P.PaymentType, P.CheckNo, P.ReceivedAmount
from
 ( select *,
      row_number() over (partition by CustCode, Date order by InvoiceNo) as rn
   from SalesHistory
   where CustCode='1701'
 ) S
Full outer Join
 ( select *,
      row_number() over (partition by CustCode, Date order by CheckNo) as rn
   from PaidHistory
   where CustCode='1701'
 ) P
ON P.CustCode = S.CustCode
and P.Date=S.Date
and s.rn = p.rn
order by
  ISNULL(S.Date,P.Date)

I added CustCode to the row_numbers and the join, just in case you want to run this with more than a single customer.


text:
Q: Xcode std::cout output acting odd I've been using Xcode for 2 years and have written quite a few C++ command line applications.  For the past few months, I've abandoned command line applications and have focused on GUI applications, but after coming back to some older command line applications, I noticed that std::cout isn't working the way I last remember.  If I have a cout statement such as "enter age: " before a cin statement, when running the app in Xcode, it no longer shows the cout statement first, but rather after the input from cin.  I read somewhere that the output was buffered and required an '\n' in order to display the text line, but to my knowledge, I never used to have to do this.  Did something change in a newer version of Xcode (I keep Xcode updated entirely)?  I use to be able to print items to the screen without needing a newline in order to do it.  My old applications are no longer working correctly because of this.  Is there a setting somewhere to change it?
Any help would be greatly appreciated.

A: Guess 8.3.2 is the answer!  This update just popped up on my comp:


text:
Q: How to get same claims in .cshtml page and in API in a hosted Blazor WA?
*

*Hosted Blazor WA app with IdentityServer4 - standard template.

*Scaffolded Identity pages.

*Custom ProfileService which adds several claims.

Everything works as expected in strictly Blazor and API realms.
However inspecting User claims in Pages in Identity pages I notice that my custom claims added in ProfileService are missing.
My current configuration in Program.cs looks like this:
builder.Services.AddAuthentication()
    .AddIdentityServerJwt();

I have tried extending config in AddApiAuthorization to add custom claim, but it did not help.
builder.Services.AddIdentityServer()
    .AddApiAuthorization<User, ApplicationDbContext>(options =>
    {
        options.IdentityResources["openid"].UserClaims.Add("name");
        options.ApiResources.Single().UserClaims.Add("name");
        options.IdentityResources["openid"].UserClaims.Add("role");
        options.ApiResources.Single().UserClaims.Add("role");
        options.IdentityResources["openid"].UserClaims.Add("mn");
        options.ApiResources.Single().UserClaims.Add("mn");
    })
    .AddSigningCredentials();

How to configure app to be able to access all claims added in ProfileService in .cshtml?


text:
Q: Greedy Algorithm on Knockout Tournaments: Proof of Correctness You are given a function $\operatorname{rk}:\{1\dots 2^k\}\rightarrow \mathbb{N^+}$ representing the ranks of the players $1\dots2^k$ in a participating in a tournament. The tournament evolves in a random way, so that when player $i$ faces player $j$, he wins with probability $\frac{\operatorname{rk}(i)}{\operatorname{rk}(i)+\operatorname{rk}(j)}$. When a player loses a game, he gets knocked out of the tournament, thus the tournament finishes in $k$ rounds.
You are requested to arrange the players into a knockout tournament starting line-up (i.e. on the leaves of a complete binary tree of height $k$) in the way that maximizes the probability that player $1$ wins the tournament.
The official greedy solution, presented without any trace of proof, is the following:

*

*Sort the players $1, r_2, r_3, \dots r_{2^k}$, where $r_2, \dots r_{2^k}$ are the players $2 \dots 2^k$ sorted in ascending order of their rank.

*Arrange players $1, \dots, 2^{k-1}$ in the left-subtree and $2^{k-1} + 1, \dots 2^k$ in the right subtree and recurse.

*For each node $v$ of the tree compute (bottom-up using dynamic programming) the probability vector $P_v$ such that $P_v[x]$ is the probability of player $x$ winning the sub-tournament rooted at $v$.

This algorithm runs in $\mathcal{O}(n^2 \log n)$.
How to prove that the algorithm is also correct?
The original problem is from ICPC NWERC 2017 (problem K). Here we posted a simplified version.


text:
Q: Alternatives to "Proofs and Types" I'm going through "Proofs and Types" and it's a wonderfully written book! First few chapters felt like a pleasure (especially for someone who already went through TAPL and TTFP, and had some experience with writing dependently typed code), but the ones on semantics, coherence spaces and the likes (namely, chapters 8, 12, and, to some extent, 9) feel quite over my current level.
So, a couple of questions:

*

*Is the presentation in the book relevant? I heard something about categorical interpretation, so not sure what's the current state of the art in this area.

*Is the subject itself relevant? Is this something that everyone wanting to understand type theory (and possibly eventually contribute to the research) knows, or is it rather a dedicated branch on its own?

*In any case, is there anything more accessible?


text:
Q: Attaching metadata to Stripe Payment Link Is it possible to attach metadata to a Stripe Payment link (that directs to Stripe for payment)?
I've set up a basic link to a Stripe payment and have a link to the payment on my site.
What I hope to achieve is to have a rendered mustache template attached to that link some extra parameters/query data, that will act as a metadata set.
ie:
 <button>Pay Now</button> ...
I hope to link who's account is making the payment via this metadata.

A: The way I've solved this with Payment Links - I generate a unique Payment Link for each purchase and add metadata on Link creation (order_id in my case). This way it gets propagated to webhooks.
Create Payment Link cURL example:
curl https://api.stripe.com/v1/payment_links \
  -u sk_test_51INcGzGixr<..> \
  -d "line_items[0][price]"=price_1KPia<..> \
  -d "line_items[0][quantity]"=1 \
  -d "metadata[order_id]"=6735

This involves a bit more code than you might anticipate with Payment Links, but definitely lighter on implementation side that Checkout.
Also, don't forget to cleanup the Payment Links afterwards:
curl https://api.stripe.com/v1/payment_links/plink_1KPoiiGixr8beE1DMeFarexg \
  -u sk_test_51INcGzGixr<..> \
  -d active=false

A: I managed to post to the backend endpoint,  using checkout.sessions.create.
This creates a payment attempt, where it directs you to a stripe side payment UI.
This payload example is what is passed to the Stripe API,
Though I am using node-red and the Stripe payment node, you should be able to do this concept elsewhere.
msg.payload = {

     payment_intent_data: {
         metadata : {
            "user_id": msg.user._id,
            "email" : msg.user.user,
         },
     },
     payment_method_types : ['card'],
     mode: 'payment',
     success_url: 'https://somesite.com/payment_success',
     cancel_url: 'https://somesite.com/payment_cancel',

     line_items : [
         {
             quantity : 1,
             price_data : {
                 currency: 'usd',
                 product_data: {
                     name: 'Some Product'
                 },
                 unit_amount: 1200
             }
         }
     ]
}

A: You can now add some information within the Stripe Payment Link URL directly.
You can set:

*

*client_reference_id (your reference),

*prefilled_email (prefill the email in the payment link),

*prefilled_promo_code (prefill a promo code).

Documentation: https://stripe.com/docs/payments/payment-links#url-parameters


text:
Q: Getting System.Net.WebException: The underlying connection was closed but cannot fix it I have read many blogs and many questions here among stacks, but could not find my exact scenario (which is very simple one actually).
Context
I have a service written inside a library in a Visual Studio 2010 project. The i wrote the interface for the service contract and the service class implementing that contract.
namespace MyNS.WebSrvLibrary {
[ServiceContract(Namespace = "http://schemas.dummy.com")]
public interface IEchoService {
  [OperationContract()]
  EchoMessageResponse Echo(EchoMessage msg);
}
}

The service:
namespace MyNS.WebSrvLibrary {
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class EchoService : IEchoService {
  public EchoService() {}
  [OperationBehavior()]
  public virtual EchoMessageResponse Echo(EchoMessage msg) {
    return new EchoMessageResponse("Ciccio");
  }
  public static IEchoService GetChannel(string addr = "") {
    // Create the service endpoint
    Binding binding = new BasicHttpBinding();
    ServiceEndpoint endpoint =
      new ServiceEndpoint(
            ContractDescription.GetContract(typeof(IEchoService)),
            binding,
            new EndpointAddress(addr));
    // Create channel factory and get proper channel for service.
    ChannelFactory<IEchoService> channelFactory = new ChannelFactory<IEchoService>(endpoint);
    IEchoService svc = channelFactory.CreateChannel();
    return svc;
  }
}
}

Classes like EchoMessageResponse and EchoMessage have DataContracts applied and they are ok.
The service as I said before is compiled into a dll (assembly) that i import into a web application in the bin folder just by adding a reference. In this web application I have the svc file for the web service:
<%@ ServiceHost Language="C#" Debug="true" Service="MyNS.WebSrvLibrary.EchoService" %>

And this is the Web.config file:
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="MyNS.WebSrvLibrary.EchoService">
        <endpoint name="basicHttpBinding" address=""
                                     binding="basicHttpBinding"
                                     bindingConfiguration="basicHttpBinding_Svc"
                                     contract="MyNS.WebSrvLibrary.IEchoService"/>
        <endpoint name="mexHttpBinding" address="/Mex"
                                     binding="mexHttpBinding"
                                     contract="IMetadataExchange"/>
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding maxReceivedMessageSize="2147483647" openTimeout="12:00:00" receiveTimeout="12:00:00" closeTimeout="12:00:00" sendTimeout="12:00:00">
          <readerQuotas maxStringContentLength="1310720"
                        maxArrayLength="16384"
                        maxBytesPerRead="24096"
                        maxDepth="10000"
                        maxNameTableCharCount="16384"/>
        </binding>
        <binding name="basicHttpBinding_Svc" maxReceivedMessageSize="2147483647" openTimeout="12:00:00" receiveTimeout="12:00:00" closeTimeout="12:00:00" sendTimeout="12:00:00">
          <readerQuotas maxStringContentLength="1310720"
                        maxArrayLength="16384"
                        maxBytesPerRead="24096"
                        maxDepth="10000"
                        maxNameTableCharCount="16384"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

So, finally, I have a client application compiling to an executable .exe file which is the following:
class Program {
  static void Main(string[] args) {
    IEchoService svc = EchoService.GetChannel("http://localhost:80/T/Service.svc");
    EchoMessageResponse rmsp = svc.Echo(new EchoMessage("Hello"));
    System.Threading.Thread.Sleep(10000);
  } /* Main */
} /* Program */

Information on server-side matters
The web application is hosted in IIS in the Default Web Site listening to port 80 of course.
The problem
When I run my executable application, I get this System.ServiceModel.CommunicationException exception:

An error occurred while receiving the HTTP response to
  http://localhost/T/Service.svc. This could be due to the service
  endpoint binding not using the HTTP protocol. This could also be due
  to an HTTP request context being aborted by the server (possibly due
  to the service shutting down). See server logs for more details.

Whose innerException is of type: System.Net.WebException:

The underlying connection was closed: An unexpected error occurred on
  a receive.

Whose innerException (the last in the exception tree) is of type System.Net.Sockets.SocketException:

An existing connection was forcibly closed by the remote host.

The complete stack is the following:

Server stack trace:     at
  System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
  webException, HttpWebRequest request, HttpAbortReason abortReason)
  at
  System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)    at
  System.ServiceModel.Channels.RequestChannel.Request(Message message,
  TimeSpan timeout)    at
  System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)    at
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
Exception rethrown at [0]:     at
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    at
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    at
  DDBR.DiscoveryServiceLibrary.IEchoService.Echo(EchoMessage msg)    at
  DDBR.TestClient.Program.Main(String[] args) in
  C:\Data\ROOT_APPS\DistributedDataBackupAndRecovery\TestClient\Program.cs:line
  20    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,
  String[] args)    at System.AppDomain.ExecuteAssembly(String
  assemblyFile, Evidence assemblySecurity, String[] args)    at
  Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  ignoreSyncCtx)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state)    at
  System.Threading.ThreadHelper.ThreadStart()

Which can be found in the StackTrace property of the first exception (the initial one, not the inner ones).
Something very strange...
The very strange thing is that if I open my browser and type:
http://localhost/T/Service.svc

I get the famous screen my Microsoft IIS that exposes some basic info about the service. This means that the web service is alive and running at the specified address (endpoint).
I looked for this exception but no one has these peculiarities... generally a more detailed and complex context is involved.
What to do?
One thing more...
You are probably wondering why I do not use service references... Because I do not want to. There are reasons for this. The point here is that the GetChannel approach has always worked with me so far... do not understand why I have problems now...
Actually what kind of problem is it supposed to be? It cannot be timeout really do not believe this, it is a simple method acting in the fastest of the many possible ways. It is strange... really.

A: Looks like you need to add a service reference to your console app and use the proxy object and not the actual service class that you are using.  You are using the service as a client. Instead of calling the service through the auto generated proxy classes that get created when you add a service reference to your client project.

A: The problem was a DataContract related one. In one of my classes that I use as messages to be passed to service methods, I had a property miswritten that caused the serializer to experience loops... This caused StackOverflow Exception which caused the serializer to go Berserk and the connection to be closed.
I thought the problem was not a data related one and did not provide the code for this. Sorry for bothering guys. At least my question could provide some useful info regarding errors in DataContracts but that one cannot really grasp by looking at the exception description.


text:
Q: create function to calculate total score of player on multiple crietera My  data  is  somethine  like  this
            f         g     h       i    points new  points old
name        runs    balls   4's    6's
xxy         40         60    2      4      50         26
aabc        25         45    2      0      25         13.5
lmn         102        80    10     4      138        70

I need  to  calculate  total  points  scored  by  players  on  following criteria

*

*player score 1 point for each runs scored earlier he was getting  0.5 point

*player  score  2  point  for each  6's hit  earlier   he  was  earning 1 point

*player  score  1   point  for each  4's  hit  earlier he  was  earning  0.5 point

*Player   score  8  bonus  point  for  scoring  50,  earlier  it  was 4

*Player   score  16 bonus  point   for  scoring 100  earlier  it  was 8

*Starting  Eleven  earns   2  points

*players earns  negative  points  for  low  strike  strike as below

*

*strike  rate below  50%         negative point   -6  earlier   -3

*strike  rate between  50  to  60 negative point  -4  earlier   -2

*strike  rate between  60  to  70 negative point  -2  earlier   -1

*Out  for  duck  (zero) negative point -2 (no  change )
I have lengthy excel  formula which is  difficult change  in case any  change in scoring  system.  That is way I propose to put various criteria in one sheet and  player data along with result in another sheet to calculate the point scored  by  player.
That is  way  I propose  to  put  various  criteria   in  one  sheet  and  player data in  another  sheet to  calculate  the  point scored  by  player .
I  have  tried  to  create  function to  start  with  to  calculate  the  point scored by  the player. But  it  I  cannot  end it  properly.  Moreover I want  put criteria in another  sheet  and  calculate  point, How do I create function for that. I have started with something like this:
Function tscore(tscore) As Integer
    strikerate = 0
    economyrate = 0
    halfcentry = 0
    century = 0
    ducks = 0
    wickets = 0
    runs = 0
    SIXERS = 0
    BOUNDERY = 0
    starteleven=2
    If Range("f2") > 0 Then
        runs = Range("F2") * 1
    End If
    If Range("H2") > 0 Then
        BOUNDERY = Range("H2") * 1
    End If
    If Range("H2") > 0 Then
       SIXERS = Range("I2") * 2
    End If
    If Range("F2") / Range("G2") < 50 Then
       strikerate = -3
    Else
       If Range("F2") / Range("G2") >= 50 And Range("F2") / Range("G2") <= 59.9  Then
           strikerate = -2
       Else
           If Range("F2") / Range("G2") >= 60 And Range("F2") / Range("G2") <= 70 Then
               strikerate = -1
           endIf
       endif
    endif
    endif

    tscore=runs+  BOUNDERY+ SIXERS+strikerate+starteleven
end function

Actual results should  be
 name        points  new     points  old
 xxy           50                26
 aabc          25                13.5
 lmn           138                70

But I could  not complete the vba function.

A: When you create a function, pass in all the information the function needs as arguments. Don't read data from external sources like other cells. If the function needs it, pass it in.
Don't name arguments the same as your function name. To return a value, assign that value to the name of the function. If you have an argument with the same name, it gets confused.
This example doesn't add up because I didn't understand all the conditions, but it should give you a start and you can fix what's wrong.
Public Function Score(ByVal Runs As Long, ByVal Balls As Long, ByVal Fours As Long, ByVal Sixers As Long, _
    ByVal RunFactor As Long, ByVal FourFactor As Long, ByVal SixerFactor As Long, _
    ByVal HalfFactor As Long, ByVal CentFactor As Long, _
    ByVal Rate1Factor As Long, ByVal Rate2Factor As Long, ByVal Rate3Factor As Long) As Double

    Dim dReturn As Double

    dReturn = (Runs * RunFactor) + (Fours * FourFactor) + (Sixers * SixerFactor)

    If Runs >= 50 Then dReturn = dReturn + HalfFactor
    If Runs >= 100 Then dReturn = dReturn + (CentFactor - HalfFactor)

    Select Case Runs / Balls
        Case Is < 0.5
            dReturn = dReturn - Rate1Factor
        Case Is <= 59.9
            dReturn = dReturn - Rate2Factor
        Case Is <= 70
            dReturn = dReturn - Rate3Factor
    End Select

    Score = dReturn

End Function

You don't need a separate variable (dReturn) but I like to use one. You use the function in a cell like this
=score(F2,G2,H2,I2,1,1,2,8,16,3,2,1)

Note that my factors are all hardcoded, but you could point those to ranges too
=score(F2,G2,H2,I2,Sheet2!A1,Sheet2!A2,Sheet2!A3,Sheet2!A4,Sheet2!A5,Sheet2!A6,Sheet2!A7,Sheet2!A8)

Even better, use named ranges
=score(F2,G2,H2,I2,Run,Four,Sixer,Half,Century,Strike1,Strike2,Strike3)


text:
Q: Error: Actions may not have an undefined "type" property I am new to Redux, semi-new to React. I've made a few simple applications with it. I understand the basic concept of Redux (storing state in a central location) which sounds more elegant than passing things along via components/props.
However, I am getting the following error:
Error: Actions may not have an undefined "type" property. Have you misspelled a constant?
onSubmit
src/containers/Login.js:28
  25 |
  26 | const mapDispatchToProps = (dispatch) => ({
  27 |   onSubmit: (username, password) => {
> 28 |     dispatch(login(username, password))
  29 |   }
  30 | })
  31 |

LoginForm._this.onSubmit
src/components/LoginForm.js:29
  26 |
  27 | onSubmit = (event) => {
  28 |   event.preventDefault()
> 29 |   this.props.onSubmit(this.state.username, this.state.password)
  30 | }
  31 |
  32 | render() {

As you can see, there appears to be an issue with the dispatch line in Login.js.
Login.js looks like this:
import React from 'react'
import { connect } from 'react-redux'
import { Redirect } from 'react-router'

import LoginForm from '../components/LoginForm'
import {login} from  '../actions/auth'
import {authErrors, isAuthenticated} from '../reducers'

const Login = (props) => {
  if(props.isAuthenticated) {
     return  <Redirect to='/' />
  }

  return (
     <div className="login-page">
       <LoginForm {...props}/>
    </div>
  )
}

const mapStateToProps = (state) => ({
  errors: authErrors(state),
  isAuthenticated: isAuthenticated(state)
})

const mapDispatchToProps = (dispatch) => ({
  onSubmit: (username, password) => {
    dispatch(login(username, password))
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(Login);

My guess based on what I've been googling is that I'm not actually missing any sort of type data, but there's actually probably a problem somewhere in my middleware.
What might be going on? How would I troubleshoot this or interpret it?
EDIT - here's my login function:
export const login = (username, password) => ({
  [RSAA]: {
    endpoint: '/api/auth/token/obtain/',
    method: 'POST',
    body: JSON.stringify({username, password}),
    headers: { 'Content-Type': 'application/json' },
    types: [
      LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE
    ]
  }
})

A: There is a certain 'boilerplate' that we need to follow when using redux. Based on the error message, it simply means dispatch action is expecting an object with type property
dispatch({ type: 'ACTION_TYPE', .... });

so depending on what login(username, password) return, redux dispatch will expect an object with property type


text:
Q: Visual Studio, add connected service does not register app in azure AD I followed the steps as per
https://github.com/OfficeDev/O365-WebApp-MultiTenant and added the connected service.  However this does not register the app under Windows Azure Active Directory Applications.  I have properly linked my office 365 account into Azure.  However when I add the connected service it is still empty.  Is this a known issue and what is the work around?

A: No, this isn't a known issue. The "Add Connected Service" wizard is not generating a client ID and secret in your web.config?
As a workaround you could login to the Azure Management Portal and register the app manually, then put the client ID and secret into your web.config.

A: I just had the same issue and spend some hours on it. Finally it turns out that I had used a user account to log in in visual studio that was assigned to a different MS Azure account.
In my case I was using the user of production environment instead of my own developer account to log in.


text:
Q: Sarama Partition Consumer with ConsumerGroup I have tried shopify/sarama library to consume kafka messages. I used both Consumer interface and ConsumerGroup interface. I can consume from specific partitions using ConsumePartition() method in Consumer. But when I use ConsumerGroup interface, I do not seem to have the capability to consume from a specific partition.
Is there a way for me to assign certain partitions to specific consumers inside a consumer group? Or is it something I cannot interfere with?

A: It seems like I cannot give exact partitions to consume when using ConsumerGroup. However I can choose the strategy that I want to assign partitions to my consumers, out of 2 strategy options.

*

*Balance Strategy Range

BalanceStrategyRange is the default and assigns partitions as ranges to consumer group members.
Example with one topic T with six partitions (0..5) and two members (M1, M2):
M1: {T: [0, 1, 2]}
M2: {T: [3, 4, 5]}

*Balance Strategy Round-Robin

BalanceStrategyRoundRobin assigns partitions to members in alternating order.
Example with topic T with six partitions (0..5) and two members (M1, M2):
M1: {T: [0, 2, 4]}
M2: {T: [1, 3, 5]}

I can give this as a configuration when creating the ConsumerGroup.
config.Consumer.Group.Rebalance.Strategy = BalanceStrategyRange