text:
Q: Drag and Drop between multiple Listviews in Flutter I am building an app in Flutter in which I will need to Drag an Drop between multiple Listviews in Flutter. The Listviews will also scroll when an Item is hovered over the boundaries of the ListViews. This will be an implementation of something resembling a Kanban Board but not exactly. I have tried Boardview found BoardView but I need to implement multiple levels of listviews within listviews so boardview doesn't fit my needs. ReorderableListView only works for a single list. Drag Drop Lists is also not suitable for same reason Drag_Drop_Lists
The Screenshot what I have done so far is as follows:-

I have found some blog posts of tutorials which recommend using global keys. The problem I am facing is that only the first ListView scrolls no matter where I drag the item to. Probably something to do with the keys. I have tried using global keys as well as the context passed in the build method the results are no different.
I started by building two components - 1. A draggable Item Widget and 2. Drag Drop ListView so as to make the code more manageable. The code is as follows:-
The Draggable Item Class:-

import 'package:flutter/material.dart';

class Item {
  String title;
  Item({
    required this.title,
  });
}

typedef DragStarted<ItemType extends Item> = void Function(
  ItemType item,
);
typedef DragEnded<ItemType extends Item> = void Function(
  ItemType item,
);
typedef OnWillAccept<ItemType extends Item> = bool Function(
    ItemType? source, ItemType? target);
typedef OnAccept<ItemType extends Item> = void Function(
    ItemType source, ItemType target);

class DraggableItemWidget<ItemType extends Item> extends StatelessWidget {
  final DragStarted<ItemType> _dragStarted;
  final DragEnded<ItemType> _dragEnded;
  final OnWillAccept<ItemType> _onWillAccept;
  final OnAccept<ItemType> _onAccept;
  final Widget? _header;
  final Widget? _body;
  final Widget? _footer;
  final Color _borderColor;
  final Color _backgroundColor;

  final ItemType _value;

  DraggableItemWidget({
    super.key,
    required DragStarted<ItemType> dragStarted,
    required DragEnded<ItemType> dragEnded,
    required OnWillAccept<ItemType> onWillAccept,
    required OnAccept<ItemType> onAccept,
    Widget? header,
    Widget? body,
    Widget? footer,
    required Color backgroundColor,
    required Color borderColor,
    required ItemType value,
  })  : _value = value,
        _borderColor = borderColor,
        _backgroundColor = backgroundColor,
        _onWillAccept = onWillAccept,
        _onAccept = onAccept,
        _header = header,
        _body = body,
        _footer = footer,
        _dragStarted = dragStarted,
        _dragEnded = dragEnded;

  final Key _key = UniqueKey();

  @override
  Widget build(BuildContext context) {
    Widget column = Card(
      key: _key,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(9.0),
        ),
      ),
      color: _backgroundColor,
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(
            color: _borderColor,
            width: 3,
          ),
          borderRadius: const BorderRadius.all(
            Radius.circular(10.0),
          ),
        ),
        child: Column(
          children: [
            if (_header != null)
              _header!
            else
              ListTile(
                title: Text(
                  _value.title,
                ),
              ),
            if (_body != null) _body!,
            if (_footer != null) _footer!,
          ],
        ),
      ),
    );

    Widget draggable = LayoutBuilder(builder: (context, constraints) {
      return LongPressDraggable<ItemType>(
        data: _value,
        // axis: Axis.vertical,
        maxSimultaneousDrags: 1,
        childWhenDragging: Opacity(
          opacity: 0.5,
          child: column,
        ),
        feedback: Material(
          elevation: 4.0,
          child: ConstrainedBox(
            constraints: constraints,
            child: column,
          ),
        ),
        child: column,
        onDragStarted: () => _dragStarted(_value),
        onDragEnd: (details) => _dragEnded(_value),
        onDraggableCanceled: (velocity, offset) => _dragEnded(_value),
      );
    });
    return DragTarget<ItemType>(
      onWillAccept: (data) => _onWillAccept(data, _value),
      onAccept: (data) {
        _onAccept(data, _value);
      },
      builder: (
        BuildContext context,
        List<ItemType?> candidateData,
        List<dynamic> rejectedData,
      ) {
        return Column(
          children: <Widget>[
            AnimatedSize(
              duration: const Duration(milliseconds: 100),
              child: candidateData.isEmpty
                  ? Container()
                  : Opacity(
                      opacity: 0.0,
                      child: column,
                    ),
            ),
            candidateData.isEmpty ? draggable : column
          ],
        );
      },
    );
  }
}

The Drag Drop List:-

import 'package:flutter/material.dart';

import 'package:draggable_scrollable_demo/draggable_item.dart';

typedef OnAcceptList<ItemType extends Item> = void Function(
  List<ItemType> target,
  ItemType sourceItem,
  int targetIndex,
);

typedef OnWillAcceptList<ItemType extends Item> = bool Function(
  List<ItemType> target,
  ItemType sourceItem,
  ItemType targetItem,
);

typedef OnDragStartedList<ItemType extends Item> = void Function(
  List<ItemType> sourceList,
  ItemType value,
);

typedef OnDragEndedList<ItemType extends Item> = void Function(
  List<ItemType> sourceList,
  ItemType value,
);

class DragDropListview<ItemType extends Item> extends StatefulWidget {
  final List<ItemType> _items;
  final OnDragStartedList<ItemType> _onDragStartedList;
  final OnDragEndedList<ItemType> _onDragEndedList;
  final OnWillAcceptList<ItemType> _onWillAcceptList;
  final OnAcceptList<ItemType> _onAcceptList;
  final Axis _scrollDirection;
  final bool _shrinkWrap;

  const DragDropListview({
    super.key,
    required List<ItemType> items,
    required OnDragStartedList<ItemType> onDragStartedList,
    required OnDragStartedList<ItemType> onDragEndedList,
    required OnWillAcceptList onWillAcceptList,
    required OnAcceptList onAcceptList,
    Axis scrollDirection = Axis.vertical,
    bool shrinkWrap = false,
  })  : _scrollDirection = scrollDirection,
        _shrinkWrap = shrinkWrap,
        _onAcceptList = onAcceptList,
        _onWillAcceptList = onWillAcceptList,
        _onDragStartedList = onDragStartedList,
        _onDragEndedList = onDragEndedList,
        _items = items;

  @override
  State<DragDropListview<ItemType>> createState() =>
      _DragDropListviewState<ItemType>();
}

class _DragDropListviewState<ItemType extends Item>
    extends State<DragDropListview<ItemType>> {
  bool _isDragging = false;
  late final ScrollController _scroller;
  // final _listViewKey = GlobalKey();

  @override
  void initState() {
    _scroller = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _scroller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Listener(
      child: ListView.builder(
        // key: _listViewKey,
        scrollDirection: widget._scrollDirection,
        shrinkWrap: widget._shrinkWrap,
        itemBuilder: (context, index) => DraggableItemWidget<ItemType>(
          dragStarted: (value) {
            setState(() {
              _isDragging = true;
              widget._onDragStartedList(widget._items, value);
            });
          },
          dragEnded: (value) {
            setState(() {
              _isDragging = false;
              widget._onDragEndedList(widget._items, value);
            });
          },
          backgroundColor: Colors.amber,
          borderColor: Colors.blue,
          onAccept: (source, target) {
            setState(() {
              int indexOfTarget = widget._items.indexOf(target);
              widget._onAcceptList(widget._items, source, indexOfTarget);
            });
          },
          onWillAccept: (source, target) => widget._onWillAcceptList(
            widget._items,
            source as ItemType,
            target as ItemType,
          ),
          value: widget._items[index],
        ),
        itemCount: widget._items.length,
        controller: _scroller,
      ),
      onPointerMove: (event) {
        setState(() {
          if (!_isDragging) {
            return;
          }
          RenderBox render = context.findRenderObject() as RenderBox;
          // RenderBox render =
          //     _listViewKey.currentContext?.findRenderObject() as RenderBox;
          Offset position = render.localToGlobal(Offset.zero);
          if (widget._scrollDirection == Axis.vertical) {
            _scrollVertically(position, render, event, _scroller);
          } else {
            _scrollHorizontally(position, render, event, _scroller);
          }
        });
      },
    );
  }

  void _scrollVertically(
    Offset position,
    RenderBox render,
    PointerMoveEvent event,
    ScrollController scroller,
  ) {
    double topY = position.dy;
    double bottomY = topY + render.size.height;

    const detectedRange = 100;

    const moveDistance = 100;
    if (event.position.dy < topY + detectedRange) {
      var to = scroller.offset - moveDistance;
      to = (to < 0) ? 0 : to;
      scroller.animateTo(
        to,
        duration: const Duration(milliseconds: 100),
        curve: Curves.ease,
      );
    }
    if (event.position.dy > bottomY - detectedRange) {
      scroller.animateTo(
        scroller.offset + moveDistance,
        duration: const Duration(milliseconds: 100),
        curve: Curves.ease,
      );
    }
  }

  void _scrollHorizontally(
    Offset position,
    RenderBox render,
    PointerMoveEvent event,
    ScrollController scroller,
  ) {
    double leftX = position.dx;
    double rightX = leftX + render.size.width;

    const detectedRange = 100;

    const moveDistance = 100;
    if (event.position.dy < leftX + detectedRange) {
      var to = scroller.offset - moveDistance;
      to = (to < 0) ? 0 : to;
      scroller.animateTo(
        to,
        duration: const Duration(milliseconds: 100),
        curve: Curves.ease,
      );
    }
    if (event.position.dy > rightX - detectedRange) {
      scroller.animateTo(
        scroller.offset + moveDistance,
        duration: const Duration(milliseconds: 100),
        curve: Curves.ease,
      );
    }
  }
}

I then used a row of these Listviews many times to create the lists
As you can see I have commented out the portions with the global key to experiment with the build context. But apparently that is not making any difference to the final result.
Any help is greatly appreciated. Thanks in advance.


text:
Q: Cython + OpenCV and NumPy I have a program with mainly OpenCV and NumPy, with some SciPy as well. The system needs to be a real-time system with a frame rate close to 30 fps but right now only about 10 fps. Will using Cython help speed this up? I ask because OpenCV is already written in C++ and should already be quite optimized, and NumPy, as far as I understand, is also quite optimized. So will the use of Cython help improve the processing time of my program?

A: Using Cython won't make a significant difference in this problem.
To get a profile/benchmark of your code the Pycharm IDE has a profiling tool, or you can use kernprof.
However, as a test, you can convert your code to the Cython code or C code with these instructions:

*

*Compile main Python program using Cython.

*Specifically, convert python code to C code.

[NOTE]:
This approach is for Python3, but it can also be applied to Python2.7 with a few changes. I've tested it before.

[UPDATE]:
You can also use PyInstaller and Nuitka to test another way to convert your code as compiled executable.

A: Hope this helps someone
Found this awesome post Use Cython to get more than 30X speedup on your Python code
Used the same factorial calculation inside video stream through the camera for two frames each
video_python.py
import numpy as np
import cv2
import time

