text:
Q: jQuery: Refreshing DIV before fading I'm a beginner in jQuery and I'm trying to get my fade between DIVs to work as I want. However, I'm running into problems. I want the script to completely refresh the content I'm loading dynamically into my DIV before it fades. This way I know the content displayed are current and I will avoid any flashes of the content because it's refreshed after the DIV has faded in.
Here is my code;
$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;
    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }
    var next = divs.eq(nextIndex);
    next.stop().fadeIn(3000, function() {
        $('#div1').load('div1.php');
        $('#div2').load('div2.php');
        $('#div3').load('div3.php');
        $('#div4').load('div4.php');
        $('#div5').load('div5.php');
        $(this).addClass('current');
    });
    current.stop().fadeOut(3500, function() {
        $(this).removeClass('current');
        setTimeout(fade, 60000);
    });
}
fade();
});

So how can I make the next DIV be refreshed BEFORE the fade into the next DIV?

A: In jQuery, fadeIn() works like this:
$('element').fadeIn(3000, function() {
    /* code to be executed AFTER the fade animation */
})

It is the same for $.fadeOut();
So you need to insert all your content and only after that call the $.fadeIn(3000); method.
It should look something along these lines:
HTML:

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Content 1

Javascript:
$(document).ready(function () {
    var divs = $('.fade');

    setInterval(fade, 5000);

    function fade() {

        var current = $('.current');

        var currentIndex = divs.index(current);

        var next = $(divs[currentIndex + 1]);

        current.removeClass('current');
        next.addClass('current');

        $(current).fadeOut(1000, function () {
            $(this).children('#div1').load('div1.php');
            $(this).children('#div2').load('div2.php');
            $(this).children('#div3').load('div3.php!');
            $(this).children('#div4').load('div4.php');
            $(this).children('#div5').load('div5.php', function () {
                $(this).parent().fadeIn(1000);
            });
        });
    }
});

Tested this on my Chrome browser. It cycles and updates every div one by one every 5 seconds.
Here's a new JSFiddle: LINK
If this is not exactly what you need, you can work your way from there :)


text:
Q: How do I go about putting the returnCharacterStats function as a method in Preset? Frankly, I have no idea what I am doing and trying to learn Python without a teacher has been the equivalent of banging my head into my desk multiple times hoping that eventually it will result in the code magically working. I need to know how I go about moving returnCharacterStats into Preset as a method, or better yet, if you could work out a way I could make the method by not having to call a bunch of functions within a method that would be great. I tried just putting it into Preset as a method as well as calling the function by doing
instantiateCharacter=Preset() then
instantiateCharacter.returnCharacterStats()
but the console went
TypeError: __init__() missing 1 required positional argument: 'creature'
pls help before I lose my sanity. A thorough explanation would be appreciated because I'll just dig a bigger ditch for myself if I copy paste a kind person's code without understanding what they did.
def getName():
 syllables = ['en','da','fu','ka','re','toh','ko','noh','tuk','el','kar']
 firstName = (random.choice(syllables))
 secondName = (random.choice(syllables))
 thirdName = (random.choice(syllables))
 return firstName+'-'+secondName+'-'+thirdName

class Preset():
 def __init__(self, creature, health=100):
     self.health = 100
     self.name = getName()

#Gives different attributes to each sub-class
class Barbarian(Preset):
 def __init__(self, power=70, specialAttackPower=20, speed=50, creature="barbarian"):
     super().__init__(creature, 100)
     self.power = power
     self.specialAttackPower = specialAttackPower
     self.speed = speed

 def returnBarbarianStats(self):
     print(self.name,"the barbarian's stats:")
     print("Health:",self.health)
     print("Power damage:",self.power)
     print("Special attack power damage:",self.specialAttackPower)
     print("Speed:",self.speed)

class Elf(Preset):
 def __init__(self, power=70, specialAttackPower=20, speed=50, creature="elf"):
     super().__init__(creature, 100)
     self.power = power
     self.specialAttackPower = specialAttackPower
     self.speed = speed

 def returnElfStats(self):
     print(self.name,"the elf's stats:")
     print("Health:",self.health)
     print("Power damage:",self.power)
     print("Special attack power damage:",self.specialAttackPower)
     print("Speed:",self.speed)

class Wizard(Preset):
 def __init__(self, power=70, specialAttackPower=20, speed=50, creature="wizard"):
     super().__init__(creature, 100)
     self.power = power
     self.specialAttackPower = specialAttackPower
     self.speed = speed

 def returnWizardStats(self):
     print(self.name,"the wizard's stats:")
     print("Health:",self.health)
     print("Power damage:",self.power)
     print("Special attack power damage:",self.specialAttackPower)
     print("Speed:",self.speed)

class Dragon(Preset):
 def __init__(self, power=70, specialAttackPower=20, speed=50, creature="dragon"):
     super().__init__(creature, 100)
     self.power = power
     self.specialAttackPower = specialAttackPower
     self.speed = speed

 def returnDragonStats(self):
     print(self.name,"the dragon's stats:")
     print("Health:",self.health)
     print("Power damage:",self.power)
     print("Special attack power damage:",self.specialAttackPower)
     print("Speed:",self.speed)

class Knight(Preset):
 def __init__(self, power=70, specialAttackPower=20, speed=50, creature="knight"):
     super().__init__(creature, 100)
     self.power = power
     self.specialAttackPower = specialAttackPower
     self.speed = speed

 def returnKnightStats(self):
     print(self.name,"the knight's stats:")
     print("Health:",self.health)
     print("Power damage:",self.power)
     print("Special attack power damage:",self.specialAttackPower)
     print("Speed:",self.speed)

#10 randomly generated characters.
i = 0
army = []
while i < 10:
 creatures = ['barbarian','elf','wizard','dragon','knight']
 creatureType = (random.choice(creatures))
 if creatureType == 'barbarian':
     army.append(Barbarian())
 elif creatureType == 'elf':
     army.append(Elf())
 elif creatureType == 'wizard':
     army.append(Wizard())
 elif creatureType == 'dragon':
     army.append(Dragon())
 elif creatureType == 'knight':
     army.append(Knight())
 i = i + 1
#I need to turn this into a method, or alternatively, simplify this code so this is replaced by a method that
#serves the same function but doesn't need the seperate functions within the subclasses.
def returnCharacterStats():
    instantiateBarbarian=Barbarian()
    instantiateBarbarian.returnBarbarianStats()

    instantiateElf=Elf()
    instantiateElf.returnElfStats()

    instantiateWizard=Wizard()
    instantiateWizard.returnWizardStats()

    instantiateDragon=Dragon()
    instantiateDragon.returnDragonStats()

    instantiateKnight=Knight()
    instantiateKnight.returnKnightStats()

returnCharacterStats()

A: You are not using the best OOP concepts here, your problem is that you are not making use of polymorphism. Replace returnCharacterStats() with this one:
def returnCharacterStats():
    for solider in army:
        solider.returnStats()

Now change all stats returning function names to this returnStats().
You are not realizing that you just have to ask the solider that please show me your stats right, it is duty of the solider to return his stats and not some other solider's stats. You don't have to name like returnBarbarianStats(), returnElfStats() etc, just name them returnStats()
Your object will return his stats not someone else's. I hope it is clear and detailed as you asked. I replaced your 15 lines into 2

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to create a nested dictionary of list I have a dictionary like this:
mydic = {
  0: [('comp.sys.mac.hardware_51563', 0.31), ('rec.motorcycles_103140', 0.29), ('alt.atheism_54143', 0.27), ('misc.forsale_76672', 0.26), ('rec.motorcycles_104809', 0.26)],
  1: [('alt.atheism_54143', 0.31), ('comp.sys.mac.hardware_51563', 0.30), ('rec.motorcycles_104885', 0.30), ('talk.religion.misc_84064', 0.28), ('rec.sport.baseball_104619', 0.27)],
  2: [('alt.atheism_54143', 0.29), ('talk.religion.misc_84064', 0.29), ('rec.sport.hockey_53859', 0.26), ('sci.electronics_54162', 0.25), ('comp.sys.mac.hardware_52124', 0.25)]
}

What I want to do is to cut the digits in the last part of string and then count the frequency of them per key. However I need to keep the order of them as well to have the result like this:
{
  0: {'comp.sys.mac.hardware': [1, 1], 'rec.motorcycles': [2,2], 'alt.atheism': [1,3], 'misc.forsale': [1, 4]},
  1: {'alt.atheism': [1,1], 'comp.sys.mac.hardware': [1,2], 'rec.motorcycles': [1,3], 'talk.religion.misc': [1,4], 'rec.sport.baseball': [1,5]},
  2: {'alt.atheism': [1,1], 'talk.religion.misc': [1,2], 'rec.sport.hockey': [1,3], 'sci.electronics': [1,4], 'comp.sys.mac.hardware': [1,5]}
}

here 'comp.sys.mac.hardware': [1, 1] means comp.sys.mac.hardware has frequency 1 and is the first thing in the initial list. Or 'alt.atheism': [1,3] means has been repeated 1 time and is the third item in the original list.
I have worked on this and so far have come up with a result using the code below. My problem is that I cannot include the order in the dictionary, :
{
  0: {'comp.sys.mac.hardware': 1, 'rec.motorcycles': 2, 'alt.atheism': 1, 'misc.forsale': 1},
  1: {'alt.atheism': 1, 'comp.sys.mac.hardware': 1, 'rec.motorcycles': 1, 'talk.religion.misc': 1, 'rec.sport.baseball': 1},
  2: {'alt.atheism': 1, 'talk.religion.misc': 1, 'rec.sport.hockey': 1, 'sci.electronics': 1, 'comp.sys.mac.hardware': 1}
}

freq_dic = collections.defaultdict(dict)
for k, va in mydic.items():
    lst = []
    for m in va:
        el = m[0].split('_')[0]
        if el in freq_dic[k]:
            freq_dic[k][el] = freq_dic[k][el] + 1
        else:
            freq_dic[k][el] = 1

A: You need only to augment your iteration, and you will have order available within the loop.
for order, m in enumerate(va,1):
    el = m[0].split('_')[0]
    if el in freq_dic[k]:
        freq_dic[k][el][0] += 1
    else:
        freq_dic[k][el] = [1, order]


