text:
Q: Adding Multiple Markers in real time google maps v2 android I want to add markers when ever on camera change listener is called.
@Override
public void onCameraChange(CameraPosition position) {
    // TODO Auto-generated method stub
    double[] newValues = { position.target.latitude,
            position.target.longitude };
    new GetPlaces().execute(newValues);
}

AsyncTask Class which is used to get the center location of the map and get known places arround that location
private class GetPlaces extends AsyncTask<double[], Void, Boolean> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

    }

    @Override
    protected Boolean doInBackground(double[]... params) {
        // TODO Auto-generated method stub
        double[] vals = params[0];
        HttpRequest request = new HttpRequest();
        try {
            locs = request.getPlaces(vals[0], vals[1]);
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        if (result) {
                if (mMap != null) {
            if (locs.size() > 0) {

                    mMap.clear();

                    for (com.matsoltech.android.apps.easysavinghunter.Location loc : locs) {

                        Log.e("APPLICATION", "LOCATIONS FOUND ");
                        mMap.addMarker(new MarkerOptions()
                                .position(
                                        new LatLng(loc.getPoint()
                                                .getLatitude(), loc
                                                .getPoint().getLongitude()))
                                .title(loc.getName())
                                .icon(BitmapDescriptorFactory
                                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
                    }

                } else {
                    Toast.makeText(MainActivity.this, "No Deal Found",
                            Toast.LENGTH_LONG).show();
                }
            } else {
                Log.e("APPLICATION", "MAP IS NULL");
            }
        } else {
            Toast.makeText(
                    MainActivity.this,
                    "Oops..Something went wrong. Please check your connection and try again",
                    Toast.LENGTH_LONG).show();
        }
    }
}

In logcat the values are correct and data is being fetched properly .. the only problem is that my markers are not showing on the map. Please help!!

A: The answer is that i wasn't putting the right values of Lat and Lng in the Point object. Now its working find!!


text:
Q: Differences in nested flexbox between Chrome and Firefox with scrolling UPDATE: I'm not convinced this is a duplicate question. While the implied minimum size of flex content might be causing the issue, I still am curious why I'm getting different results in Chrome and Firefox.
I'm working on a project with nested flexboxes, where one of the nested divs has overflowing content and should scroll. I have it working just as expected in Chrome and Safari, but both Firefox and Edge behave differently.
Here's the jsFiddle: https://jsfiddle.net/e3p6xk0L/4/
Also, here's the code / example inline

body {
  padding: 0px;
  margin: 0px;
}

div {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: blue;
  position: relative;
}

.top {
  flex-basis: 40px;
  background: purple;
}

.middle {
  display: flex;
  flex: 1;
  background: orange;
}

.bottom {
  flex-basis: 40px;
  background: yellow;
}
.left {
  flex-basis: 20px;
  background: green;
}

.center {
  flex: 1;
  background: red;
}

.right {
  flex-basis: 200px;
  background: orange;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 10px;
}

.right-content {
  height: 1000px;
  background: gray;
}

Basically, there should always be a purple bar of fixed height at the top, and a yellow bar of fixed height on the bottom. The gray content, which overflows the right div, should only cause that right div to scroll.
Does anyone see anything obvious that I'm doing incorrectly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class Extends Fatal error: Class 'DatabaseObject' not found I've been following a PHP OOP course of LinkedIn. When I arrive to "Inheritance" part, the code in my PC fails and I cannot fix it.
The code has an auto load in the very first file.
This is when the project fails. It Never failed before, but when I arrive to inheritance, it fails.

Example: Class B extends A. This fails.

I've tried the following:

*

*Add __DIR__ to the autoload. Some warnings disappear, but the error still alive.

*Change php tag <?php to short version <?

*Change permissions to 777 (755 by default).

I expect to load the view called bicycles.php. A table with all the bicycles. This view works always, but in the moment I use inheritance, it fails.

initialize.php
<?php
    foreach(glob('/classes/*.class.php') as $file) {
    require_once($file);
  }

  // Autoload class definitions
  function my_autoload($class) {
    if(preg_match('/\A\w+\Z/', $class)) {
      include('classes/' . $class . '.class.php');
    }
  }
  spl_autoload_register('my_autoload');

  $database = db_connect();
  DatabaseObject::set_database($database);
?>

Parent Class: DatabaseObject
<?php
    class DatabaseObject {

          static protected $database;
          static protected $table_name = "";
          static protected $columns = [];
          public $errors = [];
  }
?>

Child Class: Bicycle
<?php

class Bicycle extends DatabaseObject {

  static protected $table_name = 'bicycles';
  static protected $db_columns = ['id', 'brand', 'model', 'year', 'category', 'color', 'gender', 'price', 'weight_kg', 'condition_id', 'description'];

  public $id;
  public $brand;
  public $model;
  public $year;
  public $category;
  public $color;
  public $description;
  public $gender;
  public $price;
  public $weight_kg;
  public $condition_id;

  public const CATEGORIES = ['Road', 'Mountain', 'Hybrid', 'Cruiser', 'City', 'BMX'];

  public const GENDERS = ['Mens', 'Womens', 'Unisex'];

  public const CONDITION_OPTIONS = [
    1 => 'Beat up',
    2 => 'Decent',
    3 => 'Good',
    4 => 'Great',
    5 => 'Like New'
  ];

  public function __construct($args=[]) {
    //$this->brand = isset($args['brand']) ? $args['brand'] : '';
    $this->brand = $args['brand'] ?? '';
    $this->model = $args['model'] ?? '';
    $this->year = $args['year'] ?? '';
    $this->category = $args['category'] ?? '';
    $this->color = $args['color'] ?? '';
    $this->description = $args['description'] ?? '';
    $this->gender = $args['gender'] ?? '';
    $this->price = $args['price'] ?? 0;
    $this->weight_kg = $args['weight_kg'] ?? 0.0;
    $this->condition_id = $args['condition_id'] ?? 3;

    // Caution: allows private/protected properties to be set
    // foreach($args as $k => $v) {
    //   if(property_exists($this, $k)) {
    //     $this->$k = $v;
    //   }
    // }
  }
?>

Errors and Warnings
Warning: include(classes/DatabaseObject.class.php): failed to open stream: No such file or directory in /home/................/chain_gang/private/initialize.php on line 45
Warning: include(): Failed opening 'classes/DatabaseObject.class.php' for inclusion (include_path='.:/usr/share/php') in /home/............/chain_gang/private/initialize.php on line 45
Fatal error: Uncaught Error: Class 'DatabaseObject' not found in /home/............../chain_gang/private/initialize.php:51 Stack trace: #0 /home/................/chain_gang/public/staff/bicycles/index.php(1): require_once() #1 {main} thrown in /home/................./chain_gang/private/initialize.php on line 51

Project directory:

PS: The codes examples are not complete at all. Only the most important part I think.

A: There is a } missing after the declaration of the DatabaseObject class
Note that your autoloader is not usefull because you do a require_once of all the classes in the /classes directory ;)

A: It's working for me, adding strtoupper after glob.
// Load class definitions manually
// -> Individually
// require_once('classes/song.class.php');
// -> All classes in directory
foreach (glob (strtoupper('Controller/*.Controller.php')) as $file) {
    require_once($file);
}

So the error message disappeared.


text:
Q: Swift 4 Variable Initialization in viewDidLoad() I'm a bit of a Swift newbie, and I've run into a problem that is really stumping me...
In the code below:
class TestViewController: UIViewController {

  var userNames : [String] = {return DatabaseMethods.getUsers()}()

  override func viewDidLoad() {
    super.viewDidLoad()
    print(userNames)
  }
}

The print statement will print an empty array every time. (I) I'm not sure why this is happening, and (II) I haven't figured out a way to get around this issue. Just for a bit more context, Here is what the DatabaseMethods class looks like:
class DatabaseMethods {

static func getUsers() -> [String] {
    var userNames = [String]()
    db.collection("users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let data = document.data()
                let first : String = data["First"] as! String
                let last : String = data["Last"] as! String
                userNames.append("\(first) \(last)")
            }
        }
    }
    return userNames
}

}

A: db.collection("users").getDocuments() is asynchronous, that is why it takes a closure. With DispatchGroup you can make getUsers() synchronous so you get all users back at the end of the call.
static func getUsers() -> [String] {
    let group = DispatchGroup()
    group.join()
    var userNames = [String]()
    db.collection("users").getDocuments() { (querySnapshot, err) in
        defer { group.leave() }
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let data = document.data()
                let first : String = data["First"] as! String
                let last : String = data["Last"] as! String
                userNames.append("\(first) \(last)")
            }
        }
    }
    group.wait()
    return userNames
}

Since arrays are value-types an empty copy would have been returned and so updates would not have reached it either with the old method, since value-types are getting copied as opposed to reference-types which are not.

A: Use the viewdidload method to make the petition, i hope your method is not executed because you are not intialize in viewdidload and you have an asynchronous problem. Try to make some like this:
class TestViewController: UIViewController {

  var userNames : [String] = []

  override func viewDidLoad() {
    super.viewDidLoad()
    userNames = DatabaseMethods.getUsers()
    print(userNames)
  }
}

in your code you are trying to make a lazy var, not just a var.


text:
Q: Multiple packages definition While browsing the source code of the Scala API, I met this package definition in scala/tags/R_2_8_0_final/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala:
package scala.util.parsing
package combinator
package syntactical

What does that mean? That the class will be available in more than one package?

A: The Scala reference mentions (chapter 9, section 9.1):