def function(number):

    cap = cv2.VideoCapture(0)

    increment = 0

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Our operations on the frame come here
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Display the resulting frame
        cv2.imshow('frame',gray)

        start_time = time.time()
        y = 1
        for i in range(1, number+1):
            y *= i

        increment+=1
        if increment >2:
            # print(time.time()-start_time)
            print('Python increment ',increment)
            break
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()
    return 0

video_cython.pyx
import numpy as np
import cv2
import time

cpdef int function(int number):

    cdef bint video_true = True

    cap = cv2.VideoCapture(0)

    cdef int y = 1
    cdef int i

    cdef int increment = 0
    cdef int increment_times = 0

    while(video_true):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Our operations on the frame come here
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Display the resulting frame
        cv2.imshow('frame',gray)

        start_time = time.time()

        for i in range(1, number+1):
            y *= i
        increment_times+=1

        if increment_times > 2:
            # print(time.time()-start_time)
            print('Cython increment ',increment_times)
            break

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
    return 0

setup.py
from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules = cythonize('video_cython.pyx',compiler_directives={'language_level' : "3"}))

then run
python setup.py build_ext --inplace
video_test.py
import video_python
import video_cython
import time
number = 100000

start = time.time()
video_python.function(number)
end =  time.time()

py_time = end - start
print("Python time = {}".format(py_time))

start = time.time()
video_cython.function(number)
end =  time.time()

cy_time = end - start
print("Cython time = {}".format(cy_time))

print("Speedup = {}".format(py_time / cy_time))

result:

Python increment  3
Python time = 6.602917671203613
Cython increment 3
Cython time = 0.4903101921081543
Speedup = 13.466817083311046

So doing any kind of python related stuff inside the loop can increase speed

A: It all depends on what your program is doing.
If you program is just stringing together large operations that are implemented in C++ then cython isn't going to help you much if at all.
If you are writing code that works directly on individual pixels then cython could be a big help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Regex match phone Number I have a regex that trying to match these phone number format. I'm super close except 1 scenario:
Regex: ^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$
Phone number format are trying to match:

*

*(123) 456-7890

*(123) 4567890

*123-456-7890

*123-4567890

*1234567890

*1234567890

I also want to match this.... there is leading spaces before and after the area code:
[empty spaces] (123) [emtpy spaces] 456-7890

A: ^\s*\(?(\d{3})\)?[-\. ]*(\d{3})[-. ]?(\d{4})$

This should do it.
The * character means 0 or more of preceding.
Regexr is probably the best tool I know to figure out how to change regex patterns.


text:
Q: How to properly define and call a method on a derived class in C# with an unknown type parameter I am trying to define a "Transformation" class that will be responsible for returning a simplified array object based on a complex type.  The class will accomplish this via a "transform" method that accepts the complex type.  This is based on Fractal (http://fractal.thephpleague.com/transformers/), but I am trying to implement something similar in C#.
So far, I have defined an abstract base TransformerAbstract class that contains some properties and methods common to every derived transformer class:
public abstract class TransformerAbstract
{
    public abstract object transform(object entity);
}

I am struggling with how to implement the transform method, because I need to know what the complex type is so I can create the transformation, which will be different for every derived transformation class (for example: CycleTransformer, etc.)
 public class CycleTransformer : TransformerAbstract
 {
    public override object transform(object entity)
    {
        throw new NotImplementedException();
    }
}

I have several other places in my applicationwhere I want to be able to transform the data - for example, take the following snippet:
    protected object[] fireTransformer(TransformerAbstract transformer, object data)
    {
        var includedData = new object();

        var transformedData = transformer.transform(data);

        if (transformerHasIncludes(transformer))
        {
            includedData = fireIncludedTransformers(transformer, data);
            //serialize & merge includes
        }

        object[] returnData = new object[1];
        returnData[0] = transformedData;
        returnData[1] = includedData;

        return returnData;
    }

I appear to have two problems:

*

*I can't mark the method as abstract because I need to know the entity type.

*If I mark the method as virtual then the code always calls the base class instead of the derived one, even though I can see at run time via debugging that the correct instance of the class is generated.

I tried using generics early on (e.g. TransformerAbstract<T> : ITransformer<T>) but that forced me to supply a type constraint on any class that uses TransformerAbstract, which I thought was overly restrictive.

A: I'd probably stop using object and instead use interfaces.
interface ITransformResult<T>
{

}

interface ITransformable<T>
{

}

interface ITransformInclude<T>
{

}

interface ITransformer<T>
{
    ITransformResult<T> Transform(ITransformable<T> data);
    bool HasIncludes { get; }

    IEnumerable<ITransformInclude<T>> FireIncludes(ITransformable<T> data);
}

class TransformedData<T>
{
    public ITransformResult<T> Result { get; set; }
    public IEnumerable<ITransformInclude<T>> Includes { get; set; }
}

Now that you have a strongly typed structure your function would be as simple as:
protected TransformedData<T> fireTransformer<T>(ITransformer<T> transformer,
                                                ITransformable<T> data)
{
    return new TransformedData<T>
    {
        Result = transformer.Transform(data),
        Includes = transformer.HasIncludes
                   ? transformer.FireIncludes(data)
                   : null
    };
}

A: I am not sure this works for your case or not. You can try virtual and override keywords.
public abstract class TransformerAbstract
{
    public virtual object transform(object entity);
}

public class CycleTransformer : TransformerAbstract
 {
    public override object transform(object entity)
    {
        throw new NotImplementedException();
    }
}

Have a look at below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class A
    {
        public virtual void show()
        {
            Console.WriteLine("Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public override void show()
        {
            Console.WriteLine("Derived Class!");
            Console.ReadLine();
        }
    }

    class Polymorphism
    {
        public static void Main()
        {
            A a2 = new B();
            a2.show(); // calls derived class.
        }
    }
}

A: Would this do what you need?
    public class CycleTransformer : TransformerAbstract
    {
        public override object Transform(object entity)
        {
            if (entity is CycleData)
            {
                // Do transform
            }
            else if (entity is FireData)
            {
                // Do transform
            }
            else
            {
                throw new NotImplementedException();
            }
        }
    }


text:
Q: Why Hardy-Littlewood method is called circle method? I read the phrase Hardy-Littlewood circle method in many places in Analytic number theory books and papers. I would like to know why it is called circle method, what is the idea behind it? Is it possible to visualize it?
Is there any lecture note or other reference that explains it. I read Iwaniec-Kowalski book in ANT but I did not get where the circle comes from, it says something in Cauchy integral formula, but I like to see more visualize.
Also I did not understand exactly the meaning and reason of calling major arc and minor arc how to choose in practice which arc is major and which is minor, in this method?
Thanks for any help.

A: It is called the circle method because, as the commentors have mentioned, the method culminates with (trying to evaluate) an integral around the unit circle in the complex plane.
When we do this, we parameterise it using the interval [0,1]; and we split the integral over this interval into 2 parts - the major and minor arcs. The major arc is so called because it is supposed to contribute significantly more to the value of the integral than the minor arc (and hence why the latter is called minor too). Ironically the major arc actually comprises a much smaller proportion of the interval [0,1], at least when applying the circle method to the Goldbach conjecture.
To add a bit more info, we want to find an expression for the major arc and an asymptotic expression for the minor arc via big O notation. This means that as we go to infinity the minor arc contributes a negligible amount to the integral. It is apparently bounding the minor arc that is often the biggest problem in applying the method.
I found this link very helpful as an intro.


text:
Q: Составной MySQL запрос Как мне правильно составить составной MYSQL запрос выборки из двух таблиц по одному общему полю?
Если использовать INNER JOIN и USING, но он выводит только общие строки. Например,
SELECT * FROM nomenclature INNER JOIN description using(id);
+----+----------+---------------------+
| id | name     | description         |
+----+----------+---------------------+
|  1 | Книга    | Замечательная книга |
|  3 | Карандаш | Красный карандаш    |
+----+----------+---------------------+

А мне нужно, чтобы выводило следующим образом:
+----+----------+---------------------+
| id | name     | description         |
+----+----------+---------------------+
|  1 | Книга    | Замечательная книга |
|  2 | Ручка    |                     |
|  3 | Карандаш | Красный карандаш    |
+----+----------+---------------------+

Ну то есть, чтобы из таблицы nomenclature он выводил все записи и если есть соответствия в таблице description, то дописывал, а если нет, то просто оставлял поле пустым

A: SELECT * FROM nomenclature LEFT JOIN description using(id);
Настоятельно советую почитать про left/right/inner join.


text:
Q: Table locked in mysql server I am getting following error but not able to solve it.
TABLE LOCK table `db`.`Trans` trx id 13610756 lock mode IX
RECORD LOCKS space id 1456 page no 2259 n bits 160 index PRIMARY of table `db`.`Trans` trx id 13610756 lock_mode X locks rec but not gap
Record lock, heap no 80 PHYSICAL RECORD: n_fields 18; compact format; info bits 0
0: len 10; hex 32323731303239373931; asc 2271029791;;

I am not able to execute any DDL commands, Any idea how to solve it?

A: I would check here, I think you are running into a concurrency bug
https://bugs.mysql.com/bug.php?id=43591


text:
Q: I dont get Submit button when i press register (register/login system php) So i made a register form and it works all fine except when i press register it should give me back Submited but it doesnt i dont know why is there a mistake in the code cuz i dont see it please help me out here..
register.php:

<?php

require_once 'core/init.php';

if(input::exists()) {
echo 'Submitted';
}

?>

<form action="" method="">

        Username
        <input type="text" name="username" id="username" value="" autocomplete="off">

        Create a password
        <input type="password" name="password" id="password">

        Enter your password again
        <input type="password" name="password_again" id="password_again">

        Enter your password again
        <input type="text" name="name" id="name">

    <input type="submit" value="Register"

input.php:
<?php
class input {
    public static function exists($type = 'post') {
        switch($type) {
            case 'post':
                return (!empty($_POST)) ? true : false;
            break;
            case 'get':
                return (!empty($_GET)) ? true : false;
            break;
            default:
                return false;
            break;
        }
    }
}

and init.php
<?php
session_start();

$GLOBALS ['config'] = array(
    'mysql' => array(
        'host' => '127.0.0.1',
        'username' => 'root',
        'password' => '',
        'db' => 'lr'
    ),
    'remember' => array(
        'cookie_name' => 'hash',
        'cookie_expiry' => 604800
        ),
    'session' => array(
        'session_name' => 'user'
    )
);

spl_autoload_register(function($class) {
    require_once 'classes/' . $class . '.php';

});

require_once 'functions/sanitize.php';
?>

A: The button was not closed
you have
<input type="submit" value="Register"

should be
<input type="submit" value="Register">

More over the form needs to be closed
</form>

Also You have form action="" this will need $_GET["username"] etc to get the values
In the function exists() default type is post so u will need to set the form method as post or while calling the
if(input::exists()) {
echo 'Submitted';
}

you should do as
if(input::exists("get")) {
echo 'Submitted';
}

So in the 2nd case you can keep the form action as ""

A: i found the problem
<form action="" method="">

forgot to put post in it
<form action="" method="post">


text:
Q: Determine bounds of shape / graphics drawn into a Canvas I have a simple HTML5 Canvas example that lets the user draw paths onto a canvas. Is there any way to determine the rectangular bounds of the path / shape that was drawn? (i.e., what is the width, height of the rectangular region surrounding the path).
I realize I could do the math while the shape is being drawn to figure out the bounds, but I wanted to see if there was an easier / built in way.

A: I assume you are using lineTos the only way I could think of would be to keep a min/max stored for the height and width as the user is drawing paths. Other than that the only way to pull back info from the canvas would be to use getImageData which will only give you raw pixel information.
Quick example showing this

var ctx = document.getElementById("canvas").getContext("2d");
var xMin, xMax, yMin, yMax;

// These are set to where the path starts, i start them at 10,10
xMin = xMax = 10;
yMin = yMax = 10;

ctx.beginPath();
ctx.moveTo(10,10);

for(var i = 0; i <10; i++){
    var x = Math.floor(Math.random()*150),
        y = Math.floor(Math.random()*150);

    ctx.lineTo(x,y);
    if(x < xMin){
     xMin = x;
    }
    if(x > xMax){
     xMax = x;
    }

    if(y < yMin){
     yMin = y;
    }
    if(y > yMax){
     yMax = y;
    }
}
ctx.strokeStyle = "rgb(0,0,0)";
ctx.stroke();
ctx.closePath();

ctx.strokeStyle = "rgb(255,0,0)";
ctx.strokeRect(xMin,yMin,xMax - xMin,yMax - yMin);
#canvas{
    width: 300px;
    height: 300px;
}
<canvas id="canvas"></canvas>