text:
Q: ¿Cómo mostrar aleatoriamente la comida en el juego de snake c#? using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace snake
{

    class Program
    {

        static void Main(string[] args)
        {

            int x, y;
            x = 1;
            y = 1;

            string direccion = "E";

            Console.CursorVisible = false;

            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\n\n\n\n\n\n\n\n\n\n                     presiona enter");

                System.Console.ReadLine();
                for (; ; )
                {

                    switch (direccion)
                    {
                        case "S":
                            y++;
                            break;
                        case "N":
                            y--;
                            break;
                        case "E":
                            x++;
                            break;
                        case "O":
                            x--;
                            break;
                    }
                    Console.Clear();
                    Console.SetCursorPosition(x, y);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("o");

                    Thread.Sleep(90);

                    if (Console.KeyAvailable)
                    {
                        ConsoleKey key = Console.ReadKey(true).Key;
                        switch (key)
                        {
                            case ConsoleKey.DownArrow:
                                if ((direccion == "E") || (direccion == "O"))
                                    direccion = "S";
                                break;
                            case ConsoleKey.LeftArrow:
                                if ((direccion == "N") || (direccion == "S"))
                                    direccion = "O";
                                break;
                            case ConsoleKey.RightArrow:
                                if ((direccion == "N") || (direccion == "S"))
                                    direccion = "E";
                                break;
                            case ConsoleKey.UpArrow:
                                if ((direccion == "E") || (direccion == "O"))
                                    direccion = "N";
                                break;
                        }//fin del switch(key)
                    }//fin del if (console.readkeyAvailable)
                }
            }
            catch (Exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("\n\n\n\n\n\n\n\n\n\n                                     Game over");
                Console.ReadKey();
            }

        }

    }
}

A: Puedes utilizar un objeto Random para calcular de forma aleatoria la posición de la comida. Ten en cuenta que habría que evitar las posiciones ocupadas por la serpiente.
Deberías calcular una nueva posición para la comida cada vez que la posición de la cabeza de la serpiente y de la comida coincidan:
namespace snake
{
    struct Position
    {
        public Position(int x, int y)
        {
            X = x;
            Y = y;
        }

        public int X;
        public int Y;

        public static Position Empty => new Position(-1, -1);
    }
    class Program
    {
        static void Main(string[] args)
        {

            int x, y;
            x = 1;
            y = 1;

            Position foodPosition = Position.Empty;
            Random rnd = new Random();

            string direccion = "E";

            Console.CursorVisible = false;

            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("\n\n\n\n\n\n\n\n\n\n                     presiona enter");

                System.Console.ReadLine();
                for (;;)
                {

                    switch (direccion)
                    {
                        case "S":
                            y++;
                            break;
                        case "N":
                            y--;
                            break;
                        case "E":
                            x++;
                            break;
                        case "O":
                            x--;
                            break;
                    }

                    if (x == foodPosition.X && y == foodPosition.Y
                        || foodPosition.Equals(Position.Empty))
                    {
                        do
                        {
                            foodPosition = new Position(rnd.Next(0, Console.WindowWidth - 1), rnd.Next(0, Console.WindowHeight - 2));
                        } while (foodPosition.X == x && foodPosition.Y == y);
                    }

                    Console.Clear();
                    Console.SetCursorPosition(foodPosition.X, foodPosition.Y);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("x");
                    Console.SetCursorPosition(x, y);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("o");

                    Thread.Sleep(90);

                    if (Console.KeyAvailable)
                    {
                        ConsoleKey key = Console.ReadKey(true).Key;
                        switch (key)
                        {
                            case ConsoleKey.DownArrow:
                                if ((direccion == "E") || (direccion == "O"))
                                    direccion = "S";
                                break;
                            case ConsoleKey.LeftArrow:
                                if ((direccion == "N") || (direccion == "S"))
                                    direccion = "O";
                                break;
                            case ConsoleKey.RightArrow:
                                if ((direccion == "N") || (direccion == "S"))
                                    direccion = "E";
                                break;
                            case ConsoleKey.UpArrow:
                                if ((direccion == "E") || (direccion == "O"))
                                    direccion = "N";
                                break;
                        }//fin del switch(key)
                    }//fin del if (console.readkeyAvailable)
                }
            }
            catch (Exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("\n\n\n\n\n\n\n\n\n\n                                     Game over");
                Console.ReadKey();
            }

        }

    }
}


text:
Q: How can I improve the performance of Wrap Widget with multiple child? When I move from tabs in the UI it's takes too long to load the chips under the tabs.
I've used the AutomaticKeepAliveClientMixin<> but it broke my Scrollbar and still takes time to load large Chips children from the Wrap Widget. What I would need is a Wrap.builder() but doesn't exist. Is there something I can do to optimize the code to load smoothly?
I have an interactive sample code of the current problem:
https://dartpad.dev/009e9ccae07175074cb77d7792c3692b
Try moving the tabs left to right in the sample to see the performance issue.
If it can't be fixed, I wonder if I can detect when the widget is rendering to show a circular progress indicator while switching tabs.
Any Ideas?
Thanks

A: Technically the idea of Wrap.builder wouldn't be a solution here because the issue persists even when all the items are in the displayed (nothing to display on demand)
You can make the swiping experience better by delaying the rendering of the tab content until after the swiping animation is done

class _ChipsContentState extends State<ChipsContent> {
  bool visible = false;
  final List<String> _filters = <String>[];

  @override
  void initState() {
    super.initState();
    Future.delayed(kTabScrollDuration).then((value) {
      if (mounted) {
        setState(() => visible = true);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!visible) {
      return Center(child: CircularProgressIndicator());
    }
    return ListView(
      children: [
        if (visible)
          Wrap(
            spacing: 8.0,
            children: widget.chipData.map((chipName) => ChipFilter(chipName: chipName, filter: _filters)).toList(),
          ),
      ],
    );
  }
}

A: A Wrap.builder() is indeed missing from Flutter. A GitHub issue was opened about this but then closed without a satisfying solution.
I can think of a few workarounds, like using a swiper/carousel, a GridView.builder(), or a List.builder() with Rows inside it. Of course, they're far from being as convenient as a Wrap in this case.

A: Try Changing your filterChips and "build" methods as follows,
List<Widget> get filterChips {
    List<Widget> widgets = [];
    for (final chipName in widget.chipData) {
       widgets.add(ChipFilter(chipName: chipName, filter: _filters));
    }
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    // super.build(context);
    return Scrollbar(
           child: SingleChildScrollView(
          child: Wrap(//IS THERE A Wrap.builder()? OR ALTERNATIVE TO DESIRED LAYOUT?
            spacing: 8.0,
            children: filterChips,
          ),),
    );

}


text:
Q: Excel AddIn - Keeping windows form always visible while w/in Excel First of all, thank you for your time and assistance in reviewing this!...
I'm trying to upgrade an Excel VBA workbook to a VSTO Excel Add-in in VB.NET using VS 2010. In the original (i.e.- VBA) version I have a modeless UserForm (called frmMain) that floats on top and is visible at all times while the user is still within the Excel application, but is not visible if the user moves to another window outside of Excel.
For example, within Excel the user can click on any worksheet tab, select any cell, etc. and the UserForm is still visible. This is exactly how I'd like it.
The problem is, that in the new VSTO add-in, I can not get the Windows form to mimic this same behavior.
I use frmMain.Show() to show the form as a modeless form, but the moment the user clicks an Excel worksheet (i.e.- activates a worksheet) the form becomes hidden behind the worksheet.
I can manually Alt-Tab to bring the form back into view, but I need it to always remain in view - floating on top of the Excel worksheets so long as the user hasn't left the Excel application.
I tried various things, including setting the form to TopMost, however, that causes the form to be TopMost everywhere - including outside of Excel. Worse than that, if the user does anything that would normally result in Excel's launching a dialog box (e.g.- closing an open workbook, raising the alert "Do you want to save the changes...") the alert dialog box itself is hidden and inaccessible behind the frmMain form (since the frmMain is TopMost).
How can I get my form to behave in the desired way (i.e.- the same way it did in VBA)?
Thanks!!!
Rob

A: You should take a look at Custom Task Panes which can be docked or floated within the Excel application. You could also look into the COM interfaces for a lower level connection (see related SO Post) - although Task Panes are really what this type of behavior was intended for.

A: This method might work (worked for me):

*

*Create a worksheet_selectionChange event handler inside your form class

*Put these lines in this event handler:
 Dim FormHandle As IntPtr = Me.Handle
 Me.Visible = False
 Me.Show(NativeWindow.FromHandle(FormHandle))


text:
Q: Insert data into database using Javascript in OpenERP POS module currently I'm modifying point of sale module in OpenERP 7.
I want to insert data into my new model(ex: res.cashier),
but I don't understand how to do it at all as I have no experience in javascript,
as far as I know it use Backbone.JS to connect into database.
please guide me by giving me an example or explanation,
any help will be greatly appreciated..

A: figured it out myself,
I'm wrong to think that JS directly access the database,
instead it call python function first and then execute the insert,here's the example:
self.$('#insertcashier').click(function(){
    (new instance.web.Model('res.cashier')).call('cashier_funct',[[param]],undefined,{ shadow:true })
                .fail(function(unused, event){
                    event.preventDefault();
                    console.error('Failed');
                })
                .done(function(){
                    console.info('success');
                });
            });


text:
Q: How to create a child attribute table in doctrine 2? How can I create a child attribute table through doctrine 2 (basically like a join table but without an entity on the other side).  Do I need to make a separate entity for it (I know if I do a ManyToMany with a join table it'll just create the join table in the db but does not create an Entity).
i.e.- I have work orders that can have a bunch of assigned work dates.  I want to be able to fill a table with those dates so
______________________
|      Orders        |
|____________________|
        id
         1
         2
         3
______________________
|     Order_Dates    |
|____________________|
order_id |   Date
   1     | 2019-01-01
   1     | 2019-05-01
   2     | 2019-01-01
   2     | 2019-02-01
   2     | 2019-03-01
   3     | 2019-01-02
   3     | 2019-01-05

So basically so far I have
class Orders
{
    public function __construct()
    {
        $this->dates = new ArrayCollection();
    }

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * One Order has Many Dates
     */
    private $dates;

    public function getDates() : ArrayCollection
    {
        return $this->dates;
    }

    public function addDate(\DateTime $date): self
    {
        $this->dates->add($date);

        return $this;
    }

    public function setDates(ArrayCollection $dates): self
    {
        $this->dates = $dates;

        return $this;
    }
}

I assume I need a @OneToMany or something but against I'm expecting the child table to be FILLED FROM the Order Entity, not a mapping.  Everything I look in the doctrine association documentation at here seems to expect some sort of mapping (perhaps I'm reading it wrong?)
Thanks in advance!
Edit:
This is my controllers now:
Orders
    /**
     * @ORM\OneToMany(targetEntity="OrderDates", mappedBy="order", cascade={"persist", "remove"}, orphanRemoval=TRUE)
     */
    private $dates;

...

    public function getDates() : PersistentCollection
    {
        return $this->dates;
    }

    public function addDate(\DateTime $date): self
    {
        $orderDate = new OrderDates();
        $orderDate->setDate($date);
        $orderDate->setOrder($this);
        $this->dates[] = $orderDate;

        return $this;
    }

    public function setDates(array $dates): self
    {
        foreach($dates as $date)
        {
            $this->addDate(new \DateTime($date));
        }

        return $this;
    }

OrderDates

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\OrderDatesRepository")
 */
class OrderDates
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="datetime")
     */
    private $date;