A compilation unit consists of a sequence of packagings, import clauses, and class and object definitions, which may be preceded by a package clause.
A compilation unit
package p1;
...
package pn;
stats

starting with one or more package clauses is equivalent to a compilation unit consisting of the packaging
package p1 { ...
  package pn {
   stats
  } ...
}

See also Organizing Code in Files and Namespaces on nested packages.
(From Programming Scala: Scalability = Functional Programming + Objects
By Dean Wampler, Alex Payne, page 44, Chapter 2)

A: This is basically the same as
package scala.util.parsing.combinator.syntactical

import scala.util.parsing._
import scala.util.parsing.combinator._

...

So by "stacking" the packages the way you wrote you can get super-packages in scope. See also these answers.
[Update] Here is a new article written by Martin Odersky about this topic: http://www.artima.com/scalazine/articles/chained_package_clauses_in_scala.html


text:
Q: for_each_process - Does it iterate over the threads and the processes as well? I would like to iterate all the tasks in the kernel (threads and processes) and print tid/pid and name using for_each_process macro:
#define for_each_process(p) \
    for (p = &init_task ; (p = next_task(p)) != &init_task ; )

How can I distinguish between thread and process?
So I'll print it like that:
 if (p->real_parent->pid == NULL)
      printk("PROCESS: name: %s pid: %d \n",p->comm,p->pid);
 else
      printk("THREAD: name: %s tid: %d \n",p->comm,p->pid);

A: The following macros are what you need:
/*
 * Careful: do_each_thread/while_each_thread is a double loop so
 *          'break' will not work as expected - use goto instead.
 */
#define do_each_thread(g, t) \
        for (g = t = &init_task ; (g = t = next_task(g)) != &init_task ; ) do

#define while_each_thread(g, t) \
        while ((t = next_thread(t)) != g)

Use them like this:
        rcu_read_lock();
        do_each_thread(g, t) {
            //...
        } while_each_thread(g, t);

        rcu_read_unlock();


text:
Q: MySql Select Query is not acting properly I want to search in a Date column.
I use this query:
SELECT * FROM requestserverdb.closedrequests
WHERE
ClosingTimeStamp >= '2014-09-04'
AND
ClosingTimeStamp <= '2014-09-19';

I only get results from 04-09-2014 to 18-09-2014 , it does not include the last day !
also if I use:
SELECT * FROM requestserverdb.closedrequests
WHERE
ClosingTimeStamp >= '2014-09-04'
AND
ClosingTimeStamp <= '2014-09-04';

I will not get any results at all !
how come ?
what am I doing wrong ?
its just ignores the '=' sign...
please help :)
Dave.

A: Another option for solving this is to add "23:59:59" to the end of the date. This would make things easier in automatically generated queries than bothering with advancing the date one day. Plus if you set it ahead a day and you actually have a closed request with the timestamp of '2014-09-20 00:00:00' that WILL be included in the results. Which I would assume you do not want. You could do this instead.
SELECT * FROM requestserverdb.closedrequests
WHERE
ClosingTimeStamp >= '2014-09-04'
AND
ClosingTimeStamp <= '2014-09-19 23:59:59';

A: It's because '2014-09-19' means 19 September 2014 at midnight (00:00:00), so the query won't return any records with ClosingTimeStamp equals 2014-09-19 09:25:00 for example. You should add one day to the upper bound of the second where condition and make it < instead of <= to avoid the query from returning any record with ClosingTimeStamp equals 2014-09-20 00:00:00
SELECT * FROM requestserverdb.closedrequests
WHERE
ClosingTimeStamp >= '2014-09-04'
AND
ClosingTimeStamp < '2014-09-20';

A: Try to convert your string to DateTime with time part:
SELECT * FROM requestserverdb.closedrequests
WHERE
ClosingTimeStamp between STR_TO_DATE('2014-09-04 0:0:0' , '%Y/%c/%d %H:%i:%s')) AND
STR_TO_DATE('2014-09-19 23:59:59' , '%Y/%c/%d %H:%i:%s'))


text:
Q: How to fix : Cannot convert lambda expression to type int because is not delegate? i am trying to get user decision from the list but i get that  Cannot convert lambda expression to type int because is not delegate. How can i solve this? I have had a look on the internet but since i am quite new i am not sure what is the right solution
public static List<int> UserDecisionResult  { get; set; }