note I just create a bunch of random points. The main thing to remember is set the min/max vals to the coords of the first path a user creates.
I guess you knew that though, so the real answer is no there is unfortunately no built in way currently to do it..

A: Although you have to track it yourself, I would suggest wrapping it up in reusable functionality. Here's a minimal example, tracking it only for moveTo and lineTo. See the live example here: http://phrogz.net/tmp/canvas_bounding_box.html
function trackBBox( ctx ){
  var begin = ctx.beginPath;
  ctx.beginPath = function(){
    this.minX = this.minY = 99999999999;
    this.maxX = this.maxY = -99999999999;
    return begin.call(this);
  };
  ctx.updateMinMax = function(x,y){
    if (x<this.minX) this.minX = x;
    if (x>this.maxX) this.maxX = x;
    if (y<this.minY) this.minY = y;
    if (y>this.maxY) this.maxY = y;
  };
  var m2 = ctx.moveTo;
  ctx.moveTo = function(x,y){
    this.updateMinMax(x,y);
    return m2.call(this,x,y);
  };
  var l2 = ctx.lineTo
  ctx.lineTo = function(x,y){
    this.updateMinMax(x,y);
    return l2.call(this,x,y);
  };
  ctx.getBBox = function(){
    return {
      minX:this.minX,
      maxX:this.maxX,
      minY:this.minY,
      maxY:this.maxY,
      width:this.maxX-this.minX,
      height:this.maxY-this.minY
    };
  };
}

...

var ctx = myCanvas.getContext("2d");

// Cause the canvas to track its own bounding box for each path
trackBBox(ctx);
ctx.beginPath();
ctx.moveTo(40,40);
for(var i=0; i<10; i++) ctx.lineTo(Math.random()*600,Math.random()*400);

// Find the bounding box of the current path
var bbox = ctx.getBBox();
ctx.strokeRect(bbox.minX,bbox.minY,bbox.width,bbox.height);

A: Inspired by @Phrogz's answer, the answer from Calculate bounding box of arbitrary pixel-based drawing, and his two slightly different demos http://phrogz.net/tmp/canvas_bounding_box.html  and http://phrogz.net/tmp/canvas_bounding_box2.html, here is a version not using the alpha channel (it did not work in my case) but just using a comparison to white color.
function contextBoundingBox(ctx){
    var w=ctx.canvas.width,h=ctx.canvas.height;
    var data = ctx.getImageData(0,0,w,h).data;
    var x,y,minX,minY,maxY,maxY;
    o1: for (y=h;y--;)        for (x=w;x--;)           if ((data[(w*y+x)*4] != 255) && (data[(w*y+x)*4+1] != 255) && (data[(w*y+x)*4+2] != 255)) { maxY=y; break o1 }
    o2: for (x=w;x--;)        for (y=maxY+1;y--;)      if ((data[(w*y+x)*4] != 255) && (data[(w*y+x)*4+1] != 255) && (data[(w*y+x)*4+2] != 255)) { maxX=x; break o2 }
    o3: for (x=0;x<=maxX;++x) for (y=maxY+1;y--;)      if ((data[(w*y+x)*4] != 255) && (data[(w*y+x)*4+1] != 255) && (data[(w*y+x)*4+2] != 255)) { minX=x; break o3 }
    o4: for (y=0;y<=maxY;++y) for (x=minX;x<=maxX;++x) if ((data[(w*y+x)*4] != 255) && (data[(w*y+x)*4+1] != 255) && (data[(w*y+x)*4+2] != 255)) { minY=y; break o4 }
    return {x:minX,y:minY,maxX:maxX,maxY:maxY,w:maxX-minX,h:maxY-minY};
}


text:
Q: Empty span giving parent weird layout behavior I am making a table-type layout with divs and spans. I am getting some weird behavior when any of the spans are empty - a margin appears at the top of the parent.
I think it might be linked to using display: inline-block but I'm not sure why it is doing this.
Here is what I am talking about
Is there any way to fix this strange layout behavior?

A: Add vertical-align:top to .ListView_ColParent
.ListView_ColParent {
    display:inline-block;
    vertical-align:top;
}

jsFiddle example


text:
Q: Modelling friendship with aws amplify Here is an example of my schema
type User @model {
  id: ID!
  friends: [Friendship] @connect(name: "UserFriends")
  outgoingFriendRequests: [FriendRequest] @connect(name: "SenderRequests")
  incomingFriendRequests: [FriendRequest] @connect(name: "ReceiverRequests")
}

