text:
Q: Better to take gold or experience in Might & Magic Heroes VI? In Might & Magic Heroes VI there are certain treasure chests that let you choose between gold and experience. To beat the game most easily which one should you choose early on?

A: Because your hero carries over from one campaign level to the next, and because I've never been limited by gold at least so far, I've always been taking experience in the campaign.  If you need a boost of gold to accomplish some goal, then by all means take it, but I would only give up the potential experience if you're going to put the gold to an immediate use.  It takes a lot of experience to level up as you get further in the game, and one extra level up can mean a very powerful new skill.

A: 2000 gold or 1500 experience - I take experience. 1000 gold or 500 experience - I take gold. 1500 gold or 1000 experience - it depends but usually gold.

A: It depends.
Generally speaking, a larger army is better than a few levels on a hero, so that would indicate that it is better to take the gold.  However, as your hero gains levels, it takes more and more experience to gain a level, which makes the experience in the treasure chests worth relatively less, which indicates that you should take the experience to maximize its effectiveness.
Therefore, I usually choose gold on a small / medium map (when I know I will encounter enemy heroes in a short timeframe) and experience on larger maps (when I know I will have time to explore and build out my main town prior to encountering the enemy).
In the late game, you usually have more than enough gold and a high level hero, which is when I start leaving the treasure chests so that secondary heroes can get a few easy levels.

A: Depends on situation. Early on in a map you probably want to take the gold, to level up your town faster, but if you already have enough gold to do that properly, then go for experience.
If you play the campaign, you will probably hit the exp cap if you fight most neutral monsters you can find, and if you have a big set of well developed towns chances are you wont afford all creatures.
There is no easy answer, but simplified; if you need gold take it, otherwise go for the exp.

A: I never or rarely rarely take XP,XP means nothing when you're in the high levels,you could get XP anywhere by killing monsters as long as you recruit your army as strong and early as possible with your high money instead of getting XP in the boxes but owning a weak army


text:
Q: Take File and Split Into Two LinkedLists to Determine if Second List has numbers that are in first list I'm supposed to take a file that has integers in individual lines and scan that into a list. Then I'm to break this list into two linked lists. And finally I need to say if a number in the second list is in the first one.
I understand (at least I think I do) the second part of this. And I feel like I understand how to do the entire problem because I can't find a flaw in my logic but the command doesn't seem to work.
import java.util.*;
import java.io.*;

public class FindKeys {

private static LinkedList<Integer> foo;
private static LinkedList<Integer> list1;
private static LinkedList<Integer> list2;
private static TreeMap<Integer, Boolean> list3;
private static int firstValue;
private static int numberA;
private static int numberB;

public FindKeys() {
}

public void main(String [] args) {
    foo = new LinkedList<Integer>();
    read(foo);
    listA(foo);
    listB(foo);
    discover(list1);
    print(list3);
}

private void read(LinkedList<Integer> foo){
    Scanner scan;
    int number;
    try{
        scan = new Scanner( new FileReader("Stuff.txt"));
    }
    catch(FileNotFoundException e){
        System.err.println("FileNotFoundException: " + e.getMessage());
        return;
    }
    catch(ArrayIndexOutOfBoundsException f){
        System.err.println("ArrayIndexOutOfBoundsException: " + f.getMessage());
        return;
    }

    while(scan.hasNextInt()){
        number = scan.nextInt();
        foo.add(number);
    }
}

private void listA(LinkedList<Integer> foo){

    firstValue = foo.getFirst();

    for( int i = 1; i<firstValue; i++){
        System.out.println(foo.get(i));

        int temp = foo.get(i);
  //This is where the issue is.

        list1.set(i,temp);
    }
}

private void listB(LinkedList<Integer> foo){

    firstValue = foo.getFirst();

    for( int i = firstValue; i<foo.size(); i++){
        numberB = foo.get(i);
        list2.add(numberB);
    }
}

private void discover(LinkedList<Integer> list1){
    for(int i=0; i<list1.size(); i++){
        if(list2.contains(list1.get(i))){
            boolean a = true;
            list3.put(list1.get(i),a);
            return;

        }
        boolean b = false;
        list3.put(list1.get(i),b);
    }
}

private void print(TreeMap<Integer, Boolean> list3){
    for(int numberA : list1){
        System.out.printf("%3i   %b" , numberA, list3);
    }
}
}

The issues comes when I am trying to add the number from the first list into the second one. And the problem seems to be that the LinkedList list1 has a size of 0. I thought that this was a simple misunderstanding on my part, that I didn't understand how to change the size of a list or how to add one more each time that I put on a new element but I can't find this in the first 20 pages of Google nor on this site. Having said that, I'm going to also assume that someone on here has this magical connection to the search gods and can possibly point me in the right direction, or maybe just tell me why that I can't add to the list. It just tells me that there is an issue because:
java.lang.NullPointerException
at FindKeys.listA(FindKeys.java:58)
at FindKeys.main(FindKeys.java:21)
java.lang.NullPointerException
at FindKeys.listA(FindKeys.java:58)
at FindKeys.main(FindKeys.java:21)

and quite frankly I don't know what that means and when I looked it up I got more confused.

A: Initialize the data structures
private static LinkedList<Integer> list1 = new LinkedList<Integer>();
private static LinkedList<Integer> list2 = new LinkedList<Integer>();
private static TreeMap<Integer, Boolean> list3 = new TreeMap<Integer, Boolean>();