public void GetUserDecision()
        {
            List<int> userDecision = new List<int>();
            if (FilterAllItems) userDecision.Add(_parentCategoryId = -1);
            if (FilterBeginnerItems) userDecision.Add(_parentCategoryId = 1);
            if (FilterIntermediateItems) userDecision.Add(_parentCategoryId = 2);
            if (FilterUpperIntermediateItems) userDecision.Add(_parentCategoryId = 3);
            if (FilterAdvancedItems) userDecision.Add(_parentCategoryId = 4);
            UserDecisionResult = userDecision;

        }

        private static List<Article> FindAllArticlesForPurchase(List<Article> allArticles)
        {
            var result = UserDecisionResult;

            if (_parentCategoryId != -1)
            {
                foreach (var categoryGroup in _allUserCategoryGroups)
                {
                    var allGroupCategories = _allCategories.Where(m => m.CategoryGroupId == categoryGroup.Id).ToList();

                    if (_parentCategoryId != -1)
                    {
                        foreach (var category in allGroupCategories)
                        {
                            if (category.ParentId == _parentCategoryId && _parentCategoryId != -1)
                            {

                                var categoryArticles = _allArticlesForPurchase.Where(result.Contains(m => m.CategoryId == category.Id).ToList();
                                //var categoryArticles = _allArticlesForPurchase.Where(result.Contains(m => m.CategoryId == category.Id).ToList());
                                allArticles.AddRange(categoryArticles);
                            }
                        }
                    }
                }
            }
            else
            {
                allArticles = _allArticlesForPurchase;
            }

            return allArticles;
        }

A: Your lambda expression is wrong here due to syntax. You can try:
var categoryArticles = _allArticlesForPurchase
                       .Where(m => m.CategoryId == category.Id
                              && result.Contains(m.CategoryId))
                       .ToList();

or if Contains here is some custom implementation then try :
var categoryArticles = _allArticlesForPurchase
                   .Where(_ => result.Contains(m => _.CategoryId == category.Id))
                   .ToList();


text:
Q: Convert alphanumeric string to numeric - Oracle I have this alphanumeric string
000193CA020008AA190038AA

I want it to be a unique number, for example
123456791011121314151617.

Is there a way to do it on PLSQL?
Not all aphanumerics are the same length,  does not contain hex numbers only.
I have tried
create or replace FUNCTION FN_BOM_STEEL_CHAR_TO_NUMBER(
  value IN VARCHAR2
) RETURN NUMBER DETERMINISTIC
IS
  c        CHAR(1);
  up_value VARCHAR2(5000) := LTRIM(UPPER(value),'0');
  total    NUMBER  := 0;
  len      PLS_INTEGER    := COALESCE(LENGTH(up_value),0);
BEGIN
  FOR i IN 1 .. len LOOP
    c := SUBSTR(up_value,i,1);
    total := total * 36
                   + CASE
                     WHEN '0' <= c AND c <= '9'
                     THEN TO_NUMBER(c)
                     ELSE ASCII(c) - 55
                     END;
  END LOOP;
  RETURN total;
END FN_BOM_STEEL_CHAR_TO_NUMBER;

and it worked really well but I have just found there are some duplicates with different alphanumeric strings, for example

*

*010000AA000001AA020019AA020047AA020138AA020139AA060018AA190016AA

*010000AA000001AA020019AA020047AA020138AA020139AA060019AA190016AA
You can see there is a 18 and 19 that makes the difference on them but when I select the function I'm getting the same ID for both. There are more cases like these.
Here's the select I'm trying for those examples
SELECT FN_BOM_STEEL_CHAR_TO_NUMBER('010000AA000001AA020019AA020047AA020138AA020139AA060018AA190016AA
') AS ID
FROM   DUAL;

and this is the ID for both:
3095673299759705115226102843045930360610000000000000000000000000000000000000000000000000000000000
I need them to be different.
Thanks in advance!

A: If you just have the characters 0123456789ABCDEF then you can use:
SELECT TO_NUMBER(
         '000193CA020008AA190038AA',
         'XXXXXXXXXXXXXXXXXXXXXXXX'
       ) AS from_hex_value
FROM   DUAL;

Which outputs:

|            FROM_HEX_VALUE |
| ------------------------: |
| 1906840079024071083309226 |

If you have the characters 0-9A-Z and want to treat it as a base 36 string then you could create the function:
CREATE FUNCTION base36_to_number(
  value  IN VARCHAR2,
  -- The value to parse from base 36 to base 10.
  width  IN INT DEFAULT 0,
  -- The width of the substring to consider; 0 is the entire string.
  offset IN INT DEFAULT 0
  -- The number of widths to offset from the least-significant digit.
) RETURN NUMBER DETERMINISTIC
IS
  c         CHAR(1);
  total     NUMBER := 0;
  len       PLS_INTEGER    := COALESCE(LENGTH(value),0);
  start_pos PLS_INTEGER;
  end_pos   PLS_INTEGER;
BEGIN
  IF width < 0 THEN
    RAISE_APPLICATION_ERROR( -20000, 'Invalid width.' );
  ELSIF offset < 0 THEN
    RAISE_APPLICATION_ERROR( -20000, 'Invalid offset.' );
  ELSIF width = 0 THEN
    start_pos := 1;
    end_pos   := len;
  ELSIF width * offset > len THEN
    RETURN 0;
  ELSIF width * (offset + 1) > len THEN
    start_pos := 1;
    end_pos   := len - width  * offset;
  ELSE
    start_pos := len - width * ( offset + 1 ) + 1;
    end_pos   := start_pos + width - 1;
  END IF;

  FOR i IN start_pos .. end_pos LOOP
    c := SUBSTR(value,i,1);
    total := total * 36
                   + CASE
                     WHEN '0' <= c AND c <= '9'
                     THEN TO_NUMBER(c)
                     WHEN 'A' <= c AND c <= 'Z'
                     THEN ASCII(c) - 55
                     WHEN 'a' <= c AND c <= 'z'
                     THEN ASCII(c) - 87
                     ELSE NULL
                     END;
  END LOOP;

  total := total * POWER( 36, width * offset );
  RETURN total;
END;
/

Then:
SELECT BASE36_TO_NUMBER('000193CA020008AA190038AA') AS from_base36_value
FROM   DUAL;

Outputs:

|                FROM_BASE36_VALUE |
| -------------------------------: |
| 16743829188442650222733747166386 |

The maximum size of a NUMBER is 38 decimal digits and you cannot fit more than a 24 character base-36 number into this. If you have a larger value then you will need to convert it to multiple numbers:
I.e.:
CREATE TABLE table_name ( value ) AS
SELECT '010000AA000001AA020019AA020047AA020138AA020139AA060018AA190016AA' FROM DUAL UNION ALL
SELECT '010000AA000001AA020019AA020047AA020138AA020139AA060019AA190016AA' FROM DUAL UNION ALL
SELECT 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZzzzzzzzzzzzzzzzzzzzzzzzz' FROM DUAL;

Then:
SELECT BASE36_TO_NUMBER( value, 24, 0 ) AS low_value,
       BASE36_TO_NUMBER( value, 24, 1 ) AS mid_value,
       BASE36_TO_NUMBER( value, 24, 2 ) AS high_value
FROM   table_name;

Outputs:

                             LOW_VALUE |                                                                   MID_VALUE |                                                                                HIGH_VALUE
-------------------------------------: | --------------------------------------------------------------------------: | ---------------------------------------------------------------------------------------------------:
   34663123071664682325935025837090322 |    777948567801018784511679412336101916888000000000000000000000000000000000 |    3095673299759705115226102065097362559570000000000000000000000000000000000000000000000000000000000
   34663123071664682329591184277153298 |    777948567801018784511679412336101916888000000000000000000000000000000000 |    3095673299759705115226102065097362559570000000000000000000000000000000000000000000000000000000000
22452257707354557240087211123792674815 | 504103876157462118901767181449118688664000000000000000000000000000000000000 | 4011991914547630480065052883598567655228000000000000000000000000000000000000000000000000000000000000

db<>fiddle here


text:
Q: Resources$NotFoundException with include-dynamic navigation graph I have a dynamic feature module with it's own nested navigation graph. I also have a dynamic feature module that's just a single fragment. If you have a dynamic feature module with it's own navigation graph, I understand you need to use the include-dynamic tag. When I build the app and deploy the app to the Play Store for internal testing, the dynamic modules download correctly. However If I and building/running locally - the app crashes when I try and navigate to the dynamic feature module that contains the navigation graph. I thought that everything was bundled when running locally? Is there something I'm missing?
The error I get is android.content.res.Resources$NotFoundException: com.xyz.app_name.two:navigation/two_navigation
main_navigation_graph
<!-- this works locally. module does not contain a nav graph -->
<fragment
    android:id="@+id/OneFragment"
    android:name="com.xyz.app_name.one.OneFragment"
    android:label="{nickname}"
    app:moduleName="one"
    tools:layout="@layout/one_fragment">
    <argument
        android:name="nickname"
        app:argType="string" />
</fragment>

<!-- this doesn't work locally -->
<include-dynamic
    android:id="@+id/two_graph"
    app:graphPackage="com.xyz.app_name.two"
    app:graphResName="two_navigation"
    app:moduleName="two" />

feature_two_graph
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/two_graph"
    app:moduleName="two"
    app:startDestination="@id/twoFragment">

    <fragment
        android:id="@+id/twoFragment"
        android:name="com.xyz.app_name.two.TwoFragment"
        android:label="{nickname}"
        tools:layout="@layout/two_fragment">
        <argument
            android:name="nickname"
            app:argType="string" />
        <action
            android:id="@+id/action_twoFragment_to_dialogFragment"
            app:destination="@id/dialogFragment" />
    </fragment>

    <dialog
        android:id="@+id/dialogFragment"
        android:name="com.xyz.app_name.two.ui.DialogFragment"
        android:label="bottom_sheet"
        tools:layout="@layout/bottom_sheet" />

</navigation>

A: I had the same problem.
When trying to add a dynamic-feature graph as destination, using include-dynamic as follow:
<include-dynamic
    android:id="@+id/nestedMyfeatureGraph"
    app:graphPackage="com.mycompany.myapp.mydynamicfeature"
    app:graphResName="nav_graph_feature"
    app:moduleName="mydynamicfeature"
    />

one should keep in mind that app:graphPackage is supposed to reference the dynamic-feature's applicationId (I know, it's confusing). If you have any custom gradle script adding suffix to applicationId or stuff like that, then referencing the graph will fail.
It probably only worked for you on playstore because I guess your script only adds suffix for non-prodRelease build types, which is a common pattern.
So, to fix the problem I had to replace
    app:graphPackage="com.mycompany.myapp.mydynamicfeature"

with
    app:graphPackage="${applicationId}.mydynamicfeature"


text:
Q: C++ use of class Classname; I am  viewing cocos2dx c++ source code and in it there are many places where they use
class Classname;

e-g in CCNode.h line 43
class CCCamera;

Classname is name of the class they are using and later I dont see any reference to that I never seen this before.
I would like to know what that means.

A: This is a forward declaration so that the actual imports occur in the .cpp files instead of the header files. This is a common practice in C++ OOP.
For a good explanation, see this post with a similar question
C++ Forward declaration
When you make a forward declaration, you are informing the compiler you intend to use something in advance. The important take aways, as declared in the link above, are that forward declarations break cyclic references and reduce compiler build times.


text:
Q: Match TableViewCell's Label from other TableViewCell's Label My problem is little complicated to define for me, even I understand what I am trying to do, I try my best to write this problem to understandable, guide me if I lack anything in question description.
So the problem is that I have a UITableView inside a UITableViewCell, both of UITableViews have  custom UITableViewCell classes. Datasource and delegate of both outer an dinner UITableView's are in same class. I am handling the data array like this
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView==self.mainTableView) {
        return titleArray.count;
    }
    return timeArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.mainTableView)
    {
        MainTableViewCell *cell = [tableView dequeueReusableCellWitentifier:@"cell"];
        cell.label.text = [dataArray objectAtIndex:indexPath.row];
        return cell;
    }
    InnerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.view.backgroundColor = [UIColor greenColor];
    return cell;
}

My custom cell's description

*

*Main UITableViewCell cusotm class properties - UILabel (eg.
myLabel),UITableView(inside)

*Inside UITableViewCell custom class properties  - UIView (eg.
myView)

Now I want to show myView only on that cell when 'myLabel' matches with my array of string object. for eg.
if([myLabel.text isEqualTostring:@"22"]){
cell.myView.backgroundColor = [UIColor blackColor];

}
For eg. if I have 5 views and 2 label, now 2 rows in Main UITableView and 5 rows in inside UITableView but every view should be in the outer cell
only if it matches the myLabel'text.
P.S Don't think about where matching data coming from its not an issue issue of matching data.
As a final conclusion I want to create different row count for each inner UITableView cell.

A: Did you tried this?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( tableView == self.mainTableView )
    {
        MainTableViewCell *cell = [tableView dequeueReusableCellWitentifier:@"cell"];
        cell.label.text = [dataArray objectAtIndex:indexPath.row];
        return cell;
    }
    InnerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    MainTableViewCell *parentCell = (MainTableViewCell*)cell.superView;
    NSIndexPath *parentIndexPath = [self.mainTableView indexPathForCell:parentCell];

    NSString *text = [dataArray objectAtIndex:parentIndexPath.row];
    if( [text isEqualTostring:@"22"] //your condition goes here
    {
        cell.view.backgroundColor = [UIColor blackColor];
    }
    else
    {
        cell.view.backgroundColor = [UIColor greenColor];
    }

    return cell;
}


text:
Q: Running out of memory when executing composer inside a docker container I'm running composer on docker container and I'm trying to install predis so I run the command

docker-compose run --rm composer require predis/predis

But I get this error

Can someone explain me how to fix?
that's my dockerfile
FROM php:7.2-fpm-alpine

RUN docker-php-ext-install pdo pdo_mysql

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer --version

and that's my docker-compose
   services:
      nginx:
        image: nginx:stable-alpine
        container_name: nginx
        ports:
          - "8088:80"
        volumes:
          - ./src:/var/www/html
          - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
        depends_on:
        - mysql
        - php
        networks:
        - laravel

      mysql:
        image: mysql:5.7.22
        container_name: mysql
        restart: unless-stopped
        tty: true
        ports:
          - "4306:3306"
        environment:
          MYSQL_DATABASE: homestead
          MYSQL_USER: homestead
          MYSQL_PASSWORD: secret
          MYSQL_ROOT_PASSWORD: secret
          SERVICE_TAGS: dev
          SERVICE_NAME: mysql
        networks:
        - laravel

      php:
        build:
          context: .
          dockerfile: Dockerfile
        container_name: php
        volumes:
          - ./src:/var/www/html
        ports:
          - "9000:9000"
        networks:
          - laravel

      redis:
            image: redis:5.0.0-alpine
            restart: always
            container_name: redis
            ports:
                - "6379:6379"
            networks:
              - laravel