    /**
     * @ORM\ManyToOne(targetEntity="Orders", inversedBy="dates")
     */
    private $order;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getDate(): ?\DateTimeInterface
    {
        return $this->date;
    }

    public function setDate(\DateTimeInterface $date): self
    {
        $this->date = $date;

        return $this;
    }

    public function getOrder(): Orders
    {
        return $this->order;
    }

    public function setOrder(Orders $order): self
    {
        $this->order = $order;

        return $this;
    }
}

A: You have to create an entity for Order_Dates and use OneToMany annotation if you want an extra database table to be created for order dates. Doctrine does not support associations between entities handled by Doctrine and entities handled by another driver. Doctrine doesn't even support associations between entities handled by different entity managers.
To sum it up: You have to create a OrderDates entity and setup the association the traditional way.
EDIT: You should set up your association like this:
class Orders {
    // id and other fields here...
    /**
     * @ORM\OneToMany(targetEntity="OrderDates", mappedBy="order", cascade={"persist", "remove"}, orphanRemoval=TRUE)
     */
    private $dates;

    public function addDate(\DateTime $date): self
    {
        $orderDate = new OrderDates();
        $orderDate->setDate($date);
        $orderDate->setOrder($this);
        $this->dates[] = $orderDate;

        return $this;
    }
}

class OrderDates {
    // id here...
    /**
     * @ORM\ManyToOne(targetEntity="Order", inversedBy="dates")
     */
    private $order;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime")
     */
    private $date;
    // setters and getters here
}


text:
Q: Passport auth stuck in controller? I tried forwarding my routes to controllers, but it doesn't seem to work for me with Passport.js
router.get('/login', (req, res, next) => UserController.getLogin(req, res, next));
router.post('/login', (req, res, next) => UserController.postLogin(req, res, next));

Now, the only routes that don't work are specifically the ones with Passport.
static getLogin(req: Request, res: Response, next: NextFunction) {
...
}
static postLogin(req: Request, res: Response, next: NextFunction) {

        passport.authenticate('local', {
            successRedirect: '/success',
            failureRedirect: '/failed'
        });
        // res.send('hello from POST'); would work
}

I'm using TypeScript

A: Passport is asynchronous. It's often used as a middleware that is passed a callback. e.g., the docs have this example:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                failureRedirect: '/login' }));

The thing to remember here is that passport.authenticate returns a function that accepts (req, res, next). It then acts on that data and calls next when it's done.  In your code you are calling authenticate (returns a function) and then doing nothing with it.  I have a few suggestions.
The first is reducing noise by simplifying things. Depending on the framework you can usually pass a stack of functions to handle a route. In this case you only need one.
router.post('/login', passport.authenticate('local', {
    successRedirect: '/success',
    failureRedirect: '/failed'
}))

If you wanted to do more than just the auth you could pass more functions.
router.post('/login',
    passport.authenticate('local', {
        successRedirect: '/success',
        failureRedirect: '/failed'
    }),
    UserController.doThing // accepts (req, res, next)
)

You'll notice I didn't create an anonymous function to pass the same 3 params through to the controller. It's not necessary. For most purposes they are the same.


text:
Q: Unable to cast object of type ,Drawing Item How to fix problem follow :
when I drawItem, then get message error:
"Unable to cast object of type 'System.Collections.Generic.List`1[mypro.InfoDialog+Mycontact]' to type 'Mycontact'."
C# code at line number:
public class Mycontact
{
        public string P_DISPLAY_NAME    { get; set; }
        public string P_AVAILABILITY    { get; set; }
        public string P_AVATAR_IMAGE    { get; set; }
}

Mycontact fbContact;

private void AddDataToList()
{
    var fbList = new List<Mycontact>();
    foreach (dynamic item in result.data)
    {
        fbContact = new Mycontact() { P_DISPLAY_NAME = (string)item["name"], P_AVAILABILITY = (string)item["online_presence"]};
        fbList.Add(fbContact);
        listBox1.Items.Add(fbList);
    }
}

private int mouseIndex = -1;

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{

    if (e.Index == -1) return;

    line number:
    Mycontact contact = (Mycontact)listBox1.Items[e.Index];

    Brush textBrush = SystemBrushes.WindowText;
        if (e.Index > -1)
        {
            // Drawing the frame
            if (e.Index == mouseIndex)
            {
                e.Graphics.FillRectangle(SystemBrushes.HotTrack, e.Bounds);
                textBrush = SystemBrushes.HighlightText;
            }
            else
            {
                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                {
                    e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
                    textBrush = SystemBrushes.HighlightText;
                }else{
                    e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
                }
                // Drawing the text
                e.Graphics.DrawString(contact.P_DISPLAY_NAME, e.Font, textBrush,    e.Bounds.Left + 20, e.Bounds.Top);
            }
        }
}

A: It seems the whole listed is added to listbox1 instead of a single item (listBox1.Items.Add(fbList))
Shouldn't it be:
listBox1.Items.Add(fbContact);

Alternatively, you could set listBox1.DataSource = fbList after the loop

A: You are adding the full list to the listbox as a single item:
listBox1.Items.Add(fbList);
So the line
(Mycontact)listBox1.Items[e.Index];
Returns a list of MyContact objects instead of a single MyContact object.
So to fix it you could just add contact per contact to the list like this
listBox1.Items.Add(fbContact);


text:
Q: How can I pass a variable to an event that isn't a class instance? I have an Event that I fire when someone favourites an entity on my system.  This is fired using Event::fire(new AddedAsFav($entity_id));.
In that event I want to pull some info about that $entity_id.  To do this I believe I need to pass the $entity_id as part of the constructor of my Listener and then I can access it.  Unfortunately the constructor expects a type, and I can't seem to pass just an integer.  The docs have lots of examples where they pass Eloquent ORM instances, which is prefixed with the name of the class (Entity $entity, for example).  But I don't want to pass a full object, just an ID, as the controller it's coming from only has an ID.  I'd rather do the query (which is expensive and time consuming, hence the event) in the event itself.
So how can I pass and access a basic int?
Here's my listener:
<?php

namespace App\Listeners;

use App\Events\AddedAsFav;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class GetFullEntity
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(int $entity_id)
    {
        $this->entity_id = $entity_id;
    }

    /**
     * Handle the event.
     *
     * @param  MovieAddedAsToWatch  $event
     * @return void
     */
    public function handle(AddedAsFav $event)
    {
        dd($event);
    }
}

A: If you will have public $entity_id in you Event file, then you will be able to get that value in Listener's handle method like so: $event->entity_id.

A: You only type cast something you may want to use in the listener.
if you want to simply access the data/object/array you passed to the event class, assign it to a public property in the event class:
class AddedAsFav extends Event
{

    public $entity_id;

    public function __construct($entity_id)
    {

        $this->entity_id = $entity_id;

    }
}

You can now access it in your listener like any property:
<?php

namespace App\Listeners;

use App\Events\AddedAsFav;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class GetFullEntity
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Handle the event.
     *
     * @param  MovieAddedAsToWatch  $event
     * @return void
     */
    public function handle(AddedAsFav $event)
    {
        $entity_id = $event->entity_id;
    }
}


text:
Q: How to implement GradCam on the trained model and plot scatterplot of the images I am trying to visualize the last layer of the model and the input image is of shape (1024 , 1024). I want to save the images of the grad-cam and then view these images on a scatter plot. I have trained the model and trying to refer this link for the task to be completed How to implement Grad-CAM on a trained network
Predictions on the image :
image = cv2.imread('/content/drive/MyDrive/updated_images/test/SampleImages/bellingham10.jpg')
image = cv2.resize(image, (1024, 1024))
image = image.astype('float32') / 255
image = np.expand_dims(image, axis=0)

preds = reconstructed_model.predict(image)
i = np.argmax(preds[0])
icam = GradCAM(reconstructed_model, i, 'conv2d_18')
heatmap = icam.compute_heatmap(image)
heatmap = cv2.resize(heatmap, (1024, 1024))

image = cv2.imread('/content/drive/MyDrive/updated_images/test/SampleImages/bellingham1-0.jpg')
image = cv2.resize(image, (1024, 1024))
print(heatmap.shape, image.shape)

(heatmap, output) = icam.overlay_heatmap(heatmap, image, alpha=0.5)

Screenshot of the Error that I am unable to fix:

Code of the function where it is failing :
  def compute_heatmap(self, image, eps=1e-8):
        # construct our gradient model by supplying (1) the inputs
        # to our pre-trained model, (2) the output of the (presumably)
        # final 4D layer in the network, and (3) the output of the
        # softmax activations from the model
        gradModel = Model(
            inputs=[self.model.inputs],
            outputs=[self.model.get_layer(self.layerName).output, self.model.output])

        # record operations for automatic differentiation
        with tf.GradientTape() as tape:
            # cast the image tensor to a float-32 data type, pass the
            # image through the gradient model, and grab the loss
            # associated with the specific class index
            inputs = tf.cast(image, tf.float32)
            (convOutputs, predictions) = gradModel(inputs)

            loss = predictions[:, tf.argmax(predictions[0])]

        # use automatic differentiation to compute the gradients
        grads = tape.gradient(loss, convOutputs)

        # compute the guided gradients
        castConvOutputs = tf.cast(convOutputs > 0, "float32")
        castGrads = tf.cast(grads > 0, "float32")
        guidedGrads = castConvOutputs * castGrads * grads
        # the convolution and guided gradients have a batch dimension
        # (which we don't need) so let's grab the volume itself and
        # discard the batch
        convOutputs = convOutputs[0]
        guidedGrads = guidedGrads[0]

        # compute the average of the gradient values, and using them
        # as weights, compute the ponderation of the filters with
        # respect to the weights
        weights = tf.reduce_mean(guidedGrads, axis=(0, 1))
        cam = tf.reduce_sum(tf.multiply(weights, convOutputs), axis=-1)

        # grab the spatial dimensions of the input image and resize
        # the output class activation map to match the input image
        # dimensions
        (w, h) = (image.shape[2], image.shape[1])
        heatmap = cv2.resize(cam.numpy(), (w, h))
        # normalize the heatmap such that all values lie in the range
        # [0, 1], scale the resulting values to the range [0, 255],
        # and then convert to an unsigned 8-bit integer
        numer = heatmap - np.min(heatmap)
        denom = (heatmap.max() - heatmap.min()) + eps
        heatmap = numer / denom
        heatmap = (heatmap * 255).astype("uint8")
        # return the resulting heatmap to the calling function
        return heatmap

Model Summary :


text:
Q: How to pass a list/array as argument to python fire? I have function like this -
def my_func(my_list_arg=["one", "two"]):

Which I'm trying to call from command line using python-fire.
I have tried several ways -

Attempt 1:
fire_runner.py my_func [one, two]

Results in two separate arguments "[one" and "two]".

Attempt 2:
fire_runner.py my_func ["one", "two"]

which has the same result.