and main method
public static void main(String [] args) {
    FindKeys fk = new FindKeys();
    foo = new LinkedList<Integer>();
    fk.read(foo);
    fk.listA(foo);
    fk.listB(foo);
    fk.discover(list1);
    fk.print(list3);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Link error when compiling opencv from source when including ffmpeg compiled from source I've been stuck on this problem for weeks.
I'm trying to build opencv on a raspberry pi 4 with x264 support. To do this I need to include ffmpeg, and also build that from source.
However when compiling opencv, I'm consistently getting these linker errors:
/usr/bin/ld: ../../lib/libopencv_videoio.so.4.5.3: undefined reference to `avcodec_get_context_defaults3'
/usr/bin/ld: ../../lib/libopencv_videoio.so.4.5.3: undefined reference to `av_lockmgr_register'
/usr/bin/ld: ../../lib/libopencv_videoio.so.4.5.3: undefined reference to `av_register_all'

I'm new to Linux, so I'm not exactly sure how to get started troubleshooting this. I believe I have ffmpeg correctly compiled and installed.
Here's the steps I use:
Configure ffmpeg:
sudo ./configure \
--prefix=/usr \
--extra-ldflags="-latomic" \
--enable-shared \
--extra-libs='-lpthread -lm' \
--ld=g++ \
--enable-gpl \
--disable-debug \
--enable-nonfree \
--enable-libx264 \
--enable-omx \
--enable-omx-rpi \
--enable-gnutls \
--enable-libfreetype \
--enable-libmp3lame

Then build it:
sudo make -j4
Then install it as a package: (so opencv cmake will detect it)
sudo checkinstall -y --deldoc=yes --pkgversion=9999 --pkgname=ffmpeg

Then configure opencv (ffmpeg is detected)
sudo cmake ../opencv_sources -D CMAKE_BUILD_TYPE=RELEASE \
-D OPENCV_EXTRA_MODULES_PATH= $PWD/../opencv_contrib/modules \
-D ENABLE_NEON=ON \
-D ENABLE_VFPV3=ON \
-D BUILD_TESTS=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D CMAKE_SHARED_LINKER_FLAGS='-latomic -L/usr/lib' \
-D WITH_V4L=ON \
-D WITH_QT=OFF \
-D BUILD_EXAMPLES=OFF \
-D CPU_BASELINE=NATIVE \
-D CMAKE_INSTALL_PREFIX="$HOME/opencv_build" \
-D BUILD_opencv_apps=OFF \
-D BUILD_opencv_python2=OFF \
-D BUILD_SHARED_LIBS=ON \
-D WITH_FFMPEG=ON

Then build opencv:
sudo make -j4

And this is where I get linking errors.
I checked in /usr/lib and the .so files appear to be there:
ls /usr/lib | grep libav

libavcodec.a
libavcodec.so
libavcodec.so.59
libavcodec.so.59.4.101
libavdevice.a
libavdevice.so
libavdevice.so.59
libavdevice.so.59.0.100
libavfilter.a
libavfilter.so
libavfilter.so.8
libavfilter.so.8.1.103
libavformat.a
libavformat.so
libavformat.so.59
libavformat.so.59.4.101
libavutil.a
libavutil.so
libavutil.so.57
libavutil.so.57.3.100

How do check where opencv is looking when linking? And is there a way I can check the shared libraries that ffmpeg generated to make sure they work?
The ffmpeg version is: git-2021-08-10-c245963
And opencv is 4.5.3-dev

A: TL;DR:
I was compiling the master branch of ffmpeg. This version removed some deprecated functions and was incompatible with my opencv version. Or at least the build tests failed. By switching to the release/4.4 branch and repeating my previous build steps I was able to successfully build opencv.
Details:
I was able to determine that it's not a linking problem. I wrote a short program that calls avcodec_get_context_defaults3(...), as well as avcodec_version(), which is another function that should be in there. Upon linking libavcodec.so, the avcodec_version() is found, but avcodec_get_context_defaults3() is not. Therefore I believe this is a version compatibility issue between ffmpeg and opencv.
I then  confirmed that the function was removed from ffmpeg. The latest version does not have it, old versions do. I used git's search function and found this commit:
Author: Andreas Rheinhardt <andreas.rheinhardt@gmail.com>
Date:   Thu Feb 25 20:37:24 2021 +0100

    avcodec: Remove deprecated avcodec_get_context_defaults3

    Deprecated in 04fc8e24a091ed1d77d7a3c0cbcfe60baec19a9f.

    Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt@gmail.com>
    Signed-off-by: James Almer <jamrial@gmail.com>

I switched to the release/3.4 branch of FFMPEG and repeated the steps. But that was missing some other things. I repeated the steps a 3rd time with release/4.4 and that worked.
The command I used to download the correct branch was this:
sudo git clone https://github.com/FFmpeg/FFmpeg --branch release/4.4 --depth 1 ffmpeg_sources


text:
Q: Sortable Js is not working in chrome with Select/Option tag but working fine with ul/li tags I need a help in sorting my text according their order. I have used Sortable js for sorting their order. I have implement it in select/option tag. Its working fine in mozilla but in chrome it doesnot work. But When i am using ul/li tag then its working fine in both browser. Can any one help me to do this task in select/option tag.
This is the demo: https://rubaxa.github.io/Sortable/
This is files link: https://github.com/RubaXa/Sortable
Thnaks in Advance.
<!DOCTYPE html>

<select id="foo1" multiple>
<option value="1">Sunny Thakur</option>
<option value="2">Deepak kanyan</option>
<option value="3">Harpreet Singh</option>
<option value="4">karmjeet Singh</option>
<option value="5">Gurvinder Singh</option>
</select>

A: The only solution I can come up with right now is to create your own custom select list widget using JavaScript and CSS. It is a concept I borrowed from the Mozilla Developer Network. Here is a link to the live version of it that you can test in Chrome (Sortable Select List in Chrome).
HTML
<form class="no-widget">
  <select name="myFruit">
    <option>Cherry</option>
    <option>Lemon</option>
    <option>Banana</option>
    <option>Strawberry</option>
    <option>Apple</option>
  </select>

    Cherry

Cherry

Lemon

Banana

Strawberry

Apple

</form>

CSS
.widget select,
.no-widget .select {
  position : absolute;
  left     : -5000em;
  height   : 0;
  overflow : hidden;
}

/* --------------- */
/* Required Styles */
/* --------------- */

.select {
  position: relative;
  display : inline-block;
}

.select.active,
.select:focus {
  box-shadow: 0 0 3px 1px #227755;
  outline: none;
}

.select .optList {
  position: absolute;
  top     : 100%;
  left    : 0;
}

.select .optList.hidden {
  max-height: 0;
  visibility: hidden;
}

/* ------------ */
/* Fancy Styles */
/* ------------ */

.select {
  font-size   : 0.625em; /* 10px */
  font-family : Verdana, Arial, sans-serif;

  -moz-box-sizing : border-box;
  box-sizing : border-box;

  padding : 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
  width   : 10em; /* 100px */

  border        : 0.2em solid #000; /* 2px */
  border-radius : 0.4em; /* 4px */

  box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */

  background : #F0F0F0;
  background : -webkit-linear-gradient(90deg, #E3E3E3, #fcfcfc 50%, #f0f0f0);
  background : linear-gradient(0deg, #E3E3E3, #fcfcfc 50%, #f0f0f0);
}

.select .value {
  display  : inline-block;
  width    : 100%;
  overflow : hidden;

  white-space   : nowrap;
  text-overflow : ellipsis;
  vertical-align: top;
}

.select:after {
  content : "▼";
  position: absolute;
  z-index : 1;
  height  : 100%;
  width   : 2em; /* 20px */
  top     : 0;
  right   : 0;

  padding-top : .1em;

  -moz-box-sizing : border-box;
  box-sizing : border-box;

  text-align : center;

  border-left  : .2em solid #000;
  border-radius: 0 .1em .1em 0;

  background-color : #000;
  color : #FFF;
}

.select .optList {
  z-index : 2;

  list-style: none;
  margin : 0;
  padding: 0;

  background: #f0f0f0;
  border: .2em solid #000;
  border-top-width : .1em;
  border-radius: 0 0 .4em .4em;

  box-shadow: 0 .2em .4em rgba(0,0,0,.4);

  -moz-box-sizing : border-box;
  box-sizing : border-box;

  min-width : 100%;
  max-height: 10em; /* 100px */
  overflow-y: auto;
  overflow-x: hidden;
}

.select .option {
  padding: .2em .3em;
}

.select .highlight {
  background: #000;
  color: #FFFFFF;
}

JavaScript
// ------- //
// HELPERS //
// ------- //

NodeList.prototype.forEach = function(callback) {
  Array.prototype.forEach.call(this, callback);
}

// -------------------- //
// Function definitions //
// -------------------- //

function deactivateSelect(select) {
  if (!select.classList.contains('active')) return;

  var optList = select.querySelector('.optList');

  optList.classList.add('hidden');
  select.classList.remove('active');
}

function activeSelect(select, selectList) {
  if (select.classList.contains('active')) return;

  selectList.forEach(deactivateSelect);
  select.classList.add('active');
};

function toggleOptList(select, show) {
  var optList = select.querySelector('.optList');

  optList.classList.toggle('hidden');
}

function highlightOption(select, option) {
  var optionList = select.querySelectorAll('.option');

  optionList.forEach(function(other) {
    other.classList.remove('highlight');
  });

  option.classList.add('highlight');
};

function updateValue(select, index) {
  var nativeWidget = select.previousElementSibling;
  var value = select.querySelector('.value');
  var optionList = select.querySelectorAll('.option');

  optionList.forEach(function(other) {
    other.setAttribute('aria-selected', 'false');
  });

  optionList[index].setAttribute('aria-selected', 'true');

  nativeWidget.selectedIndex = index;
  value.innerHTML = optionList[index].innerHTML;
  highlightOption(select, optionList[index]);
};

function getIndex(select) {
  var nativeWidget = select.previousElementSibling;

  return nativeWidget.selectedIndex;
};

// ------------- //
// Event binding //
// ------------- //

window.addEventListener("load", function() {
  var form = document.querySelector('form');

  form.classList.remove("no-widget");
  form.classList.add("widget");
});

window.addEventListener('load', function() {
  var selectList = document.querySelectorAll('.select');

  selectList.forEach(function(select) {
    var optionList = select.querySelectorAll('.option'),
      selectedIndex = getIndex(select);

    select.tabIndex = 0;
    select.previousElementSibling.tabIndex = -1;

    updateValue(select, selectedIndex);

    optionList.forEach(function(option, index) {
      option.addEventListener('mouseover', function() {
        highlightOption(select, option);
      });

      option.addEventListener('click', function(event) {
        updateValue(select, index);
      });
    });

    select.addEventListener('click', function(event) {
      toggleOptList(select);
    });

    select.addEventListener('focus', function(event) {
      activeSelect(select, selectList);
    });

    select.addEventListener('blur', function(event) {
      deactivateSelect(select);
    });

    select.addEventListener('keyup', function(event) {
      var length = optionList.length,
        index = getIndex(select);

      if (event.keyCode === 40 && index < length - 1) {
        index++;
      }
      if (event.keyCode === 38 && index > 0) {
        index--;
      }

      updateValue(select, index);
    });
  });
});

//initialize Sortable
var list = document.getElementById("myList");

Sortable.create(list);


text:
Q: Tab Through Hidden Inputs in Angular I'm looking for a way in angular to tab through hidden inputs. So I have multiple input forms but when not on focus I want them to just display the text. I'm looking for the ability to once I've selected an input to tab through the other inputs even though they are currently hidden.
Any suggestions?

A: Use Angular directives to make your inputs into inline editors. When the page loads you'll be in display mode (i.e. the display div will be shown and the editor div will be hidden), then on clicking, the mode switches to Edit mode and the visibility is reversed.
Here's a quick snippet of what a DatePicker control would look like when wrapped in such a directive. Using Angular 1 and Bootstrap 3 (follows John Papa's Angular Style Guide):
HTML Template (inlineDatePicker.html):

        <input type="hidden" data-ng-model="vm.dateModel" data-ng-required="vm.dateRequired" />{{vm.dateModel}}

            <datepicker data-ng-model="vm.dateModel" data-show-weeks="false"></datepicker>
            <button type="button" class="btn btn-sm btn-info" ng-click="vm.today()">Today</button>
            <button type="button" class="btn btn-sm btn-danger" ng-click="vm.cancel()">Cancel</button>

And the underlying directive (inlineDatePicker.directive.js):
(function () {
    'use strict';

    angular.module('myApp.inlineEdit')
    .directive('inlineDatePicker', inlineDatePicker);

    function inlineDatePicker() {
        'use strict';
        inlineDatePickerController.$inject = ['$scope', '$timeout'];

        return {
            restrict: 'A',
            replace: true,
            transclude: false,
            templateUrl: '/App/inlineEdit/date/inlineDatePicker.html',
            scope: {
                dateModel: '=',
                dateRequired: '@',
                dateChanged: '&'
            },
            controller: inlineDatePickerController,
            controllerAs: 'vm',
        };

        function inlineDatePickerController($scope, $timeout) {
            /* jshint validthis:true */
            var vm = this;
            vm.inEditMode = false;
            vm.dateModel = $scope.dateModel;
            vm.dateRequired = $scope.$eval($scope.dateRequired);
            vm.enableEditMode = enableEditMode;
            vm.cancel = cancel;
            vm.today = today;

            function enableEditMode() {
                vm.inEditMode = true;
            }

            function cancel() {
                vm.inEditMode = false;
            }

            function today() {
                vm.dateModel = new Date();
            }

            $scope.$watch('vm.dateModel', function (curr, orig) {
                $scope.dateModel = vm.dateModel;
                if (curr != orig && vm.inEditMode) {
                    $timeout($scope.dateChanged, 0);
                }
                vm.inEditMode = false;
            });

            $scope.$watch('dateModel', function () {
                vm.dateModel = $scope.dateModel;
            });
        }
    }
})();


text:
Q: Spark Streaming crashes to Kafka Ran out of messages before reaching ending offset exception In one of our streaming usecase; one of our sensor software is sending 5 each ~20MB JSON messages/Sec to Kafka topic with 50 partitions, when spark streaming is trying to read messages from Kafka it crashes with below exception.
In order to understand situation better, we manage to make the sensor software send only 1 20MB message/Sec but spark application crashes with the same error.Please let me know if I am missing anything that need to be done to handle such scenario.
We have the following config
-Kafka 0.9.0 server.properties
message.max.bytes=60000000
replica.fetch.max.bytes=120000000

-Spark 1.6.1 Config DirectAPI on yarn
val kafkaParams = Map[String, String](
      "security.protocol" -> "SASL_PLAINTEXT",
      "group.id" -> groupid,
      "metadata.broker.list" -> kafkaBrokerList,
      "max.partition.fetch.bytes" -> "60000000")

-Spark Submit
spark-submit \
--verbose \
--master yarn-cluster \
--num-executors 3  \
--executor-memory 7g \
--executor-cores 3 \
--conf spark.driver.memory=1024m  \
--conf spark.streaming.backpressure.enabled=false \
--conf spark.streaming.kafka.maxRatePerPartition=3 \
--conf spark.streaming.concurrentJobs=3 \
--conf spark.speculation=true \
--conf spark.hadoop.fs.hdfs.impl.disable.cache=true \
--files kafka_jaas.conf#kafka_jaas.conf,user.headless.keytab#user.headless.keytab \
--driver-java-options "-Djava.security.auth.login.config=./kafka_jaas.conf -Dhttp.proxyHost=PROXY_IP -Dhttp.proxyPort=8080 -Dhttps.proxyHost=PROXY_IP -Dhttps.proxyPort=8080 -Dlog4j.configuration=file:/home/user/spark-log4j/log4j-topic_name-driver.properties" \
--conf "spark.executor.extraJavaOptions=-Djava.security.auth.login.config=./kafka_jaas.conf -Dlog4j.configuration=file:/home/user/spark-log4j/log4j-topic_name-executor.properties" \
--class com.spark.demo.StreamProcessor /home/user/demo.jar /tmp/data/out 60 KAFKA_BROKER:6667 "groupid" topic_name

-Exception:
User class threw exception: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3, IP_HOST): java.lang.AssertionError: assertion failed: Ran out of messages before reaching ending offset 197 for topic x_topic_3 partition 24 start 196. This should not happen, and indicates that messages may have been lost
at scala.Predef$.assert(Predef.scala:179)
at org.apache.spark.streaming.kafka.KafkaRDD$KafkaRDDIterator.getNext(KafkaRDD.scala:211)
at org.apache.spark.util.NextIterator.hasNext(NextIterator.scala:73)
at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:308)
at scala.collection.Iterator$class.foreach(Iterator.scala:727)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
at scala.collection.AbstractIterator.to(Iterator.scala:1157)
at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1335)
at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1335)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1881)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1881)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Driver stacktrace

:

A: add ("fetch.message.max.bytes" -> "20971520") in kafkaParams, you can find the source code in ConsumerConfig.scala#114 (Spark 1.6.2)


text:
Q: Android Spinner popup callback InputEventReceiver warning I followed @CommonsWare answer(How to get a callback when a Spinner popup dialog is dismissed?) to implement a callback when the spinner popup is closed.
When I select an item everything works, but when I click outside of the bounds of the spinner I get this warning on logcat: Attempted to finish an input event but the input event receiver has already been disposed.
I already tried registering the OnTouchListener too, but nothing is called when I click outside.
Someone can tell me what this warning means? I already googled that but didn't find nothing.

A: I have same problem. I have PopupWindow with button (R.id.imageView1). I have callback on that button. I deregister callback when popup is disimissed (popupWindow.setOnDismissListener).
What is strange, warning message does not occur in debug mode.
    PopupWindow popupWindow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
     //layout for popup window
     LayoutInflater layoutInflater=       (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
        View popupView = layoutInflater.inflate(R.layout.grid, null);

        popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
}

    public void showPopup(View view) {
            final View  popupView=popupWindow.getContentView();
            popupView.findViewById(R.id.imageView1).setOnClickListener(new PopupOnClickListener(popupWindow,this));

           //required if I want popup to close on click outside popup area
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());

            popupWindow.showAsDropDown(view, 50, -30);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    popupView.findViewById(R.id.imageView1).setOnClickListener(null);
                }
            });
        }

A: I had this problem earlier and it seemed that I was closing my onCreate() method too soon.
Check your code very carefully!


text:
Q: Rails 3: How to use a ruby gem for date validation for non-model data In my rails app, I have a situation where a user enters a date of birth on a web page.
I would like to do validation of their age based on this date of birth. I would like to do the validation in the model because even though the date of birth that the user is providing is not part of the model, I do need to query the model about what is the age the user has to have for the certain item they are trying to access.
I found the date_validator gem but that only works on the model.
To top it off I am not using a date field so I will have the date of birth in three pieces, 3 strings of month, day and year and then need to somehow convert that to a date and based on that date, validate if their age is greater than or equal to the age that they are supposed to have.
I am not sure if there is a gem for what I'm trying to do but I figured I'd ask before I try to code out my own validator.

A: rails provides several helpers to deal with dates.
if you want to have a date input that is separated in several fields you can use the date_select http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html
even if you cook your own soup, rails is flexible enough to merge seperate fields into one date-field:
Event.new("date(1i)"=>"2007", "date(2i)"=>"8", "date(3i)"=>"11").date
=> date: "2007-08-10"


text:
Q: "RVM is not a function" error when running in ruby script and irb I get an error when I run %x{rvm use @myapp} in ruby and irb. The error is "RVM is not a function, selecting rubies with 'rvm use ...' will not work".
Here's what I've tried:
1. the "rvm use @myapp" command works in OSX command prompt (using OSX Mavericks)
2. made sure RVM is the latest version.
3. reloaded RVM check RVM is a function in the command prompt
4. (still fails in irb and ruby's %x{})
5. According to some SO posts, I changed OSX terminal preferences from login shell to /bin/bash and /bin/bash --login. Quit, opened new terminal windows but all efforts were in vain.
6. checked .bash_profile for [[-s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
Any ideas on how I can get %x{rvm use @myapp} to work in ruby and irb?

A: What happens here is that the shell you had started ruby or irb with had rvm defined both as a function and added to PATH the function takes precedence in shell and it all worked fine, but when you open ruby or irb it is a new process and it inherits only environment variables which includes PATH and does not inherit functions, additionally running %x{} from ruby creates another shell process which is neither a login or interactive shell, and they respectively would make shell load ~/.bash_profile and ~/.bashrc.
Depending on what do you want to do you have few options, to execute another ruby/gem you can use rvm ... do ... for from %x{} like this:
rvm @myapp do ruby -e '...'

OR:
rvm @myapp do gem install ...

OR:
rvm @myapp do bundle install

it allows single command to run in the context of given ruby

A: Try this trick:
%x{bash -c 'source "$HOME/.rvm/scripts/rvm"; rvm use @myapp'}

However, you really can use rvm as you've specified because even if you've set up the rvm you then lost your session because your terminal will be closed. Try to setup your environment with session gem, and control bash session with it.
require 'session'

@myapp = 'ruby-1.8.7-p374'

bash = Session::Bash.new

stdout, stderr = bash.execute 'source "$HOME/.rvm/scripts/rvm"'

stdout, stderr = bash.execute "rvm use #{@myapp}"
puts stdout

# => Using /home/malo/.rvm/gems/ruby-1.8.7-p374


text:
Q: Boolean of show() or hide() function i have this code. i what that if my div{display:block} alert('yes') esle
div{display:none} alert('no')

or
if ( Boolean ( $('.C-1').css({'display':'block'}) ) == true ) { alert('yes' }
if ( Boolean ( $('.C-1').css({'display':'block'}) ) == false ) { alert('no') }

but this code doesn't work !
So what do u suggest ?

A: Use :visible and :hidden pseudo-selectors.
To check if the element is visible:
$('.C-1').is(':visible')

This will return true if the element .C-1 is visible, false otherwise.
Docs: https://api.jquery.com/visible-selector/
To check if element is hidden:
$('.C-1').is(':hidden')

This will return true if the element .C-1 is hidden, false otherwise.
Docs: https://api.jquery.com/hidden-selector/
Your code
if ($('.C-1').is(':visible')) {
    alert('Yes');
} else {
    alert('No');
}

A: You can use .is() along with :visible selector:
if($('.C-1').is(':visible')){
  alert('yes');
}else{
  alert('no');
}

A: Check with is(':visible').
If you have check div is visible or not use :visible and div is hidden use :hidden psudeo selector in jquery
if($('.C-1').is(':visible')){
   // div is visible
}
else {
   // div is not visible
}

A: if($('.C-1').css('display') === 'none'){
   //hidden
}else{
   // shown
}


text:
Q: JSP GETTER SETTER SHOWING RESULT NULL I am trying to retrieve and show data from getters of my java class but unable to show the result. It is showing 0 and null in my jsp page. I am unable to figure out this problem. I have added first the servlet code then DAO code then jsp code.
 PrintWriter out = response.getWriter();
            String input = request.getParameter("list");
            String txtField = request.getParameter("txtField");
            String op = request.getParameter("op");
            String bSearch = request.getParameter("bookingSearch");

            try{
                if(op.equals("1")){
                    Searching search1 = new Searching();
                    search1.setInputList(input);
                    search1.setTxtField(txtField);
                    SearchDAO searchDAO = new SearchDAO();
                    boolean searchDriver = searchDAO.searchDriver(search1);
                    if(searchDriver){
                        response.sendRedirect("driversearchresult.jsp");

                        //response.sendRedirect("SearchOutPut.jsp?op=" + search1.getPassingValue());
                    }
                    else {
                        out.println("");
                        out.println("");
                        out.println("");
                        out.println("<META HTTP-EQUIV= Refresh CONTENT=0;URL=SearchDriver.jsp>");
                    }

                }

    package com.vechile.dao;

    import java.sql.ResultSet;
    import com.vechile.model.DriverSearchResult;
    import com.vechile.model.Searching;
    import com.vechile.utils.DBConnection;

    public class SearchDAO {
        private String sql;
        private ResultSet rs, rs1;

        public boolean searchDriver(Searching searching) {
            try {

                sql = String.format("select * from adddriver where (%s) = '%s'",
                        searching.getInputList(), searching.getTxtField());

                rs = DBConnection.executeQuery(sql);

                if(rs.next()) {
                    DriverSearchResult searchResult = new DriverSearchResult();
                    Integer driverId = new Integer(rs.getInt(1));
                    String driverIdString = driverId.toString();
                    searchResult.setId(driverIdString);
                    searchResult.setName(rs.getString("dname"));
                    searchResult.setAddress(rs.getString("daddress"));
                    searchResult.setCity(rs.getString("dcity"));
                    searchResult.setContact(rs.getString("dcontact"));
                    searchResult.setCountry(rs.getString("dcountry"));

                    return true;
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
            return false;
        }

        public boolean searchBooking(Searching searching) {
            try {
                sql = String.format(
                        "select * from booking where booking_id = '%s'",
                        searching.getBookingSearch());

                rs1 = DBConnection.executeQuery(sql);
                if (rs1.next()) {

                    return true;

                }

            } catch (Exception e) {
                e.getStackTrace();
            }
            return false;
        }

    }

    <%@page import="com.vechile.dao.UserDAO"%>
    <%@page import="com.vechile.model.DriverSearchResult"%>
    <%@page import="com.vechile.model.Vehicle"%>
    <%@page import="com.vechile.model.Searching"%>
    <%@page import="java.util.List"%>
    <%@page import="com.vechile.dao.SearchDAO"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Booking Search Result</title>

    <%
    DriverSearchResult dSR = new DriverSearchResult();

    %>

    ID

    <%=dSR.getId() %>

    Name

    <%=dSR.getName() %>

A: The problem is that you create a new DriverSearchResult in your jsp code:
DriverSearchResult dSR = new DriverSearchResult();

Since it is a new object its values are uninitialized. Then you print them out.
The problematic code:
 <%
    DriverSearchResult dSR = new DriverSearchResult(); // <- you create a new object

    %>

    ID

    <%=dSR.getId() %>

    Name

    <%=dSR.getName() %>


text:
Q: How to calculate Lipschitz constant? How can I calculate a Lipschitz constant for a 2-dimensional real-valued $C^{\infty}$ function with bounded derivatives?

A: By the mean value theorem
$$
f(x)-f(y)=\nabla f(\xi)\cdot(x-y)
$$
for some $\xi$ in the segment joining $x$ and $y$. Since $f$ has bounded partial derivatives, there is an $M>0$ such that $|\nabla(x)|\le M$ for all $x\in\mathbb{R}^2$. Then
$$
|f(x)-f(y)|\le M\,|x-y|.
$$
($|z|$ is the Euclidean norm in $\mathbb{R}^2$ of $z=(z_1,z_2)$.)


text:
Q: Find $\lim_{x \to \infty} e^{2x \cdot \ln \frac{x+1}{x-2}}$ without l'Hospital. I have managed to get my limit to this state, but how should I procceed?
Thanks.

A: Hint: Suppose $$y=e^{2x\ln\frac{x+1}{x-2}}$$
then $$\ln y=2x\ln\frac{x+1}{x-2}=2x\ln(1+\frac{3}{x-2})=\ln(1+\frac{3}{x-2})^{2x}$$
or $$y=(1+\frac{3}{x-2})^{2x}$$
Now use the limit $$\lim_{n\to\infty}(1+\frac{1}{n})^n=e$$
to proceed.

A: $e^{2x\ln \frac {x+1}{x-2}}\\
(\frac {x+1}{x-2})^{2x}\\
(1 + \frac {3}{x-2})^{2x}$
$\lim_\limits{n\to\infty} (1+\frac 1n)^n = e\\
\lim_\limits{n\to\infty} (1+\frac xn)^n = e^x\\$
We have
$\lim_\limits{x\to\infty}(1 + \frac {3}{x-2})^{2x}$
If you want to be a little bit more thorough
$(1 + \frac {3}{x-2})^{2(x-2) + 4}$
The limit of the product is the product of the limits (if both limits are real numbers).
$\lim_\limits{x\to\infty}((1 + \frac {3}{x-2})^{x-2})^2\lim_\limits{x\to\infty}((1 + \frac {3}{x-2})^4)$
The first evaluates to $e^6$, the second evaluates to $1$

A: $\begin{align}\displaystyle\lim_{x \to \infty} e^{2x\ln \frac{x+1}{x-2}}&=\displaystyle\lim_{x \to \infty} e^{\ln\left(\frac{x+1}{x-2}\right)^{2x}}\\&=\displaystyle\lim_{x \to \infty}\left(\frac{x+1}{x-2}\right)^{2x}\\&=\displaystyle\lim_{x \to \infty}\left(\frac{(x-2)+3}{x-2}\right)^{2x}\\&=\displaystyle\lim_{x \to \infty}\left(1+\frac{3}{x-2}\right)^{2x}\\&=\displaystyle\lim_{x \to \infty}\left[\left(1+\frac{3}{x-2}\right)^{(x-2)+2}\right]^2\\&=\displaystyle\lim_{x \to \infty}\left[\left(1+\frac{3}{x-2}\right)^{(x-2)}\left(1+\frac{3}{x-2}\right)^2\right]^2\\&=\displaystyle\lim_{x \to \infty}\left[\left(1+\frac{3}{x-2}\right)^{(x-2)}\right]^2\left[\left(1+\frac{3}{x-2}\right)^2\right]^2\\&=\displaystyle\lim_{x \to \infty}\left[\left(1+\frac{3}{x-2}\right)^{(x-2)}\right]^2\displaystyle\lim_{x \to \infty}\left(1+\frac{3}{x-2}\right)^4\\&=\left[\displaystyle\lim_{x \to \infty}\left(1+\frac{3}{x-2}\right)^{(x-2)}\right]^2\displaystyle\lim_{x \to \infty}\left(1+\frac{3}{x-2}\right)^4\\&=\left[\displaystyle\lim_{(x-2) \to \infty}\left(1+\frac{3}{x-2}\right)^{(x-2)}\right]^2\displaystyle\lim_{x \to \infty}\left(1+\frac{3}{x-2}\right)^4\\&=(e^3)^2\cdot 1\\&=\boxed{\boxed{e^6}}\end{align}$


text:
Q: Pandoc: how split title going from html to docx In a HTML document that I need to convert to DOCX I have a long title that I want to split into two lines in the resulting DOCX. But if I put a
 in the <title> the text after the break disappears. To reproduce:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Scientist and father:
my journey from ignorance to Montessori enthusiasm</title>

Bla bla bla.

Process it as: pandoc split.html -o split.docx
If you remove the
 the title appears correctly on one line. Yes, I know that a break in title in HTML does not make much sense, but this is only an intermediate file to generate the DOCX.


text:
Q: Why does LLVM projects use GCC Headers I am looking at a project that is built with Clang but it needs GCC headers.
Why would a project require both Clang and GCC headers?

A: By default, clang builds with the standard library installed on the system, so objects can be linked with libraries/programs built by other compilers. If you have installed libc++, you can use it with the flag -stdlib=libc++.
For more information have a look at the documentation.


text:
Q: Getting List indexed memory locations. Not value locations but List index locations From what I am aware, Python stores Lists as "arrays" in memory; however, the "array" stores pointers to the PyObject's in the List.
I am using hex(id(...)) to view the memory addresses of the List and of all the items in the list. But I also want to see the memory location of the "array" positions.
This is my interpreter code so far...
>>> def memory_locations_of(value):
        for index, element in enumerate(value):
            print("{: <15}{}\n{: <15}{}\n".format("index[" + str(index) + "] ", hex(id(element)), str(element), hex(id(str(element)))))

>>> a = ["hello", "world", "!", "!"]
>>> a
['hello', 'world', '!', '!']

>>> memory_locations_of(a)
index[0]       0x34b4bc0
hello          0x34b4bc0
index[1]       0x4053dc0
world          0x4053dc0
index[2]       0x3616620
!              0x3616620
index[3]       0x3616620
!              0x3616620

>>> a[0] = "Hello"
>>> a
['Hello', 'world', '!', '!']

>>> memory_locations_of(a)
index[0]       0x406e260
Hello          0x406e260
index[1]       0x4053dc0
world          0x4053dc0
index[2]       0x3616620
!              0x3616620
index[3]       0x3616620
!              0x3616620

>>> hex(id(a))
'0x3f7cc10'

The last 2 lines are the closest memory location that I want. That memory location is the location of the actual List. That should also be the location of the actual a[0] position (or very close to it). I also want to get the real location of a1, a[2], and a[3]. It based on my code they should be at '0x3f7cc10' + "index_offset".
Is there an easy way of getting this or is it rather contrived?


text:
Q: cycript access elements in JavaUtilArrays_ArrayList I am running cycript on iOS and calling internal API in an App.
I have a variable of type JavaUtilArrays_ArrayList returned from a call
cy# l

"[<FieldDescriptor: 0x170a74fc0>, <FieldDescriptor: 0x170a75a00>, <_FieldDescriptor: 0x170a76200>, <FieldDescriptor: 0x170a76240>, <FieldDescriptor: 0x170a76280>]"

I would like to iterate over this list to access the elements (preferably with #element)
In general I would iterate like so
for (x of [1,2,3]) {x+x}

However, trying
for (e of l){e}

or
for(e in l ){l[e]}

results in throw new Error("*** _assert(static_cast(static_cast(value)) == value):../Execute.cpp(347):CYCastJSValue")
furthermore, accessing an individual element
l[0]

Return nothings
I am very new to cycript. Can anybody help me with this?

A: JavaUtilArrays_ArrayList was just another random objective-c object.
I used class dump to find its definition and appropriate method to access the elements.
I then called the method using objective c syntax [l getvaluefunc:]


text:
Q: "Warning: Out of range value for column" inserting a datetime value into MySQL Pulling some data from MongoDB and inserting it into a MySQL database, using Python and the Mysqldb library.
+-------------------+------------+------+-----+---------+----------------+
| Field             | Type       | Null | Key | Default | Extra          |
+-------------------+------------+------+-----+---------+----------------+
| id                | int(16)    | NO   | PRI | NULL    | auto_increment |
| subject           | tinytext   | NO   |     | NULL    |                |
| created_at        | datetime   | NO   |     | NULL    |                |
+-------------------+------------+------+-----+---------+----------------+

created_at  = "2012/06/08 11:47:40 -0700"
sql1 = ("INSERT INTO `items` (`description`, `created_at`) VALUES (%s, %s)", (description, created_at)
try:
    cursor.execute(*sql1)
except MySQLdb.Error, e:
    print "Error %s: %s" % (e.args[0], e.args[1])

For the first insert into the database I get a warning, however I don't receive that warning for subsequent inserts.

conf/db_tools-import.py:53: Warning: Out of range value for column 'created_at' at row 1
        cursor.execute(*sql1)

How can I resolve this?
Thanks.

A: You are receiving an warning because you are inserting a long date into a date field.  The date filed is "YYYY-MM-DD" (http://dev.mysql.com/doc/refman/5.1/en/datetime.html).
I did my own test in Mysql, take a look:
mysql> create table bigtable (created_at date);
Query OK, 0 rows affected (0.07 sec)

mysql>

Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show warnings;
+---------+------+-------------------------------------------------+
| Level   | Code | Message                                         |
+---------+------+-------------------------------------------------+
| Warning | 1265 | Data truncated for column 'created_at' at row 1 |
+---------+------+-------------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from bigtable;
+------------+
| created_at |
+------------+
| 2012-06-08 |
+------------+
1 row in set (0.00 sec)

if you want to avoid the warning, just pass "YYYY-MM-DD" or change the column to datetime,
Good luck


text:
Q: ruby on rails, adding a partial to each html page in the system I'm currently working on a project which has ROR in backend, I need to add a noscript tag to every page in the system to show a banner to the user.
Does ROR provide an easy way to add a piece of html to every page?

A: Add it to the application layout file /app/views/layouts/application.html.erb.  That file gets loaded for every view unless you have disabled this layout or have used a different layout.
If you have multiple layouts then place the <noscript>...</noscript> in a partial and render the partial in all the layouts.


text:
Q: Verifying an external signature of a very large file in c# i have a large file that needs to be signed in order to be archived. It's a CSV file that is generated once in a month and has a size of > 2Gb (don't ask me what this is good for :) ).
Anyway.. The signing of the file is not the problem, there is a lib for that, i generate the hash and i get my signature.
What i want to do now, is to verify the signature.
tutorials want me to do something like this:
byte[] sig = ReadFile(signatureFile);
SignedCms cms = new SignedCms(new ContentInfo(ReadFile(dataFile)), true);
cms.Decode(sig);
cms.CheckSignature(false);

this actually works.. but as you can imagine, i don't feel like loading the entire content of a 2 GB file into memory.
the msdn article about the ContentInfo class tells me, that i can choose the oid for the content, i want my contentInfo initialized with.
the oid for hashed data would be "1.2.840.113549.1.7.5"
so here i am:
byte[] sig = ReadFile(signatureFile);
SignedCms cms = new SignedCms(new ContentInfo(new byte[]{}), true);
cms.Decode(sig);
SignerInfo inf = cms.SignerInfos[0];
string algorithm = inf.DigestAlgorithm.FriendlyName;
cms = new SignedCms(new ContentInfo(new Oid("1.2.840.113549.1.7.5"), GetHash(algorithm, dataFile)), true);
cms.Decode(sig);
cms.CheckSignature(false);

now CheckSignature throws me an exception saying that the hash is incorrect.
the following would work:
byte[] sig = ReadFile(signatureFile);
SignedCms cms = new SignedCms(new ContentInfo(new byte[]{}), true);
cms.Decode(sig)
byte[] compareableHash = GetHash(algorithm, dataFile);
foreach (var t in inf.SignedAttributes)
{
    if (t.Oid.Value == "1.2.840.113549.1.9.4")
    {
        Pkcs9MessageDigest digest = (Pkcs9MessageDigest)t.Values[0];
        if (CompareableHash(compareableHash, digest.MessageDigest)) // this compares the hashes bytewise
        {
            Console.WriteLine("hash is correct!");
        }
    }
}

can i trust this method to be 100% reliable or is there a better way?


text:
Q: Parsing out text after final "_" I'm a SQL Newbie trying to solve a problem.  I need to parse out a name from a field, but the field is not static, the length can vary.  I always need the last text field after the final _
For example:
aaa_bbb_ccc_ddd   I need to return ddd
aaa_bbb_ccc       I need to return ccc

I've been struggling using both regexp and substr.  Does anyone have any suggestions on how I can get this done ?   Thank you in advance !
DB is Oracle in case there are specific functions that I'm not aware of.

A: In Oracle, the REGEXP_SUBSTR function should provide what you need
The regex would be something like [^_]+$ (1 or more none underscore char at the end of the string)

A: You can use INSTR and SUBSTR together to get what you want:
strLast_name := SUBSTR(SOME_FIELD, INSTR(SOME_FIELD, '_', -1)+1);

will return 'ddd' if SOME_FIELD contains 'aaa_bbb_ccc_ddd`.
Best of luck.

A: You can approach this problem in 2 ways:
INPUT test table:
CREATE TABLE Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255)
);