A: In your docker-compose file, add an environment entry with COMPOSER_MEMORY_LIMIT: -1  to your php service
So your php services look like -
  php:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: php
    volumes:
      - ./src:/var/www/html
    environment:
      COMPOSER_MEMORY_LIMIT: -1
    ports:
      - "9000:9000"
    networks:
      - laravel


text:
Q: exception handling in C++ never catches baisc type of exception, always result in segmentation fault I am good with C and know basics of C++ and g++ to execute my code.
I am trying try catch exceptions in C++.
My code inside try section is mostly C code.
I wrote:
try{
  ....
}
catch (std::exception& e)
{
  std::cerr << "exception caught: " << e.what() << '\n';
}

In the try section, I tried couple of bad code:
char str[3];
free(str);   // Memory Violation

this gave me Segmentation fault and program     terminated
while(1);     // stack overflow

this kept on running for long. I did ^c to abort it
int x = 5/0;    // divide by 0 exception

This gave me some random or zero value.
int arr[5];
cout<<arr[100]     // array out of bound

this gave me some garbage value
    cout<< arr[1000]   /// memory violateion
This gave me seg fault
I don't want to use, throw statement. I want to protect my code, in case I throw any random
error, my program should catch it, print it and then move on to next thing.
I read alot on website. I understand C++ doesn't handle segmentation fault as an exception.
My majority of code will be in C. IN some cases I will be using std: vector/ std: string
I don't want to use throw,
Here I have couple of questions:
1) can't C++ throw, an exception without using throw  statement or exception function.
2) For testing my code I am looking for example which cause, stack overflow, array out of bond , division by zero or any sort of exception. Can someone point to some examples
3) is try catch  in  C++ made works only for exception handling specific to only STD?
Later I also tried using set_terminate and set_unexpected:
using the following code:
typedef void (*pfv)();
void my_terminate()
{      cout << "Call to my terminate" << endl; }
void my_unexpected()
{      cout << "Call to my unexpected" << endl; }
int  Divisor()
{
    int result;
    result = number%num;

    if (result == 0 && num < 21)
    {
            num+1;
            Divisor();

            if (num == 20 && result == 0)
            {
                    return number;
            }
    }

    else if (result != 0)
    {
            number++;
            Divisor();
    }
}

int main ()
{

  pfv old_term = set_terminate(my_terminate);
  pfv old_unex = set_unexpected(my_unexpected);
    Divisor();
}

This should have outputted result to call of my_unexpected via set_terminate
But I got segmentation fault.
I have used g++ to run my programs and all i get is segmentation fault as a result in case of exception.
Seems like I am missing some basic and important exception. need some inputs

A: *

*No.  You can actually turn off throw support in most compilers.  Interoperability with C is one reason why you might want to do it; C has no support for throw at all.

*Unlike Java or C#, there is no intermediate code interpreter that detects these conditions, so they will not throw exceptions when they occur.  C and C++ are much closer to the hardware; at the processor level, there is no "throw" construct and no stack unwinding.

*No.  In C++, you can throw anything; integers, pointers, references, objects... you name it.  You don't necessarily have to extend std::exception.  Catching std::exception is useful when you make heavy use of standard libraries that might throw it, but there is no reason that you have to use it if you don't want to.


text:
Q: Checkbox to be checked flutter I'm a super beginner in programming and flutter. In my application I need my checkbox to be checked. Any ideas? :)
// Check Todo
  Widget _todoTask(context, task) {
    return ListTile(
      leading: Checkbox(
        value: task.status,
        onChanged: null,
      ),

      //Delete TodDO
      title: Text(task.message),
      trailing: IconButton(
        icon: Icon(Icons.close),
        onPressed: () {
          var state = Provider.of<MyState>(context, listen: false);
          state.removeTask(task);
        },
      ),
    );
  }
}

A: this is the way how checkbox works..
bool checkedValue = false;
Checkbox(
                              tristate: false,
                              checkColor: Colors.red,
                              activeColor: Colors.white,
                              value: checkedValue,
                              onChanged: (newValue) {
                                setState(() {
                                  checkedValue = newValue;
                                });
                              },
                            ),


text:
Q: How we increase Recyler View Item from 0-9 to Infinite?
My Code is:
  JSONArray jsonArray=new JSONArray(response);
                        if(jsonArray.length()==0){
                            Toast.makeText(context,"No Data",Toast.LENGTH_SHORT).show();
                        }else {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                innerListData = new TakeAttendanceModel();
                                innerListData = ((TakeAttendanceModel) JSonUtil.jsonToObject(jsonArray.getString(i), TakeAttendanceModel.class));
                                innerListData.status = "P";
                                innerListData.attendanceDate = DateTimeUtils.getDate();
                                attenList.add(innerListData);
                            }
                            submitAtten=(Button)rootView.findViewById(R.id.takeAttendanceSubmit);
                            submitAtten.setVisibility(View.VISIBLE);
                        }
                            Log.d("Responsse : ", response);

                    }
                    takeAttendanceAdapter = new TakeAttendanceAdapter(context,attenList);
                    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context);
                    recyclerViewAttendanceList.setLayoutManager(mLayoutManager);
                    recyclerViewAttendanceList.setItemAnimator(new DefaultItemAnimator());
                    recyclerViewAttendanceList.setAdapter(takeAttendanceAdapter);
                    takeAttendanceAdapter.notifyDataSetChanged();

My Adapter code is:
 private List<TakeAttendanceModel> list;

    public TakeAttendanceAdapter(Context context, List<TakeAttendanceModel> list) {
        this.context = context;
        this.list = list;

    }
    @Override
    public AttendanceListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View convertview = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.inner_list_attendance, parent, false);

        return new AttendanceListViewHolder(convertview);
    }

    @Override
    public void onBindViewHolder(final AttendanceListViewHolder holder, final int position) {
        holder.textViewStudentName.setText(list.get(position).studFullName);
        holder.textViewStudentRollNumber.setText(list.get(position).primaryKey);
        holder.texViewStudentPreFix.setText(list.get(position).prefix);

        holder.SSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                //final LinkedList<String> innerLinklist=new LinkedList<>();
                if (isChecked) {
                    /*innerLinklist.add(list.get(position).primaryKey);
                    innerLinklist.add(list.get(position).studFullName);
                    innerLinklist.add(list.get(position).status="P");*/
                    // linkedList.add(innerLinklist);
                    //Log.v("Attndce Liist After Toggle",linkedList.toString());
                    list.get(position).status="P";
                } else {
                    /*innerLinklist.add(list.get(position).primaryKey);
                    innerLinklist.add(list.get(position).studFullName);
                    innerLinklist.add(list.get(position).status="A");*/
                    // linkedList.add(innerLinklist);
                    //Log.v("Attndce Liist After Toggle",linkedList.toString());
                    list.get(position).status="A";
                }

                Log.v("Attndce Inner",list.toString());
                //DataManager.factory().linkedList.add(innerLinklist);

                //Log.v("Attndce Full Linklist",DataManager.factory().linkedList.toString());
            }

        });

        //Log.v("Attndce Liist After Toggle",DataManager.factory().linkedList.toString());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class AttendanceListViewHolder extends RecyclerView.ViewHolder {
        /*public ImageView imageViewProfilePic;*/
        public TextView textViewStudentName, textViewStudentRollNumber,texViewStudentPreFix;
        public SwitchCompat SSwitch;
        public AttendanceListViewHolder(View convertview) {
            super(convertview);
            texViewStudentPreFix=(TextView)convertview.findViewById(R.id.textAttendanceStudentPrfix) ;
            textViewStudentName = (TextView) convertview.findViewById(R.id.textViewAttendanceStudentName);
            textViewStudentRollNumber = (TextView) convertview.findViewById(R.id.textViewAttendanceStudentRollno);
            SSwitch = (SwitchCompat) convertview.findViewById(R.id.textViewAttendanceSwitch);
        }
    }

This is My adapter code in which switch is placed.
Actually in RecylerView I place a Switch button and when switch button is on at 0 position then Automatically switch is ON after 9th position.
Please give me a solution.

A: First things first, make a proper POJO class for your adapter.
never use something like list.get(position).variable instead of this make your variable as private and use setters and getters like list.get(position).getVariable() or list.get(position).setVariable(variable)
Then as you know, since RecyclerView always recycle the views, its advisable to use if followed by else for every UI change. In your case you are just changing the switch condition without resetting it anywhere.

And the most important part, never use the position that is passed as
  a paremeter. Instead use the adapter position as I specified in the
  solution

Check the updated code below:
    @Override
    public void onBindViewHolder(final AttendanceListViewHolder holder, final int position) {
        final int adapterPosition = holder.getAdapterPosition();
        holder.textViewStudentName.setText(list.get(adapterPosition).studFullName);
        holder.textViewStudentRollNumber.setText(list.get(adapterPosition).primaryKey);
        holder.texViewStudentPreFix.setText(list.get(adapterPosition).prefix);
        holder.SSwitch.setSelected(list.get(adapterPosition).getStatus());

        holder.SSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                list.get(adapterPosition).setStatus(isChecked);
                notifyItemChanged(adapterPosition);
                Log.v("Attndce Inner",list.toString());
            }
        });
    }