Attempt 3:
fire_runner.py my_func [\"one\", \"two\"]

same result.

A: Adding this answer just for a special case.
given that your function is like this:
def my_func(dates: List[str] = []):
    ...

In case you need to send list of dates (or any combination of numbers and characters) from the CLI, the following WON'T work.
fire_runner.py my_func --dates 2021-09-20,
fire_runner.py my_func --dates "[2021-09-20]"
fire_runner.py my_func --dates [2021-09-20]

In all the above cases, dates will be read as one string instead of list of strings. For proper reading of list of strings you can use the following.
fire_runner.py my_func --dates "[\"2021-09-20\"]"
fire_runner.py my_func --dates "[\"2021-09-20\", \"2021-09-76\"]"

A: Fire converts a comma-separated digit string to tuple as follows:
fire_runner.py my_func  1,2,3

and for a comma-separated string you can use:
fire_runner.py my_func  \'2021-2\',\'20212-3\',\'2023-4\'

A: Not keeping any space after the comma worked for me.
fire_runner.py my_func [one,two]

A: Adding a special corner case solution for one element lists, as the above syntaxes did not seem to work (list was parsed as a string starting with [ ):
fire_runner.py my_func "['one']"

A: Your list will first be parsed by the command line shell. This means you need to force it as a single argument. There are many ways to do this:

*

*No space: [one,two]

*Escape the space: [one,\ two]

*Quotes: "[one, two]".
Note that you could modify your function to take a list of arguments using the following syntax:
def my_func(*args):

The name args here is convention, but it is just a variable name, so it can be anything. This will allow you to call your function as
fire_runner.py my_func one two


text:
Q: Fetch invoices by user id in Eloquent ORM I want to fetch all invoices a user has raised using the Eloquent ORM.
At the moment, I'm fetching the invoice.id from a join table UsersInvoices by the user.id and then looping through and fetching the invoices from the Invoices table based on the id.
$user = Sentry::getUser();
$invoiceIDs = UsersInvoice::where('user_id', '=', $user->id)->get()->toArray();
$invoices = array();

foreach ($invoiceIDs as $key => $row) {
    array_push($invoices, Invoice::find($row['invoice_id']));
}

$this->data['title'] = 'Invoices';
$this->data['invoices'] = $invoices;

/** render the template */
App::render('@invoices/pending/index.twig', $this->data);

But I think this could/should be handled by the ORM by modelling the relationship between user and invoices.
It looks as though I should be able to manage this like so by simply posting the user.id into the invoices table as a foreign key - Maybe I don't need a join table as there is nothing that is unique to the relationship that needs to be stored... ?

A: Note: Posting from my phone. Sorry, I can't put code examples that way.
If I understand correctly, the relationships between Users and Invoices are
- User hasMany Invoice

- Invoice belongsTo User

If so then you'll need to set it up in the Eloquent models by defining the relationship and methods to get at the relayed data (at least in the User model). The Eloquent ORM expects there to be a user_id field in the invoices table.
Then you can do:
$user = User::find($id);

$user->invoices(); //assuming you put an invoices method in the User model

Or:
$invoice = Invoice::find($id);

$invoice->user(); //assuming you setup a user method in the Invoice model

More info on relationships here: http://laravel.com/docs/eloquent#relationships

A: It seems that you have stored the user_id and invoice_id in a separate table.
Simply keep user_id in the Invoices table and then use a single query to fetch all.
And also do not convert the results to array.
foreach( $invoices as $inv ) {
    echo $inv->invoice_id;
}


text:
Q: pyarrow.lib.ArrowNotImplementedError pyarrow version is 0.17.1
pandas version is 1.0.4
pyspark 2.3.4

I have a pyspark dataframe with 4 columns as shown below:
  A      B       C        D
-----  -----   -----    -----
  1      2       3      My Name is cat
  2      4       5      I like to code

I need to add another column 'prediction' to the dataframe based on the column 'D'. The model, which predicts, expects a pandas dataframe with single column as input and returns numpy array as output. So, I wrote a Scalar Pandas UDFs to implement it.
@pandas_udf(ArrayType(BooleanType()),PandasUDFType.SCALAR)
def t_func(pdf):
    predict=classifier.predict(pdf)[:,1]
    #Note: classifier.predict returns values as follows array([[0.706,0.293],[0.986,0.0713]])
    #Note: predict values would look like as follows array([0.293],[0.0713])
    #Note: type of predict is <class 'numpy.ndarray'>
    predictions = predict > decision_threshhold
    #Note: predictions values would look like as follows array([False,False])
    #Note: type of predictions is <class 'numpy.ndarray'>
    return pd.Series(predictions)

X = X.withColumn('prediction",t_func('D'))

Final output should look like as follows:
  A      B       C        D                 prediction
-----  -----   -----    -----               -------------
  1      2       3      My Name is cat     False
  2      4       5      I like to code      False

But, I get the following error and not sure what was the issue:

pyarrow.lib.ArrowNotImplementedError: NumPyConverter doesn't implement <list<item: bool>> conversion


text:
Q: countDownTimer isn't working, why? I have a service B that sends a specific number of messages in a fixed interval.
this service is called from another service A.
the code used in service A is
@Override
public void onStart (Intent intent,int startid)
{
    Toast.makeText(this, "Service A Running onStart", Toast.LENGTH_LONG).show();

    Thread MessagesThread = new Thread(new Runnable()
    {
        public void run()
        {
            ApplicationPreferences AppPrefs = new ApplicationPreferences(getApplicationContext());
            int NumberOfMessagesToSend = Integer.parseInt(AppPrefs.getNumberOfMessagesToSend());
            int NumberOfSentMessages;

            for (NumberOfSentMessages = 0 ; NumberOfSentMessages < NumberOfMessagesToSend; NumberOfSentMessages++ )
            {startServiceB();
             }
        }
    });
    MessagesThread.start();
}

public void startServiceB()
{
    final Intent sendingMessages = new Intent(this, ServiceB.class);
    startService(sendingMessages);
}

the toasts are to keep track of what is happening
The code in service B is as follow
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    Toast.makeText(getApplicationContext(), "Service B at start ", Toast.LENGTH_LONG).show();
    new CountDownTimer(30000,1000)
    {
        public void onTick (long millisUntilFinished) {}

        public void onFinish()
        {
            showToast();
        }
    }.start();
}

the showToast() function is as follow
public void showToast()
{
    Toast.makeText(getApplicationContext(), "Service B in timer", Toast.LENGTH_LONG).show();
}

As I said I am using the toasts to keep track of what's happening. the problem is when running it, i am getting the first toast (service B at start) 10 times consequently then the second one (service B in timer) 10 times consequently with no time between them.
how do i make each of this toasts appear once every 30 seconds?

A: If you want to make a toast every 30 seconds than you can do it by using a handler:
 Handler myHandler = new Handler();
Runnable run = new Runnable()
{
    public void run()
    {
        showToast();
    }
};
myHandler.postDelayed(run, 30000);

If you have problem with this just post here and I will try to help you..

A: Ok, so the final answer could be something like this:
Call only once the B service and in it we will have the handler that will loop at an interval of 30 seconds..
Service B code:
 int loop = 5;
    int counter = 0;
Handler myHandler;
Runnable run;

    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        Toast.makeText(getApplicationContext(), "Service B at start ", Toast.LENGTH_LONG).show();
        myHandler = new Handler();
        run = new Runnable()
        {
         public void run()
         {
          if (counter<loop){
           showToast();
           counter++;
          } else {
            myHandler.removeCallbacks(run);
          }
         }
       };
       myHandler.postDelayed(run, 30000);

    }

I hope this helps someone else too!


text:
Q: What's the quickest way to compute log2 of an integer in C#? How can I most efficiently count the number of bits required by an integer (log base 2) in C#?  For example:
int bits = 1 + log2(100);

=> bits == 7

A: You can simply count how many times you have to remove bits until the value is zero:
int bits = 0;
while (n > 0) {
  bits++;
  n >>= 1;
}

More efficient for large numbers, you can count groups of bits first:
int bits = 0;
while (n > 255) {
  bits += 8;
  n >>= 8;
}
while (n > 0) {
  bits++;
  n >>= 1;
}

Edit:
The most efficient method would be to use the binary steps that Flynn1179 suggested (upvoted for the inspiration :), but expanding the loop into hard coded checks. This is at least twice as fast as the method above, but also more code:
int bits = 0;
if (n > 32767) {
  n >>= 16;
  bits += 16;
}
if (n > 127) {
  n >>= 8;
  bits += 8;
}
if (n > 7) {
  n >>= 4;
  bits += 4;
}
if (n > 1) {
  n >>= 2;
  bits += 2;
}
if (n > 0) {
  bits++;
}

A: The Cleanest and Quickest...  (works in .Net core 3.1 and up and takes the performance lead starting in .Net 5.0)
int val = BitOperations.Log2(x);

Runner up... (fastest in versions below .Net 5, 2nd place in .Net 5)
int val = (int)((BitConverter.DoubleToInt64Bits(x) >> 52) + 1) & 0xFF;

Notes:

*

*The idea of using the exponent in a floating-point was inspired by SPWorley
3/22/2009.

*This also supports more than 32 bits. I have not tested the max but did go to at least 2^38.

*Use with caution on production code since this can possibly fail on architectures that are not little-endianness.

Here are some benchmarks: (code here: https://github.com/SunsetQuest/Fast-Integer-Log2)
                                      1-2^32                  32-Bit  Zero
Function                Time1 Time2 Time3 Time4 Time5 Errors Support Support
Log2_SunsetQuest3       18     18    79167  19    18    255      N       N
Log2_SunsetQuest4       18     18    86976  19    18      0      Y       N
LeadingZeroCountSunsetq -      -        -   30    20      0      Y       Y
Log2_SPWorley           18     18    90976  32    18   4096      N       Y
MostSigBit_spender      20     19    86083  89    87      0      Y       Y
Log2_HarrySvensson      26     29    93592  34    31      0      Y       Y
Log2_WiegleyJ           27     23    95347  38    32      0      Y       N
Leading0Count_phuclv     -      -        -  33    20    10M      N       N
Log2_SunsetQuest1       31     28    78385  39    30      0      Y       Y
HighestBitUnrolled_Kaz  33     33   284112  35    38   2.5M      N       Y
Log2_Flynn1179          58     52    96381  48    53      0      Y       Y
BitOperationsLog2Sunsetq -      -        -  49    15      0      Y       Y
GetMsb_user3177100      58     53   100932  60    59      0      Y       Y
Log2_Papayaved         125     60   119161  90    82      0      Y       Y
FloorLog2_SN17         102     43   121708  97    92      0      Y       Y
Log2_DanielSig          28     24   960357  102  105     2M      N       Y
FloorLog2_Matthew_Watso 29     25    94222  104  102      0      Y       Y
Log2_SunsetQuest2      118    140   163483  184  159      0      Y       Y
Msb_version            136    118  1631797  212  207      0      Y       Y
Log2_SunsetQuest0      206    202   128695  212  205      0      Y       Y
BitScanReverse2        228    240  1132340  215  199     2M      N       Y
Log2floor_version       89    101 2 x 10^7  263  186      0      Y       Y
UsingStrings_version  2346   1494 2 x 10^7 2079 2122      0      Y       Y

Zero_Support = Supports Zero if the result is 0 or less
Full-32-Bit  = Supports full 32-bit (some just support 31 bits)
Time1 = benchmark for sizes up to 32-bit (same number tried for each size)
Time2 = benchmark for sizes up to 16-bit (for measuring perf on small numbers)
Time3 = time to run entire 1-2^32 in sequence using Parallel.For. Most results range will on the larger end like 30/31 log2 results. (note: because random was not used some compiler optimization might have been applied so this result might not be accurate)
Time4 = .Net Core 3.1
Time5 = .Net 5

Benchmark notes: AMD Ryzen CPU, Release mode, no-debugger attached, .net core 3.1
I really like the one created by spender in another post. This one does not have the potential architecture issue and it also supports Zero while maintaining almost the same performance as the float method from SPWorley.
Update 3/13/2020: Steve noticed that there were some errors in Log2_SunsetQuest3 that were missed.
Update 4/26/2020: Added new .Net Core 3's BitOperations.LeadingZeroCount() as pointed out by phuclv.

A: Efficiency in terms of lines of code, or runtime execution speed?
Code's easy: Math.log(n, 2).
Runtime speed's a little trickier, but you can do it with a kind of 'binary search':
int bits = 1;
for (int b = 16; b >=1; b/=2)
{
  int s = 1 << b;
  if (n >= s) { n>>=b; bits+=b; }
}

I'm not 100% certain I've got the logic right there, but hopefully the idea's clear. There might be some overheads in the .NET VM, but in principle it should be faster.
The 16 in the for loop initialializer is based on half the number of bits needed for an int. If you're working with longs, start it at 32, etc.

A: Slight improvement to Guffa's answer... Since the amount you are adding to the result is always a power of two using bit operations can produce slight improvement on some architectures. Also since our context is bit patterns it is slightly more readable to use hexadecimal. In this case it is useful to shift the arithmetic by a power of 2.
int bits = 0;

if (n > 0xffff) {
  n >>= 16;
  bits = 0x10;
}

if (n > 0xff) {
  n >>= 8;
  bits |= 0x8;
}

if (n > 0xf) {
  n >>= 4;
  bits |= 0x4;
}

if (n > 0x3) {
  n >>= 2;
  bits |= 0x2;
}

if (n > 0x1) {
  bits |= 0x1;
}

Further a check for n==0 should be added since the above will yield a result of 0 and Log(0) is undefined (regardless of base).
In ARM assembly this algorithm produces very compact code as the branch after comparison can be eliminated with conditional instructions which avoids pipeline flushing. For Example:
if (n > 0xff) {
   n >>= 8;
   bits |= 0x8;
}

becomes (let R0 = n, R1 = bits)
CMP R0, $0xff
MOVHI R0, R0, LSR $8
ORRHI R1, R1, $0x8

A: In .NET Core 3.0 there are BitOperations.LeadingZeroCount() and BitOperations.Log2. They're mapped to the underlying hardware instructino like x86's LZCNT/BSR so that should be the most efficient solution
int bits = BitOperations.Log2(x); // or
int bits = x == 0 ? 1 : 32 - BitOperations.LeadingZeroCount(x);

A: direct convert to IEEE754 32bit has wrong result after about 33554431
public unsafe static int ByPtr754_32(ulong bits) {
    var fp = (float)bits;
    return (int)(((*(uint*)&fp >> 23) & 255) - 127);
}

convert to FP64 and ILogB has wrong result after 53bits, about 18014398509481983
public unsafe static int ByPtr754_64(ulong bits) {
    var fp = (double)bits;
    return ((int)(*(ulong*)&fp >> 52) & 2047) - 1023;
}
public static int ByILogB(ulong bits) {
    return Math.ILogB(bits);
}

lg and ln has wrong after about 47bits, about 281474976710655
static readonly double ln2 = Math.Log(2.0), divLn2 = 1 / ln2;
public static int ByLn(ulong bits) {
    //return (int)(Math.Log(bits) * divLn2);
    return (int)(Math.Log(bits) / ln2);
}

lb wrong after 48bits, about 562949953421311
public static int ByLog2(ulong bits) {
    return (int)Math.Log2(bits);
}

Binary Search is very slow.
public static int BySearch(ulong bits) {
    if (0 == bits) {
        return -1;
    }

    int min = 0, max = 64;
    for (; ; ) {
        int mid = (max + min) >> 1;
        if (mid == min) {
            break;
        }
        if (bits >> mid != 0) {
            min = mid;
        } else {
            max = mid;
        }
    }
    return min;
}

My suggestion is here:
Fast one:
public unsafe static int ByPtr754_64(ulong bits) {
    var fp = (double)bits;
    return ((int)(*(ulong*)&fp >> 52) & 2047) - 1023;
}

const int Fp64Prec = 53;
static int[] CreateTableMix() {
    var ret = new int[1 << (64 - Fp64Prec)];
    for (int i = ret.Length; --i >= 0;) {
        ret[i] = ByPtr754_64((uint)i) + Fp64Prec;
    }
    return ret;
}
static readonly int[] _TableMix = CreateTableMix();
public static int ByTableMix(ulong bits) {
    int r;
    return (r = _TableMix[bits >> Fp64Prec]) > 0 ? r : ByPtr754_64(bits);
}

Simple one:
const int Fp64Prec = 53;
static int[] CreateTableMix() {
    var ret = new int[1 << (64 - Fp64Prec)];
    for (int i = ret.Length; --i >= 0;) {
        ret[i] = ByPtr754_64((uint)i) + Fp64Prec;
    }
    return ret;
}
public static int By754Adj(ulong bits) {
    const int lack = 64 - Fp64Prec;
    int r;
    return (r = ByPtr754_64(bits >> lack)) > 0 ? r+lack : ByPtr754_64(bits);
}

Speed test result:
 Search: 649830
 ByTest: 535859
 ByLog2: 560492
   ByLn: 376675
   ByLg: 392090
 ByILog: 252594
Table16: 136847
ByUnion: 123453
 754_64: 101358
 754_32: 118379
TableMx: 106201
 754Adj: 174889


text:
Q: ASP.Net restart / GAC refresh How should I "properly" restart the ASP.NET (IIS 5.1) server in order to refresh the loaded assemlies? I tried several things, but without success:

*

*tried to stop and start the web site in IIS manager

*touched web.config file

*tried using iisreset

*tried to kill ASP.NET processes

*my assemblies are not strongly-named, so they are not in GAC (checked using gacutil anyway)

Right now, every time I have a new version, I publish my site from the development machine, and then manually copy assemblies into the /bin folder - but I need to restart the server after every update in order to have my web site actually updated. Aspx pages update immediatelly (I can change them and see them update on-the-fly), but code-behind assemblies are not reloaded until I actually restart the machine.
To be sure of this, I am displaying the SVN revision number (hardcoded in my assembly during build time): <% Response.Write(SvnInfo.CurrentRev); %>
[Edit] Oooops - my mistake after all. It turns out that Publish command does not rebuild assemblies every time. I rebuilt the release version manually, published it, and it was running as soon as I copied assemblies to the bin folder.

A: Oooops - my mistake after all. It turns out that Publish command in Visual Studio does not rebuild assemblies every time.
I rebuilt the release version manually, published it, and it was running without problems as soon as I copied assemblies to the bin folder.


text:
Q: Log off citrix session I want to terminate a session hosted in xen app server. When i pass the following parameter to execute on command line  such as
/username:TestUser /domain:TestDomina /password:xxxxyyyz /cmdline:logoff  using shell api ?
The wfc command line usgae pop up comes up. DOes it mean that we cannot log off using the command line option in wfc ?
Thanks

A: To logoff the current session from the app the user is running you can use the following.
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false)

http://msdn.microsoft.com/en-us/library/windows/desktop/aa383836%28v=vs.85%29.aspx


text:
Q: How to configure Gradle for Spring in Eclipse? I am getting an error when i use to configure Gradle in Eclipse
I have also tried on different systems.
Is it x86 or x64 dependant ?
Listner Gradle:
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'

repositories {
   mavenCentral()
}

dependencies {
    compile  'org.springframework.boot:spring-boot-starter:1.1.4.RELEASE'
    compile  'org.springframework:spring-jms:4.0.6.RELEASE'
    compile  'org.apache.activemq:activemq-broker:5.12.0'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.2.+'
    compile 'com.fasterxml.jackson.core:jackson-core:2.2.+'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.2.+'
    compile 'org.mongodb:mongo-java-driver:2.12.4'
}

Sender Gradle
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'

repositories {
   mavenCentral()
}

dependencies {
    compile  'org.springframework.boot:spring-boot-starter:1.1.4.RELEASE'
    compile  'org.springframework:spring-jms:4.0.6.RELEASE'
    compile  'org.apache.activemq:activemq-broker:5.12.0'
}

build.gradle
I need another build automation tool that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the more traditional XML form of declaring the project configuration


text:
Q: Inserting Data in mysqli is not working I am wondering why my insert statement does not work. There are no records shown in the database and it does not show any errors. Here is the code
<?php
    if(isset($_POST['submit'])){
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        $conf_pass = trim($_POST['conf_password']);
        $email = trim($_POST['email']);
        require_once('./includes/Db/CheckPassword.php');
        $check_pwd = new Db_CheckPassword($password);
        $passwordOK =$check_pwd->check();
        $password_match = Db_CheckPassword::confirmPassword($password,$conf_pass);
        require_once('./includes/Db/CheckUsername.php');
        $check_user = new Db_CheckUsername($username,$conn);
        $userOK = $check_user->check();

        if($userOK && $passwordOK && $password_match){
            $hashedpass = crypt($password);

            $sql = "INSERT INTO accounts ('username','password','email') VALUES('{$username}','{$hashedpass}','{$email}')";
            $conn->query($sql);
        }else{
            $pass_error =  $check_pwd -> getErrors();
            $user_error  = $check_user->getErrors();
        }
    }
?>

This is where I insert records into the database
if($userOK && $passwordOK && $password_match){
                $hashedpass = crypt($password);

                $sql = "INSERT INTO accounts ('username','password','email') VALUES('{$username}','{$hashedpass}','{$email}')";
                $conn->query($sql);

A: In mySQL the identifier quote character is the backtick , so replace the single-quotes surrounding the column-names by backticks:
$sql = "INSERT INTO accounts (`username`,`password`,`email`)
                     VALUES('{$username}','{$hashedpass}','{$email}')";


text:
Q: Technical question about the proof of the chain rule In Spivak calculus proof of the chain rule, which is essentially the same as this proof, Spivak mentioned that

the continuity of  $\phi(h)$ is the crux of the whole proof

I'm not sure I see why it is the crux move in this proof, any help?

A: I believe Spivak is alluding to the following result-

(Carathéodory formulation of the derivative) A function $f : \mathbb R \to \mathbb R$ is differentiable at $x\in\mathbb R$ iff there exists a function $\Phi:\mathbb R\to \mathbb R$ (depending on $x$) continuous at $h=0$ such that (at least near $h=0$)
   $$ f(x+h) = f(x) + \Phi(h)h.$$
  In addition,  $f'(x) = \Phi(0)$.

The equivalence is not hard to show at all, but it allows you an alternative proof of all the differentiation rules that is very mechanical.
Say we write $\Phi_{f,x}(h) = \Phi_f(h)$ to make the dependence on $x,f$ explicit: $$f(x+h) = f(x) + \Phi_f(h)h,$$
$$g(x+h) = g(x) + \Phi_g(h)h.$$
It is immediate from mere algebraic properties of continuous functions (without any $\epsilon-\delta$ management)
$$ (f+g)(x+h) = (f+g)(x) + \underbrace{(\Phi_{f}+\Phi_g)(h)}_{=\Phi_{f+g}(h)}h,$$
$$ (fg)(x+h) = f(x)g(x) + f(x)\Phi_g(h)h +  \Phi_f(h)g(x)h +  \Phi_f(h) f(x)\Phi_g(h)h^2\\ = (fg)(x) +  \Big(\underbrace{f(x)\Phi_g(h) +  \Phi_f(h)g(x) +  \Phi_f(h) f(x)\Phi_g(h)h}_{=\Phi_{fg}(h)}\Big) h,$$
$$ \frac{1}{f(x+h)}=\frac1{f(x)} + \frac{f(x) - f(x+h)}{f(x+h)f(x)} = \frac1{f(x)} + \underbrace{\frac{-\Phi_f(h)}{f(x+h)f(x)}}_{=\Phi_{1/f}(h)} h \quad (\text{if }f(x)\neq 0),$$
and finally chain rule (this time using $\Phi_f = \Phi_{f,g(x)}$ instead of $\Phi_{f,x}$)
$$ f\circ g(x+h) = f\circ g(x) + \Phi_f(g(x+h)-g(x))(g(x+h)-g(x)) \\ =f\circ g(x) + \underbrace{\Phi_f(\Phi_g(h)h)\Phi_g(h)}_{= \Phi_{f\circ g}(h)}h. $$
In this way, each rule for derivatives follows with no effort from the corresponding rule for continuous functions.
(PS there is more discussion about the Carathéodory derivative, in particular higher dimensional analogues here)

A: If $\Phi$ was not continuous at 0, you wouldn't be able to write
$\lim_{h \to 0} \left( \Phi(h) \cdot \frac{\Delta_h}{h} \right) = \lim_{h \to 0} \left( \Phi(h) \right) \cdot \lim_{h \to 0} \left( \frac{\Delta_h}{h}\right)$ because you wouldn't know whether $\lim_{h \to 0} \left( \Phi(h) \right)$ even exists.
The lemma fortunately proves that the limit does exist, and therefore that $\Phi$ is continuous.
Edit: whether it is the "crux" of the proof I am not sure either, but it is certainly necessary for the proof to be valid.


text:
Q: Change language of installation DVD I have downloaded Ubuntu and burned the ISO to DVD. When the disk opens, it is in Dutch (I think) and doesn't seem to have any options for changing to English.
I tried installing it via Windows XP Add Program (control panel) but can't find a setup file.
I tried booting from the DVD, but my Acer Aspire One doesn't seem to like that. It runs on a Crucial 256GB SSD and the start-up screen only lasts for a fraction of a second, meaning I can't press the F2 at the 'crucial' moment!
Any ideas?

A: To change Language:

*

*Boot from your Media which has the Ubuntu ISO

*Wait for the LiveCD / LiveUser to load

*By Default you will get a window pop asking to Install or Try Ubuntu

*On this menu you will have option to change Language

If above does not work for you:
Suggest you download a fresh ISO from Ubuntu.com
For BOOT Menu:
If you are using Win8, it has tendency to boot real quick. Thus switch off your laptop (no restart) and press the power on button and F2 key almost with a littel delay- make sure you start with power on first.
These worked for me in a test Laptop (Sony Vaio E)


text:
Q: Any way to disable /wp-login.php redirecting to the site folder? We have our WP installs in folders on the server. We created folders called wp-admin and login to thwart hackers. However, incredulously, when you type in /wp-login.php it REDIRECTS to our mysite.com/folder.
I cannot believe WP is making it this easy.
How to disable anyone accessing wp-login.php through the address bar?

A: The best way to block access is in the pre_virtualhost.conf or your equivalent httpd configuration file.
This code will block any access to yourdomain.com/wp-admin and redirect to a blank page with message, "Denied". However, it will not block anyone trying to access yourdomain.com/somefolder/wp-admin.
<Location /wp-admin>
order deny,allow
Deny from all
allow from localhost 127.0.0.1 207.58.143.240
ErrorDocument 403 "Denied."
</Location>

I would advise familiarizing yourself with mod_rewrite.c, which allows you to set explicit conditions with incredible flexibility.


text:
Q: TCPDF Page number as int $pdf->getAliasNumPage() gets the page number in the content as string, which not works. Since I am tryting to determine what page number is next. So theoreticaly $pdf->getAliasNumPage() + 1;
I tryed using the $pdf->PageNo();, how ever it always returns 1. If I add it to footer as
$this and PageNo() it works fine, but in the content. It doesn't.
Im using $content .= lines;
and
$pdf->writeHTML($content, true, 0, true, 0);

for the output.

A: Looking at the documentation, getAliasNumPage() is nothing more than placeholder text which eventually tells the TCPDF compiler to display the current page number. You can only use this function to display the current page number in your PDF and it cannot be used for logic such as the addition which you are trying to do.
Try it:
echo $pdf->getAliasNumPage();
die();

As for PageNo() the documentation does say that it returns an integer, HOWEVER this integer is only updated when you are not creating a PDF using writeHTML(). This integer only gets incremented after you call the AddPage() method yourself.
The reason for this is that when you are building your HTML, PageNo() is executed right away and is always on page #1. The writeHTML() function has no idea that you are trying to use PageNo() as an expression because the integer already exists in $content.
Since $content will render as a variable height block of content, TCPDF simply keeps overflowing it onto new pages as needed and the integer produced by PageNo() will always be the same.
In order for TCPDF to work the way you are trying to use it, TCPDF would have to provide an expression placeholder which the compiler would be able to understand and evaluate.

As for the footer, PageNo() works because the footer function is called on an as-needed basis.
From the docs:

Footer( )
This method is used to render the page footer. It is automatically called by AddPage() and could be overwritten in your own inherited class.

The bolded section explains why PageNo() actually gets incremented as expected in the footer. This holds true for the Header() as well.


text:
Q: Replacing the value 1 with the word Ace in a deck of cards We got the assignement to make a program that shuffles a deck of cards. I'm still quite new to programming so this hasn't been the easiest assignement to do for me. We got the tip to do some research into itertools, so that's what I did. The program I have so far is as followed:
import itertools
import random

deck = list(itertools.product(range(1,14),['Heart','Spade','Club','Diamond']))

random.shuffle(deck)

print("Order of deck:")
for i in range(52):
    print(deck[i][0], "of", deck[i][1])

If you run this you get:
Order of deck:
9 of Heart
10 of Diamond
2 of Spade
1 of Heart
11 of Spade
4 of Diamond
10 of Heart
...

You get a shuffled deck, as I wanted.
The only thing left to do is to change the values of 1 to "Ace", 11 to "Jack", ...
But I can't figure out how to do this, because my list "deck" consists of 52 items with each card as a tuple. For example
deck[0] = (1, 'Spade')

So far the only things I learned to replace are
deck.replace(1,"Ace")

and
for n, i in enumerate(deck):
    if i == 1:
        deck[n] = "Ace"

But these both don't work.
The first one doesn't work because my deck isn't a string, but a list.
And if I run the second one nothing changes, the output remains the exact same as without that piece of code.
So to sum everything up, I want to change the 1 to "Ace" in my little program, and then I could do the same for 11 to "Jack", ...
(Sorry for any bad English, hope everything is clear)

A: There are two ways to achieve this, depending on what you're trying to do. If you want to capture the notion that the value of Jack is 11, then you'll need to change only the displayed value (i.e. check before you print and replace 11 with Jack, etc). However, if the value isn't of particular concern, then you can fiddle with the deck at creation time:
deck = list(itertools.product(["A", *range(2,11), 'J', 'Q', 'K'],['Heart','Spade','Club','Diamond']))

A: Create your list with the strings that you would like to display:
values = ['Ace'] + [str(i) for i in range(2,11)] + ['Jack', 'Queen', 'King']
suits = ['Heart', 'Spade', 'Club', 'Diamond']
deck = list(itertools.product(values, suits))

A: You don't need to replace anything. You can use a function to return the appropriate string value
def get_face(x):
    if x == 1:
        return 'Ace'
    elif x == 11:
        return 'Jack'
    else:  # TODO: add others
        return x

for card in deck:
    print(get_face(card[0]), "of", card[1])


text:
Q: QPushButton get color In this function I am trying to get the bgColor of the button that triggers it, so the background color can be set to its default color again.
def clickColor(button, color):
    bgColor = button.palette().color(QPalette.Background)
    button.setStyleSheet("background-color: %s" % color)
    QTimer.singleShot(300, lambda: unClickColor(button, bgColor))

def unClickColor(button, beforeColor):
    button.setStyleSheet("background-color: %s" % bgColor)

It gives the following error message:
Could not parse stylesheet of object 0x234ba20

Printing the bgColor variable gives:
<PyQt5.QtGui.QColor object at 0x7f28792c8358>

A: Must use color name() method and the color parameter name in unclick function:
def unClickColor(button, beforeColor):
    button.setStyleSheet("background-color: %s" % beforeColor.name())

Tested and works.


text:
Q: Loop over 24-hour period using list of dates in Python I have a list of np.datetime64 dates in Python:
['2016-12-01T02:00:00.000000000', '2016-12-01T04:00:00.000000000',
 '2016-12-01T06:00:00.000000000', '2016-12-01T08:00:00.000000000',
 '2016-12-01T10:00:00.000000000', '2016-12-01T12:00:00.000000000',
 '2016-12-01T14:00:00.000000000', '2016-12-01T16:00:00.000000000',
 '2016-12-01T18:00:00.000000000', '2016-12-01T20:00:00.000000000',
 '2016-12-01T22:00:00.000000000', '2016-12-02T00:00:00.000000000',
 '2016-12-02T02:00:00.000000000', '2016-12-02T04:00:00.000000000',
 '2016-12-02T06:00:00.000000000', '2016-12-02T08:00:00.000000000',
 '2016-12-02T10:00:00.000000000', '2016-12-02T12:00:00.000000000',
 '2016-12-02T14:00:00.000000000', '2016-12-02T16:00:00.000000000',
 '2016-12-02T18:00:00.000000000', '2016-12-02T20:00:00.000000000',
 '2016-12-02T22:00:00.000000000', '2016-12-03T00:00:00.000000000',
 '2016-12-03T02:00:00.000000000', '2016-12-03T04:00:00.000000000',
 '2016-12-03T06:00:00.000000000', '2016-12-03T08:00:00.000000000',
 '2016-12-03T10:00:00.000000000', '2016-12-03T12:00:00.000000000',
 '2016-12-03T14:00:00.000000000', '2016-12-03T16:00:00.000000000',
 '2016-12-03T18:00:00.000000000', '2016-12-03T20:00:00.000000000',
 '2016-12-03T22:00:00.000000000']

and I wish to loop over each calendar day within the list. I have tried to extract each unique date from the list (i.e. finding the min and max date and creating a list of dates between these) but this isn't ideal for what I want to do.
My desired outcome would be to have code that allows me to loop over each date/calendar day found in the list and obtain the datetimes corresponding to this date:
for each_date in date_list:
    ***get all datetimes corresponding to each_date***

(loop would occur 3 times in this example)

NOTE:
1) Solutions that iterate over every [n:n+24] or whatever will not work as not every day will have the same number of time steps.

A: If the timestamps are ordered, we can use the itertools.groupby function to group the elements of the array by the corresponding day.
The day can be obtained with np.datetime64.astype(..., dtype='datetime64[D]'), so we can write it like:
from numpy import datetime64
from functools import partial
from itertools import groupby

for day, timestamps in groupby(data_array,
                               partial(datetime64.astype, dtype='datetime64[D]')):
    # process day and timestamps
    pass
Here day is a datetime64[D] numpy object (it contains only the day), and timestamps is an iterable (not a list, but we can convert it to a list) of the corresponding timestamps. data_array is the array that contains the initial data.
For example:
>>> for day, timestamps in groupby(data_array,
...                                partial(datetime64.astype, dtype='datetime64[D]')):
...     print((day, list(timestamps)))
...
(numpy.datetime64('2016-12-01'), [numpy.datetime64('2016-12-01T02:00:00.000000000'), numpy.datetime64('2016-12-01T04:00:00.000000000'), numpy.datetime64('2016-12-01T06:00:00.000000000'), numpy.datetime64('2016-12-01T08:00:00.000000000'), numpy.datetime64('2016-12-01T10:00:00.000000000'), numpy.datetime64('2016-12-01T12:00:00.000000000'), numpy.datetime64('2016-12-01T14:00:00.000000000'), numpy.datetime64('2016-12-01T16:00:00.000000000'), numpy.datetime64('2016-12-01T18:00:00.000000000'), numpy.datetime64('2016-12-01T20:00:00.000000000'), numpy.datetime64('2016-12-01T22:00:00.000000000')])
(numpy.datetime64('2016-12-02'), [numpy.datetime64('2016-12-02T00:00:00.000000000'), numpy.datetime64('2016-12-02T02:00:00.000000000'), numpy.datetime64('2016-12-02T04:00:00.000000000'), numpy.datetime64('2016-12-02T06:00:00.000000000'), numpy.datetime64('2016-12-02T08:00:00.000000000'), numpy.datetime64('2016-12-02T10:00:00.000000000'), numpy.datetime64('2016-12-02T12:00:00.000000000'), numpy.datetime64('2016-12-02T14:00:00.000000000'), numpy.datetime64('2016-12-02T16:00:00.000000000'), numpy.datetime64('2016-12-02T18:00:00.000000000'), numpy.datetime64('2016-12-02T20:00:00.000000000'), numpy.datetime64('2016-12-02T22:00:00.000000000')])
(numpy.datetime64('2016-12-03'), [numpy.datetime64('2016-12-03T00:00:00.000000000'), numpy.datetime64('2016-12-03T02:00:00.000000000'), numpy.datetime64('2016-12-03T04:00:00.000000000'), numpy.datetime64('2016-12-03T06:00:00.000000000'), numpy.datetime64('2016-12-03T08:00:00.000000000'), numpy.datetime64('2016-12-03T10:00:00.000000000'), numpy.datetime64('2016-12-03T12:00:00.000000000'), numpy.datetime64('2016-12-03T14:00:00.000000000'), numpy.datetime64('2016-12-03T16:00:00.000000000'), numpy.datetime64('2016-12-03T18:00:00.000000000'), numpy.datetime64('2016-12-03T20:00:00.000000000'), numpy.datetime64('2016-12-03T22:00:00.000000000')])

So here for every day, we have opted to print a list of corresponding timestamps, but this is of course one of the options. Like the example shows, not all slices have the same length (the last two have an extra element)
Note that the timestamps is an iterator, and thus gets exhausted, if you do not convert it to a list, then after one loop, the iterator is exhausted.
The groupby works in linear time, since each time it checks if the "group key" is the same as the previous element, but as said before the contraint is data must be ordered.

A: You can use collections.defaultdict for an O(n) solution. You can use Pandas to normalize your datetime objects, although this should also be possible via NumPy.
import pandas as pd
from collections import defaultdict

d = defaultdict(list)

for item in L:
    day = pd.to_datetime(item).normalize().to_datetime64()
    d[day].append(item)

print(d)

defaultdict(list,
            {numpy.datetime64('2016-12-01T00:00:00.000000000'):
                 [numpy.datetime64('2016-12-01T02:00:00.000000000'),
                  ...
                  numpy.datetime64('2016-12-01T22:00:00.000000000')],
             numpy.datetime64('2016-12-02T00:00:00.000000000'):
                 [numpy.datetime64('2016-12-02T00:00:00.000000000'),
                  ...
                  numpy.datetime64('2016-12-02T22:00:00.000000000')],
             numpy.datetime64('2016-12-03T00:00:00.000000000'):
                 [numpy.datetime64('2016-12-03T00:00:00.000000000'),
                  ...
                  numpy.datetime64('2016-12-03T22:00:00.000000000')]})


text:
Q: WPF ComboBox with CheckBoxes display info about checked items? Im trying to make a ComboBox that have checkboxes as items and based on what is checked display different things when the combobox is "closed".
The look Im trying achieve can be seen in the image.

Ideally I dont want the user to be able to select the text in the top ( in the image).
Is there a simple solution to this? I've seen solutions where one can display more information when all the items are shown by using DataTriggers to hide different nested controls, but that is not really what Im looking for.
Any ideas?
/Erik

A: Using a combination of the @Erik83 and @Xavier solution I still had the problem that selecting a ComboBoxItem in a location right from the CheckBox text closes the ComboBox-DropDown and shows the ToString() value of the ComboBoxItem as the CheckBox is not stretched to DropDown-Width. I solved it by adding

HorizontalContentAlignment="Stretch"

to the CheckBox and adding the ItemContainerStyle:
<ComboBox x:Name="combobox"
    Background="White"
    Padding="2"
    Text="{Binding ElementName=DockPanelTemplateComboCheck, Path=ComboTextFilter}"
    IsEditable="True"
    IsReadOnly="True"
    HorizontalAlignment="Stretch"
    ItemsSource="{Binding ...}"
    IsDropDownOpen="{Binding Path=DropOpen, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, UpdateSourceTrigger=PropertyChanged}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Eintrag}" HorizontalContentAlignment="Stretch" Checked="CheckBox_Checked_Unchecked" Unchecked="CheckBox_Checked_Unchecked"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

CodeBehind:
    private string combotextfilter = "<No Selection>";

    public string ComboTextFilter
    {
        get { return combotextfilter; }
        set
        {
            if (value != null && value.IndexOf("ComboModel") != -1) return;
            combotextfilter = value;
            NotifyPropertyChanged(nameof(ComboTextFilter));
        }
    }

    private void CheckBox_Checked_Unchecked(object sender, RoutedEventArgs e)
    {
        switch (((ObservableCollection<ComboModel>)combobox.ItemsSource).Count(x => x.IsChecked))
        {
            case 0:
                ComboTextFilter = "<No Selection>";
                break;
            case 1:
                ComboTextFilter = ((ObservableCollection<ComboModel>)combobox.ItemsSource).Where(x => x.IsChecked).First().Eintrag;
                break;
            default:
                ComboTextFilter = ((ObservableCollection<ComboModel>)combobox.ItemsSource).Where(x => x.IsChecked).Select(x => x.Eintrag).Aggregate((i, j) => i + " | " + j);
                //ComboTextFilter = "<Multiple Selected>";
                break;
        }

        NotifyPropertyChanged(nameof(C_Foreground));
    }

    public bool DropOpen
    {
        get { return dropopen; }
        set { dropopen = value; NotifyPropertyChanged(nameof(ComboTextFilter)); }
    }
    private bool dropopen = false;

A: @Xaviers answer works 99% of the way. However the user is able to accidently select a checkbox and then the ToString() of the checkbox is shown as the selected text. This can happen quite alot actually. I havent yet worked out why this happens, but I've found a way to prevent this.
Create a bool property that binds to the DropDownOpen property of the combobox and when the DropDownOpen has changed to false it means that the DropDown has just been closed and you might be facing the above problem.
So here you just raise the propertychanged event for the viewmodel and pass the property bound to the Text property of the combobox.

A: Here is a way to achieve most of what you want using a ComboBox, except that the text can still be selected (using custom text only works when IsEditable is true). It is not editable though because of IsReadOnly="true".
View
<ComboBox
    IsEditable="True"
    IsReadOnly="True"
    ItemsSource="{Binding Items}"
    Text="{Binding Text}">
    <ComboBox.ItemTemplate>
        <DataTemplate
            DataType="{x:Type local:Item}">
            <CheckBox
                Content="{Binding Name}"
                IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Viewmodel
// ObservableObject is a custom base class that implements INotifyPropertyChanged
internal class MainWindowVM : ObservableObject
{
    private ObservableCollection<Item> mItems;
    private HashSet<Item> mCheckedItems;

    public IEnumerable<Item> Items { get { return mItems; } }

    public string Text
    {
        get { return _text; }
        set { Set(ref _text, value); }
    }
    private string _text;

    public MainWindowVM()
    {
        mItems = new ObservableCollection<Item>();
        mCheckedItems = new HashSet<Item>();
        mItems.CollectionChanged += Items_CollectionChanged;

        // Adding test data
        for (int i = 0; i < 10; ++i)
        {
            mItems.Add(new Item(string.Format("Item {0}", i.ToString("00"))));
        }
    }

    private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
        {
            foreach (Item item in e.OldItems)
            {
                item.PropertyChanged -= Item_PropertyChanged;
                mCheckedItems.Remove(item);
            }
        }
        if (e.NewItems != null)
        {
            foreach (Item item in e.NewItems)
            {
                item.PropertyChanged += Item_PropertyChanged;
                if (item.IsChecked) mCheckedItems.Add(item);
            }
        }
        UpdateText();
    }

    private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "IsChecked")
        {
            Item item = (Item)sender;
            if (item.IsChecked)
            {
                mCheckedItems.Add(item);
            }
            else
            {
                mCheckedItems.Remove(item);
            }
            UpdateText();
        }
    }

    private void UpdateText()
    {
        switch (mCheckedItems.Count)
        {
            case 0:
                Text = "<none>";
                break;
            case 1:
                Text = mCheckedItems.First().Name;
                break;
            default:
                Text = "<multiple>";
                break;
        }
    }
}

