text:
Q: Changing the adapter of a ListView with Button click - GUI glitch I have a ListView and two buttons above it. The contents of the ListView changes depending on which button is clicked. To do this, I have two BaseAdapters. ListView.SetAdapter() is called when the user clicks a button. I am getting a GUI glitch when I change adapter; attached are screen shots of the problem.
@Bondax briefly mentions the problem in this post: Is it okay to change a ListView's adapter dynamically? . But I have found no solution. Code attached for onCreate of fragment containing ListView and of the two adapters. Also, if it's relevant, each distinct row in the listview is ConstraintLayout. Any and all help would be appreciated! :)
Recorded tracks button First time loads fine.

Then I click All Time Button, which sets new adapter. GUI glitch here.

Then I click Recorded tracks again and it too, bugs out.

CODE:
onCreate of fragment that contains listview
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_stats, container, false);

        trackStatsListView = (ListView) view.findViewById(R.id.listOfTracksListView);
        trackStatsListView.setBackgroundColor(Color.WHITE);
        ImageButton recordedTracksButton = (ImageButton) view.findViewById(R.id.recordedTracksButton);
        ImageButton allTimeBestButton = (ImageButton) view.findViewById(R.id.allTimeBestButton);

        //All Time stats clicked
    allTimeBestButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            recordedTracksClicked = false;
            trackStatsListView.setAdapter(null);

            final allTimeBestAdapter allTimeBestAdapter = new allTimeBestAdapter(getActivity());

            trackStatsListView.setAdapter(allTimeBestAdapter);
        }
    });

    //Recorded Tracks clicked (click by default when Fragment loads up)
    recordedTracksButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            recordedTracksClicked = true;

            SkiCompanionDatabase db = new SkiCompanionDatabase(getActivity());

            PopulateTrack populateTrack;

            //TODO: add in location awareness
            //populating data for each track
            listOfTracks = new ArrayList<>();
            Cursor trackIDPosition = db.getAllTrackIDs();
            trackIDPosition.moveToFirst();
            for (int i = 0; i < db.numberOfTracks(); i++) {
                currentID = trackIDPosition.getLong(trackIDPosition.getColumnIndex(Constants.COL_TRACK_DESC_ID));
                populateTrack = new PopulateTrack(getActivity(), currentID);
                listOfTracks.add(new TrackDescription(currentID, db.getNameFromTrackID(currentID), db.getDateFromTrackID(currentID), "Whistler", populateTrack.totalDuration(), populateTrack.totalDistance()));
                trackIDPosition.moveToNext();
            }

            trackStatsListView.setAdapter(null);

            final StatsAdapter statsAdapter = new StatsAdapter(getActivity(), listOfTracks);

            //setting an adapter to put list data into the ListView
            trackStatsListView.setAdapter(statsAdapter);

            //setting the onClick for each element in the list - will replace current fragment with new fragment
            trackStatsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (recordedTracksClicked) {
                        //getting the ID of the track selected
                        Bundle itemClicked = new Bundle();
                        itemClicked.putLong("trackID", listOfTracks.get(listOfTracks.size() - 1 - i).getId());

                        //adding the id as an extra (argument) for the next fragment
                        Fragment trackStatsFragment = new TrackStatsFragment();
                        trackStatsFragment.setArguments(itemClicked);

                        android.app.FragmentManager manager = getFragmentManager();
                        FragmentTransaction transaction = manager.beginTransaction();

                        //replacing fragment, we push to backStack so that StatsFragment is still navigable with the back button
                        transaction.replace(R.id.fragmentContainer, trackStatsFragment);
                        transaction.addToBackStack(null);
                        transaction.commit();
                    }
                }
            });
        }
    });

    recordedTracksButton.callOnClick();

    return view;
}