type Friendship @model {
  id: ID!
  user: User! @connect(name: "UserFriends")
  friend: User! @connect

type FriendRequest @model {
  id: ID!
  sender: User! @connect(name: "SenderRequests")
  receiver: User! @connect(name: "ReceiverRequests")

Here assume for userA and userB,
suppose userA added userB as friend(added an entry to friendship model).
{
  id: 'some-id
  user: user-A-id
  friend: user-B-id

}

Here we can query the userA's friends field to see userB as his friend(by relationship below)
@connect(name: "UserFriends")

But for userB, userA is still not available in its friends field. Is there any workaround we can do in the model design in order to mutually notify the added friendship. Or am I doing something wrong?


text:
Q: Regarding embeddings of locally convex spaces If $f:E\rightarrow E'$ is a linear embedding of locally convex topological vector spaces, and $A\subseteq E$ open and convex, can we always find $A'\subseteq E'$ open and convex sucht that $f(A)=f(E)\cap A'$?  Maybe with the additional requirement that $A$ is balanced?
My first thought was to choose some linear complement $F'\subseteq E'$ of $f(E)$ and considering the set $f(A)+F'$, but I couldn't prove it to be open...

A: OK, I think I got it.  First we can assume w.l.o.g. that $0\in A$, I won't need $A$ to be balanced.  Since $f$ is an embedding we can find $B'\subseteq E'$ open with $f(A)=f(E)\cap B'$ but this $B'$ doesn't have to be convex.
Now choose a convex, open neighbourhood $U'\in{\cal U}(0)$ in $E'$ such that $U'\subseteq B'$.  For each $x\in A$ we find some $\epsilon>0$ such that $x+\epsilon A\subseteq A$, this holds for all convex, open sets.  If we define $U'_{x,\epsilon}:=x+\epsilon U'$ for such $x,\epsilon$, we also have $$x\in U'_{x,\epsilon}\cap f(E)\subseteq f(A).$$
Now set $A'$ as the union over all $U'_{x,\epsilon}$ such that, as above, $x\in A$ and $U'_{x,\epsilon}\cap f(E)\subseteq f(A)$.  $A'$ is obviously open and $f(A)=f(E)\cap A'$ but we need to show that $A'$ is indeed convex.  But for $U'_{x,\epsilon},U'_{y,\delta}\subseteq A'$ and $0<\lambda<1$ one can easily verify $$\lambda U'_{x,\epsilon}+(1-\lambda)U'_{y,\delta}=U'_{\lambda x+(1-\lambda y),\lambda\epsilon+(1-\lambda)\delta}\subseteq A'$$ which concludes the proof.


text:
Q: Angular 2 get all directives of the same type inside the directive class I'm trying to achieve an active state on one of my directives, so that the element that has the directive on it gets an active class whenever isActive is set to true in the directive instance.
The issue is that I can't seem to pick up more than 1 directive at any given time, which also appears to be the same element which is fetching the other directives.
export class ModalOpenDirective {
  @ContentChildren(ModalOpenDirective) modalOpenDirectives: QueryList<ModalOpenDirective>;
  @Input() modalId: string;
  @Input() modalTemplate: string;

  public modalOpen: string;

  constructor(private modalApi: ModalApiService) {}

  @HostListener('click')
  open(): void {

    this.modalApi.open(this.modalId, this.modalTemplate);

    this.toggleActiveClass();
  }

  @HostBinding('class.active')
  isActive: boolean;

  toggleActiveClass(): void {

    this.modalOpenDirectives.map((directive) => {
      directive.isActive = false;
    });

    console.log(this.modalOpenDirectives);

    this.isActive = true;
  }
}

How can I make sure that it picks up all other directives of the same type? I'm pretty sure @ContentChildren is the way to go but it doesn't appear to work.
EDIT: Here's how I use them:
<button modalOpen modalId="test1">Open modal nr 1</button>
<button modalOpen modalId="test2">Open modal nr 2</button>
<button modalOpen modalId="test3">Open modal nr 3</button>

So when modalOpen with modalId="test1" gets triggered, that button should get an active class and all other buttons should lose theirs.

A: modalOpen only contains a single element, therefore ContentChildren only returns one.
If you change it to
<div modalOpen>
  <button modalId="test1">Open modal nr 1</button>
  <button modalId="test2">Open modal nr 2</button>
  <button modalId="test3">Open modal nr 3</button>
</div>

ContentChildren will return 3 elements.
This won't pass modalId to modalOpen though.


text:
Q: Automatically processing the Amazon SES notifications for bounce and complaint notifications We are using AWS SES for sending mails. Amazon SES sends bounce and complaint notifications through emails or AWS SNS. We would like to automatically process the bounce and complaint notifications (coming from email or AWS SNS) to extract the email ids, so that these emails can be removed from the original list.
One way to automate is to send these notifications to a topic in AWS SNS, then subscribe to the topic using AWS SQS and finally read the messages in the AWS SQS. SNS supports subscription over the following protocols - HTTP/HTTPS/EMail/EMail(JSON)/SMS/SQS. This is feasible, but I find it too cumbersome for a simple task of automatically processing the bounce and complaint notifications.
Is there any elegant way of tacking this problem?

I have found a blog entry from Amazon with the code in C#. Is there a better solution?

A: I think the way you describe IS probably the most elegant way. You already have very appropriate services in SNS and SQS that have associated SDK's in most major languages to allow you to do what you need easily. The hardest part is writing the code to update/remove the records in your mailing lists.

A: Through trial an error I have come up with this one - it is for Django but does a decent job for me.
First the models, then the request handler...
class ComplaintType:
    ABUSE = 'abuse'
    AUTH_FAILURE = 'auth-failure'
    FRAUD = 'fraud'
    NOT_SPAM = 'not-spam'
    OTHER = 'other'
    VIRUS = 'virus'

COMPLAINT_FEEDBACK_TYPE_CHOICES = [
    [ComplaintType.ABUSE, _('Unsolicited email or some other kind of email abuse')],
    [ComplaintType.AUTH_FAILURE, _('Unsolicited email or some other kind of email abuse')],
    [ComplaintType.FRAUD, _('Some kind of fraud or phishing activity')],
    [ComplaintType.NOT_SPAM, _('Entity providing the report does not consider the message to be spam')],
    [ComplaintType.OTHER, _('Feedback does not fit into any other registered type')],
    [ComplaintType.VIRUS, _('A virus was found in the originating message')]
]

class SES_Complaint(models.Model):
    subject = models.CharField(max_length=255)
    message = models.TextField()
    email_address = models.EmailField(db_index=True)
    user_agent = models.CharField(max_length=255)
    complaint_feedback_type = models.CharField(max_length=255, choices=COMPLAINT_FEEDBACK_TYPE_CHOICES)
    arrival_date = models.DateTimeField()
    timestamp = models.DateTimeField()
    feedback_id = models.CharField(max_length=255)

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'SES Complaint'
        verbose_name_plural = 'SES Complaints'

    def get_reason(self):
        return self.get_complaint_feedback_type_display()

class BounceType:
    UNDETERMINED = 'Undetermined'
    PERMANENT = 'Permanent'
    TRANSIENT = 'Transient'

class BounceSubType:
    UNDETERMINED = 'Undetermined'
    GENERAL = 'General'
    NO_EMAIL = 'NoEmail'
    SUPPRESSED = 'Suppressed'
    MAILBOX_FULL = 'MailboxFull'
    MESSAGE_TOO_LARGE = 'MessageToolarge'
    CONTENT_REJECTED = 'ContentRejected'
    ATTACHMENT_REJECTED = 'AttachmentRejected'

BOUNCE_TYPE_CHOICES = [
    [BounceType.UNDETERMINED, _('Unable to determine a specific bounce reason')],
    [BounceType.PERMANENT, _('Unable to successfully send')],
    [BounceType.TRANSIENT, _('All retry attempts have been exhausted')],
]

BOUNCE_SUB_TYPE_CHOICES = [
    [BounceSubType.UNDETERMINED, _('Unable to determine a specific bounce reason')],
    [BounceSubType.GENERAL, _('General bounce. You may be able to successfully retry sending to that recipient in the future.')],
    [BounceSubType.NO_EMAIL, _('Permanent hard bounce. The target email address does not exist.')],
    [BounceSubType.SUPPRESSED, _('Address has a recent history of bouncing as invalid.')],
    [BounceSubType.MAILBOX_FULL, _('Mailbox full')],
    [BounceSubType.MESSAGE_TOO_LARGE, _('Message too large')],
    [BounceSubType.CONTENT_REJECTED, _('Content rejected')],
    [BounceSubType.ATTACHMENT_REJECTED, _('Attachment rejected')]
]

class SES_Bounce(models.Model):
    subject = models.CharField(max_length=255)
    message = models.TextField()
    bounce_type = models.CharField(max_length=255, choices=BOUNCE_TYPE_CHOICES)
    bounce_sub_type = models.CharField(max_length=255, choices=BOUNCE_SUB_TYPE_CHOICES)
    timestamp = models.DateTimeField()
    feedback_id = models.CharField(max_length=255)
    status = models.CharField(max_length=255)
    action = models.CharField(max_length=255)
    diagnostic_code = models.CharField(max_length=255)
    email_address = models.EmailField(db_index=True)

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True, db_index=True)

    class Meta:
        verbose_name = 'SES Bounce'
        verbose_name_plural = 'SES Bounces'

    def get_reason(self):
        return '%s - %s' % (self.get_bounce_type_display(), self.get_bounce_sub_type_display())

And here is the request handler:
@csrf_exempt
def aws_sns(request):
    logger.debug('Incoming SNS')

    if request.method == 'POST':

        logger.debug('Incoming SNS is POST')

        sns_message_type = request.META.get('HTTP_X_AMZ_SNS_MESSAGE_TYPE', None)

        if sns_message_type is not None:

            logger.debug('Incoming SNS - %s', sns_message_type)

            json_body = request.body
            json_body = json_body.replace('\n', '')
            js = loads(json_body)

            if sns_message_type == "SubscriptionConfirmation":

                subscribe_url = js["SubscribeURL"]
                logger.debug('Incoming subscription - %s', subscribe_url)
                urllib.urlopen(subscribe_url)

            elif sns_message_type == "Notification":

                message = js.get("Message", None)
                message = message.replace('\n', '')
                message = loads(message)

                notification_type = message.get("notificationType", None)

                if notification_type == 'AmazonSnsSubscriptionSucceeded':
                    logger.debug('Subscription succeeded')

                elif notification_type == 'Bounce':

                    logger.debug('Incoming bounce')

                    bounce = message['bounce']
                    bounce_type = bounce['bounceType']
                    bounce_sub_type = bounce['bounceSubType']
                    timestamp = bounce['timestamp']
                    feedback_id = bounce['feedbackId']

                    bounce_recipients = bounce['bouncedRecipients']

                    for recipient in bounce_recipients:
                        status = recipient.get('status')
                        action = recipient.get('action')
                        #diagnostic_code = recipient['diagnosticCode']
                        email_address = recipient['emailAddress']

                        SES_Bounce.objects.filter(email_address=email_address).delete()

                        SES_Bounce.objects.create(
                            message=message,
                            bounce_type=bounce_type,
                            bounce_sub_type=bounce_sub_type,
                            timestamp=timestamp,
                            feedback_id=feedback_id,
                            status=status,
                            action=action,
                            #diagnostic_code=diagnostic_code,
                            email_address=email_address
                        )

                elif notification_type == 'Complaint':

                    logger.debug('Incoming complaint')

                    complaint = message['complaint']

                    user_agent = complaint.get('userAgent')
                    complaint_feedback_type = complaint.get('complaintFeedbackType')
                    arrival_date = complaint.get('arrivalDate')

                    timestamp = complaint['timestamp']
                    feedback_id = complaint['feedbackId']
                    recipients = complaint['complainedRecipients']

                    for recipient in recipients:
                        email_address = recipient['emailAddress']

                        SES_Complaint.objects.filter(email_address=email_address).delete()

                        SES_Complaint.objects.create(
                            #subject=subject,
                            message=message,
                            email_address=email_address,
                            user_agent=user_agent,
                            complaint_feedback_type=complaint_feedback_type,
                            arrival_date=arrival_date,
                            timestamp=timestamp,
                            feedback_id=feedback_id
                        )

                else:
                    logger.exception('Incoming Notification SNS is not supported: %s', notification_type)

            return HttpResponse()
        else:
            logger.exception('Incoming SNS did not have the right header')

            for key, value in request.META.items():
                logger.debug('Key: %s - %s', key, value)

    else:
        logger.exception('Incoming SNS was not a POST')

    return HttpResponseBadRequest()

A: I find that directly subscribing to SNS using an HTTP endpoint is the most straightforward approach. You literally have to write only a few lines of code. Here's my django example:
def process(request):
    json = request.raw_post_data
    js = simplejson.loads(json)
    info = simplejson.loads(js["Message"])
    type = info["notificationType"]           # "Complaint" or "Bounce"
    email = info["mail"]["destination"][0]

    # do whatever you want with the email

A: Recently, I was able to get this working using an HTTP Endpoint via SNS.  I use python/django to consume the notification. You have to process the subscription message first before you consume the notifications; you can read about subscriptions in the SNS documentation.
I think if you have a smaller application that doesn't send to many emails; http endpoint should work fine.  This code requires that you have a notification model created.
#process an amazon sns http endpoint notification for amazon ses bounces and complaints
@csrf_exempt
def process_ses_notification(request):

    if request.POST:

        json_body = request.body
        #remove this control character(throws an error) thats present inside the test subscription confirmation
        js = loads(json_body.replace('\n', ''))

        if js["Type"] == "SubscriptionConfirmation":

             subscribe_url = js["SubscribeURL"]
             urllib.urlopen(subscribe_url)
             return HttpResponse(status=200)

    elif js["Type"] == "Notification":

        #process message from amazon sns
        arg_info = loads(js["Message"]) # may need to use loads(js["Message"]) after testing with amazon
        arg_notification_type = arg_info["notificationType"]

        if arg_notification_type == 'Bounce':
            #required bounce object fields
            arg_emails=arg_info["bounce"]["bouncedRecipients"]
            arg_notification_subtype=arg_info["bounce"]["bounceType"]
            arg_feedback_id=arg_info["bounce"]["feedbackId"]
            arg_date_recorded=arg_info["bounce"]["timestamp"]
        elif arg_notification_type == 'Complaint':
            #required complaint object fields
            arg_emails=arg_info["complaint"]["complainedRecipients"]
            arg_feedback_id=arg_info["complaint"]["feedbackId"]
            arg_date_recorded=arg_info["complaint"]["timestamp"]
            #check if feedback type is inside optional field name
            if "complaintFeedbackType" in arg_info["complaint"]:
                arg_notification_subtype=arg_info["complaint"]["complaintFeedbackType"]
            else:
                arg_notification_subtype=""
        else:
            HttpResponse(status=400)

        #save notifications for multiple emails
        for arg_email in arg_emails:
            notification = SES_Notification(info=json_body, notification_type=arg_notification_type,
                                            email=arg_email["emailAddress"], notification_subtype=arg_notification_subtype,
                                            date_recorded=arg_date_recorded, feedback_id=arg_feedback_id)
            notification.save()
        return HttpResponse(status=200)

return HttpResponse(status=400)

A: all the answers above are great, but just a small and important addition:
you first need to verify that the request is from amazon sns: (as described at Verifying the Signatures of Amazon SNS Messages)
for the python code that validate the signature - a good example is here


text:
Q: A doubt in understanding a proof in Galois Theory
Let $K/F$ be a cyclic extension of degree $n$, and suppose that $F$ contains a primitive $n$th root of unity. If $K=F(\sqrt[n]{a})$ with $a\in F$, then any intermediate field of $K/F$ is of the form $F(\sqrt[m]{a})$ for some divisor $m$ of $n$.

In the proof of it, $\sigma$ is assumed to be the generator of $Gal(K/F)$. Then any subgroup of $Gal(K/F)$ is of the form $<\sigma^t>$ for some divisor of $n$. So the intermediate fields will be the fixed field of $\sigma^t$. If $t$ is a divisor of $n$, write $n=tm$ and let $\alpha = \sqrt[n]{a}$. Then $\sigma^t(\alpha^m)=(\omega^t\alpha)^m=\alpha^m$, so $\alpha^m$ is fixed by $\sigma^t$.
My doubt:

*

*$\alpha^m$ is fixed by $\sigma^t \implies$ $F(\alpha^m)=F(\sqrt[t]{a})$ is the fixed field,

OR,

*$\alpha^m$ is fixed by $\sigma^t \implies$ the fixed field of $\sigma^t$ has degree $m$ over $F$, so $F(\sqrt[m]{a})$ is the fixed field.

I cannot understand. Can someone please clear my doubt?
Thank you

A: If $F$ contains a $n$-root of unity $e_n$, $
e_n^p\sqrt[n]a,p=1,2,...,n$ are roots of $X^n-a$ so $K$ is the splitting field of $X^n-a$ and is separable, so the extension is Galoisian. You can apply the fundamental theorem of the Galois theory.
An intermediate field $L$ if the set of elements fixed by $\sigma^t$ and if $n=mt$, $\sigma^t(\alpha^m)=\alpha^m$, we deduce that $\alpha^m\in L$, $[L:F]=t$ and the minimal polynomial of $\alpha^m$ is $X^t-a$. We deduce that $[F(\alpha^m):F]=t$ and $F(\alpha^m)=L$.
https://en.wikipedia.org/wiki/Fundamental_theorem_of_Galois_theory


text:
Q: Add a mobile friendly "dot grabb" at the end of a progress bar (seek bar) to custom htm5 audio player I found a custom html5 audio player and successfully redesigned it, now I want to add a "grabber" to be able to grab and move the seek bar progress line at specific time (mobile friendly). I want something like a "dot" in iOS to be able to grab (with a touch) and move progress bar (seek bar) to exact time that I wanted.
I am new to JS and I dont't know how to get this done with this source code
Full code CodePen
How it can be done?

function calculateTotalValue(length) {
  var minutes = Math.floor(length / 60),
    seconds_int = length - minutes * 60,
    seconds_str = seconds_int.toString(),
    seconds = seconds_str.substr(0, 2),
    time = minutes + ':' + seconds

  return time;
}

function calculateCurrentValue(currentTime) {
  var current_hour = parseInt(currentTime / 3600) % 24,
    current_minute = parseInt(currentTime / 60) % 60,
    current_seconds_long = currentTime % 60,
    current_seconds = current_seconds_long.toFixed(),
    current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);

  return current_time;
}