// Test item class
// Test item class
internal class Item : ObservableObject
{
    public string Name { get; private set; }

    public bool IsChecked
    {
        get { return _isChecked; }
        set { Set(ref _isChecked, value); }
    }
    private bool _isChecked;

    public Item(string name)
    {
        Name = name;
    }

    public override string ToString()
    {
        return Name;
    }
}

If the selectable text is an issue, you may want to create a custom ComboBox control template (default example here). Alternatively, you could use something else instead of a ComboBox, and make it look like a ComboBox.
Screenshot of example:


text:
Q: Waterline sails-msql ER_NO_SUCH_TABLE: Table doesn't exist I'm receiving an error only when I try to update the 'bookings' mysql field with sails.js.
Here is the bookings model:
module.exports = {

    tableName: 'bookings',
    adapter: 'mysql',
    autoCreatedAt: true,
    autoUpdatedAt: true,

  attributes: {

      id: {type: 'integer',autoIncrement: true,primaryKey: true},
      booking_n: {type: 'integer'},
      customer: { model:'customers'},
      room: {type: 'string'},
      departure: {type: 'date'},
      createdAt: {type: 'date'},
      updatedAt: {type: 'date'},
      invoice: {mode:'invoices'}
    }
};

As you can see there are 2 "one to many" associations, (an invoice can have several bookings, etc..), here the invoices model:
module.exports = {

    tableName:'invoices',
    adapter: 'mysql',
    autoPK:false,
    autoCreatedAt: true,
    autoUpdatedAt: true,

attributes: {

id: {type: 'integer', autoIncrement: true, primaryKey: true},
doc_mod: {type:'string'},
doc_n: {type:'integer'},
createdAt: {type:'date'},
updatedAt: {type:'date'},
invoice_line: {collection:'invoice_lines', via:'invoice'},
customer: {model:'customers'},
bookings:{collection:'bookings', via:'invoice'}
  }
}