select * from PERSONS;
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (1,'a_rbit_aaa',null,null,null);
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (2,'t_obt_bbb',null,null,null);
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (3,'t_co_mp_ccc',null,null,null);
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (4,'t_d_or_ddd',null,null,null);
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (5,'cramp_123',null,null,null);
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (6,'p_o_d_abc',null,null,null);
insert into PERSONS(PersonID,LastName,FirstName,Address,City) values (7,'123_abc_uvw_xyz',null,null,null);

commit;

1) The substring approach:
This is better in your case since we do not need to extract a pattern and/or use backreferences and manipulate a string. A regex approach will be slow down your query and consumes more memory/cpu.
select substr(lastname, Instr(lastname, '_',-1) +1)from PERSONS;

result:
aaa
bbb
ccc
ddd
123
abc
xyz

2) The regex approach:
Just for learning purpose and fun, let me introduce the regex approach (not necessary for your specific case), you can choose to extract the part that you need from your string using regex_substr or do it the other way around: remove everything that is not required in your string.
select regexp_substr(lastname, '[^_]+$')from PERSONS; --the regex will fetch only the non underscore characters at the end of the string

or
select regexp_replace(lastname, '^(:?[^_]*_)*', '')from PERSONS; --remove every block of non underscore char followed by one underscore, till will keep only the last non underscore part as is