function initProgressBar() {
  var player = document.getElementById('player');
  var length = player.duration
  var current_time = player.currentTime;

  // calculate total length of value
  var totalLength = calculateTotalValue(length)
  jQuery(".end-time").html(totalLength);

  // calculate current value time
  var currentTime = calculateCurrentValue(current_time);
  jQuery(".start-time").html(currentTime);

  var progressbar = document.getElementById('seekObj');
  progressbar.value = (player.currentTime / player.duration);
  progressbar.addEventListener("click", seek);

  if (player.currentTime == player.duration) {
    $('#play-btn').removeClass('pause');
  }

  function seek(evt) {
    var percent = evt.offsetX / this.offsetWidth;
    player.currentTime = percent * player.duration;
    progressbar.value = percent / 100;
  }
};

function initPlayers(num) {
  // pass num in if there are multiple audio players e.g 'player' + i

  for (var i = 0; i < num; i++) {
    (function() {

      // Variables
      // ----------------------------------------------------------
      // audio embed object
      var playerContainer = document.getElementById('player-container'),
        player = document.getElementById('player'),
        isPlaying = false,
        playBtn = document.getElementById('play-btn');

      // Controls Listeners
      // ----------------------------------------------------------
      if (playBtn != null) {
        playBtn.addEventListener('click', function() {
          togglePlay()
        });
      }

      // Controls & Sounds Methods
      // ----------------------------------------------------------
      function togglePlay() {
        if (player.paused === false) {
          player.pause();
          isPlaying = false;
          $('#play-btn').removeClass('pause');

        } else {
          player.play();
          $('#play-btn').addClass('pause');
          isPlaying = true;
        }
      }
    }());
  }
}

initPlayers(jQuery('#player-container').length);

A: Not sure if it can be done with "progress" element but can be possible with "range" element
First, remove the "progress" and add this
<input id="seekObj" type="range" name="rng" min="0" step="0.25" value="0" onchange="seekAudio()" oninput="seekAudio()" style="width: 99%">

After that let's add some css to make it look like a good seek bar, in your case you are using "SCSS" so here is the code
$background_color_1: #df7164;