AllTimeAdapter and RecordedTrackAdapter:
//helper class to populate ListView
    class StatsAdapter extends BaseAdapter {
        private ArrayList<TrackDescription> listOfTracks;
        private Context context;

        //Constructor
        StatsAdapter(Context context, ArrayList<TrackDescription> listOfTracks) {
            this.context = context;
            this.listOfTracks = listOfTracks;
        }

        //total number elements in list
        @Override
        public int getCount() {
            return listOfTracks.size();
        }

        //returns the object of an item at index i in ListView
        @Override
        public Object getItem(int i) {
            return listOfTracks.get(i);
        }

        //used for returning index of Database element
        @Override
        public long getItemId(int i) {
            return i;
        }

        //method which populates ListView. The Row design is specified in list_of_tracks_row.xml
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //ViewHolder is a kind of cache and is a public helper class. When an object is scrolled outside of view
            //(into recycler), its data is store in ViewHolder, so that it can be quickly loaded when the user scrolls over it again.
            ViewHolder viewHolder;

            if (view == null) {
                //inflating layout list_of_tracks_row.XML on each iteration
                view = layoutInflater.inflate(R.layout.list_of_tracks_row, viewGroup, false);

                //populating ViewHolder object
                viewHolder = new ViewHolder();
                viewHolder.tv1 = (TextView) view.findViewById(R.id.trackName);
                viewHolder.tv2 = (TextView) view.findViewById(R.id.trackDate);
                viewHolder.tv3 = (TextView) view.findViewById(R.id.trackLocation);
                viewHolder.tv4 = (TextView) view.findViewById(R.id.trackDuration);
                viewHolder.tv5 = (TextView) view.findViewById(R.id.trackDistance);

                //associating current view with the relevant ViewHolder
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            //setting the text of the TextViews in the row
            //newest to oldest
            viewHolder.tv1.setText(listOfTracks.get(listOfTracks.size() - 1 - i).getName());
            viewHolder.tv2.setText(listOfTracks.get(listOfTracks.size() - 1 - i).getDate());
            viewHolder.tv3.setText(listOfTracks.get(listOfTracks.size() - 1 - i).getLocation());
            viewHolder.tv4.setText(millisToHMS(listOfTracks.get(listOfTracks.size() - 1 - i).getDuration()));
            viewHolder.tv5.setText(String.valueOf((int) listOfTracks.get(listOfTracks.size() - 1 - i).getDistance()) + "m");

            //TODO: to speed up fragment load time, use distance and duration stored in database.
//            viewHolder.tv5.setText(String.valueOf((int) skiCompanionDatabase.getDistanceFromTrackID(30)) + "m");

            return view;
        }
    }

    class allTimeBestAdapter extends BaseAdapter {
        private Context context;
        private AppPreferences appPreferences;

        public allTimeBestAdapter(Context context) {
            this.context = context;
            this.appPreferences = new AppPreferences(context);
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        //number of different types in list, ie. speed, altitude...
        @Override
        public int getViewTypeCount() {
            return 8;
        }

        @Override
        public int getCount() {
            return 6;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //ViewHolder is a kind of cache and is a public helper class. When an object is scrolled outside of view
            //(into recycler), its data is store in ViewHolder, so that it can be quickly loaded when the user scrolls over it again.
            final ViewHolder viewHolder;

            //i is the current row number. Switch statement determines the layout to be inflated depending on the row number
            //row 0: speed: track_list_row_speed , row 1: altitude: track_list_row_altitude , etc...
            switch (i) {
                /*      DURATION      */
                case 0:
                    if (view == null) {
                        //inflating layout specific to the row 1, ie. track_list_row_speed
                        view = layoutInflater.inflate(R.layout.track_list_row_duration, viewGroup, false);

                        //populating ViewHolder object
                        viewHolder = new ViewHolder();
                        viewHolder.tv1 = (TextView) view.findViewById(R.id.statsListTotalDuration);
                        viewHolder.tv2 = (TextView) view.findViewById(R.id.statsListAscentDuration);
                        viewHolder.tv3 = (TextView) view.findViewById(R.id.statsListDescentDuration);

                        //associating current view with the relevant ViewHolder
                        view.setTag(viewHolder);
                    } else {
                        viewHolder = (ViewHolder) view.getTag();
                    }

                    viewHolder.tv1.setText(millisToHMS(appPreferences.getAllTimeTotalDuration()));
                    viewHolder.tv2.setText(millisToHMS(appPreferences.getAllTimeAscentDuration()));
                    viewHolder.tv3.setText(millisToHMS(appPreferences.getAllTimeDescentDuration()));

//                    viewHolder.tv1.setText(millisToHMS(track.getTotalDuration()));
//                    viewHolder.tv2.setText(millisToHMS(track.getAscentDuration()));
//                    viewHolder.tv3.setText(millisToHMS(track.getDescentDuration()));
                    break;
                /*      DISTANCE      */
                case 1:
                    if (view == null) {
                        //inflating layout specific to the row 1, ie. track_list_row_speed
                        view = layoutInflater.inflate(R.layout.track_list_row_distance, viewGroup, false);

                        //populating ViewHolder object
                        viewHolder = new ViewHolder();
                        viewHolder.tv1 = (TextView) view.findViewById(R.id.statsListTotalDistance);
                        viewHolder.tv2 = (TextView) view.findViewById(R.id.statsListAscentDistance);
                        viewHolder.tv3 = (TextView) view.findViewById(R.id.statsListDescentDistance);

                        //associating current view with the relevant ViewHolder
                        view.setTag(viewHolder);
                    } else {
                        viewHolder = (ViewHolder) view.getTag();
                    }

                    viewHolder.tv1.setText(String.valueOf((int) appPreferences.getAllTimeTotalDistance()) + 'm');
                    viewHolder.tv2.setText(String.valueOf((int) appPreferences.getAllTimeAscentDistance()) + 'm');
                    viewHolder.tv3.setText(String.valueOf((int) appPreferences.getAllTimeDescentDistance()) + 'm');
                    break;
                /*      SPEED      */
                case 2:
                    if (view == null) {
                        //inflating layout specific to the row 1, ie. track_list_row_speed
                        view = layoutInflater.inflate(R.layout.track_list_row_speed, viewGroup, false);

                        //populating ViewHolder object
                        viewHolder = new ViewHolder();
                        viewHolder.tv1 = (TextView) view.findViewById(R.id.statsListTopSpeed);
                        viewHolder.tv2 = (TextView) view.findViewById(R.id.statsListAvgSpeed);

                        //associating current view with the relevant ViewHolder
                        view.setTag(viewHolder);
                    } else {
                        viewHolder = (ViewHolder) view.getTag();
                    }

                    //multiplying by 18/5 converts m/s to km/h
                    viewHolder.tv1.setText(String.valueOf(appPreferences.getAllTimeTopSpeed() * (18 / 5)).substring(0, String.valueOf(appPreferences.getAllTimeTopSpeed() * (18 / 5)).indexOf('.') + 2) + "km/h");
                    viewHolder.tv2.setText(String.valueOf(appPreferences.getAllTimeAvgSpeed() * (18 / 5)).substring(0, String.valueOf(appPreferences.getAllTimeAvgSpeed() * (18 / 5)).indexOf('.') + 2) + "km/h");
                    break;
                /*      PACE      */
                case 3:
                    if (view == null) {
                        //inflating layout specific to the row 1, ie. track_list_row_speed
                        view = layoutInflater.inflate(R.layout.track_list_row_pace, viewGroup, false);

                        //populating ViewHolder object
                        viewHolder = new ViewHolder();
                        viewHolder.tv1 = (TextView) view.findViewById(R.id.statsListBestPace);
                        viewHolder.tv2 = (TextView) view.findViewById(R.id.statsListAvgPace);

                        //associating current view with the relevant ViewHolder
                        view.setTag(viewHolder);
                    } else {
                        viewHolder = (ViewHolder) view.getTag();
                    }

                    //multiplying by 18/5 converts m/s to km/h
                    viewHolder.tv1.setText(secondsToMS(appPreferences.getAllTimeBestPace()));
                    viewHolder.tv2.setText(secondsToMS(appPreferences.getAllTimeAvgPace()));

                    break;
                /*      ALTITUDE      */
                case 4:
                    if (view == null) {
                        view = layoutInflater.inflate(R.layout.track_list_row_altitude, viewGroup, false);

                        viewHolder = new ViewHolder();
                        viewHolder.tv1 = (TextView) view.findViewById(R.id.statsListMinAltitude);
                        viewHolder.tv2 = (TextView) view.findViewById(R.id.statsListMaxAltitude);
                        viewHolder.tv3 = (TextView) view.findViewById(R.id.statsListGainAltitude);
                        viewHolder.tv4 = (TextView) view.findViewById(R.id.statsListLossAltitude);

                        view.setTag(viewHolder);
                    } else {
                        viewHolder = (ViewHolder) view.getTag();
                    }

                    //setting the text of the TextViews in the row
                    viewHolder.tv1.setText(String.valueOf((int) appPreferences.getAllTimeMinAltitude()) + 'm');
                    viewHolder.tv2.setText(String.valueOf((int) appPreferences.getAllTimeMaxAltitude()) + 'm');
                    viewHolder.tv3.setText(String.valueOf((int) appPreferences.getAllTimeGainAltitude()) + 'm');
                    viewHolder.tv4.setText(String.valueOf((int) appPreferences.getAllTimeLossAltitude()) + 'm');
                    break;
                /*      GRADIENT      */
                case 5:
                    if (view == null) {
                        view = layoutInflater.inflate(R.layout.track_list_row_gradient, viewGroup, false);

                        viewHolder = new ViewHolder();
                        viewHolder.tv1 = (TextView) view.findViewById(R.id.statsListMaxGradient);
                        viewHolder.tv2 = (TextView) view.findViewById(R.id.statsListGainGradient);

                        view.setTag(viewHolder);
                    } else {
                        viewHolder = (ViewHolder) view.getTag();
                    }

                    viewHolder.tv1.setText(String.valueOf((int) appPreferences.getAllTimeMaxGradient()) + '\u00B0');
                    viewHolder.tv2.setText(String.valueOf((int) appPreferences.getAllTimeAvgGradient()) + '\u00B0');
            }

            return view;
        }
    }

UPDATE: XML CODE:
list_of_track_row:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:id="@+id/trackName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Track name"
        android:textColor="@color/colorStatsListTitle"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/trackDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/trackName"
        android:layout_alignLeft="@+id/trackName"
        android:layout_alignRight="@+id/trackName"
        android:layout_alignStart="@+id/trackName"
        android:layout_below="@+id/trackName"
        android:text="Date"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/trackName" />

    <TextView
        android:id="@+id/trackLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/trackDate"
        android:layout_alignLeft="@+id/trackDate"
        android:layout_alignRight="@+id/trackDate"
        android:layout_alignStart="@+id/trackDate"
        android:layout_below="@+id/trackDate"
        android:text="Location"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/trackDate" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="29dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/trackLocation"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/trackName"
        app:layout_constraintBottom_toBottomOf="@+id/trackLocation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_chevron_right" />

    <TextView
        android:id="@+id/trackDistance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/trackDistanceDescription"
        android:layout_alignEnd="@+id/trackDistanceDescription"
        android:layout_alignLeft="@+id/trackDistanceDescription"
        android:layout_alignRight="@+id/trackDistanceDescription"
        android:layout_alignStart="@+id/trackDistanceDescription"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="0.0 km"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="@+id/trackDuration"
        app:layout_constraintStart_toStartOf="@+id/trackDuration"
        app:layout_constraintTop_toBottomOf="@+id/trackDuration" />

    <TextView
        android:id="@+id/trackDuration"
        android:layout_width="wrap_content"
        android:layout_height="16dp"
        android:layout_above="@+id/trackDurationDescription"
        android:layout_alignEnd="@+id/trackDurationDescription"
        android:layout_alignLeft="@+id/trackDurationDescription"
        android:layout_alignRight="@+id/trackDurationDescription"
        android:layout_alignStart="@+id/trackDurationDescription"
        android:layout_marginEnd="24dp"
        android:layout_marginTop="8dp"
        android:text="00:00:00"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toStartOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/imageView" />

</android.support.constraint.ConstraintLayout>

A: For any people in the future with this problem: There is a bug/glitch with the newly developed ConstraintLayout, released 2017. I have switched to RelativeLayout in my custom ListView rows and the world is normal once again.


text:
Q: MP3 loading using librosa return empty data when start_time metadata is 0 I have a dataset of thousands of bird chirps audios (mp3) and I try to load them using librosa.load()
MP3 files are loaded but, most of the time, resulting data is an empty np.ndarray instead of a np.ndarray filled with floats
Using pydub.utils.mediainfo() I wanted to compare MP3 metadata. This function return information such as sampling_rate, codec, duration, bitrate, start_time, ...
I found out that start_time information was the explanation of failed loadings. Indeed, every file where start_time is 0 are not loaded correctly. At the contrary every file where start_time is over 0 are loaded correctly.
I have no problem listening every single MP3 file using VLC audio player.
Is there anything that can explain this behavior? Is there any solution to make these loadings succeed?

A: I had the same very specific error. The error message I was getting was "Input signal length=0 is too small to resample from 48000->22050", which was because librosa was loading empty arrays in the same circumstances as you mention.
My workaround for it was to specify a duration parameter, in this case I set it to the full length of the file:
dur = pydub.utils.mediainfo(filepath)["duration"]

data, sr = librosa.load(filepath,  duration = math.floor(float(dur)))

This solved the empty arrays for me

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python import CSV short code (pandas?) delimited with ';' and ',' in entires I need to import a CSV file in Python on Windows. My file is delimited by ';' and has strings with non-English symbols and commas (',').
I've read posts:
Importing a CSV file into a sqlite3 database table using Python
Python import csv to list
When I run:
with open('d:/trade/test.csv', 'r') as f1:
    reader1 = csv.reader(f1)
    your_list1 = list(reader1)

I get an issue: comma is changed to '-' symbol.
When I try:
df = pandas.read_csv(csvfile)

I got errors:

pandas.io.common.CParserError: Error tokenizing data. C error: Expected 1 fields in line 13, saw 2.

Please help. I would prefer to use pandas as the code is shorter without listing all field names from the CSV file.
I understand there could be the work around of temporarily replacing commas. Still, I would like to solve it by some parameters to pandas.

A: Pandas documentation says for parameters:
pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
sep : str, default ','

    Delimiter to use. If sep is None, will try to automatically determine this.

Pandas did not parse my file delimited by ; because default is not None denoted for automatic but ,. Adding sep parameter set to ; for pandas fixed the issue.

A: Pandas solution - use read_csv with regex separator [;,]. You need add engine='python', because warning:

ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.

import pandas as pd
import io

temp=u"""a;b;c
1;1,8
1;2,1
1;3,6
1;4,3
1;5,7
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="[;,]", engine='python')
print (df)

   a  b  c
0  1  1  8
1  1  2  1
2  1  3  6
3  1  4  3
4  1  5  7

A: Unless your CSV file is broken, you can try to make csv guess your format.
import csv

with open('d:/trade/test.csv', 'r') as f1:
    dialect = csv.Sniffer().sniff(f1.read(1024))
    f1.seek(0)
    r = csv.reader(f1, dialect=dialect)
    for row in r:
        print(row)

A: Try to specify the encoding, you will need to find out what is the encoding of file one is trying to read.
I have used ASCII for this example, but it could be different.
df = pd.read_csv(fname, encoding='ascii')

A: To avoid below warning in your code,

ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'

Use property names inside of your read_csv function. Check the example for both cases where this warning comes and where it won't.
CODE THAT THROW WARNING:
selEncoding = "ISO-8859–1"

dfCovid19DS = pd.read_csv(dsSrcPath, selEncoding)

CODE WITHOUT WARNING:
selEncoding = "ISO-8859–1"

dfCovid19DS = pd.read_csv(dsSrcPath, encoding = selEncoding)


text:
Q: Событие click у user control Как при помощи user control вызвать другую форму.
Есть Form1 с user_control1 и есть Form2. Как показать Form2 по щелчку по user_control1.
P.S. user_control1 добавляется динамически на форму.


text:
Q: Auto mapper 3 accessing destination getter I have a map which ignores all unmapped items in the destination object but for some reason it is accessing the getter of mapped destination items which is then throwing a null value exception. My map is as follows
Mapper.CreateMap<A, Entities.B>()
.IgnoreAllUnmapped()
.ForMember(d => d.Registration, opt => opt.MapFrom(s => s.Registration))
.ForMember(d => d.VIN, opt => opt.MapFrom(s => s.Vin))
.ForMember(d => d.MonthReg, opt => opt.MapFrom(s => s.MonthOfRegistration))
.ForMember(d => d.YearReg, opt => opt.MapFrom(s => s.YearOfRegistration))
.ForMember(d => d.BodyColour, opt => opt.MapFrom(s => s.BodyColour));

It is throwing a null value exception on d.MonthReg in that items get method, but it should not be calling it as I'm trying to set it.
How do I get around this?
Here is a code snippet:
public class A
{
    public string Vin { get; set; }
    public string Registration { get; set; }
    public int? MonthOfRegistration { get; set; }
    public int? YearOfRegistration { get; set; }
    public string BodyColour { get; set; }
}

public class Entities.B
{
    public string VIN
    {
      get
      {
        return this.Attributes["VIN"].Value as string;
      }
      set
      {
        this.Attributes["VIN"].Value = (object) value;
      }
    }
    public string Registration
    {
      get
      {
        return this.Attributes["Registration"].Value as string;
      }
      set
      {
        this.Attributes["Registration"].Value = (object) value;
      }
    }
    public int MonthReg
    {
      get
      {
        return (int) this.Attributes["MonthReg"].Value;
      }
      set
      {
        this.Attributes["MonthReg"].Value = (object) value;
      }
    }
    public int YearReg
    {
      get
      {
        return (int) this.Attributes["YearReg"].Value;
      }
      set
      {
        this.Attributes["YearReg"].Value = (object) value;
      }
    }
    public string BodyColour
    {
      get
      {
        return this.Attributes["BodyColour"].Value as string;
      }
      set
      {
        this.Attributes["BodyColour"].Value = (object) value;
      }
    }
}

error thrown
Test method TestMappingV1 threw exception:
AutoMapper.AutoMapperMappingException:

Mapping types:
A-> B
A -> B

Destination path:
B

Source value:
A ---> System.NullReferenceException: Object reference not set to an instance of an object.

at B.get_MonthReg() in source file
at lambda_method(Closure, Object)
at AutoMapper.Impl.PropertyGetter.GetValue(Object source)
at AutoMapper.PropertyMap.GetDestinationValue(Object mappedObject)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)

Code being run is
Mapper.CreateMap<Vehicle, Entities.Vehicle>()
.IgnoreAllUnmapped()
.ForMember(d => d.Registration, opt => opt.MapFrom(s => s.Registration))
.ForMember(d => d.VIN, opt => opt.MapFrom(s => s.Vin))
.ForMember(d => d.MonthReg, opt => opt.MapFrom(s => s.MonthOfRegistration))
.ForMember(d => d.YearReg, opt => opt.MapFrom(s => s.YearOfRegistration))
.ForMember(d => d.BodyColour, opt => opt.MapFrom(s => s.BodyColour));

Mapper.CreateMap<Assessment, Entities.Assessment>()
.IgnoreAllUnmapped()
.BeforeMap((s, d) =>
{
    if (d.IsNull.State)
    {
        d.State = Entities.AssessmentStateEnum.Uninitialised;
    }
})
.ForMember(d => d.AssessmentNumber, opt => opt.MapFrom(s => s.AssessmentNumber))
.ForMember(d => d.State, opt => opt.MapFrom(s => s.State))
.ForMember(d => d.Vehicle, opt => opt.MapFrom(s => s.Vehicle != null ? Mapper.Map<A, Entities.B>(s.Vehicle) : null))

[TestMethod]
public void TestMappingV1()
{
    Interface.v1.Assessment assessment =
        new Interface.v1.Assessment
        {
            AssessmentNumber = "KDCTEST",
            State = "2",

            Vehicle = new A
            {
                Registration = "ET53 LCO",
                Vin = "VIN123456789",
                MonthOfRegistration = 12,
                YearOfRegistration = 2013
            }
        };

        Mapper.Map(assessment, _assessment);

}

public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(
this IMappingExpression<TSource, TDest> expression)
{
    expression.ForAllMembers(opt => opt.Ignore());
    return expression;
}

A: As per the same question on Github, it seems no solution could be found for such issue.
Quoting library author:

Don't think I can get to this one, looking at the source code it seems that the appropriate action would be to have getters that don't throw.


text:
Q: how to import an existing array as an array with py I have the problem to understand how to import an created and existing array from the file.txt which has just that array in it and save it in the new .py file under an new name to work with it.
the file.txt has following content:
[['name1', 'x', '1', 'a'], ['name2', 'y', '2', 'b'], ['name3', 'b', '3', 'c'], ['name4', '1', '44', '12']]

i tried somethings like that:
text_file = open("file.txt", "r")
lines = text_file.readlines()
print(lines)
text_file.close()

type is list but i have the same list just with new [""] and same content
print(type(lines))
["[['name1', 'x', '1', 'a'], ['name2', 'y', '2', 'b'], ['name3', 'b', '3', 'c'], ['name4', '1', '44', '12']]"]

and if i try to read the array with
print(lines[1])

or
print(lines[1][2])

i get an error. thx for any help
Update:
The answer is:
import ast
  text_file = open("file.txt", "r")
  line          = text_file.readlines();
  lines         = eval(line[0])
  text_file.close()

A: Yes, you can use ast.literal_eval:
import ast
text_file = open("file.txt", "r")
lines = ast.literal_eval(text_file.readlines())
print(lines)
text_file.close()

Here you need to convert the string representation to list.


text:
Q: Draw circle when touched and when touch is removed in a custom view I am trying to draw to different circles when the user touches the screen and when the touch is removed.
I am somewhat successfull but the start touch circle disapperas when the "ACTION_UP" event circle is drawn.
Not sure What is going wrong.
My OnDraw and OnTouch functions are below
public void onDraw(Canvas canvas) {
    //drawing lines
        //lines
        canvas.drawCircle(point.x, point.y, 5, paint);
        //circles
        //canvas.drawCircle(point.x, point.y, 5, paint);
    }

public boolean onTouch(View view, MotionEvent event) {
    // if(event.getAction() != MotionEvent.ACTION_DOWN)
    // return super.onTouchEvent(event);
  //  points.add(point);
    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN :
        point.x = (int)event.getX();
        point.y = (int)event.getY();
        paint.setColor(Color.BLACK);
        break;

    case MotionEvent.ACTION_UP:
        point.x = (int)event.getX();
        point.y = (int)event.getY();
        paint.setColor(Color.BLUE);
        break;
    }
    invalidate();
    return true;
}

}

A: if you are trying to draw multiple circles when the user touches the screen and touch removed, you need to use a List of circles. you can have an ExampleCircle class where it have an x,y and color field.
public class ExampleCircle{

int x,y;
Color color;
//setters and getters

}

//onTouch
//assuming you already have a List object (List circleList=new ArrayList(); )
ExampleCircle newCircle=new ExampleCircle();
 switch(event.getAction()){
   case MotionEvent.ACTION_DOWN :
    newCircle.setX((int)event.getX());
    newCircle.setY((int)event.getY()) ;
    newCircle.setColor(paint.setColor(Color.BLACK));
    break;

case MotionEvent.ACTION_UP:
    newCircle.setX((int)event.getX());
    newCircle.setY((int)event.getY()) ;
    newCircle.setColor(paint.setColor(Color.BLACK));
    break;
}

circleList.add(newCircle);
invalidate();
return true;

//on draw method
replace
    canvas.drawCircle(point.x, point.y, 5, paint);

with
for(int i=0;i<circleList.size();i++){
   ExampleCircle currentCircle=circleList.get(i);

        canvas.drawCircle(currentCircle.getX(), currentCircle.getY(), 5, paint or currentCircle.getColor());

}


text:
Q: Field not populating in Flow Because of an external tools dependency, I'm having to add the "Full Name" of a user to the Account record, despite there being a lookup field on the Account as well.
We've hit the 15-unique object references threshold on formula fields on the SF Account object, so I am creating a text field "Growth Manager Full Name" and using a Flow to populate that field whenever the "Growth Manager" lookup field is changed.
The trigger logic is working fine. The problem is that, although the action step to populate Growth Manager Full Name with the value of $Record > Growth Manager > Full Name is successfully running, it's coming back null.

But the user I'm testing with (myself) has a Full Name value (see below).  Why would this be coming back "Null" in the flow?


text:
Q: Is there any way to modify the radius of navmesh agent via code at runtime? I have an object which gets smaller over time. As it gets smaller it becomes able to go to areas which were to tight for it before.
I tried changing radius property in my NavMeshAgent variable and then rebaking navMesh, but unfortunatelly it didn;t bring any result
_agent.radius = radius;


text:
Q: Unity - Wrong positioning of game objects after instantiating them I instantiate a Board GameObject using this code:
mainBoard.transform.position = camera.ViewportToWorldPoint(new Vector3(0f, 0f, camera.nearClipPlane));

Then I try to fill this board by instantiating Tiles GameObjects with loop:
for (int x = 0; x < width; x++)
         {
             for (int y = 0; y < height; y++)
             {
                 Vector3 tempPosition = camera.ViewportToWorldPoint(new Vector3(x, y, camera.nearClipPlane));
                 GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity) as GameObject;
                 backgroundTile.transform.SetParent(this.transform);
                 backgroundTile.name = "( " + x + "," + y + ")";

                 allTiles[x, y] = backgroundTile;
             }
         }

But the tiles are placed on wrong place. They should be placed one next to each other at the bottom left of the screen but only the first Tile is at correct position.
How can I get all tiles correctly placed on the board?
EDIT
Here is the prefab I am instantiating:

This is what I get:

and this is what I am trying to get:

Thank you.

A: I did not fully look at your code but try this;
for (int x = 0; x < width; x++)
         {
             for (int y = 0; y < height; y++)
             {
                 Vector3 tempPosition = camera.ViewportToWorldPoint(new Vector3(x, y, camera.nearClipPlane));
                 GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity,this.transform) as GameObject;

                 backgroundTile.name = "( " + x + "," + y + ")";

                 allTiles[x, y] = backgroundTile;
             }
         }

give it a try, sometimes UI makes stupid things if you set parent after you instantiate. So it is better to setparent when you instantiate like this;
GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity,this.transform) as GameObject;

A: If it is for building UI element, I would use the grid component or the vertical/horizontal  layout depending on what you want to do. Just set the instantiated element to the grid parent that will take care of the layout


text:
Q: Why is there a 'move zero,ra' at the entry of a MIPS program? I used a cross compiler mipsel-unknown-linux-gnu-gcc to compile a hello-world C program, and disassembled it with mipsel-unknown-linux-gnu-objdump, and get the following:
00400d00 <__start>:
  400d00:   03e00021        move    zero,ra
  400d04:   04110001        bal     400d0c <__start+0xc>
  400d08:   00000000        nop
  400d0c:   3c1c004b        lui     gp,0x4b
  400d10:   279c2010        addiu   gp,gp,8208
  400d14:   0000f821        move    ra,zero
  400d18:   8f848018        lw      a0,-32744(gp)
  400d1c:   8fa50000        lw      a1,0(sp)
  400d20:   27a60004        addiu   a2,sp,4
  400d24:   2401fff8        li      at,-8
  400d28:   03a1e824        and     sp,sp,at
  400d2c:   27bdffe0        addiu   sp,sp,-32
  400d30:   8f87801c        lw      a3,-32740(gp)
  400d34:   8f888020        lw      t0,-32736(gp)
  400d38:   00000000        nop
  400d3c:   afa80010        sw      t0,16(sp)
  400d40:   afa20014        sw      v0,20(sp)
  400d44:   afbd0018        sw      sp,24(sp)
  400d48:   8f998024        lw      t9,-32732(gp)
  400d4c:   00000000        nop
  400d50:   04110097        bal     400fb0 <__libc_start_main>
  400d54:   00000000        nop

The first instruction is 0x03e00021, and I translate it as opcode=0,rs=31,rt=0,rd=0,shamt=0,funct=33, so it is addu $0, $31, $0, writing to register $0, which is always zero. Why is there such a weird instruction?


text:
Q: I just updated to Https from Http, Should I change WordPress Address (URL) and Site Address in Wordpress Dashboard? I have just updated my blog technosamigos.com from http to https. I got the SSL via cPanel provided by Comodo. For me everything looks fine but one thing I see on popular results for 'http to https guide' on web is to change the website URL. Contradicting to this, I see lot of similar questions to this one, have gone through most of them and all have reported site went down after URL change.
Should I change WordPress Address (URL) and Site Address [URL] in Wordpress Dashboard from Settings > General? Currently they are set to http version.


text:
Q: Remove List elements selected in JTable I have a JTable based on table model that uses a List, I would like to delete elements that are selected in this JTable, from the List, the JTable is sortable, so when i get selected rows, I can't simply list.remove, because order is different. Any idea to solve this?

A: Take a look at JTable methods convertRowIndexToView and convertRowIndexToModel:

The selection is always in terms of JTable so that when
  using RowSorter you will need to convert using convertRowIndexToView
  or convertRowIndexToModel.
  The following shows how to convert coordinates from JTable to that of
  the underlying model:
  int[] selection = table.getSelectedRows();
  for (int i = 0; i < selection.length; i++) {
    selection[i] = table.convertRowIndexToModel(selection[i]);
  }
  // selection is now in terms of the underlying TableModel

Check out How to Use Tables # Sorting and Filtering for some examples.


text:
Q: How to retrieve current Django user and feed it into a db entry Question Closed: Please see response posted by Alasdair for solution.
I am adding instances of Pets to a table:
class Pet(models.Model):
   petName = models.CharField(max_length=100, default='My Pet')
   petImage = models.ImageField(default='default.png', blank=True)
   author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

The code above is fine, however "User" on the last line gives me all the Users ever signed up on my app in a dropdown menu (when viewed as a form). I want the author (i.e. the User that is logged in) to be automatically associated with this new pet object.
I dont know the ins and outs of the inbuilt auth_user database, so I dont know how to reference this specific instance of user, meaning the one who is logged in. I know that request.user on the other pages returns the user logged in, I just dont know how to feed that variable into this model. Any ideas?
* UPDATE: Included views.py *
@login_required(login_url="/accounts/login/")
def add_pet(request):
    if request.method == 'POST':
        form = forms.AddPet(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            return redirect('yourPet')
    else:
        form = forms.AddPet()
    return render(request, 'records/pet_create.html', {'form': form},)

A: First, edit your model form to remove the author field.
class AddPet(forms.ModelForm):
    class Meta:
        model = Pet
        fields = ['petName', 'petImage']  # leave out author

Then in your view, you can set instance.author to request.user before you save the instance.
if request.method == 'POST':
    form = forms.AddPet(request.POST, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.author = request.user
        instance.save()
        return redirect('yourPet')

The last step is to consider the case when the user is not logged in, but you have already covered this by using the login_required decorator.


text:
Q: Entity Framework Core 6 - ignoring annotations I want to create a migration with EF Core 6 and I'm getting an error because in table in column password I already have hash string of password which is 32 chars long but my model has an annotation for max length = 20.
My question is: how can I make the migration ignore the StringLength annotation?
[Required]
[DataType(DataType.Password)]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Password length must be between 3 and 20 characters long.")]
public string Password { get; set; }

Error:

Value too long for type character varying(20)

Database used is Postgres


text:
Q: How to disable auto set UserName & Password when type is Password I have developed an website in Asp.net c#. I have two login page one is for main website login and other is for Core functionality login.
My Problem is when main lagin page password is remembered and i open core functionality login page it will automatic Set user name and password of main login page to Core functionality page.
Both login page have different credential and different tables.
When i remove password type from password text box it will not fill credential, but this is not right way.
Basically, i don't want to auto fill/set credential to login page if browser saved it.
<asp:TextBox ID="txtInUserName" runat="server" autocomplete="off" Text="">
<asp:TextBox ID="txtInPassword" autocomplete="off" runat="server" Text="" TextMode="Password">

When i remove TextMode="Password" from Password textbox it will working fine, But it will shows password to everyone while typing.
Thanks.

A:
Basically, i don't want to auto fill/set credential to login page if browser saved it.

Basically, you cannot. You can state your intention by providing the autocomplete="off" attribute. However, newer browsers will gladly ignore that, since they think they know better what the user wants (and in many cases, they are right).
As an alternative, you could consider moving your "core functionality" to a different location, so that the browser realizes that these are two different web applications that require different credentials. Using a different directory might already suffice (http://example.com/core).


text:
Q: How do I see the memory locations of static variables within .bss? Supposing I have a static variable declared in gps_anetenova_m10478.c as follows:
static app_timer_id_t m_gps_response_timeout_timer_id;

I have some sort of buffer overrun bug in my code and at some point a write to the variable right before m_gps_response_timeout_timer_id in memory is overwriting it.
I can find out where m_gps_response_timeout_timer_id is in memory using the 'Expressions' view in Eclipse's GDB client. Just enter &m_gps_response_timeout_timer_id. But how do I tell which variable is immediately before it in memory?
Is there a way to get this info into the .map file that ld produces? At the moment I only see source files:
 .bss           0x000000002000011c        0x0 _build/debug_leds.o
 .bss           0x000000002000011c     0x11f8 _build/gps_antenova_m10478.o
 .bss           0x0000000020001314     0x161c _build/gsm_ublox_sara.o

A: I'll be honest, I don't know enough about Eclipse to give an easy way within Eclipse to get this. The tool you're probably looking for is either objdump or nm. An example with objdump is to simply run objdump -x <myELF>. This will then return all symbols in the file, which section they're in, and their addresses. You'll then have to manually search for the variable in which you're interested based on the addresses.
objdump -x <ELFfile> will give output along the lines of the following:
000120d8 g     F .text  0000033c bit_string_copy
00015ea4 g     O .bss   00000004 overflow_bit
00015e24 g       .bss   00000000 __bss_start
00011ce4 g     F .text  0000003c main
00014b6c g     F .text  0000008c integer_and

The first column is the address, the fourth the section and the fifth the length of that field.
nm <ELFfile> gives the following:
00015ea8 B __bss_end
00015e24 B __bss_start
0000c000 T _start
00015e20 D zero_constant
00015e24 b zero_constant_itself

The first column is the address and the second the section. D/d is data, B/b is BSS and T/t is text. The rest can be found in the manpage. nm also accepts the -n flag to sort the lines by their numeric address.


text:
Q: Should connection pool checking out match the checking in, in MongoDB Performance Events I am trying to identify a performance issue in one of my applications, with regular "MongoWaitQueueFullException"'s.  I have implemented a set of performance events to try and identify why.
        clientSettings.ClusterConfigurator = builder =>
        {
            builder.Subscribe<ConnectionPoolCheckingOutConnectionEvent>(e =>
                mongoMonitor.CheckingOutConnectionEventCount++);
            builder.Subscribe<ConnectionPoolCheckedOutConnectionEvent>(e =>
                mongoMonitor.CheckedOutConnectionEventCount++);
            builder.Subscribe<ConnectionPoolCheckingOutConnectionFailedEvent>(e =>
                mongoMonitor.CheckingOutConnectionFailedEventCount++);
            builder.Subscribe<ConnectionPoolCheckingInConnectionEvent>(e =>
                mongoMonitor.CheckingInConnectionEventCount++);
            builder.Subscribe<ConnectionPoolCheckedInConnectionEvent>(e =>
                mongoMonitor.CheckedInConnectionEventCount++);
            builder.Subscribe<ConnectionPoolAddingConnectionEvent>(e =>
                mongoMonitor.AddingConnectionEventCount++);
            builder.Subscribe<ConnectionPoolAddedConnectionEvent>(e =>
                mongoMonitor.AddedConnectionEventCount++);
            builder.Subscribe<ConnectionPoolOpeningEvent>(e =>
                mongoMonitor.OpeningEventCount++);
            builder.Subscribe<ConnectionPoolOpenedEvent>(e =>
                mongoMonitor.OpenedEventCount++);
            builder.Subscribe<ConnectionPoolClosingEvent>(e =>
                mongoMonitor.ClosingEventCount++);
            builder.Subscribe<ConnectionPoolClosedEvent>(e =>
                mongoMonitor.ClosedEventCount++);
            builder.Subscribe<ConnectionPoolClearingEvent>(e =>
                mongoMonitor.ClearingEventCount++);
            builder.Subscribe<ConnectionCreatedEvent>(e =>
                mongoMonitor.CreatedEventCount++);
        };

I then ran a load test (about 1000 clients a second) on a page that makes a database query
These are the results
Connection Pool Event   Count
Checking out    64585
Checked out 58416
Checking out failed 7094
Checking in 57119
Checked in  57095
Adding Connection   202
Added Connection    202
Opening 3
Opened  3
Closing 0
Closed  0
Clearing    0
Cleared 0
Created 202

The numbers are constantly increasing too - even though there are no current requests, or any database queries happening.
Should the Checking/ed out match the Checking/ed in?

A: I found the answer.  ++ isn't thread safe
Replacing with
Interlocked.Increment(ref CheckedOutConnectionEventCount);

Resolved the issue and so all numbers matched


text:
Q: Locking a row in a MYSQL table during a transaction I have a batch of queries like this:
START TRANSACTION
SELECT amount FROM piggybank WHERE id = 2
UPDATE piggybank SET amount = amount + 5 WHERE id = 1
COMMIT

I need to make sure that no one else can read or write the rows with ID 1 and 2, until the transaction ends. (Locking the whole table would be fine too)
The problem is, that when I read the MySQL manual, it said that starting a transaction will clear any locks made before starting it and in turn, locking will commit any outgoing transaction.
But I need to both lock the rows (or table) and use the transactions at the same time as well.

A: using a select ... for update query inside the transaction should give you the semantics you want - other updates will be locked, and other sessions attempting to take this same lock will block until you commit:
START TRANSACTION
SELECT * FROM piggybank WHERE id IN (1, 2) FOR UPDATE;
SELECT amount FROM piggybank WHERE id = 2;
UPDATE piggybank SET amount = amount + 5 WHERE id = 1;
COMMIT


text:
Q: Laravel group by issues with an inline select statement The SQL below works fine. It's taking this and implementing it in Laravel, where the issue is.
The sqlfiddle can be found here.
SELECT provider_id
     , o.shortName
     , count(b.site_id) as sites
     , ( select b.depositFee
              + ( select sum(depositFee)
                    from backhaul
                   where backhaul.parent_id=b.id
                )
       ) as entranceFee
     , ( select b.rightOfWayCharges
              + ( select sum(rightOfWayCharges)
                    from backhaul
                   where backhaul.parent_id = b.id
                )
       ) as rowFee
    FROM backhaul AS b
    JOIN organisation AS o
      ON (b.provider_id = o.id)
   WHERE isnull(b.parent_id)
   GROUP
      BY provider_id
       , entranceFee
       , rowFee

The table is recursive. Which gives me these results below:
--------------------------------------------------------
provider_id | sshortName | sites | entranceFee | rowFee
--------------------------------------------------------
802 | TM | 1 | 12500.00 | 7500.00
803 | TIME | 1 | 7500.00 | 0.00

The issue is Laravel can't seem to recognise the 'entranceFee' or 'rowFee' columns on the group by statement.
My Lararvel 5.7 implementation looks like this:
$sql = DB::raw("provider_id, o.shortName, count(b.site_id) as sites," .
"(select b.depositFee + (select sum(depositFee) from backhaul where backhaul.parent_id=b.id)) as entranceFee," .
"(select b.rightOfWayCharges + (select sum(rightOfWayCharges) from backhaul where backhaul.parent_id=b.id)) as rowFee") ;

$data = DB::table("backhaul as b")->select($sql)
   ->join("organisation as o", "b.provider_id", "=", "o.id")
   ->whereNull("b.parent_id")
   ->groupBy("b.provider_id", DB::raw("entranceFee"), DB::raw("rowFee"))
   ->paginate() ;

I'm getting the usual MySQL group by error about SELECT #4 missing from the GROUP BY statement.
I've tried adding as an array groupBy(["provider_id", DB::raw("entranceFee"), DB::raw("rowFee")]) but still it barfs. If I add the inline SQL selects as well, it barfs.

A: This was answered on Laracasts by Tray2:
The solution below is confirmed to work:
$data = DB::select('SELECT provider_id
     , o.shortName
     , count(b.site_id) as sites
     , ( select b.depositFee
              + ( select sum(depositFee)
                    from backhaul
                   where backhaul.parent_id=b.id
                )
       ) as entranceFee
     , ( select b.rightOfWayCharges
              + ( select sum(rightOfWayCharges)
                    from backhaul
                   where backhaul.parent_id = b.id
                )
       ) as rowFee
    FROM backhaul AS b
    JOIN organisation AS o
      ON (b.provider_id = o.id)
   WHERE isnull(b.parent_id)
   GROUP
      BY provider_id
       , entranceFee
       , rowFee');

A: Laravel is likely wrapping those in backticks which will cause MySQL to believe they are actual columns in a table somewhere.  Try wrapping those in DB::raw as well.
$data = DB::table("backhaul as b")->select($sql)
    ->join("organisation as o", "b.provider_id", "=", "o.id")
    ->whereNull("b.parent_id")
    ->groupBy([
        "b.provider_id",
        \DB::raw('entranceFee'),
        \DB::raw('rowFee'),
    ])
    ->paginate() ;


text:
Q: undefined an index error in php my file api upload using ajax got an undefined index error in php
this is my partial js
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");

   var request = new XMLHttpRequest();
  request.open('POST', 'upload.php');

          request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'SelectedFile=' + dataURL;

  request.send(data);
          console.log(data);

full code can be viewed here : http://jsfiddle.net/q99ek/1/
this is the result of console.log(data) SelectedFile=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMD…pgetFFfPS3PTnBRjoPiLHoaleQlFTvmiismrs6oSfsbF6KM+WMHGKsRAZxRRXFM7sP8KP/2Q==
but in my php file I tried
var_dump($_POST['']);
var)dump($_FILE['SelectedFile'];
both returned null.


text:
Q: "Index and length must refer to a location within the string" when I'm trying to create a substring I'm getting this error and I cant seem to get why.
    private void MessageReceived(String message)
    {
        int beginIndex = message.IndexOf(":");
        String index = message.Substring(1, beginIndex - 1);
        if (index == "SHOW_TIME")
        {
            String time = message.Substring(11, message.Length -1);
            if (alarm == time)
            {
                MessageBox.Show("ALARM ALARM ALARM ALARM");
            }
        }
    }

The error pops in when the program gets to the String time line.

A: You're starting at index 11, but attempting to go until message.Length - 1. That will put you outside the end of the array which is causing the error.  You need to go until message.Length - 12;
String time = message.Substring(11, message.Length - 12);


text:
Q: Create library in j2me I am a beginner in j2me.I want to create a library(jar) in j2me. Could anyone guide me regarding the same.

A: Just simple steps you have to follow.

*

*Create New Project Without any midlet.

*Create your classes which you want in library.

*Compile all classes.

*Right click on Project & Select Properties.

*Click on creating Jar & Give name for Jar & Jad

*Now Clean & Build Your Project.

*Your Library ready to use in jar file.


text:
Q: How to get environment variable from a core dump In UNIX environment(linux/solaris/AIX) my application crashing. Please help to me get environment variable from the core dump

A: Running strings -a core should produce an obvious-looking block of strings like HOME=..., HOSTNAME=..., etc.
You can also examine initial environment by looking at the 3rd argument to main, which is a envp[] -- a NULL-terminated array of pointers to the environment strings.
Finally, current environment block is pointed at by __environ or similar variable.


text:
Q: onResponse is not succesful when trying to connect with an api I am trying to retrieve images from larntech and inflate the images into a recyclerview.
But it does not succeed when "going through" onResponse, it just comes up with the toast message "error". Thereby it does not show me anything in my stacktrace- tell me if im wrong, still a beginner.
I hope someone can point me in the right direction.
  public class MainActivity extends AppCompatActivity {

private List<ImagesResponse> imagesResponseList = new ArrayList<>();
RecyclerView rv;
CustomAdapter adapter;

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

    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.grid);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);

    adapter = new CustomAdapter(new ArrayList<ImagesResponse>(), this);
    recyclerView.setAdapter(adapter);

    getAllImages();
}

public void getAllImages() {
    final Call<List<ImagesResponse>> imagesResponse = ApiClient.getInterface().getAllImages();
    imagesResponse.enqueue(new Callback<List<ImagesResponse>>() {
        @Override
        public void onResponse(Call<List<ImagesResponse>> call, Response<List<ImagesResponse>> response) {
            if (response.isSuccessful()) {
                String message = "success";
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();

                imagesResponseList = response.body();
                getAllImages();

            } else {
                String message = "error";
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<List<ImagesResponse>> call, Throwable t) {

            String message = t.getLocalizedMessage();
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        }
    });

}

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
    private List<ImagesResponse> imagesResponses;
    private Context mContext;
    private LayoutInflater layoutInflater;

    public CustomAdapter(List<ImagesResponse> imagesResponses, Context mContext) {
        this.imagesResponses = imagesResponses;
        this.mContext = mContext;
        this.layoutInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.row_grid_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        ImagesResponse photoItem = imagesResponses.get(position);
        Glide.with(mContext).load(photoItem.getUrl())
                .error(R.drawable.ic_cloud_off_red)
                .placeholder(R.drawable.ic_cloud_off_red)
                .into(holder.image_view);

    }

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

    void setImages(ArrayList<ImagesResponse> newImages) {
        imagesResponses = newImages;
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView image_view = null;
        RelativeLayout frontLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            this.image_view = itemView.findViewById(R.id.images);

        }
    }

}
 }

 public class ApiClient {

private static Retrofit getRetrofit() {

    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http:/api.larntech.net/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    return retrofit;
}

public static ApiInterface getInterface(){
    ApiInterface apiInterface = getRetrofit().create(ApiInterface.class);
return apiInterface;
}

A: in ApiInterface.java class
@Headers({ "Content-Type: application/json;charset=UTF-8"})
@GET
Call<List<Users>> getUser(
        @Url String url
);

in MainActivity class
  RecyclerView recyclerView;
  ApiInterface service;
  Retrofit retrofit;
  List<UserModelList> usersList = new ArrayList<>();
  UserListFollowAdapters adapter;

  public MainActivity() {
    // Required empty public constructor
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.MINUTES)
            .readTimeout(10, TimeUnit.MINUTES)
            .writeTimeout(10, TimeUnit.MINUTES)
            .build();
    retrofit = new Retrofit.Builder()
            .baseUrl(RetrofitGenerator.BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
    service = retrofit.create(ApiInterface.class);
   this.runOnUiThread(this::getUsers);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activitymain);
     recyclerView = findViewById(R.id.recycler_userlist);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new
    DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    recyclerView.setLayoutManager(layoutManager);
    adapter = new UserListFollowAdapters(this, usersList);
    recyclerView.setAdapter(adapter);
}

public void getUsers(){
 Call<List<Users>> call = service.getUser("http://www.example.com/get/users");
        call.enqueue(new Callback<List<Users>>() {
            @Override
            public void onResponse(Call<List<Users>> call, Response<List<Users>> response) {
                List<Users> serverResponse = response.body();
                userslist.addAll(serverResponse);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<ResponseModel> call, Throwable t) {
                Toast.make(t.getMessage());

            }
        });

}


text:
Q: Customizing event appearance primefaces schedule I'm using the Primefaces Schedule component to render events in my web app. But i need to do a little trick with him. For each rendered event i need to show a tooltip with event details. Using the window.onload listener and some jquery functions is easy to display the tooltips of the current date frame. But, since the schedule uses ajax to display the next date frame when i press the next and prev buttons, the tooltip crashes. I've tried using the:
window.addEventListener('DOMSubtreeModified', function(){
    // create bubble popups
    $('.fc-event-inner.fc-event-skin').CreateBubblePopup( options );
}, false);

But seems that it requires too much processing and the page gets slow. There is some other way to add the tooltips to each event rendered?

A: Try it like this:
$(window).load(function() {
   $(document).delegate(".fc-event-inner", "mouseenter mouseover", function(event){
       $('.fc-event-inner.fc-event-skin').CreateBubblePopup( options );

   });
});

Update
I had this feeling that somewhere in the scheduler js file they doing stopPropagation() on mouseover...
look at the following piece of code from ther js file located at primefaces-3.4.1-sources\META-INF\resources\primefaces\schedule
/* Event Element Binding
-----------------------------------------------------------------------------*/

function lazySegBind(container, segs, bindHandlers) {
    container.unbind('mouseover').mouseover(function(ev) {
        var parent=ev.target, e,
            i, seg;
        while (parent != this) {
            e = parent;
            parent = parent.parentNode;
        }
        if ((i = e._fci) !== undefined) {
            e._fci = undefined;
            seg = segs[i];
            bindHandlers(seg.event, seg.element, seg);
            $(ev.target).trigger(ev);
        }
        ev.stopPropagation();
    });
}

So...
Try to remove ev.stopPropagation();
By the way , know that the scheduler is actually a FullCalendar jQuery plugin , so you might find some usefull information if you google for fullcalendar tooltip
Here is the link for the modified Primefacess 3.4 jar (no stopPropagation for scheduler events)


text:
Q: Accidentally ran blkdiscard on root drive, screwed? Long story short. I screwed up badly and managed to run blkdiscard on my root drive instead of the intended disk. Am I completely screwed?

A: If you followed best practice, the only thing of value you have lost is /etc. Since /home, /var and friends are on different partitions, the easiest way to fix is to reinstall and restore /etcfrom backup - this will also link in the existing file systems via fstab.


text:
Q: Log4Net MemoryAppender seems to miss high speed log events I am using a log4net MemoryAppender to show my log4net output on a form text box.  The relevant part of my config file is:
<appender name="MemoryAppender" type="log4net.Appender.MemoryAppender" >
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level %date %message%newline" />
    </layout>
</appender>

The code that updates the form is fired by a timer and looks like:
var events = _memoryAppender.GetEvents();

foreach (var loggingEvent in events)
{
    textBoxOutput.Text += loggingEvent.Level + "  " + loggingEvent.MessageObject + Environment.NewLine;
}
_memoryAppender.Clear();

It is working, but when my application logs a lot of messages in a short period of time I don't seem to see them.  Does anyone have an idea what is going on?
As a workaround I am using Chainsaw and a UDP appender:
   <appender name="UdpAppender" type="log4net.Appender.UdpAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="ERROR"/>
    </filter>
    <param name="RemoteAddress" value="127.0.0.1" />
    <param name="RemotePort" value="8080" />
    <layout type="log4net.Layout.XmlLayoutSchemaLog4j, log4net" />
</appender>

I like my own UI better, though, so I am still looking for answers.

A: I assume the following happens: While you are writing your log messages in the text box, new messages are logged. When you clear the messages in the appender you also remove these new messages, which are not written to the text box.
You could improve the situation by clearing the appender before starting to write messages to the text box but I think you should create your own memory appender and provide a method that returns the messages and clears the array in one step. Something like this:
public class MyMemoryAppender : MemoryAppender
{
    public LoggingEvent[] GetAndClearEvents()
    {
        lock (m_eventList.SyncRoot)
        {
            var events = (LoggingEvent[]) m_eventsList.ToArray(typeof(LoggingEvent));
            m_eventsList.Clear();
            return events;
        }
    }
}


text:
Q: Imposible editar registros cuyo ID sea mayor a 9: not all arguments converted during bytes formatting CONTEXTO. Windows 10, Python 3.9.1, Flask 2.0.1 y MySQL 5.7.24.
QUÉ QUIERO HACER. Un CRUD con Python, Flask y MySQL.
PROBLEMA. Listo en el navegador todos los registros de una tabla de la BD, y a cada fila le pongo un link para editarlo. Cuando doy clic a editar soy redirigido a una nueva vista que muestra un formulario para editar el registro. Todo funciona bien siempre y cuando los IDs de los registros tengan un único dígito (1-9). Pero si intento editar un registro cuyo ID tiene dos dígitos (del 10 en adelante), salta este error: MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting.
ESTO ES LO QUE ESTOY HACIENDO
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'db'
mysql = MySQL(app)

app.secret_key = "mysecretkey"

@app.route('/')
def Index():
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM contacts')
    data = cur.fetchall()
    cur.close()
    return render_template('index.html', contacts=data)

@app.route('/edit/<id>', methods=['POST', 'GET'])
def get_contact(id):
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM contacts WHERE id = %s', (id))
    data = cur.fetchall()
    cur.close()
    return render_template('edit-contact.html', contact=data[0])

if __name__ == "__main__":
    app.run(port=3000, debug=True)

CÓMO HE INTENTADO SOLUCIONAR EL PROBLEMA
Googleando, encuentro que este problema está relacionado con el modo en que se arma la query dentro del cur.execute. He intentado estas variantes, sin éxito:

*

*cur.execute('SELECT * FROM contacts WHERE id = %s', (id))

*cur.execute('SELECT * FROM contacts WHERE id = \'%s\'', (id))

*cur.execute('SELECT * FROM contactsWHEREid = %s', (id))

*cur.execute("SELECT * FROM contactsWHEREid = %s", (id))

*cur.execute("""SELECT * FROM contacts WHERE id = %s""", (id))

*cur.execute("SELECT * FROM contacts WHERE id = '"+id+"'")

*También intenté convertir el ID a str: id = str(id)
Ayuda, por favor! Saludos!

A: El compañero @Christian hizo un comentario sugiriendo el uso de los f-strings. Al buscar qué son los f-strings me entero que el código porcentaje (%s) utilizado para armar queries no es muy bueno que digamos, y que lo mejor es utilizar otras alternativas, como, precisamente, los f-strings. Así que modifiqué la query, de esto:
cur.execute('SELECT * FROM contacts WHERE id = %s', (id))

A esto:
cur.execute(f"SELECT * FROM contacts WHERE id = {id}")

Y finalmente el error mencionado desapareció.
¡Gracias!


text:
Q: Exponential map on matrices I was thinking about different definition of exponential:
Case 1:
Let $z=a+ib$ be a complex number so we have the exponential map $\exp(z)=\sum \frac{z^n}{n!}$.
But one can also view $z$ as a matrix (indeed $z$ is a special automorphism of $\mathbb{R}^2$) of the form $z_r:=Z:=\begin{pmatrix}a & -b \\ b & a \end{pmatrix}$ so one has the exponential matrix map defined by $\exp(Z)=\sum \frac{Z^n}{n!}$ it is not difficult to show that $\exp(z_r)=\exp(z)_r$ (I can give more details for this if it worth, the idea is to use the polar expression of $z$ and that write $Z=a\operatorname{Id}+bI$ and use the Taylor expansion of $\sin$ and $\cos$).
Case 2: (The question)
What about the more general case of the exp function on a linear operator $\phi:\mathbb{C}^n\longrightarrow\mathbb{C}^n$?
Indeed, let $X$ be a complex matrix of size $n$, and let $X_r$ the block-matrix obtained by replacing to each $x_{ij}$ the $2\times2$ matrix ${x{_{ij}}}_r$ is it true that $\exp(X_r)=\exp(X)_r$?
Is it a general thing?
My approach:
I've tried with a calculation like the Case 1 but it seems to be more difficult to calculate. Another approach I have in mind is to use the fact that $\mathbb{C}^n$ is a real smooth variety with standard complex structure and than use the flow theorem. This approach gives me a characterization for $\exp(X_r)$ but my problem is to prove that $\exp(X)_r$ is also a solution for the flow.
(Maybe if this is not very clear I would clarify)
Questions:

*

*Is it possible to prove that $\exp(X_r)=\exp(X)_r$ by straightforward calculation?

*Is it possible to prove that $\exp(X_r)=\exp(X)_r$ by using the flow theorem?

Any hint or suggestion would be great!

A: Let's dig a bit further into your statement "let $X_r$ the block-matrix obtained by replacing to each $x_{ij}$ the $2\times2$ matrix $(x{_{ij}})_r$". I'd like to reframe that as follows: let $\Phi:M_{n \times n}(\Bbb C) \to M_{2n \times 2n}(\Bbb R)$ denote the map defined by
$$
\Phi(A + Bi) = A \otimes I + B \otimes J,
$$
where $A,B$ are real $n\times n$ matrices, $\otimes$ denotes the Kronecker product, $I$ denotes the size $2$ identity matrix, and
$$
J = \pmatrix{0&-1\\1&0}.
$$
I claim that if $X = A + Bi$, then $X_r = \Phi(X)$. Moreover, I claim the following:

*

*For real $p,q$ and $X,Y \in M_{n \times n}(\Bbb C)$, $\Phi(pX + qY) = p\Phi(X) + q\Phi(Y)$

*For $X,Y \in M_{n \times n}(\Bbb C)$, $\Phi(XY) = \Phi(X)\Phi(Y)$

*For a convergent sequence $X_n \to X$, we have $\Phi(X_n) \to \Phi(X)$. That is, $\Phi(\lim_{n \to \infty}X_n) = \lim_{n \to \infty}\Phi(X_n)$.

These results can be proved using the properties of the Kronecker product and the fact that $J^2 = -I$. Now for any $X \in M_{n \times n}(\Bbb C)$, denote
$$
\exp_N(X) = \sum_{k=0}^N \frac{X^k}{k!}.
$$
Using properties 1 and 2 above, verify that $\Phi(\exp_N(X)) = \exp_N(\Phi(X))$. From there, we can conclude that
$$
\Phi(\exp(X)) = \Phi\left(\lim_{N \to \infty} \exp_N(X)\right)
= \lim_{N \to \infty}\Phi(\exp_N(X)) = \lim_{N \to \infty} \exp_N(\Phi(X))
= \exp(\Phi(X)).
$$
That is, we indeed have $\Phi(\exp(X)) = \exp(\Phi(X))$, which is what we wanted.

A: To elaborate on my comment:

*

*If $X,Y$ commute then $e^{X+Y}=e^X e^Y$. This in particular holds for $X=a\text{ Id}$ and $Y=bI$.

*If $I^2=-\text{Id}$, then $\exp(b I)=(\cos b)\operatorname{Id}+(\sin b)I.$
Both of these may be shown by expanding out the appropriate Taylor series. Combining these, we indeed have
\begin{align}
\exp(z_r)
&=\exp(a\operatorname{Id}+bI)\\
&=\exp(a\operatorname{Id})\exp(bI)\\
&=[(e^a\cos b)\operatorname{Id}+(e^b \sin b)I]\\
&=(e^a\cos b+i e^a\sin b)_r \\
&= (e^{a+ib})_r\\
&= \exp(z)_r.
\end{align}
The limitation of this approach compared to Ben's is that theirs allows matrices $A,B$ whereas mine is specifically for scalar $a,b$.


text:
Q: Populating UITableView with timeout I am creating chatbot application, which imitates real user "typing" status, so after each message there must be 1 second (for example) delay, before application will post second message.
My messaging logic is
    let size = dictionary[key]!.count;
    let pointer = random(lower: 0, upper: UInt32(size) - 1);
    let part = dictionary[key]![pointer];

    for row in part {
        if let message = row as? Message {
            self.sendMessage(message: message);
            print("MESSAGE TRIGGERED");
            usleep(1 * 1000 * 1000)
        }

        if let question = row as? Question {

        }
    }

here i am taking random array of Messages (actually strings), and in a loop just adding them to my table, like this
func sendMessage(message: Message) {
    self.tableView.beginUpdates();

    let indexPath = IndexPath.init(row: self.log.count, section: 0);
    self.log.insert(
        message,
        at: self.log.count
    );
    self.tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.fade);
    self.tableView.endUpdates()
    self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}

problem is, that if there is 10 strings in an array of messages, i see 10 "MESSAGE TRIGGERED" logs in a console, 1 new row, each second, like i planned, but in a table, i don't see any rows for 10 second, and then they all just appears at once. Why?

A: Your problem is that you are running on the main thread and never giving the system the chance to update the table.  You violated the rule: never call sleep on the main thread.
You can fix this several ways:
1) Run your loop on a background thread, and return to the main thread to call self.sendMessage and print.
let size = dictionary[key]!.count;
let pointer = random(lower: 0, upper: UInt32(size) - 1);
let part = dictionary[key]![pointer];

DispatchQueue.global().async {
    for row in part {
        if let message = row as? Message {
            DispatchQueue.main.async {
                self.sendMessage(message: message);
                print("MESSAGE TRIGGERED");
            }
            usleep(1 * 1000 * 1000)
        }

        if let question = row as? Question {

        }
    }
}

2) Use a repeating timer with an interval of 1 second and add one item to your table each time the timer fires.
let size = dictionary[key]!.count;
let pointer = random(lower: 0, upper: UInt32(size) - 1);
let part = dictionary[key]![pointer];

var idx = 0
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in

    if idx >= part.count {
        timer.invalidate()
    } else {
        let row = part[idx]
        if let message = row as? Message {
            self.sendMessage(message: message);
            print("MESSAGE TRIGGERED");
        }

        if let question = row as? Question {

        }
    }
    idx += 1
}

3) Delay each table addition by an increasingly larger delay:
let size = dictionary[key]!.count;
let pointer = random(lower: 0, upper: UInt32(size) - 1);
let part = dictionary[key]![pointer];

var delay = 0.0
for row in part {
    if let message = row as? Message {
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            self.sendMessage(message: message);
            print("MESSAGE TRIGGERED");
        }
        delay += 1.0
    }

    if let question = row as? Question {

    }
}

A: replace your this code by:
let size = dictionary[key]!.count;
let pointer = random(lower: 0, upper: UInt32(size) - 1);
let part = dictionary[key]![pointer];

for row in part {
    if let message = row as? Message {
        self.sendMessage(message: message);
        print("MESSAGE TRIGGERED");
        usleep(1 * 1000 * 1000)
    }

    if let question = row as? Question {

    }
}

this code:
let size = dictionary[key]!.count;
let pointer = random(lower: 0, upper: UInt32(size) - 1);
let part = dictionary[key]![pointer];
var timer = Timer!
for row in part {
    if let message = row as? Message {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)
    }

    if let question = row as? Question {

    }
}
timer.invalidate()

also add this function:
  @objc func runTimedCode() {
      self.sendMessage(message: message);
        print("MESSAGE TRIGGERED");
  }

A: Do not sleep main thread.
Instead, you set a function call a second after.
You should create a timer inside every cell, then every cell have seperate timers.
class MyCustomCell: UITableViewCell {
@IBOutlet weak private var myLabel: UILabel!

private var timer: Timer?
private var timeCounter: Double = 0

var expiryTimeInterval: TimeInterval? {
    didSet {
        startTimer()
    }
}

private func startTimer() {
    if let interval = expiryTimeInterval {
        timeCounter = interval // should be 1 for 1 second.
        if #available(iOS 10.0, *) {
            timer = Timer(timeInterval: 1.0,
                          repeats: true,
                          block: { [weak self] _ in
                            guard let strongSelf = self else {
                                return
                            }
                            strongSelf.onComplete()
            })
        } else {
            timer = Timer(timeInterval: 1.0,
                          target: self,
                          selector: #selector(onComplete),
                          userInfo: nil,
                          repeats: true)
        }
    }
}

@objc func onComplete() {
    guard timeCounter >= 0 else {
        timer?.invalidate()
        timer = nil
        return
    }
    myLabel.text = String(format: "%d", timeCounter)
    timeCounter -= 1
}
}

And you can use like this ;
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell =  tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCustomCell

    cell.expiryTimeInterval = 10

    return cell
}


text:
Q: How to find a sum of the series? $ S=\sum_{n=1}^\infty\left(\frac{\sin nx}{n}+\frac{\cos nx}{n^2}\right) $
How to find a sum of the series?
  $$
S=\sum_{n=1}^\infty\left(\frac{\sin nx}{n}+\frac{\cos nx}{n^2}\right)
$$

I tried to do something like that:
$$
\begin{aligned}
&z=\cos x+i\sin x\\
&S=\sum_{n=1}^\infty\text{Im}\left(\frac{z^n}{n}\right)+\sum_{n=1}^\infty\text{Re}\left(\frac{z^n}{n^2}\right)
\end{aligned}
$$
However, $\sum_{n=1}^\infty\frac{z^n}{n^2}=\text{Li}_2(z)$, and I have no idea what $\text{Re}(\text{Li}_2(z))$ is here.
So, I'd be very grateful if someone pointed out the right way of solving this problem.


text:
Q: PowerPivot - Your beta software has expired I'm running the 32-bit version of Excel 2010 on Windows 7 64. I've downloaded the 32-bit version of PowerPivot from here however I get the following error:

Now I can see what the error message is telling me but I've downloaded the latest version. I've also done a google search and a few hits turned up in 2010 with similiar issues when running older versions of the software but the replies tend to point the user to downloading the latest version of PowerPivot. I have done that as of 15th December 2011.
Does anyone have any ideas what the issue may be here?


text:
Q: java - Exception in thread "main" java.lang.NumberFormatException: For input string: "" at I am trying to run the below example whereby if I enter a letter in an integer box/field or select Ok/Cancel without entering a value that it then exits ok or forces you to enter a valid numeric value.
For the text fields it works fine but not for the integer,  I get the below error.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)

 for this code,  is it possible to achieve what I want?  thanks for any answers in advance

import javax.swing.*;

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

    {

        //THIS IS FOR THE 1ST POP UP BOX
        // prompt the user to enter their name
        String name = JOptionPane.showInputDialog( "What is your Firstname?");

        // get the user's input. note that if they press Cancel, 'name' will be
        null
        System.out.printf("The user's name is '%s'.\n", name);

//

        //THIS IS FOR THE 2ND POP UP BOX
        // prompt the user to enter their name
        String nametwo = JOptionPane.showInputDialog(frametwo, "What is your
       Surname?");

        // get the user's input. note that if they press Cancel, 'name' will be
      null
        System.out.printf("The user's name is '%s'.\n", nametwo);

//

        //THIS IS FOR THE 3RD POP UP BOX
        // prompt the user to enter their age
        int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
      "How old are you?"));
        //if (num.isEmpty())

        // get the user's input. note that if they press Cancel, 'age' will be
       null
        System.out.printf("Your age is '%s'.\n", namethree);

        System.out.println("********************************");

        System.exit(0);
    }

    }

A: You need to add exception handling around the call to Integer.parseInt to catch the conversion error - this method will throw a NumberFormatException for any string that can't be converted into an Integer.
Something like:
try
{
    int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
        "How old are you?"));
}
catch (NumberFormatException)
{
    //TODO: display an error message and retry the input
}


text:
Q: Ruby squeeze alternative in go Ruby strings had a method called squeeze. From ruby docs :

Builds a set of characters from the other_str parameter(s) using the
  procedure described for String#count. Returns a new string where runs
  of the same character that occur in this set are replaced by a single
  character. If no arguments are given, all runs of identical characters
  are replaced by a single character.

"yellow moon".squeeze                  #=> "yelow mon"
"  now   is  the".squeeze(" ")         #=> " now is the"
"putters shoot balls".squeeze("m-z")   #=> "puters shot balls"

IS there an alternative function for this operation in golang? If not whats the best way to do it in go?

A: You can do it like this:
func Squeeze(s string) string {
    result := make([]rune, 0)
    var previous rune
    for _, rune := range s {
        if rune != previous {
            result = append(result, rune)
        }
        previous = rune
    }
    return string(result)
}

Bear in mind that strings are UTF8 in Go so you have to use runes (characters) rather than bytes in order to be compatible with non-ASCII strings.


text:
Q: How to correctly return result of matrixes multiplication I got a class for boolean matrix.
Deallocating memory in destructor does not work correctly, it tries to delete invalid pointers - as I noticed, that happens when I try to multiply.
In operator* I return local object as a result and that part causes invalid pointers - so program crashes when deleting in destructor - the question is why that happens on this code ? and how to return result properly ?
Here's the code:
#include <iostream>
using namespace std;
class BoolMatrix
{
    private:
        bool ** items;

    public:
        size_t rows, cols;
        BoolMatrix(size_t = 0, size_t = 0);
        ~BoolMatrix();

        BoolMatrix operator * (const BoolMatrix &) const;
        //some other members
};

BoolMatrix::BoolMatrix(size_t r, size_t c) : rows(r), cols(c)
{
    items = new bool*[r];
    for (size_t i = 0; i < r; i++)
    {
        items[i] = new bool[c];
        for (size_t j = 0; j < c; j++)
            items[i][j] = 0;
    }
}

BoolMatrix::~BoolMatrix()
{
    if (items)
    {
        for (size_t i = 0; i < rows; i++)
        {
            if (items[i])
                delete[] items[i];
            items[i] = NULL;
        }

        delete[] items;
        items = NULL;
    }
}

BoolMatrix BoolMatrix::operator * (const BoolMatrix& that) const
{
    //NxM * MxK = NxK
    if (cols != that.rows)
        return NULL;

    Matrix res(rows, that.cols);

    for (size_t i = 0; i < rows; i++)
    {
        for (size_t j = 0; j < that.cols; j++)
            for (size_t l = 0; l < that.rows; l++)
                res.items[i][j] = (res.items[i][j] + items[i][l]*that.items[l][j]) != 0;
    }

    return res;
}

int main(int argc, char *argv[])
{
    size_t n;
    cin >> n;
    BoolMatrix a(n, n);
    //matrix reading code
    a*a;
    return 0;
}

Thanks

A: overload '=' operator and use it like a=a*a ; and destructor must be
BoolMatrix::~BoolMatrix()
{

        for (size_t i = 0; i < rows; i++)
        {

            delete [] items[i];
        }

        delete[] items;

    }
}

A: overload the copy constructor to copy whole array, so when function deletes it's local instance of class, it will delete it's own matrix, while function in main will have it's copy of matrix (note that if you leave it like this, what u get as result of function and variable from main which you equal in main to the result of function, point to exact same memory, that's why u need copy constructor)

A: I think that what happens is that you are trying to delete[] memory on the stack.
Instead of
Matrix res(rows, that.cols);

try with
Matrix res=new Matrix(rows, that.cols);


text:
Q: confusion of View Helpers I'm on shared hosting where www only accessible by web server , so I change the structure recommended for the project based ZenFramework putting the library under the folder www :
www/
index.php
application/
Modules/
front/
admin/
  Library/
the .htaccess :
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
I tested locally under WampServer, everything works fine.
when I go online, I get errors on View Helpers :
Warning: include_once(): Unable to access /home/www/application/Modules/front/views/helpers/HeadMeta.php
there is confusion between ZendFramework views helpers and the view helpers that I create myself. and when I copy the content :
library \ Zend \ View \ Helper \
to
\ application \ modules \ front \ views \ helpers
everything works fine ! and it is the same concern for module admin/
I do not understand how why.
is what I have to keep the View helpers with my aides custom view ?
Thank you in advance for your answers.
Update:
I have not attached and any help create by myself . but I have to create action helpers, like this:
resources.frontController.moduleDirectory = APPLICATION_PATH "/Modules"
resources.frontController.defaultModule ="front"
resources.frontController.actionHelperPaths.Application_front_Controller_Helper = APPLICATION_PATH "/Modules/front/controllers/helpers/"
resources.modules[]=

Bootstrap module :
class front_Bootstrap extends Zend_Application_Module_Bootstrap

{
    public function _initHelper()

    {

        $this->bootstrap('frontController');

        $navigation = Zend_Controller_Action_HelperBroker::getStaticHelper('NavigationPath');

        Zend_Controller_Action_HelperBroker::addHelper($navigation);

    }
}

A: Several thoughts/questions/comments:

*

*It sure seems to be looking for the view helper within your Module folder. Are you attempting to call a custom HeadMeta helper developed by you, or are you are attempting to call the standard Zend_View_Helper_HeadMeta helper? Have you set any helper paths in either Bootstrap or application/config.ini?

*Your current setup has a security issue: What if someone requests the url: http://exmaple.com/application/config.ini? I don't see any protection there. Note that you don't necessarily have to move all your ZF folders up in to the document root. Rather, you could push them down and place deny-all protection on that folder. See: Zend Framework on shared hosting. That blog post offers other approaches to ZF on shared hosting, as well.

*Finally, when something works on Windows but doesn't work on Linux, there are several usual suspects to check.


text:
Q: Выделить элементы в нужном порядке Как можно с использованием nth-of-type или nth-child выделить элементы в таком порядке:
2-3-7-8-12-13-17-18... (начинать со второго, выделять каждые два и пропускать три)
и в таком:
4-5-6-9-10-11-14-15-16...
Пытаюсь сделать разметку для карточек. Первая карточка должна занимать 12 колонок, вторая и третья по 6, четвертая, пятая и шестая по 4, потом опять две карточки по 6, потом три по 4 и так далее...
Примерно так:

———————————————————————
——————————— ———————————
——————— ——————— ———————
——————————— ———————————
——————— ——————— ———————
——————————— ———————————
——————— ——————— ———————

A: Пример №1

span {
  display: inline-block;
  padding: 5px;
  background: #ccc;
  margin: 5px;
}

span:nth-of-type(5n + 2),
span:nth-of-type(5n + 3) {
  background: #f00;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Пример №2

span {
  display: inline-block;
  padding: 5px;
  background: #ccc;
  margin: 5px;
}

span:nth-of-type(5n + 4),
span:nth-of-type(5n + 5),
span:nth-of-type(5n + 6) {
  background: #f00;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


text:
Q: Job in spring batch is getting executed multiple times and not stopping I am trying to read data from cassandra using spring batch, where I have implemented ItemReader, ItemProcessor, and ItemWriter. I am able to read the data , process it and write back the data to the same table. I am creating xml file to execute the job:
xml:
    <job id="LoadStatusIndicator" job-repository="jobRepository" restartable="false">
        <step id="LoadStatus" next="">
            <tasklet>
                <chunk reader="StatusReader" processor="ItemProcessor" writer="ItemWriter"
                    commit-interval="10" />
            </tasklet>
        </step>
    </job>

    <beans:bean id="ItemWriter" scope="step"
        class="com.batch.writer.ItemWriter">
    </beans:bean>

<beans:bean id="ItemProcessor" scope="step"
        class="com.batch.processor.ItemProcessor">
    </beans:bean>
    <beans:bean id="Reader" scope="step"
        class="com.reader.ItemReader">
        <beans:property name="dataSource" ref="CassandraSource" />

    </beans:bean>

applicationcontext.xml:
<beans:bean id="CassandraSource" parent="DataSourceParent">
<beans:property name="url" value="jdbc:cassandra://${cassandra.hostName}:${cassandra.port}/${cassandra.keyspace}" />
<beans:property name="driverClassName" value="org.apache.cassandra.cql.jdbc.CassandraDriver" />
</beans:bean>

reader class:
   public static final String query = "SELECT * FROM test_1 allow filtering;";

 @Override
    public List<Item> read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException
    {
    List<Item> results = new ArrayList<Item>();
try {
results = cassandraTemplate.select(query,Item.class);
    } catch (Exception e) {
    e.printStackTrace();
    }
return results;
    }

writer classs:
@Override
public void write(List<? extends Item> item) throws Exception {
    try {
    cassandraTemplate.insert(item);
}catch(Exception e){e.printStackTrace();}

But the problem is the whole job is getting executed multiple times , infact it is not stopping at all. I have to force stop the job execution. I have only 2 rows in the table.
I think it is because of the commit-interval defined in xml, but having commit-interval = 10, job executes more than 10 times
According to my understanding, when I run the xml file that means I am running the job only one time, it calls the reader once keeps the data in the run time memory (job repository), calls item processor once (I use list ) and the whole list is inserted at once

A: SOLVED
In reader class I wrote:
if (results.size!=0)
return results;
else
return null;


text:
Q: How can we use array of 10000 rows and 10000 cols with AleaGpu? How can we use array of  10000 rows  and  10000 cols (instead of rows =10 and rows =5)  with AleaGpu ?
private void button3_Click(object sender, EventArgs e)
{
    var worker = Worker.Default;
    const int rows = 10;
    const int cols = 5;
    var rng = new Random();
    var inputs = new double[rows, cols];
    for (var row = 0; row < rows; ++row)
    {
        for (var col = 0; col < cols; ++col)
        {
            inputs[row, col] = rng.Next(1, 100);
        }
    }
    var dInputs = worker.Malloc(inputs);
    var dOutputs = worker.Malloc<double>(rows, cols);
    var lp = new LaunchParam(1, 1);
    worker.Launch(Kernel, lp, dOutputs.Ptr, dInputs.Ptr, rows, cols);
    var outputs = new double[rows, cols];
    dOutputs.Gather(outputs);
    Assert.AreEqual(inputs, outputs);
}

if I use rows = 10000 and cols = 10000 (instead of rows =10 and rows =5) :
I get an error "An unhandled exception of type 'Alea.CUDA.CUDAInterop.CUDAException' occurred in Alea.CUDA.dll" in the function : public static void Gather(this DeviceMemory dmem, T[,] array2D) :
    dmem.Worker.EvalAction(() =>
        {
            CUDAInterop.cuSafeCall(CUDAInterop.cuMemcpyDtoH(hostPtr, devicePtr,
                new IntPtr(Intrinsic.__sizeof<T>() * rows * cols)));
        });

How Can I remove this error ?

A: First, there is a enum field in CUDAException, so better you can debug to get what CUDA error it is. Such as the following code:
        catch (CUDAInterop.CUDAException x)
        {
            var code = x.Data0;
            Console.WriteLine("ErrorCode = {0}", code);
            Assert.Fail();
        }

Now, I ran it with 10000x10000 matrix, and I get the error: CUDA_ERROR_LAUNCH_FAILED. And the reason is, the kernel failed to execute, because you are iterating a big matrix in ONE thread. I create this test just for simply showing how to use 2d array, but if you are doing something real and big, avoid using such simple kernel, and execute it in 1 thread! that will cause the kernel to run for a long time, and finally the CUDA driver find it is too long to run, then driver will kill this kernel execution. So design a new real parallel kernel to iterate big matrix.