for both, result:
aaa
bbb
ccc
ddd
123
abc
xyz


text:
Q: Check if value already exists within list of dictionaries? I've got a Python list of dictionaries, as follows:
a = [
    {'main_color': 'red', 'second_color':'blue'},
    {'main_color': 'yellow', 'second_color':'green'},
    {'main_color': 'yellow', 'second_color':'blue'},
]

I'd like to check whether a dictionary with a particular key/value already exists in the list, as follows:
// is a dict with 'main_color'='red' in the list already?
// if not: add item

A: Maybe this helps:
a = [{ 'main_color': 'red', 'second_color':'blue'},
     { 'main_color': 'yellow', 'second_color':'green'},
     { 'main_color': 'yellow', 'second_color':'blue'}]

def in_dictlist(key, value, my_dictlist):
    for entry in my_dictlist:
        if entry[key] == value:
            return entry
    return {}

print in_dictlist('main_color','red', a)
print in_dictlist('main_color','pink', a)

A: Based on @Mark Byers great answer, and following @Florent question,
just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:
names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})

if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):

    print('Not exists!')
else:
    print('Exists!')

Result:
Exists!

A: Perhaps a function along these lines is what you're after:
 def add_unique_to_dict_list(dict_list, key, value):
  for d in dict_list:
     if key in d:
        return d[key]

  dict_list.append({ key: value })
  return value