input[type=range] {
    -webkit-appearance: none;
    -moz-apperance: none;
    border-radius: 6px;
    height: 6px;
    background-image: -webkit-gradient(linear, left top, right top, color-stop(0%, #df7164), color-stop(0%, #F5D0CC));
    background-image: -moz-linear-gradient(left center, #DF7164 0%, #DF7164 0%, #F5D0CC 0%, #F5D0CC 100%);
    &:focus {
        outline: none;
        border: none;
    }
    &::-webkit-slider-thumb {
        -webkit-appearance: none !important;
        background-color: $background_color_1;
        height: 13px;
        width: 13px;
        border-radius: 50%;
    }
    &::-moz-range-thumb {
        -moz-appearance: none !important;
        background-color: $background_color_1;
        border: none;
        height: 13px;
        width: 13px;
        border-radius: 50%;
    }
}
input[type="range"] {
    &::-moz-range-track {
        border: none;
        background: none;
        outline: none;
    }
}

All done now, so we have to do some changes into JS as well as HTML to make it work
Add these functions in JS
function setupSeek() {
  seek.max = player.duration;
}
function seekAudio() {
isSeeking=true;
player.currentTime = seek.value;
isSeeking=false;
}

Move the "player" and "seek" element retrieval to top as well as add a seek status holder
var isSeeking=false;
var seek = document.getElementById("seekObj");
var player = document.getElementById("player");

Now add some code inside "initProgressBar()" function to make the "range" element work
if(!isSeeking){
seek.value = player.currentTime;
}

By This point everything is done, we just need to call the functions from so HTML, so let's do the changes, From audio element, we need to call the "setUpSeek" so for that just add this to "audio"
ondurationchange="setupSeek()"

Now, we are done, you can check the CodePen for a better understanding
Some more improvements to make the slider work in a better way.
Add this Javascript code, This will make the seek bar work look and feel like a native mobile seek bar
function SetSeekColor(){
  try{
   var val = ($("#seekObj").val() - $("#seekObj").attr('min')) / ($("#seekObj").attr('max') - $("#seekObj").attr('min'));
    var percent = val * 100;
  $("#seekObj").css('background-image',
        '-webkit-gradient(linear, left top, right top, ' +
        'color-stop(' + percent + '%, #df7164), ' +
        'color-stop(' + percent + '%, #F5D0CC)' +
        ')');

    $("#seekObj").css('background-image',
        '-moz-linear-gradient(left center, #DF7164 0%, #DF7164 ' + percent + '%, #F5D0CC ' + percent + '%, #F5D0CC 100%)');
  }
  catch(e){}
}

To Make the dragging perfectly you may need to add a third party plugin/js, You can find one here


text:
Q: Visual basic 6 textbox autocomplete feature? How can i add an autocomplete feature in a textbox? As soon as i write something in a textbox(whether 1 character or 2 or 3), it should match it with the student name in the database and complete the name.

A: For a hardcore solution, here's a free ComboBox control with autocomplete, implemented from scratch in VB6 from Steve McMahon's excellent vbAccelerator.com.

A: You could trap the keypress event and make the database call there.  If you wanted a minimum of 2 or 3 characters before making the DB call to reduce the number of rows coming back just check the length of the text in the textbox before making the call.

A: On Key Up event you can get the value from the text box and choose the list of "related or similar" values from DB and then change the value of the textbox with the first value from the result from DB and repeat the above steps for every letter entered.
Here is an Auto Complete code sample for Combo box which is worth checking.

A: there is no auto complete in a textbox of visual basic 6, then you must to create it from 0, here is a sample of that.
http://www.recursosvisualbasic.com.ar/htm/trucos-codigofuente-visual-basic/6.htm


text:
Q: Filter using wildcard for relationships I have an input using a datalist where it's possible to either type in the name of the car part type or uses a dropdown. Looks like this
<input value="{{ request()->input('part-type') }}" list="part-type-list"
        name="part-type" class="form-select">
<datalist id="part-type-list">
    @foreach($partTypes as $partType)
        <option @if(request()->input('plaintext') == $partType->name) selected
                @endif value="{{$partType->name }}">{{ $partType->name }}
        </option>
    @endforeach
</datalist>

The $partTypes are coming from a query CarPartType::all() and it's used to show the values you can filter car parts by.
In my controller, I am trying to see if I have a part-type filter and then changing the query to filter out the ones that don't match it. The problem is that I don't have the name of the car part types on the car parts table but only the id. Here is an example of me trying to query it through the relationship but it does not work.
$parts = CarPart::query();

if($request->filled('part-type')) {
    $parts = $parts->where('carPartType.name', 'like', "% $request->input('part-type')%");
    return $parts->get();
}

The relationship I am trying to use
public function carPartType(): BelongsTo
{
    return $this->belongsTo(CarPartType::class);
}

A: there is two problems in your code

*

*$request->input('part-type') can not be used in quotations

*you must use whereHas to make relationship constraints.

if ($request->filled('part-type')) {

    $value = $request->input('part-type');

    $parts = $parts->whereHas('carPartType', function ($query) use ($value) {
        return $query->where('name', 'like', "%$value%");
    });

    return $parts->get();
}

I hope this works for you.


text:
Q: Ruby on rails - bootstrap material design - Add checkboxes to simple form I installed the Bootstrap Material Design in my Ruby on Rails application and every animation is functioning properly, but i can´t see the checkboxes. My code for the checkboxes is:

    <%= f.input :active, :as => :boolean, :label => false, :inline_label => true %>

Can anyone Help me please?
Thank you all!

A: use f.check_box instead of f.input this:

<%= f.check_box :active, :as => :boolean, :label => false, :inline_label => true %>

A: I finally got who it's doing:

       <%= f.check_box :active, :as => :boolean, :label => false, :inline_label => true %> Active

You need to add "checkbox" to the div class of the label and then you will see the checkbox animations for the bootstrap material design


text:
Q: Why `futures::channel::mpsc` can just notify one sender? I'm reading futures-preview 0.3 sources to find out how to do "notify any" correctly. In mpsc::channel (which is bounded), multiple senders may wait for a receipt (in case of full buffer).
Looking into the implementation of next_message and unpark_one, the receiver seems to only notify one sender per one receipt.
I doubt this works in presense of select!, because select! may lead to false notification. However, I couldn't produce a problem case.
Here's my attempt to confuse mpsc:
[package]
name = "futures-mpsc-test"
version = "0.1.0"
edition = "2018"

[dependencies]
futures-preview = { version = "0.3.0-alpha.9", features = ["tokio-compat"] }
tokio = "0.1.11"

and this:
#![feature(async_await, await_macro, futures_api, pin)]

use std::collections::HashSet;

use futures::prelude::*;

use futures::channel::mpsc::{channel, Sender};
use futures::channel::oneshot;
use futures::select;

async fn main2() {
    let channel_len = 1;
    let num_false_wait = 1000;
    let num_expected_messages = 100;

    let (mut send, mut recv) = channel(channel_len);
    // One extra capacity per sender. Fill the extras.
    await!(send.send(-2)).unwrap();

    // Fill buffers
    for _ in 0..channel_len {
        await!(send.send(-1)).unwrap();
    }

    // False waits. Should resolve and produce false waiters.
    for _ in 0..num_false_wait {
        await!(false_wait(&send));
    }

    // True messages.
    {
        let mut send = send.clone();
        await!(send.send(-2)).unwrap();
        tokio::spawn(async move {
            for i in 0..num_expected_messages {
                await!(send.send(i)).unwrap();
            }
            Ok(())
        }.boxed().compat());
    }

    // Drain receiver until all true messages are received.
    let mut expects = (0..num_expected_messages).collect::<HashSet<_>>();
    while !expects.is_empty() {
        let i = await!(recv.next()).unwrap();
        expects.remove(&i);
        eprintln!("Received: {}", i);
    }
}

// If `send` is full, it will produce false waits.
async fn false_wait(send: &Sender<i32>) {
    let (wait_send, wait_recv) = oneshot::channel();
    let mut send = send.clone();
    await!(send.send(-2)).unwrap();
    tokio::spawn(async move {
        let mut sending = send.send(-3);
        let mut fallback = future::ready(());
        select! {
            sending => {
                sending.unwrap();
            },
            fallback => {
                eprintln!("future::ready is selected");
            },
        };
        wait_send.send(()).unwrap();
        Ok(())
    }.boxed().compat());
    await!(wait_recv).unwrap();
}

fn main() {
    tokio::run(async {
        await!(main2());
        Ok(())
    }.boxed().compat());
}

I expect this to happen:

*

*The buffer is filled by -1. Therefore later senders are blocked.

*There are both "true waiters" and "false waiters".
False waiters already exited, because the other arm of select!
immediately completes.

*In each call to await!(recv.next()), at most one waiting sender is
notified. If a false waiter is notified, no one can push to the buffer,
even if the buffer has a vacant room.

*If all elements are drained without true notification,
the entire system is stuck.

Despite my expectation, the main2 async function successfully completed. Why?

A: Further investigation on the futures source code solved my problem. At last, I cannot confuse the mpsc in this way.
The point is that, the size of mpsc is flexible and can grow more than initially specified. This behavior is mentioned in the docs:

The channel's capacity is equal to buffer + num-senders. In other words, each sender gets a guaranteed slot in the channel capacity, and on top of that there are buffer "first come, first serve" slots available to all senders.

Yes, I've first read this before experimenting, but I couldn't figure out the importance of this at that time.
Problem with fixed buffer
Think of a typical bounded queue implementation, where the size of a queue cannot grow more than initially specified. The spec is this:

*

*When the queue is empty, receivers block.

*When the queue is full (that is, the size is hitting the bound), senders block.

In this situation, if the queue is full, multiple senders are waiting for a single resource (the size of the queue).
In multithread programming, this is accomplished by primitives like notify_one. However, in futures, this is fallible: unlike multithreaded programming, the notified task doesn't necessarily make use of the resource, because the task may already have given up acquiring the resource (due to constructions like select! or Deadline) Then the spec is simply broken (the queue isn't full, but all alive senders are blocked).
mpsc is flexible
As pointed out above, the buffer size for futures::channel::mpsc::channel isn't strict. The spec is summarized as:

*

*When message_queue.len() == 0, receivers block.

*When message_queue.len() >= buffer, senders may block.

*When message_queue.len() >= buffer + num_senders, senders block.

Here, num_senders is basically the number of clones of Sender, but more than that in some cases. More precisely, num_senders is the number of SenderTasks.
So, how do we avoid resource sharing? We have additional states for that:

*

*Each sender (an instance of SenderTask) has is_parked boolean state.

*The channel has another queue called parked_queue, a queue of Arc references to SenderTask.

The channel maintains the following invariants:

*

*message_queue.len() <= buffer + num_parked_senders. Note that we don't know the value of num_parked_senders.

*parked_queue.len() == min(0, message_queue.len() - buffer)

*Each parked sender has at least one message in parked_queue.

This is accomplished by the following algorithm:

*

*For receiving,

*

*it pops off a SenderTask from parked_queue and, if the sender is parked, unpark it.

*For sending,

*

*It always waits for is_parked to be false. If message_queue.len() < buffer, as parked_queue.len() == 0, all senders are unparked. Therefore we can guarantee progress in this case.

*If is_parked is false, push the message to the queue anyway.

*After that, if message_queue.len() <= buffer, it needs to do nothing further.

*if message_queue.len() > buffer, the sender is made unparked and pushed to parked_queue.

You can easily check the invariant is maintained in the algorithm above.
Surprisingly, the senders no more wait for a shared resource. Instead, A sender waits for its is_parked state. Even if the sending task is dropped before completion, it just remains in parked_queue for a while and doesn't block anything. How clever it is!

A:
I doubt this works in presense of select!, because select! may lead to false notification.

No, You can't "confuse" a mpsc channel using select!:
select! does not trigger any mspc related notification, it just return the future that finishes first.
When the message queue is full it is  await!(recv.next()) that notifies one producer that a slot into the bounded channel is now available.
In other words: there are no true waiters and false waiters:
when a channel message queue is full the producers block and await that the receiver side consumes the enqueued messages.


text:
Q: Appending an XML Document with elements from another XML Document in C# I am trying to build an automatic test grading application and I want the end result to be a savefiledialog prompt that allows the grader to save a new xml file to any location.
The trick is I need that output xml to include the original test + appended answers from  answer key + final grade.  Here is what I have so far but Im getting an error.  I am not familiar with .appendchild() so Im thinking that is where my issue lies.
    private void cbOutput_Click(object sender, EventArgs e)
    {
        XmlNode rootTest = xmlAnswers.DocumentElement;
        XmlNode rootKey = xmlAnswerKey.DocumentElement;

        XmlNodeList nodeListTest = rootTest.SelectNodes("//answer");

        foreach (XmlNode item in nodeListTest)
        {
            XmlNode importNode = rootTest.OwnerDocument.ImportNode(rootKey, true);

            item.AppendChild(importNode);
        }

        SaveFileDialog savefiledialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "XML Files|*.XML";
        saveFileDialog1.Title = "Choose Location to Save Graded Test";

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if (!string.IsNullOrEmpty(savefiledialog1.FileName))
            using (Stream s = File.Open(savefiledialog1.FileName, FileMode.Create))
            using (StreamWriter sw = new StreamWriter(s))
            {
                sw.Write(rootTest + tbTotal.Text);
            }
        }

A: I have a hard time following your code, since it is pre .Net 3.5 XML code. I started in on C# when 3.5 came out. Seems like you are adding the keys to every answer in the test? Doesn't make sense from what you wrote as your description. But if that was your goal, you can try this.
If you can use .Net 3.5 then use XElement / XDocument, using these converters do
XElement test = xmlAnswers.ToXElement();
XElement keys = xmlAnswerKey.ToXElement();

test.Descendants("answer")
    .ToList()
    .ForEach(a => a.Add(new XElement(keys))); // Add clone of keys to each answer
// Dialog stuff
test.Save(savefiledialog1.FileName);

Or, using your description (I'll have to try and make up what you should be doing, since your XML is hidden from us).
XElement test = xmlAnswers.ToXElement();
XElement keys = xmlAnswerKey.ToXElement();

test.Add(keys.Descendants("answer").ToList()); // Add Answers to test
test.Add(new XElement("finalgrade", "A")); // Add final grade
// Dialog stuff
test.Save(savefiledialog1.FileName);

PS, don't do all the converting, adding of answers etc outside the
if (saveFileDialog1.ShowDialog() == DialogResult.OK)

Otherwise, if it isn't OK then you are wasting the time of your user.


text:
Q: Preg replace callback validation So I need to re-write some old code that I found on a library.
    $text = preg_replace("/(<\/?)(\w+)([^>]*>)/e",
                         "'\\1'.strtolower('\\2').'\\3'", $text);

    $text = preg_replace("/<br[ \/]*>\s*/","\n",$text);
    $text = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n",
                         $text);

And for the first one I have tried like this:
 $text = preg_replace_callback(
   "/(<\/?)(\w+)([^>]*>)/",
   function($subs) {
       return strtolower($subs[0]);
   },
   $text);

I'm a bit confused b/c I don't understand this part: "'\\1'.strtolower('\\2').'\\3'" so I'm not sure what should I replace it with.
As far as I understand the first line looks for tags, and makes them lowercase in case I have data like
<B>FOO</B>

Can you guys help me out here with a clarification, and If my code is done properly?

A: The $subs is an array that contains the whole value in the first item and captured texts in the subsequent items. So, Group 1 is in $subs[1], Group 2 value is in $subs[2], etc. The $subs[0] contains the whole match value, and you applied strtolower to it, but the original code left the Group 3 value (captured with ([^>]*>) that may also contain uppercase letters) intact.
Use
$text = preg_replace_callback("~(</?)(\w+)([^>]*>)~", function($subs) {
    return $subs[1] . strtolower($subs[2]) . $subs[3];
 }, $text);

See the PHP demo.


text:
Q: How to mount a shared directory on a Samba server on Kubuntu 16.04 I have some python scripts that are on a Samba server. I first used them under Windows and now want to use them on a Linux machine. Therefore I mounted the server folder on my Linux machine (Kubuntu 16.04) using the following:
sudo mount -t cifs //[IP address]/Share Share -o username=guest

Now I want to run the python files in this share directory on the Linux machine. A problem arises when python has to write to files in this directory (I create .PNG files and write to a .CSV file to log my results):
IOError: [Errno 13] Permission denied: 'filename.png'

This makes kind of sense... The permissions of such files are:
-rw-rw-r--+ 1 nobody nogroup

The .PNG file I write to is actually created at that moment. So the result is an empty file with the permissions as above.
Permissions of the files that were already there (created on Windows) are:
-rwxrw-rw-+ 1 nobody nogroup

Can anyone help me out here?
I would want to be able to write to the file. It should still work/be accessible on the windows computer.
I am not sure where the problem is. I don't know why the files are owned by nobody, even if those files were just created. Then the reason for not being able to write to it is of course that the group permissions are read-only and the file is part of nogroup.
I access the same files on a Windows computer (which is not the server) and I can read and write and do whatever I want there just fine.
So my question is then, why are the files owned by nobody and part of nogroup and how do I fix this?

A: There are a number of possible issues here.

*

*you mount the share as the guest user. If this account doesn't have sufficient permissions to create the file you'll hit problems

*you don't use -o noperm, so the client tries to preempt permissions checking - as well as whatever the server wants to enforce

*does the empty PNG file already exist, or can you be completely sure it's created by your script?

*depending on whether
the server is Windows or Samba you may have server-side filesystem permissions interacting with Windows permissions


text:
Q: Is formal logic necessary for pure/"higher" mathematics? I'm asking this as an autodidact who wants to learn math rigorously for its own sake. And I was just wondering if understanding proofs could be achieved without a formal grounding in symbolic logic. I ask because I have all the books I need but I simply don't have the patience I'd like to have for the formal logic book, as I'm itching to get into continuous math.
And to clarify, I'm interested predominantly in calculus/analysis, ODEs/PDES, and differential geometry.

A: In order to study analysis and related fields you don't need any formal training in logic. At the same time, to learn computer science you don't need any formal training in analysis. Yet most universities require their students to study analysis to some degree. Why?
The reason is not to torture the students, or cull the first year acceptance rate. Or at least ideally these are not the reasons.
When you study abstract mathematics, you learn how to analyze a problem, and how to solve a problem using abstract thinking. The same principle can be applied to anything. Studying mathematics is the study of how to analyze, generalize and solve problems. And the more ways you know, the better you will be.
So while you don't need any formal training in logic and set theory, I would very much recommend at least a very good understanding of the basics of these fields. The basics of propositional calculus, predicate calculus, and naive set theory. These tools are very useful to mathematics, even if you don't apply them directly. They allow you to access better and higher understanding of the problems that you deal with, and how to deal with them.
As for my learned colleague who said that "this is basically common sense", while this is not far from the truth, you'd be surprised how many students I have seen having trouble with understanding the importance of quantifier order, or how to negate a proposition (with or without quantifiers). And Certainly understanding what does it mean for a function to be "not continuous everywhere" is important if you want to do analysis. (And you'd be surprised how many students will not be able to write that statement correctly.)

A: Certainly no deep knowledge is required, even for subjects where foundational issues come up. Some knowledge about quantifiers is at times useful, but not really necessary, since lots of people consider the use of quantifiers to be bad style (otherwise they would be used lots in serious books, but they are not); these things have no content (merely different language). This holds for all branches of mathematics apart from logic itself, for the things which you are interested in in particular. You can easily read standard PDE books such as Trudinger/Gilbarg without knowing hardly any formal logic at all (with only a working knowledge), in fact I do so and I am certainly not the only one. But again, this is in a sense not surprising. I mean of course you should know the difference between $\forall x \exists y$ and $\exists x\forall y$, but this is basically common sense. Probably you don't need any formal logic at all.

A: Nonstandard analysis consists of one branch of formal logic.  The Wolfram page in particular says:
"Crucially, however, the angle at which the nonstandard analyst looks at the axioms of analysis provides for an average case reduction in complexity that provides shorter proofs of various results, and will one day lead to the proof of a result which is not accessible to classical mathematics without nonstandard methods, precisely because its classical proof is too long to write down in the length of time humans will reside on Earth."
So, sure you can learn some of continuous mathematics without any formal logic.  However, for a deep comprehension of the subject, learning some formal logic will probably serve you well.


text:
Q: How to generate custom sales analysis report in sq Suppose my table is
CREATE TABLE SALESS (id int, product int, salesdate DATETIME, amount float)
INSERT INTO SALESS VALUES
(1, 1, '2020-10-10', 500),
(1, 1, '2020-11-10', 300),
(1, 1, '2020-12-10', 200),
(1, 2, '2020-10-10', 300),
(1, 2, '2020-11-10', 1000),
(1, 2, '2020-12-10', 200)

and my query is
select product, year(salesdate) 'year', month(salesdate) 'month', sum(amount)'total maount' from SALESS
group by product, year(salesdate), month(salesdate)
order by product, year(salesdate), month(salesdate)

Giving me the result

What I need as result is like below, how can modify my query to give me this result?

A: You can use conditional aggregation:
select year(salesdate) as year, month(salesdate) as month,
       sum(case when product = 1 then amount else 0 end) as amount_1,
       sum(case when product = 2 then amount else 0 end) as amount_2
from SALESS
group by year(salesdate), month(salesdate)
order by year(salesdate), month(salesdate);

If you really want to add three empty rows for 2021, you can add this before the order by:
union all
select v.year, null, null
from (values (2021), (2021), (2021)) v(year)


text:
Q: How to start installation after downloading apk in mono I've been struggling to get my application to update from my private server I cannot get the broadcast receiver to work nor a plain installation script PLEASE I'm going insane Any Help would be deeply appreciated.
my script
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.Site.cc/Folder/app.apk");

            // If required by the server, set the credentials.
            //request.Credentials = CredentialCache.DefaultCredentials;
            //request.IfModifiedSince = DateTime.Parse("01-01-1990");
            try
            {
                using (WebResponse response = request.GetResponse())
                {

                    //DateTime dt = System.IO.File.GetCreationTime(FilePath);        //.GetLastWriteTime(FilePath);
                   // DateTime appDate = DateTime.Parse(response.Headers["Last-Modified"].ToString());

                    try
                    {
                        ad = new AlertDialog.Builder(this).Create();
                        ad.SetTitle("INFO");

                        ad.SetMessage("Get New version");
                        ad.SetButton("NOW", delegate
                        {

                            System.IO.File.Delete("/filepath/app.apk");
                            string url = "http://www.Site.cc/Folder/App.apk";
                            DownloadManager.Request Request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
                            Request.SetDescription("Inspections Application");
                            Request.SetTitle("Download Inspections");
                            // in order for this if to run, you must use the android 3.2 to compile your app
                            if (Build.VERSION.SdkInt >= BuildVersionCodes.HoneycombMr1)
                            {
                                Request.AllowScanningByMediaScanner();
                                Request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                                Request.SetMimeType("application/vnd.android.package-archive");
                                Request.SetVisibleInDownloadsUi(true);

                            }
                            Request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, "Inspections.Inspections-Signed.apk");

                            // get download service and enqueue file
                            DownloadManager manager = (DownloadManager)GetSystemService(Context.DownloadService);
                            manager.Enqueue(Request);

                        });
                        ad.SetButton2("LATER", delegate
                        {
                            return;
                        });
                        //ad.SetButton("Continue",new IDialogInterfaceOnClickListener listner);
                        ad.SetCanceledOnTouchOutside(true);
                        ad.Show();

                    }
                    catch (System.Exception ex)
                    {
                        ad = new AlertDialog.Builder(this).Create();
                        ad.SetTitle("INFO");
                        ad.SetMessage(ex.Message);
                        ad.SetCanceledOnTouchOutside(true);
                        ad.Show();
                    }
                   /*
                        cL.DownloadFile("http://www.site.cc/folder/app.apk", Path);
                        Intent promptInstall = new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse("/sdcard/Download/Inspections.Inspections-Signed.apk")).SetType("application/vnd.android.package-archive");
                        StartActivity(promptInstall);
                    */
                    //string lastModified = DateTime.Parse(response.Headers["Last-Modified"].ToString()).ToString();
                }
            }
            catch (WebException wex)
            {

            }