A: Update code is:
 @Override
    public void onBindViewHolder(final AttendanceListViewHolder holder, int position) {
        final int adapterPosition = holder.getAdapterPosition();
        holder.textViewStudentName.setText(list.get(adapterPosition).studFullName);
        holder.textViewStudentRollNumber.setText(list.get(adapterPosition).primaryKey);
        holder.texViewStudentPreFix.setText(list.get(adapterPosition).prefix);
        holder.SSwitch.setSelected(list.get(adapterPosition).getStatus());

        holder.SSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {

                list.get(adapterPosition).setStatus(isChecked);
                notifyItemChanged(adapterPosition);
                Log.v("Attndce Inner",list.toString());

                //Log.v("Attndce Full Linklist",DataManager.factory().linkedList.toString());
            }

        });

Model Class is:
public class TakeAttendanceModel {
    public String primaryKey;
    public String prefix;
    public String studFullName;
    public String attendanceDate;
    public boolean status;

    public boolean getStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }


text:
Q: mysql insert into csv file not working in python I have tried many times and searched all over the internet and this is still not working for me.
I am trying to read from a csv file and insert data into a database with python.
This is my code, and I don't understand why it's not working
import mysql.connector
import csv
import pandas as pd

with open(r'files\files1.csv') as csv_file:
    csvfile = csv.reader(csv_file, delimiter=';')
    allvalues=[]
    for row in csvfile:
        value = (row[0],row[1],row[2])
        allvalues.append(value)

print(allvalues)

db = mysql.connector.connect(
    host = 'ip',
    user = 'user',
    passwd = 'pass',
    database = 'db',
    auth_plugin='mysql_native_password'
)

cursor = db.cursor()

query = "INSERT INTO table1 (col1, col2, col3) VALUES (%s , %s , %s)"

cursor.execute(query, allvalues)

db.commit()

this gives the following error:
   result = self._cmysql.convert_to_mysql(*params)
_mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted

I also want to mentions that I have tried many other things to insert into the table not only the method above, and everytime I get a different error.
Can someone please tell me how do I do it? I would really appreciate it
Thank you very much

A: use cursor.executemany(query, allvalues)
If you have multiple elements which are saved in a list or tuple then use,
cursor.executemany(query, list) or cursor.executemany(query, tuple)
Or you can use for loop
for value in allvalues:
    cursor.execute(query, value)


text:
Q: Split string using python and regex I have the following csv file:
NAME   DETAILS
abc    type1: Y, Property: p1,p3 , type2:N
def    type1: Y, Property: p2,p3 , type2:N
ghi    type1: N, Property: p1,p2 , type2:Y
jkl    type1: N, Property: p1,p3 , type2:Y

I want to have the ouput file as:
NAME type1 Property type2
abc  Y      p1,p3    N
def  Y      p2,p3    N
ghi  N      p1,p2    Y
jkl  N      p1,p3    Y

Using python and regular expressions, If I split Details column based on ',' the property type splits into separate columns. Is there a way I could deal with this situation?

A: There are many way to do this, but I would split each line on any punctuation/whitespace character, and then reconstruct it manually based on what you desire:
import re

t = """abc    type1: Y, Property: p1,p3 , type2:N
def    type1: Y, Property: p2,p3 , type2:N
ghi    type1: N, Property: p1,p2 , type2:Y
jkl    type1: N, Property: p1,p3 , type2:Y""".split('\n')

for x in t:
    y = re.findall(r"[\w']+", x)
    #print y
    print '\t'.join((y[0],y[2],y[4]+','+y[5],y[7]))

> abc   Y   p1,p3   N
> def   Y   p2,p3   N
> ghi   N   p1,p2   Y
> jkl   N   p1,p3   Y

Another way without regex would be to replace all delimiting characters and then reconstruct automatically. Something like this:
print [x.replace(':','\t').replace(' , ','\t').split() for x in t]

A: A sample script that uses regex and group capture to extract data
script.py
#!/usr/bin/env python

import re,sys

def main():
    p = re.compile("([a-z]+).*type1:\s+([A-Z]),\s+Property:\s+?([a-z0-9,]+)\s+,\s+?type2:([A-Z])")

    for line in sys.stdin:
        m = p.match(line)
        if m:
            print "\t".join([m.group(1), m.group(2), m.group(3), m.group(4)])

if __name__ == "__main__":
    main()


text:
Q: if statements where x can equal a series of numbers/a range of numbers? Trying to write a program for a combination lock, where if the inputted number is within 3 numbers of the correct number it will state that the lock is open. (i.e if the first number of the lock combination is 5, it will state that the lock is open if someone inputs 2, 3, 4, 5, 6, 7, or 8.)
This is the code I have so far
(I'm only trying to figure out how to get the program to recognize whether or not the first number is correct at the moment, if you're wondering why there is a second + third input.)
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the first number: ");
    int first = keyboard.nextInt();
    System.out.print("Enter the second number: ");
    int second = keyboard.nextInt();
    System.out.print ("Enter the third number: ");
    int third = keyboard.nextInt();
    if (first == )
        System.out.println("It works!");
    else
        System.out.println("It didn't work");
}

A: You may check that the difference is within a range of 3,  by using the absolute value of first - lock (or lock - first, as you prefer) .
if(Math.abs(first-lock)<=3)

A: This is how you could do it:
If (first <= lock + 3 && first >= lock - 3)
    //do something

Assuming Lock is your "5" as in your example and first the input you are willing to check.


text:
Q: jquery not parsing data held in data attribute I'm trying to parse data held in an data attribute defined as follows
HTML

jquery
var details = $(this).data('details');

when trying to parse the json as
$.parseJSON(details)

it returns in console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Any guidance is much apreciated.
*edit even when html declared as (all variables wrapped in single quotes)

the same error is reurned

A: Your details is not valid JSON, so $.parseJSON can't read it.  You need to use double quotes around your keys and your (string) values.  Valid JSON needs double quotes.

Note: You can use either single or double quotes for HTML attributes.
As noted by @Vohuman, when you do $(this).data('details'), jQuery will automagically parse the JSON for you (it will detect that it's JSON, then parse it), you don't need $.parseJSON.
Here's a demo @swatkins made: http://jsfiddle.net/dpqpL9kv/


text:
Q: Rails + Devise: Wrong Sign out message I use Devise to perform authentication for my application, and everything is ok, except the Devise logout message which is detected as unauthentication failure:
en.devise.failure.unauthenticated:
" You need to sign in or sign up before continuing "
I mean that I have this message when I log out, and not the "Signed out successfully" message.
Maybe I wrongly personnalized my Devise system. Here are the personnalisations I made:
1/ I used my own session controllers to override the default Devise session controller. My only objective, is to choose a special access (login/signup) layout:
class SessionsController < Devise::SessionsController

    layout 'access'

end

No more code. I only wanted to render using a special login/signup design, located in views/layouts/access.html.haml.
Of course, I added this to my routes.rb file:
devise_for :users, :controller => { :sessions => 'sessions' }

2/ I choosed another language for Devise (french), so I downloaded devise.fr.yml and pasted it in config/locales/ folder, and set config.i18n.default_locale = :fr in config/application.rb file
All other Devise action messages are correct. Only "Sign Out" have trouble. Any idea?
Thanks in advance.

A: It looks like there's a way to handle custom layouts for devise without inheriting the sessions controller. Take a look at this documentation:
https://github.com/plataformatec/devise/wiki/How-To:-Create-custom-layouts
EDIT
To redirect users back to the sign in page after they sign out add this to your application controller:
def after_sign_out_path_for(resource_or_scope)
  sign_ins_path
end

A: Devise uses an http DELETE request for sign out requests. Make sure you sign out with this link. <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>


text:
Q: Do not use UIImagePickerController Get photos I would like to get photos from the Photo Gallery but do not want to use UIImagePickerController

A: You can use the ALAssets library, here is an example
https://developer.apple.com/library/ios/#samplecode/MyImagePicker/Introduction/Intro.html


text:
Q: Responsive design, css Estoy intentando ver si existe la posibilidad de que al ingresar a mi pagina web, no tenga el 50% de zoom. Sin la necesidad de hacer un media de 420px(ya que tengo mucho texto y se ve feo cuando sobrepasa los 500px)
https://jolly-creponne-d89dbc.netlify.app/

A: la solución mas rápida para tu inconveniente seria que los textos escalaran según el ancho de tu pantalla así mientras la pantalla disminuya los textos mas grandes se adapten a ella:
font-size: 20vw

cambia las medidas de tus textos usando vw y no pixeles, lo que hace es que camia el tamaño según el ancho de la pantalla, así no tendrías que usar los mediaQuerys eso normalmente se usa para algo mas en general porque si dependes mucho de eso puede generar conflictos con otros estilos, además esta solución te puede funcionar por el momento, pero te recomiendo estudiar los flexbox en css, así lograras un diseño totalmente responsive-web-design de forma mas sencilla :).
aqui tienes un ejemplo mas completo para usar en tus textos:
.estilo-x {
    font-size: calc(1em + 1vw);
    line-height: 1em;
    padding: 1em;
    margin: 1em;
}