A: Just another way to do what the OP asked:
 if not filter(lambda d: d['main_color'] == 'red', a):
     print('Item does not exist')

filter would filter down the list to the item that OP is testing for. The if condition then asks the question, "If this item is not there" then execute this block.

A: Here's one way to do it:
if not any(d['main_color'] == 'red' for d in a):
    # does not exist

The part in parentheses is a generator expression that returns True for each dictionary that has the key-value pair you are looking for, otherwise False.

If the key could also be missing the above code can give you a KeyError. You can fix this by using get and providing a default value. If you don't provide a default value, None is returned.
if not any(d.get('main_color', default_value) == 'red' for d in a):
    # does not exist

A: I think a check if the key exists would be a bit better, as some commenters asked under the preferred answer enter link description here
So, I would add a small if clause at the end of the line:

input_key = 'main_color'
input_value = 'red'

if not any(_dict[input_key] == input_value for _dict in a if input_key in _dict):
    print("not exist")

I'm not sure, if wrong but I think the OP asked to check, if the key-value pair exists and if not the key value pair should be added.
In this case, I would suggest a small function:
a = [{ 'main_color': 'red', 'second_color': 'blue'},
     { 'main_color': 'yellow', 'second_color': 'green'},
     { 'main_color': 'yellow', 'second_color': 'blue'}]

b = None

c = [{'second_color': 'blue'},
     {'second_color': 'green'}]

c = [{'main_color': 'yellow', 'second_color': 'blue'},
     {},
     {'second_color': 'green'},
     {}]

def in_dictlist(_key: str, _value :str, _dict_list = None):
    if _dict_list is None:
        # Initialize a new empty list
        # Because Input is None
        # And set the key value pair
        _dict_list = [{_key: _value}]
        return _dict_list

    # Check for keys in list
    for entry in _dict_list:
        # check if key with value exists
        if _key in entry and entry[_key] == _value:
            # if the pair exits continue
            continue
        else:
            # if not exists add the pair
            entry[_key] = _value
    return _dict_list

_a = in_dictlist("main_color", "red", a )
print(f"{_a=}")
_b = in_dictlist("main_color", "red", b )
print(f"{_b=}")
_c = in_dictlist("main_color", "red", c )
print(f"{_c=}")

Output:
_a=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red', 'second_color': 'green'}, {'main_color': 'red', 'second_color': 'blue'}]
_b=[{'main_color': 'red'}]
_c=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red'}, {'second_color': 'green', 'main_color': 'red'}, {'main_color': 'red'}]

A: Following works out for me.
    #!/usr/bin/env python
    a = [{ 'main_color': 'red', 'second_color':'blue'},
    { 'main_color': 'yellow', 'second_color':'green'},
    { 'main_color': 'yellow', 'second_color':'blue'}]

    found_event = next(
            filter(
                lambda x: x['main_color'] == 'red',
                a
            ),
      #return this dict when not found
            dict(
                name='red',
                value='{}'
            )
        )

    if found_event:
        print(found_event)

    $python  /tmp/x
    {'main_color': 'red', 'second_color': 'blue'}


text:
Q: Why a 300x600 banner is being loaded in a 980x250 slot? Google DFP Is there any explanation why a banner of 300x600 is being loaded on a 980x250 unit? This unit is set to display just 980x250 banners on Google DFP but on small resolutions the 980x250 banner is still being displayed and sometimes a 300x600 unit is displayed as well (however the tag being loaded is home_1_main_980_leader)
This is the header:

Any clue, please? I'll really appreciate any help you may give me to troubleshoot this.