if I could just find a way to start the installation wiz for the app when its finished downloading
I know it must ask for permissions
Device log:
06-28 07:17:55.843 I/MonoDroid(  860): UNHANDLED EXCEPTION: Android.Content.ActivityNotFoundException: Exception of type 'Android.Content.ActivityNotFoundException' was thrown.
06-28 07:17:55.843 I/MonoDroid(  860): at Android.Runtime.JNIEnv.CallNonvirtualVoidMethod (intptr,intptr,intptr,Android.Runtime.JValue[]) [0x00024] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.7-branch/0e9eea34/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:616
06-28 07:17:55.843 I/MonoDroid(  860): at Android.Content.ContextWrapper.StartActivity (Android.Content.Intent) [0x0006b] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.7-branch/0e9eea34/source/monodroid/src/Mono.Android/platforms/android-12/src/generated/Android.Content.ContextWrapper.cs:2318
06-28 07:17:55.843 I/MonoDroid(  860): at Inspections.Activity1.<checkdate>b__8 (object,Android.Content.DialogClickEventArgs) [0x00031] in f:\aa\c#\android\Inspections\Activity1.cs:519
06-28 07:17:55.843 I/MonoDroid(  860): at Android.Content.IDialogInterfaceOnClickListenerInvoker.n_OnClick_Landroid_content_DialogInterface_I (intptr,intptr,intptr,int) [0x00010] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.7-branch/0e9eea34/source/monodroid/src/Mono.Android/platforms/android-12/src/generated/Android.Content.IDialogInterface.cs:172
06-28 07:17:55.843 I/MonoDroid(  860): at (wrapper dynamic-method) object.0ae0dbc0-1a91-4175-9a2f-597c804b25ec (intptr,intptr,intptr,int) <IL 0x00018, 0x0003b>
06-28 07:17:55.843 I/MonoDroid(  860):
06-28 07:17:55.843 I/MonoDroid(  860):   --- End of managed exception stack trace ---
06-28 07:17:55.843 I/MonoDroid(  860): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=application/vnd.android.package-archive flg=0x10000000 }
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1580)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1431)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.Activity.startActivityForResult(Activity.java:3390)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.Activity.startActivityForResult(Activity.java:3351)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.Activity.startActivity(Activity.java:3561)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.Activity.startActivity(Activity.java:3529)
06-28 07:17:55.843 I/MonoDroid(  860):  at mono.android.content.DialogInterface_OnClickListenerImplementor.n_onClick(Native Method)
06-28 07:17:55.843 I/MonoDroid(  860):  at mono.android.content.DialogInterface_OnClickListenerImplementor.onClick(DialogInterface_OnClickListenerImplementor.java:29)
06-28 07:17:55.843 I/MonoDroid(  860):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.os.Looper.loop(Looper.java:137)
06-28 07:17:55.843 I/MonoDroid(  860):  at android.app.ActivityThread.main(ActivityThread.java:4867)
06-28 07:17:55.843 I/MonoDroid(  860):  at java.lang.reflect.Method.invokeNative(Native Method)
06-28 07:17:55.843 I/MonoDroid(  860):  at java.lang.reflect.Method.invoke(Method.java:511)
06-28 07:17:55.843 I/MonoDroid(  860):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
06-28 07:17:55.843 I/MonoDroid(  860):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
06-28 07:17:55.843 I/MonoDroid(  860):  at dalvik.system.NativeStart.main(Native Method)
06-28 07:17:55.873 W/dalvikvm(  860): JNI WARNING: JNI method called with exception pending
06-28 07:17:55.873 W/dalvikvm(  860):              in Lmono/android/content/DialogInterface_OnClickListenerImplementor;.n_onClick:(Landroid/content/DialogInterface;I)V (CallObjectMethod)
06-28 07:17:55.873 W/dalvikvm(  860): Pending exception is:
06-28 07:17:55.873 I/dalvikvm(  860): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=application/vnd.android.package-archive flg=0x10000000 }
06-28 07:17:55.873 I/dalvikvm(  860):   (raw stack trace not found)
06-28 07:17:55.873 I/dalvikvm(  860): "main" prio=5 tid=1 NATIVE
06-28 07:17:55.873 I/dalvikvm(  860):   | group="main" sCount=0 dsCount=0 obj=0x4127a508 self=0x41269450
06-28 07:17:55.873 I/dalvikvm(  860):   | sysTid=860 nice=0 sched=0/0 cgrp=[no-cpu-subsys] handle=1074679600
06-28 07:17:55.873 I/dalvikvm(  860):   | schedstat=( 3794555681 1447662333 6173 ) utm=289 stm=90 core=0
06-28 07:17:55.883 I/dalvikvm(  860):   #00  pc 00001260  /system/lib/libcorkscrew.so (unwind_backtrace_thread+27)
06-28 07:17:55.883 I/dalvikvm(  860):   #01  pc 0005f97c  /system/lib/libdvm.so (dvmDumpNativeStack(DebugOutputTarget const*, int)+35)
06-28 07:17:55.883 I/dalvikvm(  860):   #02  pc 00053824  /system/lib/libdvm.so (dvmDumpThreadEx(DebugOutputTarget const*, Thread*, bool)+303)
06-28 07:17:55.883 I/dalvikvm(  860):   #03  pc 000538be  /system/lib/libdvm.so (dvmDumpThread(Thread*, bool)+25)
06-28 07:17:55.883 I/dalvikvm(  860):   #04  pc 00038e7a  /system/lib/libdvm.so
06-28 07:17:55.883 I/dalvikvm(  860):   #05  pc 00040fd8  /system/lib/libdvm.so
06-28 07:17:55.883 I/dalvikvm(  860):   at mono.android.content.DialogInterface_OnClickListenerImplementor.n_onClick(Native Method)
06-28 07:17:55.883 I/dalvikvm(  860):   at mono.android.content.DialogInterface_OnClickListenerImplementor.onClick(DialogInterface_OnClickListenerImplementor.java:29)
06-28 07:17:55.883 I/dalvikvm(  860):   at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
06-28 07:17:55.883 I/dalvikvm(  860):   at android.os.Handler.dispatchMessage(Handler.java:99)
06-28 07:17:55.883 I/dalvikvm(  860):   at android.os.Looper.loop(Looper.java:137)
06-28 07:17:55.893 I/dalvikvm(  860):   at android.app.ActivityThread.main(ActivityThread.java:4867)
06-28 07:17:55.893 I/dalvikvm(  860):   at java.lang.reflect.Method.invokeNative(Native Method)
06-28 07:17:55.893 I/dalvikvm(  860):   at java.lang.reflect.Method.invoke(Method.java:511)
06-28 07:17:55.893 I/dalvikvm(  860):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
06-28 07:17:55.893 I/dalvikvm(  860):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
06-28 07:17:55.893 I/dalvikvm(  860):   at dalvik.system.NativeStart.main(Native Method)
06-28 07:17:55.893 I/dalvikvm(  860):
06-28 07:17:55.893 E/dalvikvm(  860): VM aborting
06-28 07:17:55.893 I/mono    (  860): Stacktrace:
06-28 07:17:55.893 I/mono    (  860):
06-28 07:17:55.893 I/mono    (  860):   at Android.Runtime.JNIEnv.CallObjectMethod (intptr,intptr) [0x00000] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.7-branch/0e9eea34/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:129
06-28 07:17:55.893 I/mono    (  860):   at Java.Lang.Throwable.get_Message () [0x0003e] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.2.7-branch/0e9eea34/source/monodroid/src/Mono.Android/platforms/android-12/src/generated/Java.Lang.Throwable.cs:175
06-28 07:17:55.893 I/mono    (  860):   at (wrapper runtime-invoke) <Module>.runtime_invoke_object__this__ (object,intptr,intptr,intptr) <IL 0x00050, 0xffffffff>