From Angular I'm tring to update the bookings model with the new invoice.id:
Update:function(bookingObj){

    var BookingResource = $resource(IP_ADDRESSES.dbserver+'bookings/:id',{
        id: '@id'
    },{
        'update': {
            method: 'PUT'
        }
     });
    return BookingResource.update({id: bookingObj.id}, bookingObj).$promise;
}

but I get this error from the sails console log:
error: Sending 500 ("Server Error") response:
 Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_NO_SUCH_TABLE: Table 'prestige2.bookings_invoice__invoices_bookings' doesn't exist
    at Query.Sequence._packetToError (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequence
s\Sequence.js:48:14)
    at Query.ErrorPacket (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequences\Query.js:8
3:18)
    at Protocol._parsePacket (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Protocol.js:271:
23)
    at Parser.write (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Parser.js:77:12)
    at Protocol.write (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\Connection.js:92:28)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:529:20)
    --------------------
    at Protocol._enqueue (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Protocol.js:135:48)
    at PoolConnection.Connection.query (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\Connection.js:1
97:25)
    at __FIND__ (C:\prestigeserver\node_modules\sails-mysql\lib\adapter.js:836:20)
    at Object.module.exports.adapter.find (C:\prestigeserver\node_modules\sails-mysql\lib\adapter.js:803:9)
    at Array.async.auto.findRecords (C:\prestigeserver\node_modules\sails-mysql\lib\adapter.js:1056:21)
    at C:\prestigeserver\node_modules\sails-mysql\node_modules\async\lib\async.js:484:38
    at _each (C:\prestigeserver\node_modules\sails-mysql\node_modules\async\lib\async.js:46:13)
    at Object.async.auto (C:\prestigeserver\node_modules\sails-mysql\node_modules\async\lib\async.js:455:9)
    at __DESTROY__ (C:\prestigeserver\node_modules\sails-mysql\lib\adapter.js:1053:15)
    at afterwards (C:\prestigeserver\node_modules\sails-mysql\lib\connections\spawn.js:84:5)
    at C:\prestigeserver\node_modules\sails-mysql\lib\connections\spawn.js:40:7
    at Ping.onPing [as _callback] (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\Pool.js:94:5)
    at Ping.Sequence.end (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequences\Sequence.j
s:96:24)
    at Ping.Sequence.OkPacket (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequences\Seque
nce.js:105:8)
    at Protocol._parsePacket (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Protocol.js:271:
23)
    at Parser.write (C:\prestigeserver\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Parser.js:77:12)