A: Are all these slots on the same place in the site? Like one after another?
You are using the same size mapping (mappingDesktop) on all of your slots.
You need different size mapping for each slot. But if you want to have one place loading different sizes, it is different approach.
Your approach (probably) fixed. But on large desktop it will in fact render all of the 4 sizes (don't know if this is your goal or not?):

The example above will load 980x250 if width is 980 or bigger, 728x90 if width is 728 or bigger, 468x60 if width is 468 or bigger and 320x50 if width is 320 or bigger. It will not load any banner, if it is bellow 320.
And again, keep in mind this approach will load ALL 4 banners on width 980 or bigger.
If you want to have different sizes ON SINGLE PLACE depending on the size of the browser, you need only one ad unit and the code is much simple:

And in the body only:

Note 2 things:
1. In the body code the size of div is removed, so it doesn't "blinks" if there is no ad.
2. You don't need to have collapseEmptyDivs after each unit. Once is enough at the end.


text:
Q: PHP htmlspecialchars() function shows html safe tags in page I have a form that users fill it and send their questions, and then administrator will answer them and finally these questions will be shown in website.
To prevent attacks, I've used PDO and htmlspecialchars() function. I don't apply any change on input data and only store them using PDO. But when I want to show them in the page, I use htmlspecialchars(). But this caused that even
 tags appear in the text as part of it. What is the problem and how can I solve it?
Storing questions:
$stmt = "INSERT INTO tbl_questions (title,question) VALUES (?,?)";
$q = $db->prepare($stmt);
$q->execute(array($_POST['title'],$_POST['question']));

Displaying questions:
echo htmlspecialchars($title).'
'.htmlspecialchars($question);

A: If you want to display only text, or even control which tags are converted/removed you have the option of using strip_tags.
echo strip_tags($title, '
');

Would display your title without having your p tags displayed.
Edit: Also realize that even by allowing tags you also allow certain attributes to function normally which wouldn't keep you safe from XSS attacks.

Awesome

This would still work so using a filtering library such as HTML Purifier is recommended.

A: This is not a problem, you just didn't select a correct function for your task.
the htmlspecialchars() doesn't remove tags, it just transforms them so they are displayed instead of being executed. So, for example,
 becomes <p>.
If you want to (partially) remove the tags, use the strip_tags() function. And, if you don't need these tags, you may (and should, I think) strip them before adding your content to database.
And also, you can allow certain tags, like this:
$q->execute(array(strip_tags($_POST['title']), strip_tags($_POST['question'], "
"));

This way you'll allow
 and  in your questions. This is not needed, I'm just showing you the possibilities of the function.
However, if you want to use far more flexible rules, I'd suggest you an HTML sanitizer. For instance, I use HTMLawed. It allows to specify not only allowed tags, but also allowed attributes and classes including wildcards (for instance, you can remove anything but the class attribute, or allow everything but the style attribute).

A: The method htmlspecialchars is not perfect.
Take a look at htmlpurifier. It is way more powerfull through whitelist filter. With it, your users can write html (such as
), and you don't have the risk of XSS.
consider, to use this, before you store it in the database, so you don't need to santize your input on every page view.


text:
Q: C# Converting TIFF JPEG compression to TIFF CompressionCCITT4 gives a lot of noise For a OCR engine I need to feed the OCR engine with TIFF files with CCITT4 Compression.
Our scanner outputs TIFF files with JPEG compression. I want to convert these files with C#, using System.Drawing.Imaging.
This results in images with a lot of Noise. How can I reduce the noise?
My Code:
        List<byte[]> fRet = new List<byte[]>();
        ImageCodecInfo fImageCodecInfo = GetEncoderInfo("image/tiff");
        EncoderParameters fEncoderParameters = new EncoderParameters(3);
        fEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
        fEncoderParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ScanMethod, (int)EncoderValue.ScanMethodNonInterlaced);
        fEncoderParameters.Param[2] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)EncoderValue.RenderNonProgressive);

        //

        Image fOrgTiff = Image.FromStream(pInputTiff);
        Guid objGuid = fOrgTiff.FrameDimensionsList[0];
        FrameDimension objDimension = new FrameDimension(objGuid);
        int frameCount = fOrgTiff.GetFrameCount(objDimension);
        for (int i = 0; i < frameCount; i++)
        {
            MemoryStream ms = new MemoryStream();
            fOrgTiff.SelectActiveFrame(objDimension, i);
            fOrgTiff.Save(ms, fImageCodecInfo, fEncoderParameters);
            ms.Position = 0;
            fRet.Add(ms.GetBuffer());
        }
        return fRet;

A: As Brannon said, Ccitt4 is a binary format (black/white) so your image is automatically binarized.
The documentation says: "The Ccitt3, Ccitt4, and Rle require that the PixelFormat value be set to BlackWhite. Setting the PixelFormat to any other value resets the Compression property value to Default."
You can try to reduce the noise by choosing a better binarization threshold. You can look at algorithms provided by open-source imaging libraries like AForge.Net or EmguCV.


text:
Q: ERROR: Could not find GNU compatible version of 'tar' command while installing RVM I'm trying to follow the instructions in this post: http://net.tutsplus.com/tutorials/ruby/how-to-install-ruby-on-a-mac/
To install Ruby on my Mac. However I get this error:
RyanT:~$ \curl -L https://get.rvm.io | bash -s stable --rails --autolibs=enabled
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100 15790  100 15790    0     0  14754      0  0:00:01  0:00:01 --:--:-- 14754

ERROR: Could not find GNU compatible version of 'tar' command, make sure it's available first before continuing installation.

I did run this:
brew install gnu-tar --default-names

Having found the command in a stray blog post about GNU. However it's not helped.
Searching Google I can't find anyone else who's had this error. Does anyone have any suggestions?

A: this was a bug and should be fixed with: https://github.com/wayneeseguin/rvm/commit/b6e3993614b3cad50d5b0336f80c693fabafa6e0
if it still hapens open rvm issue here: https://github.com/wayneeseguin/rvm/issues


text:
Q: Sqlite Database does not return correct values in my Java Spring Security application? I have a problem with SQLite and Spring Security. I have prepared my first application in Spring and I want use Spring Security with SQLite.
Here is my code:
Setup for database:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .and().formLogin().loginPage("/login")
            .usernameParameter("ssoId").passwordParameter("password")
            .and().csrf()
            .and().exceptionHandling().accessDeniedPage("/Access_Denied");
}

@Autowired
DataSource dataSource;

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery(
                    "select username,password,enabled from user where username=?");
}

database:
INSERT INTO user(username,password, enabled)
VALUES ('nequeq','123', 'true' );
INSERT INTO user(username,password, enabled)
VALUES ('alex','123', 'true');

INSERT INTO authorities (username, authority)
VALUES ('nequeq', 'ROLE_USER');
INSERT INTO authorities (username, authority)
VALUES ('nequeq', 'ROLE_ADMIN');
INSERT INTO authorities (username, authority)
VALUES ('alex', 'ROLE_USER');

login page:

            <c:url var="loginUrl" value="/login" />
            <form action="${loginUrl}" method="post" class="form-horizontal">
                <c:if test="${param.error != null}">

Invalid username and password.

                </c:if>
                <c:if test="${param.logout != null}">

You have been logged out successfully.

                </c:if>

                    <input type="text" class="form-control" id="username" name="ssoId" placeholder="Enter Username" required>

                    <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>

                <input type="hidden" name="${_csrf.parameterName}"  value="${_csrf.token}" />

                    <input type="submit"
                           class="btn btn-block btn-primary btn-default" value="Log in">

            </form>

This is not full code, just most important part. Application works, I can see pages and whatever I want.
But I can not log into my system, always this code returns "Invalid username and password".
Could you help me with this?


text:
Q: Copy from Range A to Range B and don't overwrite existing date in B I want to copy from Range rngA lets say A1:F70 to Range rngB H1:M70
But Range B already might contain some data.
How should i copy the data over?
Should i check every possible cell and only copy the cell analog to it over?
using rngA.Copy rngB would just overwrite everything
I also don't want to shift the current cells down. Only overwrite the empty ones.
I tried to do my own function, but it currently just totally fails to even execute it.
RangeCopyNoOverwrite (rgLastWorkWeek, rgThisWorkWeek)

Public Sub RangeCopyNoOverwrite(ByVal rngSrc As Range, ByVal rngDest As Range)
    Application.ScreenUpdating = False
    Application.Cursor = xlWait
    Dim destCell As Range
    Dim srcCell As Range
    Dim breite As Long
    Dim hoehe As Long

    breite = rngSrc.Columns.Count
    hoehe = rngSrc.Rows.Count

    For I = 0 To hoehe
        For J = 0 To breite
            Set srcCell = Range(Cells(rngSrc.Row + I, rngSrc.Column + J), Cells(rngSrc.Row + I, rngSrc.Column + J))
            Set destCell = Range(Cells(rngDest.Row + I, rngDest.Column + J), Cells(rngDest.Row + I, rngDest.Column + J))
            If IsEmpty(destCell) = True Then
                srcCell.Copy destCell
            End If
        Next J
    Next I
    Application.ScreenUpdating = True
    Application.Cursor = xlDefault
End Sub

A: Try this:
Public Sub RangeCopyNoOverwrite(rngSrc As Range, rngDest As Range)
    Dim r As Long, c As Long
    Application.ScreenUpdating = False
    Application.Cursor = xlWait
    For r = 1 To rngSrc.Rows.Count
        For c = 1 To rngSrc.Columns.Count
            If IsEmpty(rngDest.Cells(r, c)) Then
                rngSrc.Cells(r, c).Copy rngDest.Cells(r, c)
            End If
        Next c
    Next r
    Application.ScreenUpdating = True
    Application.Cursor = xlDefault
End Sub


text:
Q: Compile with low SDK build tools version Trying to build project with lower SDK version. Got warning:
WARNING: The specified Android SDK Build Tools version (25.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.3.2.
Android SDK Build Tools 28.0.3 will be used.

Should I somehow install lower Gradle plugin version? How I can do that?

A: You can change Androd gradle plugin version in your build.gradle file of project
buildscript {
    ext.kotlin_version = '1.3.21'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

You can look to Android Gradle plugin release notes

A: Simply remove this one line from the module's build.gradle to get rid of the warning message:
buildToolsVersion "25.0.1"

The latest version matching the targetSdkVersion will be used then. Manually setting the buildToolsVersion is definitely not required anymore - and downgrading the Gradle plugin is also pointless, because you'd need to downgrade the whole IDE, in order to have matching versions.

A: You can ignore this warning as android studio is taking care of using right build tool version 'Android SDK Build Tools 28.0.3'.
You can also modify your app/build.gradle.
defaultConfig {

    buildToolsVersion = 28.0.3

}

A: Firstly, this is just a warning and you can ignore it.
This warning will not create any problem for basic development.

Secondly, this warning appears when somehow your build.gradle is using 25.0.1 as build tools version, which in turn can be from any library/package that you have used and might not be from any of your build.gradle files

In order to remove this warning completely, you need to make sure that all your module level build.gradle files contains the following lines :

    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    targetSdkVersion 28

Or, you can lower the gradle version in your project level build.gradle file (The reference you posted in  your question) with this line

dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
}

Hope it helps you :)


text:
Q: Fragment doesn't overlay whole layout I have a bottom navigation bar and a viewpager.
In one fragment there is a recyclerview with items. On Item click it needs to open details screen of that item.
   addFragment(DetailsFragment(),R.id.container)

This is an extension.
fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int) {
    supportFragmentManager.inTransaction { add(frameId, fragment).addToBackStack(null) }
}

This is my activity_main.xml
<?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:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <com.product.NonSwipableViewPager
            android:id="@+id/viewPagerFragments"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/navigation"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginStart="0dp"
            android:background="?android:attr/windowBackground"
            app:itemIconTint="@drawable/selector_bottom_navigation"
            app:itemTextColor="@drawable/selector_bottom_navigation"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

Is there any solutions to this? I tried creating another container inside of this container and it didn't work.
One solution is to use another activity. I'm just wondering if it is possible to do with a Fragment or am I doing something wrong.

A: Follow the steps
Step 1: cut this line from ConstraintLayout
android:id="@+id/container"

step 2: Add these line
<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

your final code will look like
<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"
tools:context=".MainActivity">

     <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

    <com.product.NonSwipableViewPager
        android:id="@+id/viewPagerFragments"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:itemIconTint="@drawable/selector_bottom_navigation"
        app:itemTextColor="@drawable/selector_bottom_navigation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

A: For me using R.id.content works