text:
Q: How to use runTransaction with firebase_database 9.0.3 Can anyone give where to look, or what I am missing, for how to use runTransaction in 9.0.3? (Flutter, Firebase realtime DB)
I updated firebase_database ^7.0.0 to ^9.0.3. Had to change runTransaction(MutableData mutable) to runTransaction(Object object), and the Object is null for Map data. Does return a String when point to single node of a String.
For something to work I placed + '/sap' at end of .ref(…), and it gave 'DROID'
Code Updated for Comment below:
    bool bCanWeStartGame = false;
    bool bIfiOS = false;
    bIfiOS = Theme.of(referencedData.mngGamesPageMaterialContext)
        .platform == TargetPlatform.iOS;
    DatabaseReference playersRef = referencedData.database.ref(
        TABLENAME_STARTS + '/' + referencedData.strFBGameUniqueIDKey);

    if(bIfiOS){
      //apparently iPhone needs to 'open line to DB record' to work
      playersRef.once()
          .then((DatabaseEvent event) {//dont need to do anything??
      });
    }

    TransactionResult txResult;
    //while loop to repeat runTransaction until solved
    int iWhileLoopCheck = 0; //so whileLoop does not go forever
    bool bTransactionCommittedOrGetOutAnyWay = false;
    while(!bTransactionCommittedOrGetOutAnyWay
        && (iWhileLoopCheck<30)){
      iWhileLoopCheck++;
      txResult = await playersRef
          .runTransaction(
              (Object post) {
            if (post == null) {
              if(bIfiOS){sleep(Duration(milliseconds: 3));}
              return Transaction.abort(); //out, but will retry transaction
            }
            Map<String, dynamic> _post = Map<String, dynamic>.from(post as Map);

            bTransactionCommittedOrGetOutAnyWay = true; //whichever of
            //options below take effect, dont want to continue while loop
            if (_post[STARTS_TABLE_ALL_PLAYERS] !=
                startingGames[iIndexInStartingGames].allplayers) {
              //someone has joined since trying to start
              bCanWeStartGame = false;
              //Transaction.abort() as dont want to change data
              return Transaction.abort();
            } else {
              //Nobody has joined, so can Start. Tell others Game is starting
              _post['stg'] = true;
              bCanWeStartGame = true;
              return Transaction.success(_post);
            }
          });
    } //while runtransaction doesnot get at data```


text:
Q: Memory corruption when closing Unix Socket I've designed a class that handles several UNIX socket operations such as sending and receiving single values or arrays. The point was just to unify server and client methods in order to use the same code in both cases.
My unix_socket.hpp:
#ifndef __SOCKET_HPP
#define __SOCKET_HPP

#ifndef EIGEN_NO_DEBUG
#define EIGEN_NO_DEBUG
#endif

#include <Eigen/Dense>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string>

#define DEFAULT_SOCKET_PATH (std::string(getenv("HOME"))+std::string("/msock")).data()
#define SERVER_MODE 0
#define CLIENT_MODE 1

using Eigen::VectorXd;
using std::string;

struct message{
    char type;
    double value;
};

class unix_socket{
public:
    double v_sent,v_recvd;
    char c_sent, c_recvd;

    VectorXd vector_recvd;
    VectorXd vector_sent;

    int sock, client_sock;
    unsigned int t,len;

    int mode; //0 server, 1 client

    struct sockaddr_un local,remote;

    string path;

    unix_socket();
    unix_socket(int sc_mode);
    ~unix_socket();

    void initSocket(const char* sock_path);
    void initSocket(const char* sock_path, const int sc_mode);
    void wait();
    void closeSocket();

    int sendMsg(const char type, const double value);
    int receiveMsg();
    int sendVectorXd(const VectorXd& values);
    int receiveVectorXd();

};
#endif

and unix_socket.cpp:
#include "unix_socket.hpp"

#include <iostream>
#include <cstdlib>

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

using namespace std;
using Eigen::VectorXd;

unix_socket::unix_socket(){
    v_sent=0;
    v_recvd=0;
    mode=0;
}

unix_socket::unix_socket(int sc_mode){
    v_sent=0;
    v_recvd=0;
    mode=sc_mode;
}

unix_socket::~unix_socket(){
    close(sock);
    close(client_sock);
    //system((std::string("rm ")+path).data());
}

void unix_socket::initSocket(const char* sock_path, const int sc_mode){

    if (sc_mode==0){
            // socket server
        if (mode != sc_mode) mode=sc_mode;

        if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
        }

        local.sun_family = AF_UNIX;
        strcpy(local.sun_path, sock_path);
        unlink(local.sun_path);
        len = strlen(local.sun_path) + sizeof(local.sun_family);
        if (bind(sock, (struct sockaddr *)&local, len) == -1) {
            close(sock);
            perror("bind"); exit(1);
        }

    } else if(sc_mode==1) {
            // socket client
        if (mode != sc_mode) mode=sc_mode;
        if ((client_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
        }

        remote.sun_family = AF_UNIX;
        strcpy(remote.sun_path, sock_path);
        len = strlen(remote.sun_path) + sizeof(remote.sun_family);
        if (connect(client_sock, (struct sockaddr *)&remote, len) == -1) {
            perror("connect");
            exit(1);
        }
        printf("Connected.\n");
        // ---
    } else printf("Invalid sc_mode argument: %d\n",sc_mode);
    path=string(sock_path);
}

void unix_socket::initSocket(const char* sock_path){
    initSocket(sock_path,mode);
}

void unix_socket::wait(){
    if (mode==0){
        if (listen(sock, 5) == -1) {
            perror("listen");
            exit(1);
        }
        t = sizeof(remote);
        if ((client_sock = accept(sock, (struct sockaddr *)&remote, &t)) == -1) {
            perror("accept");
            exit(1);
        }
        printf("Connected!\n");
    } else printf("Invalid call to wait(): mode %d\n, must be 0",mode);
}

void unix_socket::closeSocket(){
    //close(sock);
    close(client_sock);
}

int unix_socket::sendMsg(const char type, const double value){
    struct message msg;
    msg.type=type;
    msg.value=value;
    int n = send(client_sock, &msg, sizeof(msg), 0);
    if (n < 0) {
        perror("send");
        return -1;
    }
    c_sent=msg.type;
    v_sent=msg.value;
    return 0;
}

int unix_socket::receiveMsg(){
    struct message msg;
    int n = recv(client_sock, &msg, sizeof(msg), 0);
    if (n < 0) {
        perror("recv");
        return -1;
    }
    c_recvd=msg.type;
    v_recvd=msg.value;
    return 0;
}

int unix_socket::sendVectorXd(const VectorXd& values){
    sendMsg('A',values.rows());
    for (int i = 0; i < values.rows(); ++i){
        if (i<(values.rows()-1)) sendMsg('V',values(i));
        else sendMsg('L',values(i));
    }
    return 0;
}

int unix_socket::receiveVectorXd(){
    receiveMsg();
    if (c_recvd=='A' && v_recvd>1){
        vector_recvd=VectorXd::Zero(v_recvd);
        for (int i = 0; i < vector_recvd.rows(); ++i){
            receiveMsg();
            vector_recvd(i)=v_recvd;
        }
    }
    return 0;
};

Overall everything seems to be working fine, when testing with simple .cpp's that send large (~1000) VectorXd in both directions. However, when using in a more complex program, as posted below, I'm getting a malloc(): memory corruption: error, everytime I close the socket by calling unix_socket::closeSocket() on the server side (context: the program is sending and receiving data to and from a Webots instance running a robot controller which acts as socket client):
#include <iostream>
#include <fstream>
#include <string>
#include "../socket/unix_socket.hpp"
#include "asm.hpp"

#include <sstream>

#include <Eigen/Dense>
#include <cstdlib>

using namespace Eigen;
using namespace std;

int start_webots(const char* world){
    //starting webots as a child process with known PID
    int pid = fork();
    if (pid == 0){
        printf("Starting webots...");
        execlp("/usr/local/bin/webots","webots",world,NULL);
        printf("WEBOTS AUTOCLOSED!");
        exit(1);
    }
    else printf("Webots PID: %i\n", pid);
    return pid;
}

VectorXd asmParams(bool fall_break, int periods, double delay){
    VectorXd p(5);
    if (fall_break==true) p << 1,-1,1,periods,delay;
    else p << 1,-1,0,periods,delay;
    return p;
}

int main () {

  int periods=10;
  double delay=25.0;
  string world_path="../../worlds/darwin_cpgs_noise.wbt";

  start_webots(world_path.data());

  unix_socket server;

  server.initSocket(DEFAULT_SOCKET_PATH,0);
  server.wait();

  server.receiveVectorXd();
  server.sendVectorXd(asmParams(true,periods,delay));
  server.sendVectorXd(VectorXd::Ones(dim)*10);

  asmemory aSm;
  aSm.setMode(0);
  bool end=false;

  aSm.resetTimer();
  while (aSm.isAcquiring()){
    aSm.resetTimer();
    while(aSm.isRunningRollout()){
      server.receiveMsg();

      if (server.c_recvd=='T' && aSm.lastTimeStep()) {
        aSm.resize(NO_CHANGE,aSm.nTimeSteps()+1,NO_CHANGE);
      }
      else if (server.c_recvd=='E' && !aSm.lastTimeStep()) {
        aSm.resize(NO_CHANGE,aSm.index_t()+1,NO_CHANGE);
        end=true;
      }
      else if (server.c_recvd=='E' && aSm.lastTimeStep()) {
        end=true;
      }

      aSm.setCurrentTime(server.v_recvd);
      server.receiveVectorXd();
      if (server.vector_recvd.rows()!=aSm.nSensors()) aSm.resize(server.vector_recvd.rows(),NO_CHANGE,NO_CHANGE);
      aSm.sendToBuffer(server.vector_recvd);

      if (end) break;
      aSm.incrementTime();
      end=false;
    }
    aSm.incrementSample();
    server.sendMsg('R',-1.0);

    // crashing the program:
    server.closeSocket();

    end=false;
  }

  aSm.learnData();
  server.closeSocket();
  return 0;
}