Details:  Error: ER_NO_SUCH_TABLE: Table 'prestige2.bookings_invoice__invoices_bookings' doesn't exist

from Postman I can see the client is sending this object:
{"customer":{"id":1,"name":"John","surname":"Doe","company":"Apple","address":"5 avenue","street_n":"9A","cap":"1000","city":"NY","province":"NY","country":"USA","nationality":"USA","phone":"000000","email":"johndoe@gmail.com","tax_n":"3456756754","notes":"nope","createdAt":"2015-04-25T23:19:07.000Z","updatedAt":"2015-07-24T17:13:30.000Z"},"id":92,"booking_n":1437818426364,"room":"Suite ","guest":"Doe","guests_n":2,"arrival":"2015-07-20T22:00:00.000Z","departure":"2015-07-24T22:00:00.000Z","createdAt":"2015-07-24T22:00:00.000Z","updatedAt":"2015-07-25T10:00:48.000Z","invoice":88}

A: I found my own mistake: as mentioned in my previous comment the error refer to a wrong model association, in my case due to a typo error: I wrote invoice: {mode:'invoices'}, instead of invoice: {model:'invoices'}.


text:
Q: Why is.summary on the Python newspaper3k module returning blank? I'm presently coding a quick python script to summarize a given news article using the newspaper3k module
The following code to retrieve and print the text in the terminal works fine.
import newspaper