text:
Q: Mobile development project architecture model/pattern I would like to hear some improvement suggestions for mobile development (Android/iOS) project architectures.
I would like to go for a "safe" design, modular and that can be easily maintained in time.
As far as I know Android and also iOS platforms are built on MVC, at least have the Activities and UIViewControllers that are a sort of controller part from MVC(as many stated out there on the internet).
Also I know two approaches so far for a basic project(Android/*iOS*):
 1. My favorite (a sort of MVC)
Model - I have here the models, only simple getter/setter classes
   shaping the project entities
View - the Activities, UIViewController
   and custom views, only display, get data from the user interface here, usually gets the data from the Controller, never directly from the Acess
Controller - some singletons (not necessary but usual) that manage
   each entity data, usually are doing business jobs, loading    data
   from the Access layer and don't have access to the view layer.
Access - Database and Web Service managers, serves data back to Controller layer, can't have contact to any other layers.
2. Commonly seen (also a sort of MVC)
Model - the models, only simple getter/setter classes shaping the project entities, I usually saw also some business jobs here too.
View-Controller -(Activities and UIViewController) that manage entity data, usually are doing business jobs and also take care of displaying data to the user. Also make calls through some web service classes to get the data.
So far I am using the first variant as I consider it more decoupled and I can see the difference between who is making business jobs, user interface communication and data providers. This making it more maintainable than the second one.
The drawback for the first one is that has 2 more layers than the second one, this means more classes(but less code in each class) and at the start of a project, this can take a bit longer to develop than the second one.
What approach do you use or which do you think it is better and why?

A: I don't think either of them represent classical MVC.
Model
The model is the data and the business logic. A model contains the state of the running application. It should report data and state. It should validate input. It should update data and state based on input.

*

*The model should be independent of use. In iOS, this generally means it should derive from core Objective-C classes and use only core Objective-C objects. A good test for this would be to see if the model would work for other compilers like GCC Objective-C, or if it will work in other environments like OS X.

*The model should be externally controllable. The model should be able to be driven by unit-tests or driven by a completely separate set of controllers.
View
A view is anything that is displayed to a user. In iOS, this generally means anything derived from UIView (UILabel, UIButton, …) Views are dumb: meaning that they know nothing of the model, business logic, or context in which they are created.
Controller
The controller binds model data to views so it can be displayed to users, provides context to views so they are shown correctly (disabled, highlighted, …), and handles user input to update the model. In iOS, this generally means anything derived from UIViewController. A controller may need to process model data in some small way to get it into a view. A controller may need to process user input in some small way to make it suitable for the model.
Data Store
The data store is the permanent repository for model data. This can be a database or a web service. Usually, data stores stand outside of MVC or are attached to the model.
My Answer
Now that I got that out of the way, my answer to your question: the MVC described above is the approach I use. This has implications, some of which are difficult to deal with.

*

*A view must know nothing of the model. If you have a property in your view named price or total, then you're doing it wrong.

*A controller must not contain business logic. If you have a controller calculate sales tax, then you're doing it wrong.

Addressing concerns in the comments
Warning: I'm not an Android developer and have limited understanding of how
Android works.
Services
Like data stores, long running async processing sits outside of MVC. If you need a service that updates the model, then think of it as method of the model. If you have a service that transforms data to show it to a user, then think of it as a method of a controller.
Novel Input
Like all input, broadcast receivers, orientation changes and task switching are tasks that should be handled by a controller. I think of iOS's application delegate as a controller for the whole application: handling input which effects the whole application (like system notifications and application lifecycle changes).
Business Logic and Model Data
I see the Model composed of two parts, model data and business logic. I've learned it's best to keep them separate. In practice, this means I wrap model data with business logic or add business logic on as a category of the model data.
Who I Am
To put it bluntly, it doesn't matter who I am. I don't think I've had a good original thought in my whole life. I've based my work on understanding patterns that other developers have created and applying them as best I can to the work I need to get done.
Since you asked, I've never worked in academia. I've been a software developer for the past 14 years. I've worked on code at all levels from drivers and debuggers to shiny custom views and silly apps. I've worked on iOS for the past 2½ years and have written many apps which have been released in the app store. I use my understanding of patterns to get my work done on time and on budget.

Update More questions in comments.
Models
I try to keep my data models as clean as possible. Usually they are mostly properties, sometimes conforming to NSCopying, NSCoding, and/or a JSON mapping. More and more, I include Key-Value Validation. This can be part of the data model or in a business logic category.
- (BOOL)validateValue:(inout MyValue **)value error:(out NSError **)error
{
    if (![self complexTestWithValue:*value]) {
        if (error != NULL) {
            // Report error to caller.
            *error = [self errorInValidation];
        }

        return NO;
    }

    return YES;
}

Business Logic
In the past, I've written lots of code which looks like
[dataSource fetchObjectsWithInput:input completion:^(NSArray *objects, NSError *error) {
    // Model objects are in objects
}];

or
[dataSource fetchObjectsWithInput:input completion:^(MyClassResult *result, NSError *error) {
    // Model objects are in result.objects
}];

Recently, I've gotten into promises (I'm using PromiseKit).
[dataSource fetchObjectsWithInput:input].then(^(MyClassResult *result) {
    // Model objects are in result.objects
});

This has been a good general purpose factory pattern for Objective C.
I tend to write business logic computations in categories.
@interface MyClass (BusinessLogic)

- (NSString *)textForValue; // A string to be used as label text.
- (MyResult *)computeOperationWithInput:(MyInput *)input error:(out NSError **error);
- (MyOtherClass *)otherObjectByTransformingValues;

@end


text:
Q: count max() values in a sparse matrix by row (dataframe) I have a sparse matrix with a few columns and I want to count by row when a value is equal to the max value of that row
How can this be done?
Let's say the data looks like this:
index    A    B    C    D    MAX
0        0    0    2    1    2
1        1    4    1    0    4
2        0    3    2    3    3

where the outcome should be:
index    A    B    C    D    MAX
  0      0    0    1    0    2
  1      0    1    0    0    3
  2      0    1    0    1    4

Thanks!

A: m=[[0, 0, 2, 1],[1, 4, 1, 0],[0, 3, 2, 3]]
df = pd.DataFrame(m)
maximums = df.max(axis=1)
maxmatrix = [[int(m[i][j] == maximums[i]) for j in range(df.shape[1])] for i in range(df.shape[0])]
print(maxmatrix)

returns
[[0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 0, 1]]


text:
Q: Computation of a Schwarz Christoffel Mapping with an unbounded image I have a problem with finding the image of a Schwarz-Christoffel mapping.

Find the image of $H$ (the upper half-plane) under the map
$$ f(z)=\int_{0}^{z} \frac{d \xi}{\sqrt{\xi(\xi+1)}} $$
where the square root is chosen sich that $f(x)>0$ for $x \in
\mathbb{R}^+$. Show that $f$ is conformal on $H$.

I know that Schwarz Christoffel mappings map the upper half-plane to a polygon, so I need to determine the vertices and angles. I stared by rewriting the formula as follows
$$
\int_{0}^{z} \frac{d \xi}{\sqrt{\xi(\xi+1)}}
=\int_{0}^{z} (\xi-(-1))^{\frac{1}{2}-1} (\xi-0)^{\frac{1}{2}-1} d \xi
$$
giving me
$$
a_1=-1, a_2=0
$$
for the preimages of the vertices  and
$$
\alpha_1=\frac{1}{2}, \alpha_2=\frac{1}{2},
$$
for the angles. Since $\alpha_1+\alpha_2=1 \neq 0=n-2$ for $n=2$ I have to introduce $a_3=\infty$ and $\alpha_3=0$. This suggests that the image will be a triangle with one vertex at infinity. Now, in order to see where the three points $a_1,a_2,a_3$ get mapped and to prove that the mappping is biholomorphic (which will imply that the mapping is conformal) I attempted to compute the integral using the substitution $u=\xi+\frac{1}{2}$
$$
\int_{0}^{z} \frac{d \xi}{\sqrt{\xi(\xi+1)}}
=\int_{0}^{z} \frac{d \xi}{\sqrt{\left(\xi^2+\frac{1}{2} \right)^2- \frac{1}{4}}}
=\int_{\frac{1}{2}}^{z+\frac{1}{2}} \frac{d u}{\sqrt{u^2- \frac{1}{4}}}
=\int_{\frac{1}{2}}^{z+\frac{1}{2}} \frac{2}{\sqrt{4u^2-1}} du
$$
But now I am not sure what to do next. Also, given that I'm still unfamiliar with Schwarz Christoffel mappings I am not sure whether I have made any errors.


text:
Q: Send chars with UDP I'm trying to send text with UDP, by sending every character separately, but something seems to be wrong.
This is the client:
while(strcmp(sir,"0")!=0)
{
     printf("Text number %d:", i);
     i++;
     scanf("%s",sir);
     printf("\n");
     sirLen=strlen(sir);
     for(j=0;j<sirLen;j++)
     {     c=sir[j];
          printf("%c",c);
          sendto(sock, &c, sizeof(char), 0, (struct sockaddr *)&ServAddr, sizeof(ServAddr));
     }
}

raspunsLen=recvfrom(sock, raspuns, SIRMAX, 0,(struct sockaddr *) &fromAddr, &fromSize);
raspuns[raspunsLen] = '\0';
printf("%s",raspuns);

And this would be the server:
for (;;)
{
    cliAddrLen = sizeof(ClntAddr);
    while(sir != '0')
    {
      recvfrom(sock, &sir, sizeof(char), 0,(struct sockaddr *) &ClntAddr, &cliAddrLen);
      raspuns[i]=sir;
      printf("%c",sir);
    }
    raspunsMsgSize=strlen(raspuns);
    sendto(sock, raspuns, raspunsMsgSize, 0, (struct sockaddr *) &ClntAddr,             sizeof(ClntAddr));
}

It works when I send whole pieces of text but this way the server doesn't seem to be receiving anything. Hope someone can help.
Thank you.

A: I suspect:
while(sir != '0')

should be:
while(sir != 0)

or possibly:
while( * sir != 0 )

But really, you haven't posted enough code to be sure.


text:
Q: ReactJS: Global Okta Auth Helper Function I have my React web app authenticated using Okta however if the user is not authenticated or the token expires then it will redirect the user to the /login page.
Page1.js:
import React, { useState, useEffect } from "react";
import { useOktaAuth } from "@okta/okta-react";
import { Redirect, useHistory } from "react-router-dom";

const { authState } = useOktaAuth();
const history = useHistory();

useEffect(() => {
    if (!authState) {
      history.push("/login");
    }
});

Is there a way I can include the above into an function that I can import to each different Page[#].js instead of including the above code in each file?
Just trying to refactor and make sure my code is tidy as I go but unsure the best way to tackle this.
TIA!

A: You can wrap all the components that required users to be logged in inside a component and protect the routes.
Once the user logs in, set a token in localstorage or redux (you need to persist it). Specify the route to go through IsloggedIn component so that, those routes will only be accessible if user is logged in, else will be redirected to the login page
Example
import React from "react";
import { Redirect, Route } from "react-router-dom";

function IsLoggedIn({ Component, ...props }) {

  const isAuthenticated = localStorage.getItem("isAuthenticated");

  return (
    <Route {...props}
      render={(props) =>
        isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
}

export default IsLoggedIn;

In App.js
function App(){
  return(
    <BrowserRouter>
       <Route exact path="/login" component={Login} />
       <IsLoggedIn exact path="/" component={Page1} />
    </BrowserRouter>
  )
}

A: you can use the below
private-route component
import React, { useEffect } from 'react';
import { Route, Redirect, RouteProps, useHistory } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from 'app/config/store';
import { SecureRoute, useOktaAuth } from '@okta/okta-react';
import { authenticationSuccess } from '../reducers/authentication-slice';

export const PrivateRouteComponent = ({ component: Component, ...rest }: IOwnProps) => {
//reducer
  const isAuthenticated = useAppSelector(state => state.authentication.isOktaAuthenticated);
  const { authState, oktaAuth } = useOktaAuth();

  const dispatch = useAppDispatch();

  useEffect(() => {
    if (!isAuthenticated && authState && authState.isAuthenticated) {
      oktaAuth.token.getUserInfo().then(info => {
//action dispatch
        dispatch(authenticationSuccess({ name: info.name, email: info.email }));
      });
    }
  }, [authState, oktaAuth]); // Update if authState changes

  const renderRedirect = props => {
    return isAuthenticated && <Component {...props} />;
  };

  return <SecureRoute {...rest} render={renderRedirect} />;
};

export default PrivateRouteComponent;

in app.js
 <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
      <Switch>
            <Route path="/callback" component={LoginCallback} />
            <PrivateRoute path="/" exact={true} component={Home} />
            <PrivateRoute path="/home" exact={true} component={Home} />
      </Switch>
  </Security>


text:
Q: How to get all children data Inside a nested key Database in Firebase Realtime Database Android? I have a database structure as below.

I am able to retrieve the children's data when I give reference to date but I want to retrieve data without referencing to date but the previous nested key.
That is, when I write the following, I am able to get the data:
databaseReference = FirebaseDatabase.getInstance().getReference("LDC Wise").child("Agra").child("25-10-2022");

But when I write the following, I am getting null data:
databaseReference = FirebaseDatabase.getInstance().getReference("LDC Wise").child("Agra")

How do I go about fetching all the data in the next sublevel of the database without referencing to date key explicitly?

A:
How do I go about fetching all the data in the next sublevel of the database without referencing to date key explicitly?

This can be solved by looping through the results twice:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference agraRef = db.child("LDC Wise").child("Agra");
agraRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot snapshot : task.getResult().getChildren()) {
                for (DataSnapshot innerSnapshot : snapshot.getChildren()) {
                    //Get the data out of the innerSnapshot object.
                }
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});


text:
Q: Return all data from left table, even if where clause is not attended I have a seller_commissions table, where are related with two other tables: products and sellers (users)
I need to make a painel, where admin can update seller commissions for each product.
Products will be created over time, so I don't want to insert data in seller_commissions table when this occurs, because I would need to do this multiples times. So, my solution was:
get all products data for user's update. If seller_commissions are null for specific product, this means the target seller never has your commission updated. In other words, all sellers have commission = 0 in first moment.
I try the following queries:
-- This is the result what I want, but filtering by seller_id, but, unfortannaly this return all products for each seller (I want to specify the seller_id)
select fpp.name as product_name,
       fsc.seller_id,
       fsc.commission
from fp_products as fpp
left join fp_sellers_commissions as fsc
   on fsc.product_id = fpp.id
left join fp_users as fpu
   on fpu.id = fsc.seller_id;

-- If I use 'where' clause, not all products are returned, because seller_id is none
select fpp.name as product_name,
       fsc.seller_id,
       fsc.commission
from fp_products as fpp
left join fp_sellers_commissions as fsc
   on fsc.product_id = fpp.id
left join fp_users as fpu
   on fpu.id = fsc.seller_id
where seller_id = 1;

*

*result for first query:

*result for second query:

*expected results:

product_name
seller_id
commission

shirt
1
250

shoes
null
0

black shirt
null
0

In first query, is something similiar with what I want. Get all products and seller_commission, but I want this for a specific seller, but when I try to use WHERE clause, I don't get all products, because seller_id can be null. I try some variations of these queries, but can't get the expected result :/. Appreciate any help.
to build the schema, use:
-- Create schema
CREATE TABLE `fp_sellers_commissions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `commission` float NOT NULL DEFAULT '0',
  `product_id` int(11) NOT NULL,
  `seller_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `fp_products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) CHARACTER SET latin1 NOT NULL,
  `createdAt` datetime DEFAULT CURRENT_TIMESTAMP,
  `disabled` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`id`)
);

CREATE TABLE `fp_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) CHARACTER SET latin1 NOT NULL,
  `surname` varchar(32) CHARACTER SET latin1 NOT NULL,
   PRIMARY KEY (`id`)
);

-- Inserting data:
INSERT INTO `fp_products`
(`id`, `name`, `createdAt`, `disabled`)
VALUES
(1, 'shirt', '00:00:00', 0),
(2, 'shoes', '00:00:00', 0),
(3, 'black shirt', '00:00:00', 0);

INSERT INTO `fp_users`
(`id`,
`name`,
`surname`)
VALUES
(1, 'bilbo', 'aaa'),
(2, 'frodo', 'aaa');

INSERT INTO `fp_sellers_commissions`
(`id`, `commission`, `product_id`, `seller_id`)
VALUES
(1, 100, 1, 1),
(2, 500, 1, 2);

Or you can acess SQL FIDDLE: http://sqlfiddle.com/#!9/d6559f/5

A: I'm not sure why the expected result should be with a commission of "250" for the seller "1", but I think I got what you are searching for. If you want to filter the seller's commission and still display the other products with nulls, you could put the filter condition directly on the left join, kinda like the following.
select fpp.name as product_name,
   fsc.seller_id,
   fsc.commission
from fp_products as fpp
left join fp_sellers_commissions as fsc
 on fsc.product_id = fpp.id and fsc.seller_id = 1
left join fp_users as fpu
 on fpu.id = fsc.seller_id;

What happens here, is that the filtering condition is applied at the moment you do the left join, so if it does not match, since it is a "left" join, the results will still be returned with nulls. If you put it in the "where" clause, it will be applied after the join is applied, and it will filter out the results that do not match.

A: My suggestion is
select fpp.name as product_name,
       fsc.seller_id,
       SUM(ifnull(fsc.commission, 0)) as commission
from fp_products as fpp
left join fp_sellers_commissions as fsc
on fpp.id = fsc.product_id and fsc.seller_id = 1
group by fpp.name, fsc.seller_id
order by fsc.seller_id desc;

with this must be getting the result you need. Note: I added a group summing to commissions, but if not is the goal, just remove the group by and the sum function.
Hoping this can help you.


text:
Q: Read a text file and split the text file by removing delimiters and store it into 2 arrays I want to read a text file and split the text file by removing delimiters and store it into two 1d-arrays (one for Movie name and other for Revenue)
Example of my text file:
Jurassic World=11734562.56
Black Panther@4352749.21
The Revenant}7452893.21
Trainwreck{1547892.45

A: May be this code, solve your problem. Splitfunction take chars and parse with these values. Delimeters are removed your result. If your all text like this (first name and delimeter and revenue), you can select even index as movie name and odd index as revenue.
string allText = @"Jurassic World=11734562.56
Black Panther@4352749.21
The Revenant}7452893.21
Trainwreck{1547892.45";

string[] splitStrings = allText.Split('\n', '=', '{', '}', '@');

string[] movies = splitStrings.Where((s, i) => i % 2 == 0).ToArray();
string[] revenues = splitStrings.Where((s, i) => i % 2 == 1).ToArray();

A: Another solution which strips unwanted chars.
string val = @" Jurassic World=11734562.56
                Black Panther@4352749.21
                The Revenant}7452893.21
                Trainwreck{1547892.45";

string[] lines = val.Split('\r');

string[] movieNameArr = new string[lines.Length];
decimal[] amountsArr = new decimal[lines.Length];

for (int i = 0; i < lines.Length; i++)
{
    string[] split = lines[i].Split(new Char[] { '=', '@', '}', '{' });

    // replace new line or space chars with empty string
    split[0] = Regex.Replace(split[0], @" |\n", string.Empty);

    movieNameArr[i] = split[0];
    amountsArr[i] = decimal.Parse(split[1]);
}

Console.WriteLine("Movie arr: [{0}]", string.Join(", ", movieNameArr));
Console.WriteLine("Amounts arr: [{0}]", string.Join(", ", amountsArr));

Console.ReadKey();


text:
Q: Network Response Timed Out when Using Expo on ubuntu I'm trying to run My react-native application, I'm running it on android emulator and my phone HUAWEI Y5 and same thing happens. I was working on it fine a few days ago but suddenly this error keeps coming up

A: Is something blocking connection suddenly ? Maybe router.
Try:

expo start --tunnel


text:
Q: MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first I only use DataReaders two times within my application both times it looks like this
    MySqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
       //Code
    }
    reader.Close();

Can anyone give me some pointers on how to solve this error? Or where to look? Sorry if it's too vague but that's what the error is telling me. It points to this point:
        MySqlCommand cmdDel = new MySqlCommand("UPDATE " + _Database + " SET balance=" + balance + ", bitaddress=" + myads + ", lostbalance=" + lostbalance + " WHERE username = '" + username + "'", connection);
        cmdDel.ExecuteNonQuery();
        cmdDel.Dispose();

My guess is that executing query commands could be not allowed inside of a while(reader.Read()) can anyone confirm on this?

A: This almost certainly implies that you're sharing a connection object between multiple command objects. You should avoid doing this (unless they're all involved in a single database transaction).
The model you should follow generally is:
using(var connection = new MySqlConnection("..."))
{
   using(var cmd = new MySqlCommand("...",connection))
   {
       //Set up parameters/other settings/as required
       connection.Open();
       cmd.<Whatever ExecuteXXX method you need to use>();
       //If it was ExecuteReader, process the results now
   }
}
//If it was ExecuteScalar, or a fill of a DataSet or DataTable, consume the results now

Unless you have specific needs which prevent it, you should prefer to wrap disposables in using statements, rather than manually calling Dispose().

A: You can write query inside the while loop but make sure that you should not use the resources used by the external loop.

A: If you want to open some readers at the same time, then you should open some new connections - for each reader. Created conection can be used again after reader closing.