What could be causing the memory corruption? I assume somethings wrong in the unix_socket class, but the data is sent/received correctly, however every time I call closeSocket(), even in the middle of the loop sends a memory corruption error.
EDIT: I've tried using Valgrind, and while there seem to be a lot of memory leaks in the program, I don't really know how to interpret the output (first time using Valgrind):
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402DB9: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe91 is on thread 1's stack
==3874==
==3874==
==3874== HEAP SUMMARY:
==3874==     in use at exit: 2,451,739 bytes in 107 blocks
==3874==   total heap usage: 316 allocs, 209 frees, 2,454,518 bytes allocated
==3874==
==3874== Searching for pointers to 107 not-freed blocks
==3874== Checked 2,640,168 bytes
==3874==
==3874== 59 bytes in 1 blocks are possibly lost in loss record 1 of 4
==3874==    at 0x4C2C221: operator new(unsigned long) (vg_replace_malloc.c:298)
==3874==    by 0x4EF03B8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==3874==    by 0x4EF1D94: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==3874==    by 0x4EF1E72: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==3874==    by 0x4026FE: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==
==3874== LEAK SUMMARY:
==3874==    definitely lost: 0 bytes in 0 blocks
==3874==    indirectly lost: 0 bytes in 0 blocks
==3874==      possibly lost: 59 bytes in 1 blocks
==3874==    still reachable: 2,451,680 bytes in 106 blocks
==3874==         suppressed: 0 bytes in 0 blocks
==3874== Reachable blocks (those to which a pointer was found) are not shown.
==3874== To see them, rerun with: --leak-check=full --show-reachable=yes
==3874==
==3874== Use --track-origins=yes to see where uninitialised values come from
==3874== ERROR SUMMARY: 1620 errors from 10 contexts (suppressed: 0 from 0)
==3874==
==3874== 1 errors in context 1 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402DB9: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe91 is on thread 1's stack
==3874==
==3874==
==3874== 1 errors in context 2 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x407100: unix_socket::sendVectorXd(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402965: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe41 is on thread 1's stack
==3874==
==3874==
==3874== 1 errors in context 3 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40706E: unix_socket::sendVectorXd(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402965: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe41 is on thread 1's stack
==3874==
==3874==
==3874== 1 errors in context 4 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x407100: unix_socket::sendVectorXd(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4028D8: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe41 is on thread 1's stack
==3874==
==3874==
==3874== 1 errors in context 5 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40706E: unix_socket::sendVectorXd(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4028D8: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe41 is on thread 1's stack
==3874==
==3874==
==3874== 4 errors in context 6 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4070CC: unix_socket::sendVectorXd(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4028D8: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe41 is on thread 1's stack
==3874==
==3874==
==3874== 19 errors in context 7 of 10:
==3874== Syscall param socketcall.sendto(msg) points to uninitialised byte(s)
==3874==    at 0x573DDA2: send (send.c:28)
==3874==    by 0x406E12: unix_socket::sendMsg(char, double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4070CC: unix_socket::sendVectorXd(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402965: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x7fefffe41 is on thread 1's stack
==3874==
==3874==
==3874== 120 errors in context 8 of 10:
==3874== Invalid write of size 8
==3874==    at 0x408B56: asmemory::sendToBuffer(Eigen::Matrix<double, -1, 1, 0, -1, 1> const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402D48: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x5a1e360 is 0 bytes after a block of size 24,000 alloc'd
==3874==    at 0x4C2C73C: malloc (vg_replace_malloc.c:270)
==3874==    by 0x40313F: Eigen::internal::aligned_malloc(unsigned long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4054DA: void* Eigen::internal::conditional_aligned_malloc<true>(unsigned long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40503C: double* Eigen::internal::conditional_aligned_new_auto<double, true>(unsigned long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x404937: Eigen::DenseStorage<double, -1, -1, -1, 0>::resize(long, long, long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40C552: Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::resize(long, long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40CA07: void Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::resizeLike<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > >(Eigen::EigenBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40C3F0: void Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::_resize_to_match<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > >(Eigen::EigenBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40BDD0: Eigen::Matrix<double, -1, -1, 0, -1, -1>& Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::lazyAssign<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > >(Eigen::DenseBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40B54B: Eigen::internal::assign_selector<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >, false, false>::run(Eigen::Matrix<double, -1, -1, 0, -1, -1>&, Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40AD46: Eigen::Matrix<double, -1, -1, 0, -1, -1>& Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::_set_noalias<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > >(Eigen::DenseBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40A0C4: void Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::_set_selector<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > >(Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::internal::false_type const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==
==3874==
==3874== 1471 errors in context 9 of 10:
==3874== Invalid write of size 8
==3874==    at 0x408FD7: asmemory::setCurrentTime(double) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x402B53: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==  Address 0x5c641f0 is 0 bytes after a block of size 800 alloc'd
==3874==    at 0x4C2C73C: malloc (vg_replace_malloc.c:270)
==3874==    by 0x40313F: Eigen::internal::aligned_malloc(unsigned long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4054DA: void* Eigen::internal::conditional_aligned_malloc<true>(unsigned long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40503C: double* Eigen::internal::conditional_aligned_new_auto<double, true>(unsigned long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x405F05: Eigen::DenseStorage<double, -1, -1, 1, 0>::resize(long, long, long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x405CFC: Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >::resize(long, long) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x407605: void Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >::resizeLike<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > >(Eigen::EigenBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x4074E0: void Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >::_resize_to_match<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > >(Eigen::EigenBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x40749C: Eigen::Matrix<double, -1, 1, 0, -1, 1>& Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >::lazyAssign<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > >(Eigen::DenseBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x407477: Eigen::internal::assign_selector<Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >, false, false>::run(Eigen::Matrix<double, -1, 1, 0, -1, 1>&, Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x407442: Eigen::Matrix<double, -1, 1, 0, -1, 1>& Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >::_set_noalias<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > >(Eigen::DenseBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > > const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==    by 0x407408: void Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >::_set_selector<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > >(Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::internal::false_type const&) (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)
==3874==
==3874== ERROR SUMMARY: 1620 errors from 10 contexts (suppressed: 0 from 0)

A: For memory errors
valgrind --track-origins=yes -v [your program]
Give the traces of uninitialised memory accesses, that may be resulting in your program's undefined behavior.
For leaks,
valgrind --leak-check=full --show-reachable=yes -v [your program]
The output is in the form of a sets of traces, each trace is analyzed from bottom to top,
for ex.

==3874== 59 bytes in 1 blocks are possibly lost in loss record 1 of 4
==3874==    at 0x4C2C221: operator new(unsigned long) (vg_replace_malloc.c:298)
==3874==    by 0x4EF03B8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==3874==    by 0x4EF1D94: char* std::string::_S_construct(char const*, char const*, std::allocator const&, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==3874==    by 0x4EF1E72: std::basic_string, std::allocator >::basic_string(char const*, std::allocator const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==3874==    by 0x4026FE: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/server)

The call trace starts from main and then calls basic_string and then to the function call above it, and so on and finally reaching new call, but the function which calls the new is __S_create function, means that there is no free performed after calling this function or there is no deinit method called for this function call when the program terminated.
HTH


text:
Q: DataprocClusterCreateOperator doesnt have temp_bucket variable to define I am trying to create dataproc cluster via DataprocClusterCreateOperator via Apache airflow
Airflow version:    1.10.15
Composer version: 1.16.4
I wanted to assign a temp-bucket used by project to the cluster and not the bucket google creates during run time. This option is available when we create cluster via command line using option --temp-bucket but this same variable is not available to pass via ClusterCreateOperator.
Dataproc operator info:
https://airflow.apache.org/docs/apache-airflow/1.10.15/_modules/airflow/contrib/operators/dataproc_operator.html
create cluster via command:
gcloud dataproc clusters create cluster-name \
    --properties=core:fs.defaultFS=gs://defaultFS-bucket-name \
    --region=region \
    --bucket=staging-bucket-name \
    **--temp-bucket=project-owned-temp-bucket-name \**
    other args ...

create_cluster = DataprocClusterCreateOperator(
        task_id="create_cluster",
        project_id="my-project_id",
        cluster_name="my-dataproc-{{ ds_nodash }}",
        num_workers=2,
        storage_bucket="project_bucket",
    region="us-east4",
       ... other params...
    )

A: Unfortunately, the method DataprocClusterCreateOperator in Ariflow doesn't support the property temp-bucket. You can use this property only with the gcloud command or REST API.
With REST API, you can use these fields ClusterConfig.configBucket and ClusterConfig.tempBucket in a cluster.create.
A Possible solution could be creating a scheduler job. You can see this documentation.


text:
Q: Restangular inserting models to collection after post I am inserting a model in a restangular collection with post
var collectionService = restAngular.all('collection');
var collection = collectionService.getList();

var item = {
   title : "A title"
};

collection.post(item);

Now i could do instead of the last statement:
collection.post(item).then(function(newItem) {
    collection.push(newItem);
});

Why is the inserted model not inserted into the collection by default? Is there a reason for this? Am i missing a call or something? I would like to avoid fetching the collection again after i inserted the model

A: Firstly, the behavior for the two methods are different:
collection.post(item) - It sends a POST request to the server but doesn't add item to the collection although post() is being called on collection object. The post() method is also available on an element object.
collection.push(item) - Adds the item to the collection but no request sent to the server. You use this method if you want to defer sending update to the server until further action or if you want to update the collection with an already added item on the server in order to keep the collection sync.
If you want to send a POST request to the server and also add an item to the collection without refreshing the whole list, you should use the below code (same as in your question)
collection.post(item).then(function(newItem) {
    collection.push(newItem);
});

Framework Design Decision
Why is the inserted model not inserted into the collection by default?

Imagine if collection.post(item) and collection.push(item) adds item into collection and also sends a POST request to the server. What if the connection fails or the server error out? There is no way to report the error or to handle the error and the data added to collection is a bad stale data and out of sync with server. In order to avoid this kind of bug, the framework force the developers to add the item into collection only if the POST is successful.
You will find this programming model not only in Restangular but also in similar REST frameworks like 'ng-resource'. This programming model helps to reduce the bug and ensure that the item added to the collection is legitimate and not a bad stale data.


text:
Q: How do you use the setState() function as part of a Flutter widget? Here's a Dart Stack that I'd like to be able to reuse:
Stack(children: [
  Align(
    alignment: Alignment.centerLeft,
    child: IconButton(
        splashRadius: 20,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        tooltip: 'decrease bonus by 1',
        onPressed: () => setState(() => value -= 1)),
  ),
  Container(
      width: 90,
      child: Center(child: Text(value.toString()))),
  Align(
    alignment: Alignment.centerRight,
    child: IconButton(
        splashRadius: 20,
        icon: const Icon(Icons.keyboard_arrow_up_rounded),
        tooltip: 'increase bonus by 1',
        onPressed: () => setState(() => value += 1)),
  ),
])

Ideally, I'd like to turn this stack into a widget or function that I could call with a Widget like ArrowIncrement(value: value) or a function like ArrowIncrement(value), but I can't get it to work due to the error the function 'setState' isn't defined.
Is there a solution or workaround for this issue?

A: You can wrap it into your own widget:
class MyWidget extends StatelessWidget {
  final ValueChanged<int> onValueChanged;
  final int value;

  MyWidget({required this.value, required this.onValueChanged});

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
  Align(
    alignment: Alignment.centerLeft,
    child: IconButton(
        splashRadius: 20,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        tooltip: 'decrease bonus by 1',
        onPressed: () => onValueChanged(value-1)),
  ),
  Container(
      width: 90,
      child: Center(child: Text(value.toString()))),
  Align(
    alignment: Alignment.centerRight,
    child: IconButton(
        splashRadius: 20,
        icon: const Icon(Icons.keyboard_arrow_up_rounded),
        tooltip: 'increase bonus by 1',
        onPressed: () => onValueChanged(value+1)),
  ),
]);
  }
}

... and then use it like this in your build method (assuming you have a variable called currentBonusValue in your state):
MyWidget(
    value: currentBonusValue,
    onValueChanged: (newValue) => setState(() => currentBonusValue = newValue),
)

A: you can use a change notifier provider like this :
step one make change notifier class
class Change with Changenotifier{
int value = 0;

void inc(){
 value += 1;
 notifierliseners()
}
}
void dec(){
 value -= 1;
 notifierliseners()
}
}

then call the provider in your widget
but before this, you must wrap your widget with changenotifierprovider widget
I think you know how to do that
class Thewidget extend Statelesswidget{
 Widget build(buildcontext context){
 var provider = provider.of<change>(context);
return Stack(children: [
  Align(
    alignment: Alignment.centerLeft,
    child: IconButton(
        splashRadius: 20,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        tooltip: 'decrease bonus by 1',
        onPressed: () => provider.dec())),
  ),
  Container(
      width: 90,
      child: Center(child: Text(provider.value.toString()))),
  Align(
    alignment: Alignment.centerRight,
    child: IconButton(
        splashRadius: 20,
        icon: const Icon(Icons.keyboard_arrow_up_rounded),
        tooltip: 'increase bonus by 1',
        onPressed: () => provider.inc())),
  ),
])
}
}

when you call dec or inc methods the widget will be reloaded due to notifierlisners in the two methods

A: Try replacing => with  {} :
OnPressed : () {
 Setstate(() {
value +=1
};
}


text:
Q: How can I fake a class with templated methods without recompiling? I want to fake (i.e. swap with a testing implementation) a class like this:
class Foo {
public:
   ...
   template <typename T> void Bar(T& baz);
   ...
}

Currently, I achieve this by making an unrelated class with the same interface:
class FakeFoo {
public:
   ...
   template <typename T> void Bar(T& baz);
   ...
}

And swapping the class used throughout the codebase via a macro:
#ifdef USE_FAKE_FOO
using ClientFoo = FakeFoo;
#else
using ClientFoo = Foo;
#endif

The issues with this is that I am required to re-compile the codebase depending on whether or not I want to run tests. Even worse, when I have multiple FakeFoos which implement different functionality for different tests, I have to re-compile the codebase for each specific FakeFoo I wish to use.
Is there any way I can work around this?
NOTE: templating the code that uses a Foo does work, but I don't want to require that all client code does this just so tests can be more easily run.

A: You simply can't do it with templated code.
C++ needs to compile everything before you get your executable. "Later" modifications without a recompile is not possible. If you have a defined interface you can exchange libraries against testing  ones, but never with a templated interface if the types for the calls are different.
So you have to indirect your call via some kind of library call but that will not work with different template instances.
If it is ok for you to link again without compilation, you can also use two times the same names and signature for function calls an exchange the files you link together. But this would also work only if your code uses the same interface for the calls which did not work with you templated code.


text:
Q: Dax sum and weighted average in filtered data I'm trying to do a sum and a weighted average in DAX for Power Bi on filtered data.
For example I've a table Table and I need another column with the progressive sum of QUANTITA. This quantity must change based on the period of date filtered. I want also another calculated column with weighted-average.
Can anyone help me?
Tnx in advice.


text:
Q: Extend Display Modes Hotkey This is my first post to this forum, so please excuse missing details. If you should need any just ask and maybe tell me the terminal command as I just switched to Ubuntu 18.04 LTS a week ago.
But now to my problem:
I've got Ubuntu 18.04 installed on my Lenovo ThinkPad E470. My 'F7'-key is toggled to choose between extended display options. It shows four possible modes:

*

*only Laptop display

*extend to left

*mirror

*only external monitor

If I press my 'F7'-key it rotates through those modes and let's me choose any. But for my usage those four options are not enough. I want to add two more options to exactly this cycle:

*

*extend to right

*extend to top

So that in the end I can press the 'F7'-key and have the choice between six possibilities. I would also be willing to give up any of the default options in case I can only add four.
I don't know what information is necessary to solve this issue so I'm just gonna provide some:

*

*UEFI Bios Version: RODET94W (1.94)

*ME Firmware Version: 11.8.50.3399

*Machine Type Model: 20H1007XGE

*Graphics card: Intel HD Graphics 620 (integrated card)

*Ubuntu 18.04.4 LTS

*Gnome 3.28.2

A: That's some significant development work to make that happen. Not a switch to be flipped, but a fully designed and developed feature.
You may not be aware though that just visiting the display section in system settings enables you to rearrange your displays in any manner you like. It's not a single button press but it's pretty quick and easy to do, and the setting is retained for the next time that external display is attached.


text: Q: Venmo me button duplicate I've embedded the new Venmo Me button into my website, but for some reason the button shows up with many duplicates. It seems the duplication error occurs based on the number of dividers (div, section, p, etc.) - I get an extra button for each one I put in. I'm thinking it might be the code that comes with the Venmo Me button, but is there anything I can change in my code to fix this?


text:
Q: Django External Database Read Only , Display on Tables I am trying to start a simple django app. I have been on it for days. I was able to this in flask in a few hrs.
I need advice on connecting to an external database to grab tables and display them on django pages.
This is my code in flask
@app.route("/topgroups")
def topgroups():
    con = sql.connect("C:\\Users\\win10\\YandexDisk\\apps\\flask\\new_file.sqlite")
    con.row_factory = sql.Row

    cur = con.cursor()
    cur.execute("SELECT domain, whois, Traffic, Groups,LE,adddate FROM do_1 where Groups in (75,86,66,58,67,57,68,85,48,56,76,77,46,65,47,64,45,55,74,54,44,33,34,43)")
    rows = cur.fetchall();

    return render_template("index.html", rows = rows)

A: I will give you the python answer but read until the end because you may be losing a lot on Django if you follow this approach.
Python comes with SQLite capabilities so you don't even need to install packages Python Docs:
Connect
import sqlite3
conn = sqlite3.connect('C:\\Users\\win10\\YandexDisk\\apps\\flask\\new_file.sqlite')

Want to ensure read only? from the docs
conn = sqlite3.connect('file:C:\\Users\\win10\\YandexDisk\\apps\\flask\\new_file.sqlite?mode=ro', uri=True)

Use
cur = conn.cursor()
... (just like for flask)

Note/ My recommendation
One of the biggest advantages of Django is:

Define your data models entirely in Python. You get a rich, dynamic database-access API for free — but you can still write SQL if needed.

And you'll loose a lot without it, from basic stuff like what you asked to even unit-testing capabilities.
Follow this tutorial to integrate your database: Integrating Django with a legacy database.

You may set manage=False and Django won't touch in those tables,
  only create new ones to support the app.

If you just use that DB for some special purpose then give a look at Django Multiple databases