# Assign url
url = 'url'

# Extract web data
url_i = newspaper.Article(url="%s" % (url), language='en')
url_i.download()
url_i.parse()

# Display scraped data
print(url_i.text)

However when i replace the ".text" method in the last line with the ".summary" Nothing pops up, though i still get a code zero indicating that the compiler found no errors
It seems that it is working but is just not displaying for some reason.
Thanks.
Tried looking at the documentation and online but .summary seems to work just fine for everyone else.

A: Newspaper3k has a special syntax to print an article summary.
Here is an example from my Newspaper3kusage documentation
from newspaper import Config
from newspaper import Article

USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Firefox/78.0'

config = Config()
config.browser_user_agent = USER_AGENT
config.request_timeout = 10

base_url = 'https://www.theguardian.com/news/2020/dec/08/the-curse-of-white-oil-electric-vehicles-dirty-secret-lithium'
article = Article(base_url, config=config)
article.download()
article.parse()
article.nlp()
print(article.summary)

Output:
The sudden excitement surrounding petróleo branco ("white oil") derives from an invention rarely seen in these parts: the electric car.
More than half (55%) of global lithium production last year originated in just one country: Australia.
The Portuguese government is preparing to offer licences for lithium mining to international companies in a bid to exploit its "white oil" reserves.
As manufacture has slowed down, a glut of lithium on global markets has dampened the white oil boom, if only temporarily.
If people were better informed, he reasoned, it's just possible that public opinion could swing to their side, and the country's lithium mining plans could get shelved.


text:
Q: Gerunds in the following sentences? I was pretty clear about Gerunds. But following two examples make me confused.

he had a newspaper empire backing him

This example is from google translator https://translate.google.co.in/?um=1&ie=UTF-8&hl=en&client=tw-ob#auto/en/back . They say "backing" is verb here. But i think "backing" is used here as a gerund(noun).
Another example

I've been dreaming of summer all winter long

This example is from http://www.gingersoftware.com/content/grammar-rules/nouns/gerunds/ (at the bottom). They say "dreaming" is gerund here. But i think it is a verb.
So are these examples are wrong  or am  I  missing something ?

A:
I've been dreaming

This example is not a gerund; it is the present perfect continuous of the verb "dream".


text:
Q: "ModuleBuildError: Undefined variable: "$base-spacing" when attempting to build Vue cli-3 app on Jenkins Server Stack:

*

*Vue CLI 3.0.0-beta.11

*Node 5.6

*Jenkins 2.7

I used VUE CLI 3 to build a simple proof-of-concept in Webstorm for work.  I had no issues building locally, and creating some simple vue components. So far, great experience.
One of my dev dependencies for my project is privately hosted package which contains the global styles for the entire company. Mostly, this package contains common vars, typography, structure code, etc. I was able to add the following to my vue.config.js in order to pull the scss files in and globally use them in my .vue files.  Works great locally using npm run serve or npm run build.
config.module.rule('scss').oneOf('normal').use('sass-loader')
    .tap(options =>
      merge(options, {
        data: '@import "~@myCorp/mycorp.ui.styles/shared/vars";' +
               '@import "~@myCorp/mycorp.ui.styles/shared/structure";' +
               '@import "~@myCorp/mycorp.ui.styles/shared/typography";'
      }))

It took me a while to get this working correctly, but this seems to work great using npm run serve. Also, npm run build outputs the correct files that work great in my CDN when I run the command locally, then manually upload the files.
The problem I have is when I try and execute npm run build while on my Jenkins CI box.  I have a Jenkins job that essentially runs the following:
npm install
npm run-script build-dev
\\This just runs vue-cli-service build --mode dev

I'm consistently getting several of the following error:
Module build failed: ModuleBuildError: Module build failed:
    width: $base-spacing * 4;
      ^
    Undefined variable: "$base-spacing".

I get this error once for each of my components, and they each error on the first variable i'm using from my global scss files.  It seems the build is having issues loading the scss files, but I can't figure what would be different.
Like I said before, Webstorm has zero issue finding the files and including them in local builds, but as soon as I put them in Jenkins, it fails building.  I've tried importing the files in different ways, through a local scss import in my main.scss in my project, or even importing them directly in my main.js, but they don't get picked up by the loaders.
What am I missing?  Is there something different about paths that I need to take into account for CI/CD?

A: After upgrading to beta-15, I was no longer to able to get this to work locally. I posted an issue to the cli githib: https://github.com/vuejs/vue-cli/issues/1511
The correct answer is to not modify the sass-loader directly using tap, but to rather use the built in css.loaderOptions.sass block in vue.config.js. Thus, my vue.config.js turned into this:
css: {
    loaderOptions: {
      sass: {
        data: '@import "~@myCorp/mycorp.ui.styles/shared/vars";'
      }
    }
  }

Works great!