A: You need to start an activity with Intent parameters like this:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");

apkUri is a URI that points to your APK file.

A: Ok so I have found the Solution
System.IO.File.Delete("/sdcard/download/App_Name.apk"); //Delete previous version

.
cL.DownloadFile("http://www.Site.cc/Folder/App_Name.apk", "/sdcard/download/App_Name.apk");// Download new app via HttpWebRequest

new working code
Intent promptInstall = new Intent(Intent.ActionView).SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/download/" + "App_Name.apk")), "application/vnd.android.package-archive");
promptInstall.AddFlags(ActivityFlags.NewTask);
StartActivity(promptInstall);

Old not working code
Intent promptInstall = new Intent(Intent.ActionView).SetData(Android.Net.Uri.Parse("/sdcard/Download/App_Name.apk")).SetType("application/vnd.android.package-archive");
promptInstall.AddFlags(ActivityFlags.NewTask);
StartActivity(promptInstall);

newbie problem but its solved


text:
Q: Basic autofit feature impossible with DevExpress GridControl.View I have a DevExpress grid like this:
        <dxg:GridControl ItemsSource="{Binding CarsData}"
                         AutoPopulateColumns="True"
                         ScrollViewer.HorizontalScrollBarVisibility="Auto">
            <dxg:GridControl.View>
                <dxg:TableView Style="{StaticResource DxTableViewStyle}"/>
            </dxg:GridControl.View>
            <dxg:GridControl.Columns>
                <dxg:GridColumn Header="Car Name"  FieldName="CarName" ReadOnly="False" />
                <dxg:GridColumn Header="Brand Name" FieldName="BrandName" ReadOnly="True"/>
            </dxg:GridControl.Columns>
        </dxg:GridControl>

This grid is embeded into another container with a Fixed Width.
I would like to do something simpel but can't find how to do this, i.e.:

*

*Have the columns autofit their content and headers.

*If the columns get wider than the container of the grid, display a horizontal scroll bar

*For some columns, set a max width.

Here is my style that I can't get working like I want:
<Style TargetType="dxg:TableView" x:Key="DxTableViewStyle">
    <Setter Property="AllowBestFit" Value="True"/>
    <Setter Property="BestFitArea" Value="All"/>
    <Setter Property="BestFitMode" Value="VisibleRows"/>
    <Setter Property="AutoWidth" Value="False"/>
    <Setter Property="HorizontalScrollbarVisibility" Value="Auto"/>
</Style>

Thank you for your help!

A: Like @Sebi said in his comment, you should call the BestFitColumns on the GridView. I used to do it but now I avoid using it because it slows soooo much the loading of the grid, especially if you have an important set of data to show (it iterates through all the rows to find the best width for each column).
I recommend you to manually set the width of each column (the user can adjust the visible width if he wants to).
EDIT : Of course, if the total width of the GridView is larger than the GridControl's width, an horizontal scroll-bar will be automatically set to the veiw.


text:
Q: Why %DebugPrint doesn't print all information about my object? node --allow-natives-syntax test.js
var obj = {a: 1};
%DebugPrint(obj);

It will output:
0x053bedbc1399 <Object map = 0x53b630d1d51>
But in earlier versions of v8 it prints full information about object, something like:
0x337ab90027d9: [Map]
 - type: JS_ARRAY_TYPE
 - instance size: 32
 - inobject properties: 0
 - elements kind: PACKED_SMI_ELEMENTS
 - unused property fields: 0
 - enum length: invalid
 - back pointer: 0x337a1f6822e1 <undefined>
 - instance descriptors (own) #1: 0x337a3c307a69 <FixedArray[5]>
 - layout descriptor: 0x0
 - transitions #1: 0x337a3c307979 <TransitionArray[4]>Transition array #1:
     0x337a1f684631 <Symbol: (elements_transition_symbol)>: (transition to HOLEY_SMI_ELEMENTS) -> 0x337ab9002889 <Map(HOLEY_SMI_ELEMENTS)>

 - prototype: 0x337a3c307809 <JSArray[0]>
 - constructor: 0x337a3c304f21 <JSFunction Array (sfi = 0x337a1f6a9cb1)>
 - code cache: 0x337a1f682251 <FixedArray[0]>
 - dependent code: 0x337a1f682251 <FixedArray[0]>
 - construction counter: 0

A: This is a difference between Release and Debug builds, not between versions. In Release mode, most of the implementation of debug-printing is skipped (for binary-size reasons), so you'll only get one line of output. In Debug builds, you'll get the full details. This has not changed recently.


text:
Q: reloadData not triggering cellForRowAtIndexPath I have a UIViewController with one UITableView in it. The table view holds a list of favorites that can be changed by other parts of the app. I am using NSNotificationCenter to trigger the table view's reloadData method. The table view has an outlet declared as follows:
@property (strong,nonatomic) IBOutlet UITableView *faveTableView;

and synthesized as follows:
@synthesize faveTableView;

The delegate and datasource properties of the table view are set in the view controller's viewDidLoad as follows:
[self.faveTableView setDataSource:self];
[self.faveTableView setDelegate:self];

The NSNotificationCenter causes the following method to fire:
-(void)reloadNotificationReceived{
    [self loadData];
    [self.faveTableView reloadData];
}

loadData updates the data source which is NSMutableArray of managed objects and is working as it should.
When the view controller loads, cellForRowAtIndexPath is fired as it should be. However, when the notification is received, reloadNotificationReceived is fired and two of the table view delegate methods (numberOfRowsInSection and numberOfSectionsInTableView) ARE fired. However, cellForRowAtIndexPath is NOT fired. numberOfRowsInSection IS returning the correct number of items.
Can anyone offer up a reason why cellForRowAtIndexPath does not get fired here? Thanks!

A: The number of rows you are returning is 0.

A: Perhaps you have set the delegate/datasource of the tableview to your controller in the storyboard/xib, but you haven't wired up the "faveTableView" tableview  IBOutlet of the the controller... If the del/datasource are set, then the it will successfully get data from the controller, but without the IBOutlet being set, the self.faveTableView will remain nil and hence [self.faveTableView reloadData] won't do anything. Put a breakpoint in your viewDidLoad and check whether the self.faveTableView is not nil...


text:
Q: Specify a covariance matrix I'm trying to replicate the analysis presented on the bottenada.se and described in the ADA repository. Although the demo file is quite detailed, I didn't grasp where those values for the "C0" component come from. I would like to try other m0 combinations, but I couldn't understand how can I generate C0 values to fill in the model. The help file says:
"You need to define your prior for the election in two steps. First give your best estimates where you believe the election will end. Then you need to specify this as a covariance matrix. In Ada we specify our priors the following way (as of august 9)."
 priors2014$m0 <- c(0.227, 0.0665, 0.0645, 0.0595, 0.353, 0.08, 0.08, 0.081)
    priors2014$C0 <- diag(c(0.001024, 0.000144, 0.000144, 0.000144, 0.001024, 0.000625,
    0.000625, 0.000625))
colnames($)priors2014C0 <- rownames($)priors2014C0 <- names(priors2014$m0) <- c("M",
    "FP", "C", "KD", "S", "V", "MP", "SD")


text:
Q: DMZ forwarding on Cisco DPC/EPC2100 Cable Modem to Linksys Router for IP Cameras I have one of the old Cisco DPC/EPC2100 Cable Modems and wanted to know if anyone has had any luck setting up DMZ on it?
Link to modem: http://www.cisco.com/web/consumer/support/modem_DPC2100.html
The modem's settings doesn't allow any config; all you can do is look at statuses eg. Signal strength, IP address, Up/Downstream frequency.
I need to DMZ the cable modem to a Linksys Router to get an IP camera to work. The IP Camera is connected to the Linksys Router.
Essentially, this is what I want to do.
 [Cable Modem] --DMZ--> [Linksys Router] --> [IP Cameras 1 & 2 & 3]
If I can save on buying another cable modem that would be great. I love to know if anyone knows a backdoor to this cable modem.
Many thanks.
WD


text:
Q: Is there a way to to make the iPhone 8 version look the same as the iPod touch one? I originally made an app that works on iPhones but I want it to work on a thinner iPod touch (I am using autolayout). I have an issue of the screen not completely being shown in the iPod touch version. It looks like this.

I have looked into size classes but the size classes for both models is the same. I'm wondering if there is a framework that can solve my issue or if there is an autolayout trick.