text:
Q: Ebay API: Complete Sale External Payment I need to mark an item as paid for on ebay when a payment is maid through an external payment page (not PayPal). I have been looking at CompleteSale, but this looks like I need a transactionID but how do I get a transactionID of a transaction that hasn't occured on ebay? Maybe im going about this the wrong way.
Anyone know how to mark an item as paid through ebay API? I have the item id, sellers ID and the payer's ebay id.

A: You're on the right path with CompleteSale but missing some understanding of how it all plugs together.
The transactionID exists as soon as the buyer commits to buy, it is the TransactionID of the sale.
You need to provide the TransactionType.Item.ItemID and the TransactionType.TransactionID, if the sale is an Auction then simply put 0 (Zero) in the field as the ItemID is all that is required to uniquely identify the sale.
You don't need to provide the payer's ID as the transaction can be uniquely identified by the previous fields.
You can get the TransactionID from the eBay API by calling GetSellerTransactionsCall among others.
Hope that helps.


text:
Q: Mailchimp - Conditional Merge tage to compare dates I am trying to compare two dates using mailchimp merge tags
where both dates are not getting compare.
kindly provide solution
 *|IF:COMP_DATE=2016-06-06|*
 *|COMP_DATE|* is your completion date.
 *|END:IF|*

where  COMP_DATE has already stored value is  06-06-2016

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: DexClassLoader: Unable to extract+optimize DEX from xx err: No child processes I use DexClassloader to load a dex file from /data/data/packagename/ just like:
private static synchronized Boolean injectAboveEqualApiLevel14(
            String dexPath, String defaultDexOptPath, String nativeLibPath, String dummyClassName) {
        BaseDexClassLoader pathClassLoader = (BaseDexClassLoader) DexInjector.class.getClassLoader();
        DexClassLoader dexClassLoader = new DexClassLoader(dexPath, defaultDexOptPath, nativeLibPath, pathClassLoader);
        try {
            dexClassLoader.loadClass(dummyClassName);
            Object dexElements = combineArray(
                    getDexElements(getPathList(pathClassLoader)),
                    getDexElements(getPathList(dexClassLoader)));
            Object pathList = getPathList(pathClassLoader);
            setField(pathList, pathList.getClass(), "dexElements", dexElements);
        } catch (Throwable e) {
            LogTool.i(TAG, "Throwable: " + e.toString() + "\n" + e.getMessage() + "\n");
            e.printStackTrace();
            return false;
        }
        return true;
    }

It run perfectly on most of machine and system.......
But today, a user feedback that dex file can't be loaded,,,Here is the importance Error Log:
12-03 15:19:12.725: E/dalvikvm(32068): waitpid failed: wanted 32099, got -1: No child processes
12-03 15:19:12.725: E/dalvikvm(32068): Unable to extract+optimize DEX from '/data/data/com.test.plugin/dex/classes1.dex', err: No child processes

Phone Information: HTC 9060, Android 4.2.2,HTC Sense 5.0
It's a strange bug. Here is the complete log:
  12-03 15:19:12.725: E/dalvikvm(32068): waitpid failed: wanted 32099, got -1: No child processes
12-03 15:19:12.725: E/dalvikvm(32068): Unable to extract+optimize DEX from '/data/data/com.test.plugin/dex/classes1.dex', err: No child processes
12-03 15:19:12.725: E/System(32068): Unable to load dex file: /data/data/com.test.plugin/dex/classes1.dex
12-03 15:19:12.725: E/System(32068): java.io.IOException: unable to open DEX file
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexFile.openDexFile(Native Method)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexFile.<init>(DexFile.java:109)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexFile.loadDex(DexFile.java:149)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexPathList.loadDexFile(DexPathList.java:251)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexPathList.makeDexElements(DexPathList.java:210)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexPathList.<init>(DexPathList.java:96)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:56)
12-03 15:19:12.725: E/System(32068):    at dalvik.system.DexClassLoader.<init>(DexClassLoader.java:57)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.a.a.d(ProGuard:153)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.a.a.a(ProGuard:46)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.b.a(ProGuard:41)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.c.a(ProGuard:104)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.c.a(ProGuard:79)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.c.a(ProGuard:69)
12-03 15:19:12.725: E/System(32068):    at com.test.plugin.main.e.run(ProGuard:74)


text:
Q: Error using tmx with pygame I'm trying to follow a tutorial/lecture on use of the module pygame in Python,  http://www.youtube.com/watch?v=mTmJfWdZzbo. I also have all the files referenced in the video, here https://bitbucket.org/r1chardj0n3s/pygame-tutorial/src/a383dd24790d?at=default. My problem occurs when trying to use .tmx files as a map for the game, step 14. I've tried writing my own code, but I also tried just using the code supplied from the lecture. No matter what I do, I can't seem to get past the following error:
C:\Users\me\Copy\Div\pygame\Platformer>python platformer.py
Traceback (most recent call last):
  File "platformer.py", line 74, in <module>
    Game().main(screen)
  File "platformer.py", line 50, in main
    self.tilemap = tmx.load('map.tmx', (640,480))
  File "C:\Users\me\Copy\Div\pygame\Platformer\newtmx.py", line 573, in load
    return TileMap.load(filename, viewport)
  File "C:\Users\me\Copy\Div\pygame\Platformer\newtmx.py", line 456, in load
    layer = Layer.fromxml(tag, tilemap)
  File "C:\Users\me\Copy\Div\pygame\Platformer\newtmx.py", line 242, in fromxml
    data = data.decode('base64').decode('zlib')
  File "C:\Python27\lib\encodings\zlib_codec.py", line 43, in zlib_decode
    output = zlib.decompress(input)
zlib.error: Error -5 while decompressing data: incomplete or truncated stream

Here "platformer.py" is my exact replica of the file named "14-tillemap.py" in the supplied files (and "map.tmx" also from the supplied files).
import pygame
import tmx

class Player(pygame.sprite.Sprite):
    def __init__(self, location, *groups):
        super(Player, self).__init__(*groups)
        self.image = pygame.image.load('player.png')
        self.rect = pygame.rect.Rect(location, self.image.get_size())
        self.resting = False
        self.dy = 0

    def update(self, dt, game):
        last = self.rect.copy()

        key = pygame.key.get_pressed()
        if key[pygame.K_LEFT]:
            self.rect.x -= 300 * dt
        if key[pygame.K_RIGHT]:
            self.rect.x += 300 * dt

        if self.resting and key[pygame.K_SPACE]:
            self.dy = -500
        self.dy = min(400, self.dy + 40)

        self.rect.y += self.dy * dt

        new = self.rect
        self.resting = False
        for cell in game.tilemap.layers['triggers'].collide(new, 'blockers'):
            if last.right <= cell.left and new.right > cell.left:
                new.right = cell.left
            if last.left >= cell.right and new.left < cell.right:
                new.left = cell.right
            if last.bottom <= cell.top and new.bottom > cell.top:
                self.resting = True
                new.bottom = cell.top
                self.dy = 0
            if last.top >= cell.bottom and new.top < cell.bottom:
                new.top = cell.bottom
                self.dy = 0

        game.tilemap.set_focus(new.x, new.y)

class Game(object):
    def main(self, screen):
        clock = pygame.time.Clock()

        background = pygame.image.load('background.png')

        self.tilemap = tmx.load('map.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        while 1:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    Game().main(screen)

I really can't figure out this error, nor could I find any problem relevant to this answered somewhere else.
I'm running Python 2.7 on a 64-bit windows 8.1 (if that matters)


text:
Q: Where are Ubuntu 18 network shares configured? I have a local server running Ubuntu 18.04.1 which was recently upgraded from Ubuntu 15 where I had a few shares configured manually via Samba in /etc/samba/smb.conf like:
[myshare]
    path = /home/user
    writeable = yes
    valid users = root, user

This has continued to work just fine since the upgrade but today I noticed if I right-click on a directory in Gnome I get a dialog window with a tab called "Local Network Share" that looks like this:

I enabled it and now it's showing up on my LAN as another share.  My question is, where is this configured?  Is it using Samba as well or some other service?  I took a look at smb.conf where the other shares are configured but its not there.

A: ** "Local Network Share" is the gnome implementation ( nautilus-share ) of a Samba Usershare. Its intent was to allow an ordinary user the ability to share a directory he owned.
** A Samba Usershare and for want of a better name a Samba Classic Share both create Samba share definitions but as indicated above those definitions reside in different files. Usershare: /var/lib/samba/usershares vs ClassicShare: /etc/samba/smb.conf.
** Samba will read both and that can be a problem if both are used to define the share of the same directory because they might be defined differently as is the case here. Your guess is as good as mine which one Samba will obey.
** You cannot in this case reproduce through Nautilus the share definition you have in smb.conf because nautilus-share does not have that option: There is no "valid users" option in nautilus-share - it's either guest access or anyone with samba credentials. You cannot specify a list of users or groups.
** A Samba Classic Share offers many other options not available to Usershares so it depends on how complex your requirements are for these shares.


text:
Q: WiFi Adapter AX201 Not Found: Ubuntu 18.04 Please note that this question is specific to Intel WiFi adapters.
My laptop is an HP ENVY with an Intel AX201 Wifi Adapter. I've dualbooted Ubuntu with Windows.
AX201 WiFi adapter is not supported by latest Ubuntu 18.04 version, because Ubuntu 18.04 comes with Linux Kernel 5.0, whereas support for AX201 comes built-in in Linux Kernel 5.2+. Canonical claims that Ubuntu 18.04 will get Linux Kernel 5.3 sometime next year. However, I wont be able to wait that long.
I tried downloading and installing Kernel 5.2.14, but I cant go beyond Grub: I get the error:

error: you need to load the kernel first.

Other option is to download the Intel Backport Driver, which I tried. That didn't seem to work either. As per the tutorials, I've restarted frequently, but that didnt work either.
Also I'm not quite sure if Intel IWLWIFI Backport driver supports AX201 in the first place.
WiFi works while I'm booted in Windows.
What should I do?
Thanks in advance!
UPDATE
I tried out @Pilot6's answer, and it worked. Thanks!
I have one last question: I've read that if you upgrade the Kernel beyond what Ubuntu 18.4 supports, its kinda unsafe (which I read as prone to system crashes).
I dont want system crashes because I have only one partition (root) for Ubuntu, and any crash would likely mean all my data is lost. One method forward would be to split my Ubuntu partition into root and home.
So if I want to access WiFi on my device safely without risking any crashes, what should I do?
My understanding of Ubuntu and Linux may be wrong as they are built on forum answers only. Please correct me if Im wrong anywhere.

A: This wireless adapter is supported by the 5.3 Linux kernel.
You can install the 5.3 kernel already a normal "Ubuntu" way.
Run in a terminal
sudo apt install linux-generic-hwe-18.04-edge

That will install the 5.3 kernel used in Ubuntu 19.10.
As soon as the 5.3 kernel is provided by linux-generic-hwe-18.04 (without edge), you can replace the meta package.
Some time next year linux-generic-hwe-18.04-edge will pull some next kernel and linux-generic-hwe-18.04 will pull the 5.3. If you don't want to switch to a new major kernel version, you can always remove linux-generic-hwe-18.04-edge and install linux-generic-hwe-18.04 later.

A: Had similar problem on Ubuntu 18.04 LTS (Dell Precision 7550). Open a terminal and follow these steps:
sudo apt-get install backport-iwlwifi-dkms
sudo apt-get update
sudo modprobe iwlwifi

Then running the following command:
lshw -C Network

If you saw driver=iwlwifi then the wifi should be installed successfully.


text:
Q: PHPSlim + angular-file-upload I use angular-upload-file with a server side built with PHP Slim Framework.
On my FileUploader config I simply have :
$scope.uploader = new FileUploader({
    url: 'upload/upload.php'
});

Then in my backend, like the related wiki does :
 if ( !empty( $_FILES ) ) {
    $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
    $uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];
    move_uploaded_file( $tempPath, $uploadPath );
    $answer = array( 'answer' => 'File transfer completed' );
    $json = json_encode($answer);
    echo $json;
} else {
    echo 'No files';
}

The problem is when I put this code without using PHP Slim it works fine, but when I try to wrap it with PHPSlim , I get a GET request instead of POST:

with a such code :
 $scope.uploader = new FileUploader({
    url: 'API/upload/img'
});

And into the API :
$app->post('/upload/img', function(){
if ( !empty( $_FILES ) ) {
    $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
    $uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];
    move_uploaded_file( $tempPath, $uploadPath );
    $answer = array( 'answer' => 'File transfer completed' );
    $json = json_encode($answer);
    echo $json;
} else {
    echo 'No files';
}

});
I try to figure out where the issue come from, server or client side ?
I tried to use a similar plugin ng-file-upload but I have exactly the same problem, so I think it should be PHPSlim but I am not sure.
I need to use PHPSlim because I use a middleware for some required authentication requests.
Thanks in advance,

A: First you need to call right address for the API:
var uploader = $scope.uploader = new FileUploader({
  url: 'api/path/upload'
});

in backend you need
 $app->post('/upload', function() {
      if ( !empty( $_FILES ) ) {...
      }
 })

if you have problem with message response need to formatted I build on this way:
    $answer = array(
          'status' => 'success',
          'message' => 'File transfer completed',
        );
...
  echoResponse(200, $answer);
...
    function echoResponse($status_code, $response) {
        global $app;
        $app->status($status_code);
        $app->contentType('application/json');
        echo json_encode($response, JSON_NUMERIC_CHECK);
    }

also create and set write folder permission for
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];


text:
Q: php simple html dom  bgcolor ok i've been reading up on simple php html dom and so far it works great.
I have a table which i'm trying to convert to a mysql db.
I'm using this:
foreach($html->find('TR') as $row) {
  etc.etc.etc.
}

my table:

but how do i get the bgcolor from the tr ?

A: Did you try the $row->getAttribute('bgcolor') method?


text:
Q: Return array of interface from a .NET method via COM4J How can I return an array of objects (implementing a COM interface) from a C# method to a Java method via COM4J?
Example C# class that generates an array:
using System;
using System.Runtime.InteropServices;

namespace Example
{

    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IAnimal
    {
        string Speak();
    }

    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IFarm
    {
        [return:MarshalAs(UnmanagedType.SafeArray,
        SafeArraySubType=VarEnum.VT_UNKNOWN)]
        IAnimal[] GetAnimals();
    }

    [ComVisible(true), ClassInterface(ClassInterfaceType.None)]
    public class Farm : IFarm
    {
        public IAnimal[] GetAnimals()
        {
            return new IAnimal[] { new Cow(), new Pig() };
        }
    }

    internal class Cow: IAnimal
    {
        public string Speak()
        {
            return "Moo";
        }
    }

    internal class Pig: IAnimal
    {
        public string Speak()
        {
            return "Oink";
        }
    }
}

The interface declaration in the resulting .tlb looks like this:
[
  odl,
  uuid(1FB5E376-E78D-3A2E-BEF3-F3C798FCF44C),
  version(1.0),
  oleautomation,
  custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "Example.IFarm")
]
interface IFarm : IUnknown
{
    HRESULT _stdcall GetAnimals([out, retval] SAFEARRAY(IUnknown*)* pRetVal);
};

Java client code:
import com4j.*;

public class Example {
    public static void main(String[] args) {
        IFarm farm = ClassFactory.createFarm();
        Com4jObject[] animals = farm.getAnimals();

        for (Com4jObject o: animals) {
            IAnimal animal = o.queryInterface(IAnimal.class);

            if (animal != null) {
                animal.speak();
            }
        }
    }
}

This compiles but I get this exception at runtime:
Exception in thread "main" com4j.ComException:
    unexpected conversion type: 500 : .\invoke.cpp:470
        at com4j.Wrapper.invoke(Wrapper.java:185)
        at $Proxy5.getAnimals(Unknown Source)
        at MainClass.main(MainClass.java:7)
Caused by: com4j.ComException: unexpected conversion type: 500 : .\invoke.cpp:470
        at com4j.Native.invoke(Native Method)
        at com4j.StandardComMethod.invoke(StandardComMethod.java:35)
        at com4j.Wrapper$InvocationThunk.call(Wrapper.java:354)
        at com4j.Task.invoke(Task.java:55)
        at com4j.ComThread.run0(ComThread.java:157)
        at com4j.ComThread.run(ComThread.java:137)

Other things I have tried:

*

*Marshalling as a SAFEARRAY(VARIANT)* instead of SAFEARRAY(IUnknown*)*
(this throws the same exception.)

*Removing the MarshalAs attribute (tlbimp fails to create the proxy method)

Is there a way to marshal the array so that COM4J can convert it to a valid Java array?
Alternatively is there a way to allocate an array in Java and allow the .NET method to populate it?  (I tried this but the .NET method receives a copy of the array and the Java code never sees the objects inserted into the copy.  Maybe there's a way to override this?)

Edit: This may be related: https://stackoverflow.com/a/6340144/12048 - something similar appears to be possible from VBScript

A: Have you tried declaring your interfaces as InterfaceIsDual and/or InterfaceIsIDispatch?
[ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAnimal
{
...

Most COM interop libraries require a dispatch interface; however, I'm not sure about COM4J.  You could also use an abstract base COM class rather than an interface to achieve the same goal, but I'd be surprised if the above change doesn't get you up and running.


text:
Q: AWS Lambda: No space left on device I'm trying to create a lambda function that download 2 files from S3 - each 10 GB.
I am only able to write to /tmp folder, and there is a limit for the /tmp folder of 500MB, so I get No space left on device.
Is there a way to download those files via lambda?
Or if not via lambda, what is the preferred option (is serverless is option?!)?

A: This is not really a great job for Lambda.
I would use a service like Data pipeline and write a custom job or if it is simple enough an EC2 with a userdata script that when the task completes the instance terminates.


text:
Q: Get checkbox value without page refresh I got a table of checkboxes:
<input id="box" name="box" type="checkbox" value="1" checked />
<input id="box" name="box" type="checkbox" value="2" checked />
<input id="box" name="box" type="checkbox" value="3" checked />

I want to submit checkbox value when I check or uncheck the box (each one at a time) Without refreshing the page to:
if (isset($_GET['box'])) {
   echo "Success!"
}

By far I got this javascript code to check whether the box is checked or unchecked:
function validate(){
if (document.getElementById('box').checked){
    alert("checked") ;
}else{
    alert("You didn't check it! Let me check it for you.")
}
}

I want to add AJAX on it, but all the snippet code I try so far didn't fit good with my code. I'll thank for your help.

A: You want to use AJAX. Here is an example in jQuery without AJAX:
<input id="box1" class="box" name="box1" type="checkbox" value="1" checked />
<input id="box2" class="box" name="box2" type="checkbox" value="2" checked />
<input id="box3" class="box" name="box3" type="checkbox" value="3" checked />

JavaScript:
$(document).ready(function() {
  $('.box').on('change', function(event) {
    var checkbox = $(event.target);
    var isChecked = $(checkbox).is(':checked');
    alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
  });
});

Demo: http://jsbin.com/ipasud/1/
Now instead of doing an alert call, do a $.post to a backend URL that takes an id and a value of checked or unchecked. For example,
$.post('/submit-checkbox.php', {id: checkbox.attr('id'), value: isChecked});

And if we put that back into the code, it would look like this:
$(document).ready(function() {
  $('.box').on('change', function(event) {
    var checkbox = $(event.target);
    var isChecked = $(checkbox).is(':checked');
    $.post('/whatever-your-url-is.php', {id: checkbox.attr('id'), value: isChecked});
  });
});

A: You can use jQuery: http://jquery.com/

Then in your PHP file you can get the value selected in $_POST['value'] and return what you want (in JSON format).


text:
Q: mysql create a table character sets In phpmyadmin, I entered:
CREATE TABLE ch
 ucs2 CHAR(3) CHARACTER SET ucs2,
 gb2312 CHAR(3) CHARACTER SET gb2312
 test3 CHAR(4) CHARACTER SET utf8;

And it gives me a syntax error.  What am I doing wrong here?

A: You forgotten parentheses:
CREATE TABLE ch(
 ucs2 CHAR(3) CHARACTER SET ucs2,
 gb2312 CHAR(3) CHARACTER SET gb2312,
 test3 CHAR(4) CHARACTER SET utf8
);


text:
Q: PHP - Checkbox and Implode I have multiple checkboxes that are hidden and based on the selection, the checkbox will appear. However, when I implode the checkboxes, it returns multiple commas I was thinking of using substr and if else to remove the amount of comma based on the question selection. Here's my mark up
            <?php
              if(isset($_POST['Submit'])) {
                $QuestionUsed = implode(',', $_POST['QuestionUsed']);
                $SolutionOffered = implode(',', $_POST['SolutionOffered']);
                echo $QuestionUsed;
                echo "
";
                echo $SolutionOffered;
              }
            ?>

              <form action="testing.php" method="post">

                    Port-Out Reason

                      <select id="portoutselector" name="PortOutQuestions" class="btn-block">
                        <option value=""></option>
                        <option value="PortOut1">Demande de numéro de compte</option>
                        <option value="PortOut2">Intérêt pour offre de la compétition</option>
                        <option value="PortOut3">Demande d'annulation sans vouloir donner une raison</option>
                        <option value="PortOut4">Plainte par rapport au réseau Rogers</option>
                        <option value="PortOut5">Déménagement à l'extérieur du réseau Rogers</option>
                        <option value="PortOut6">Déménagement à l'extérieur du pays</option>
                        <option value="PortOut7">Volonté de renégocier une offre existante au dossier ou de recevoir une offre additionnelle</option>
                        <option value="PortOut8">Déverrouillage d'appareil</option>
                      </select>

                    Questions utilisées?

                        <input type="checkbox" value="1" name="QuestionUsed[]">Pour quelles raisons désirez-vous cette information?
                        <input type="checkbox" value="2" name="QuestionUsed[]">Avez-vous besoin de cette information pour effectuer un paiement?
                        <input type="checkbox" value="3" name="QuestionUsed[]">Êtes-vous entrain vous inscrire à la facturation en ligne?
                        <input type="checkbox" value="4" name="QuestionUsed[]" id="otherbox01">Autres, spécifié:
                        <input type="text" id="Other01" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="5" name="QuestionUsed[]">Quelles est l'offre que vous avez reçu d'un autre fournisseur?
                        <input type="checkbox" value="6" name="QuestionUsed[]">Quels sont  les détails de l'offre qui vous intéresse?
                        <input type="checkbox" value="7" name="QuestionUsed[]">Quel est le compétiteur qui vous intéresse?
                        <input type="checkbox" value="8" name="QuestionUsed[]">Quels sont vos besoins?
                        <input type="checkbox" value="9" name="QuestionUsed[]">Quel est votre budget mensuel consacré à vos services sans fil?
                        <input type="checkbox" value="10" name="QuestionUsed[]" id="otherbox02">Autres, spécifié :
                        <input type="text" id="Other02" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="11" name="QuestionUsed[]">Il y a-t-il une offre de la compétition qui vous intéresse ?
                        <input type="checkbox" value="12" name="QuestionUsed[]">Êtes-vous satisfait avec Rogers ? (oui/non) Pourquoi?
                        <input type="checkbox" value="13" name="QuestionUsed[]">Êtes-vous au courant de nos offres promotionnelles?
                        <input type="checkbox" value="14" name="QuestionUsed[]" id="otherbox03">Autres, spécifié :
                        <input type="text" id="Other03" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="15" name="QuestionUsed[]">Vous expérimentez cet inconvénient depuis quand?
                        <input type="checkbox" value="16" name="QuestionUsed[]">Ce problème arrive partout ou dans un endroit en particulier?
                        <input type="checkbox" value="17" name="QuestionUsed[]">Avez-vous déjà  discuté de cette situation avec le département technique?
                        <input type="checkbox" value="18" name="QuestionUsed[]" id="otherbox04">Autres, spécifié :
                        <input type="text" id="Other04" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="19" name="QuestionUsed[]">Dans quelle région déménagez-vous?
                        <input type="checkbox" value="20" name="QuestionUsed[]">Pour combien de temps pensez-vous demeurer à cette adresse?
                        <input type="checkbox" value="21" name="QuestionUsed[]">Comptez-vous réutiliser ce téléphone dans le futur?
                        <input type="checkbox" value="22" name="QuestionUsed[]">Est-ce que vous comptez avoir les services d'un autre fournisseur pendant cette période?
                        <input type="checkbox" value="23" name="QuestionUsed[]" id="otherbox05">Autres, spécifié :
                        <input type="text" id="Other05" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="24" name="QuestionUsed[]">Est-ce que le déménagement est pour une période limité (vacances, travail, etc.) ou pour une durée indéterminée?
                        <input type="checkbox" value="25" name="QuestionUsed[]">Considérez-vous revenir au pays dans le futur ?
                        <input type="checkbox" value="26" name="QuestionUsed[]">Est-ce que vous avez un membre de votre famille ou amis restant au pays qui pourrait utiliser votre appareil?
                        <input type="checkbox" value="27" name="QuestionUsed[]" id="otherbox06">Autres, spécifié :
                        <input type="text" id="Other06" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="28" name="QuestionUsed[]">Qu'est-ce-qui vous fait douter de l'offre initiale?
                        <input type="checkbox" value="28" name="QuestionUsed[]">Quel aspect de l'offre ne vous satisfait pas?
                        <input type="checkbox" value="30" name="QuestionUsed[]">Il y a t- il une offre de la compétition qui vous intéresse?
                        <input type="checkbox" value="31" name="QuestionUsed[]" id="otherbox07">Autres, spécifié :
                        <input type="text" id="Other07" style="display:none" name="QuestionUsed[]">

                        <input type="checkbox" value="32" name="QuestionUsed[]">Pour quelles raisons désirez-vous faire déverrouiller votre appareil?
                        <input type="checkbox" value="33" name="QuestionUsed[]">Êtes-vous satisfait avec votre appareil?
                        <input type="checkbox" value="34" name="QuestionUsed[]">Êtes-vous au courant de nos nouvelles offres?
                        <input type="checkbox" value="35" name="QuestionUsed[]" id="otherbox08">Autres, spécifié :
                        <input type="text" id="Other08" style="display:none" name="QuestionUsed[]">

                    Solutions offertes?

                        <input type="checkbox" value="1" name="SolutionOffered[]">Réviser l'utilisation sans fil des 3 derniers mois et offrir la meilleure solution possible.
                        <input type="checkbox" value="2" name="SolutionOffered[]">Offert au client de l'inscrire à la facturation en ligne.
                        <input type="checkbox" value="3" name="SolutionOffered[]" id="otherbox11">Autres, spécifié :
                        <input type="text" id="Other11" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="3" name="SolutionOffered[]">Réviser l'utilisation des 3 derniers mois et lui offrir une offre rétention par rapport à ses besoins.
                        <input type="checkbox" value="4" name="SolutionOffered[]">Forfait Québec à 70$
                        <input type="checkbox" value="5" name="SolutionOffered[]">Offrir des escomptes sur des plans sur le marché
                        <input type="checkbox" value="6" name="SolutionOffered[]">Revendre son plan actuel (client possédant plan rétention ou plan promotionnel
                        <input type="checkbox" value="7" name="SolutionOffered[]" id="otherbox12">Autres, spécifié :
                        <input type="text" id="Other12" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="8" name="SolutionOffered[]">Offrir au client de réviser son forfait.
                        <input type="checkbox" value="9" name="SolutionOffered[]">Offrir un offre de bonne foi (si demandé)
                        <input type="checkbox" value="10" name="SolutionOffered[]">Offrir une offre de rétention selon ses besoins
                        <input type="checkbox" value="11" name="SolutionOffered[]" id="otherbox13">Autres, spécifié :
                        <input type="text" id="Other13" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="12" name="SolutionOffered[]">Faire une résolution de problème avec le client.
                        <input type="checkbox" value="13" name="SolutionOffered[]">Offrir un OOW si nécessaire.
                        <input type="checkbox" value="14" name="SolutionOffered[]">Offrir un rehaussement d'appareil.
                        <input type="checkbox" value="15" name="SolutionOffered[]" id="otherbox14">Autres, spécifié :
                        <input type="text" id="Other14" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="16" name="SolutionOffered[]">Recommandez  un transfert de responsabilité.
                        <input type="checkbox" value="17" name="SolutionOffered[]">Offrir au client une suspension temporaire si nécessaire/offre de dernier recours.
                        <input type="checkbox" value="18" name="SolutionOffered[]" id="otherbox15">Autres, spécifié :
                        <input type="text" id="Other15" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="19" name="SolutionOffered[]">Offrir au client une suspension temporaire au dossier.
                        <input type="checkbox" value="20" name="SolutionOffered[]">Offrir au client 50% de rabais pour 6 mois ou 12 mois selon les cas
                        <input type="checkbox" value="21" name="SolutionOffered[]">Offrir au client la meilleure offre possible selon son utilisation au cours des 3 dernier mois
                        <input type="checkbox" value="22" name="SolutionOffered[]" id="otherbox16">Autres, spécifié :
                        <input type="text" id="Other16" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="23" name="SolutionOffered[]">Repositionner et revendre la valeur $$ de l'offre déjà présente au dossier.
                        <input type="checkbox" value="24" name="SolutionOffered[]">Faire une nouvelle offre lorsque les besoins du client sont différents du plan déjà offert.
                        <input type="checkbox" value="25" name="SolutionOffered[]">Offrir la migration vers Fido lorsque les conditions requises sont remplies.
                        <input type="checkbox" value="26" name="SolutionOffered[]" id="otherbox17">Autres, spécifié :
                        <input type="text" id="Other17" style="display:none" name="SolutionOffered[]">

                        <input type="checkbox" value="27" name="SolutionOffered[]">Offrez au client un nouvel appareil (si la situation le demande).
                        <input type="checkbox" value="28" name="SolutionOffered[]">Offrir offre au client la meilleure possible selon son utilisation au cours des 3 dernier mois
                        <input type="checkbox" value="29" name="SolutionOffered[]" id="otherbox18">Autres, spécifié :
                        <input type="text" id="Other18" style="display:none" name="SolutionOffered[]">

                <input type="submit" name="Submit" value="Submit">
              </form>

Current results:
,5,6,,,,,,,
,3,4,,,,,,,

Expected results:
5,6
3,4

A: What if you do this with proper checks, like:
$QuestionUsed = isset($_POST['QuestionUsed']) && is_array($_POST['QuestionUsed']) ? $_POST['QuestionUsed'] : array();
$SolutionOffered = isset($_POST['SolutionOffered']) && is_array($_POST['SolutionOffered']) ? $_POST['SolutionOffered'] : array();

foreach ($QuestionUsed as $index => $question) {
    if (empty($question)) {
        unset($QuestionUsed[$index]);
    }
}

foreach ($SolutionOffered as $index => $solution) {
    if (empty($solution)) {
        unset($SolutionOffered[$index]);
    }
}

$QuestionUsed = implode(',', $QuestionUsed);
$SolutionOffered = implode(',', $SolutionOffered);

Refactored with a small function would be:
function getCommaSeparatedStringFromArray(array $data = array()) {
    foreach ($data as $key => $value) {
        if (empty($value)) {
            unset($data[$key]);
        }
    }
    return implode(',', $data);
}

$QuestionUsed = isset($_POST['QuestionUsed']) && is_array($_POST['QuestionUsed']) ? $_POST['QuestionUsed'] : array();
$SolutionOffered = isset($_POST['SolutionOffered']) && is_array($_POST['SolutionOffered']) ? $_POST['SolutionOffered'] : array();

$QuestionUsed = getCommaSeparatedStringFromArray($QuestionUsed);
$SolutionOffered = getCommaSeparatedStringFromArray($SolutionOffered);

A: you can use trim to cut off extra comma's, like:
$QuestionUsed = trim(implode(',', $_POST['QuestionUsed']),',');


text:
Q: Fancytree does not execute in a Bootstrap modal I am using the fancytree plugin within Bootstrap. It works well on a standard page, however when invoked in a modal, it does nothing.
The function is declared and jQuery().fancytree returns true.
I am unable to also get the debug output, so looks like it is not being invoked at at all
a DIV with id ntree is defined
my HTML in the modal

A: use 'source' property instead of 'children'.
jsfiddle; http://jsfiddle.net/Lu2a67b2/
JS:
jQuery(document).ready(function(){
    // Create the tree inside the
 element.
    console.log(jQuery().fancytree);
    if (jQuery().fancytree){
        alert("function exists");
        $("#ntree").fancytree({
            source: [ // Pass an array of nodes.
                {title: "Item 1"},
                {title: "Folder 2", isFolder: true,
                    children: [
                        {title: "Sub-item 2.1"},
                        {title: "Sub-item 2.2"}
                    ]
                },
                {title: "Item 3"}
            ],
            debugLevel: 2
        });
    } else {
        alert("Fancytree is not declared");
    }
});


text:
Q: TurboCARTO ramps do not work with CartoCSS user conditional filters If you want to define manual class breaks with the ramp() function it seems you're out of luck; as far as I can tell this is not working as intended. For example, here I try to supply different colors for values that fall within user specified ranges
Code:
#layer{
           [dominant_origin = "Puerto-Rican"]{
             polygon-fill: ramp([relative_dom], (#004c6d, #3d708f, #6996b3, #94bed9, #c1e7ff), (.2, .4, .6, .8, 1), "<=");
           }
           [dominant_origin = "South American"]{
             polygon-fill: ramp([relative_dom], (#ff0000, #ff5d38, #ff8b67, #ffb297, #ffd8cb), (.2, .4, .6, .8, 1), "<=");
           }
           [dominant_origin = "Central American"]{
             polygon-fill: ramp([relative_dom], (#00ff00, #6cfb53, #97f67e, #b7f0a3, #d1eac7), (.2, .4, .6, .8, 1), "<=");
           }
           [dominant_origin = "Dominican"]{
             polygon-fill: ramp([relative_dom], (#ffff00, #fcf853, #f8f17b, #f1eb9d, #e9e4bd), (.2, .4, .6, .8, 1), "<=");
           }
           [dominant_origin = "Mexican"]{
             polygon-fill: ramp([relative_dom], (#7f00ff, #a451ff, #c181ff, #daaeff, #efdbff), (.2, .4, .6, .8, 1), "<=");
           }
           [dominant_origin = "Other"]{
             polygon-fill: ramp([relative_dom], (#000000, #363636, #6a6a6a, #a4a4a4, #e2e2e2), (.2, .4, .6, .8, 1), "<=");
           }
           [dominant_origin = "Cuban"]{
             polygon-fill: ramp([relative_dom], (#e6550d, #f17940, #f99a6b, #feba98, #ffd9c6), (.2, .4, .6, .8, 1), "<=");
           }
         }

if you console.log() the event on a metaDatachange you get this:
_buckets: Array(5)
0: {min: null, max: 0.2, value: "#004c6d"}
1: {min: 0.2, max: 0.4, value: "#3d708f"}
2: {min: 0.4, max: 0.6, value: "#6996b3"}
3: {min: 0.6, max: 0.8, value: "#94bed9"}
4: {min: 0.8, max: undefined, value: "#c1e7ff"}

If you console.log() bucket.min and bucket.max you'll get:
null
undefined

This is an issue for a few reasons. First you're getting nulls and undefined values for min and max in the first and last bins. Second, the class breaks are not explicit. Lastly, the last value supplied in the filter is ignored.
I know in a previous issue it was suggested to use the "<" mapping instead, but the result is exactly the same.

A: TurboCARTO, the CartoCSS preprocessor that works behind the scene everytime you run a ramp, does not support conditional styling. This was reported 3 years ago. So do not expect to be fixed.


text:
Q: Transistor switch with 2N2222A and cooling fan as load I am building a temperature sensor monitoring system with microcontroller.
The input node changes the value if the sensor detects a temperature higher than 70 degrees. I have checked the voltage at the input node, its 3.28V, when its supposed to be high, the fan needs 0.18A to turn on. the voltage at the output node (collector) is 2.2V, but is supposed to be 3.3V with enough current to turn on the fan.

Could someone suggest a solution to amplify the voltage at the collector and its current.
Thank you

A: If the switch were off, then the voltage at the collector of the transistor would be 12 volts. The fact that it's lower than that means that the transistor is conducting, which is bringing the voltage on the near side of the fan down lower than 12.
The way an NPN BJT transistor works is that the current flowing from the base to the emitter will allow a proportionally higher current too flow from the collector to the emitter. What you must figure out is how much current is flowing from the base to the emitter. If that is insufficient to cause sufficient collector current, then you must lower the resistor value.
What you likely want is to get the transistor into saturation. This means that there is insufficient voltage (because of the impedance of the load - the fan) to drive more current through the transistor. Increasing the base current won't make more collector current flow in this situation and the transistor will (more or less) act like a closed switch.
That said, if your input is a 5 volt logic high, then you're sending 33 mA (or so - the base-emitter junction won't be zero volts, after all), which "ought" to be enough to saturate that transistor.
I wonder if maybe 33 mA is too much current for the microcontroller pin in question. If so, you potentially might have (or might soon) blow that pin. You might consider increasing that resistor value. 220Ω or 330Ω are more like values I'd use under similar circumstances.


text:
Q: Can I add tabindex attribute to ::before I have a label element wherein I add an image to it from css.
<label id="label1" tabindex="0">Some Text</label>

CSS
label#label1:before {
 content: url(../../img/icon-radio_unselected.svg);}

Now when I reach this label using tab key, it highlights the entire label along with the image which in my case, the image should only be highlighted. I was thinking of adding the tabindex to the ::before selector, but not sure if this is at all possible.
Can anyone please suggest if this is the right way or should I use a different approach altogether.


text:
Q: MVC File upload random fails I've been working on a MVC project which includes uploading files. I cannot quite figure this one out.
I've configured so that I can upload ~1GB per file, now we're talking about a small image, say 0.05MB that I'm trying to upload. About ~30% av all times i get thrown to the error page in my project, I've notices that I can still have a perfect connection while uploading.
The problem only occurs on iPhone/iPad so far. When I choose to upload a file it works sometimes, and sometimes not. I see no specific patterns for failure, except that I get thrown to the error page, and that happens when a page/file cannot be found in my project.
I cannot debug this with breakpoints easily since the problem only occur on wireless devices (iPhone/iPad) when the project is published online. I've checked all the Views and all "return function" in the code and see no errors.
I've tried adding new values in web.config but without success (eg. executionTimeout)I've also set the web.config to accept files up to ~1GB.
As I've said, the upload process fails randomly, even if I repeat the procedure in the exact same order.
What do you think I should do, any idea what to try? Can I debug on my iPad, that would have helped me. I did install Safari for Windows, no result.
Building in VS2015.
Thank you very much!
Regards
Edit:
I've been struggling to prevent the default error message page with a custom made one (if uploaded file not found) and entered this line into Web.config:
<add name="ApiURIs-ISAPI-Integrated-4.0" path="/files/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

But since I'm not exactly sure what it does more than gives me my beautiful error page it also seems to prevent some files to be uploaded. Since I removed this line from Web.config it seems to work for the moment, if we can count on chance...


text:
Q: Check mobile token Can you tell me if there is a possibility to verify mobile tokens?
We have a mobile application, when logging into the server, the user receives a token. The token + user_id is written to the database The token is needed to send push messages through firebase cloud messaging.
That is the question: when installing the application again or updating, the user receives a new token, how to remove an old token? Perhaps there is a check in Firebase? The uniqueness by user_id is not suitable since it should be possible to install on different devices.
Do we send 3-4 tokens at a time to firebase and cannot check a specific token for sending a message? Or can we?

A: You can use Group Notifications send notifications to multiple devices with same user.
Use cloud function to create/update a device group with FCM token when it updates.
More info
When device group updated, you can send notification to that perticular group using cloud finction and it will be received by all devices. You don't need to replace or maintain expired tokens that way.

A: The best way is to store the token in the device's local storage.
If the token was refresh or an update happened, you will get a new token. Then, you check if there's another token saved or not. If saved, send both to server and do a replacement. Else, consider it a new user.


text:
Q: Stop query when SUM is reached (mysql) I have a database with colums I am working on.  What I am looking for is the date associated with the row where the SUM(#) reaches 6 in a query.  The query I have now will give the date when the number in the colum is six but not the sum of the previous rows.  example below
Date     number
----     ------
6mar16    1
8mar16    4
10mar16   6
12mar16   2

I would like to get a query to get the 10mar16 date because on that date the number is now greater than 6.  Earlier dates wont total up to six.
Here is an example of a query i have been working on:
SELECT max(date) FROM `numbers` WHERE `number` > 60

A: You could use this query, which tracks the accumulated sum and then returns the first one that meets the condition:
select   date
from     (select * from mytable order by date) as base,
         (select @sum := 0) init
where    (@sum := @sum + number) >= 6
limit 1

SQL Fiddle

A: Most databases support ANSI standard window functions.  In this case, cumulative sum is your friend:
select t.*
from (select t.*, sum(number) over (order by date) as sumnumber
      from t
     ) t
where sumnumber >= 10
order by sumnumber
fetch first 1 row only;

In MySQL, you need variables:
select t.*
from (select t.*, (@sumn := @sumn + number) as sumnumber
      from t cross join (select @sumn) params
      order by date
     ) t
where sumnumber >= 10
order by sumnumber
fetch first 1 row only;

A: Awesome!!!!  It seems to be working great.  Here is the code that I used.
SELECT  date, id, crewname
FROM     (select * FROM flightrecord WHERE `crewname` = 'brayn'
ORDER BY dutyTimeArrive DESC) as base,
         (select @sum := 0) init
WHERE    (@sum := @sum + tankDropCount) >= 6
limit 1


text:
Q: No request data ($this->request->data is empty array) when post_max_size exceeded I have a form with a file upload element on it (set to allow multiple file selection - echo $this->Form->file('filename.', array('multiple' => 'multiple'));), and when the size of files selected by the user exceeds the PHP value of post_max_size I get no error, but $this->request->data is an empty array.
Is this the expected behaviour, it doesn't seem right to me?


text:
Q: CSS Class by element ID? I have a following css
#container
{
        border:1px solid black;
}
#container #header
{
    color:blue;
}

#container #footer
{
    color:red;
}

Can i write it as
#container
{
        border:1px solid black;
        #header
        {
            color:blue;
        }

        #footer
        {
            color:red;
        }
}

So the #header and #footer are still select as #container's childs element.
Or i need to use some css framework like .LESS ?

A: Nope, CSS doesn't support that. I agree, it would be useful. However, you're right, it looks like LESS supports it.

A: Yes only if you use SASS, not possible in vanilla CSS.

A: CSS doesn't support that syntax out of the box, so yes you would have to use .LESS


text:
Q: Which file system is the fastest? I'm looking to format my hard drive. I've heard about a file system called "ext3", it's supposedly a linux partition and I think is a lot faster than NTFS.
But my question, is, is there anything faster than ext3? And how could I format my drive to that particular file system.
I'm using Windows 8.
My Drive

A: You're right ext3 (and there's also ext4) is a Linux File System. Yes, it's fast but not compatible with Windows. If you want to use an ext3/4 file system you'll need a Linux OS. For Windows 8 the default NTFS file system is plenty fast as opposed to FAT32.
Take a further read on Wikipedia about file systems

A: Ext4 is faster (I think) than Ext3, but they are both Linux filesystems, and I doubt that you can get Windows 8 drivers for either ext3 or ext4. If I were you, I would stick with NTFS.


text:
Q: Azure Media Player, hangs when clicking on the player after source is set but before playing I am seeing an issue with AMP where there is a small window of time in which the player can be clicked and it results in it hanging.
Specifically if the player is clicked when the source has been set but before the video has begun playing AMP hangs only displaying the loading icon.
In the browser debug tools I can see failed requests to blob:https://example.com/[guid] where [guid] is different on every request

The initiator tab for the request is empty so no clues there as to where the request is failing.
The source is set as follows
 myPlayer.src([{
                src: data.path,
                type: "application/vnd.ms-sstr+xml",
                protectionInfo: [{
                    type: "AES",
                    authenticationToken: "Bearer=" + data.authToken
                }],
                streamingFormats: ["SMOOTH", "DASH"]
            },]);

The video element as so
 <div id="video-view" className="videoPlayerWithToolbar" >
            <video
                style={{ height: "100%" }}
                id="azuremediaplayer"
                className="azuremediaplayer amp-default-skin amp-big-play-centered videoResponsive"
                tabIndex={0}
                controls
                poster=""
                data-setup='{"logo": { "enabled": false },"techOrder": ["azureHtml5JS", "flashSS", "silverlightSS", "html5"],
                "nativeControlsForTouch": false }' >
            </video>
        </div>

Any thoughts on why I might be seeing this behaviour or how to debug in the absence of any initiator information on the network traffic?


text:
Q: Unity GameObject.BroadcastMessage() not work on deactivated GameObjects I notice that GameObject.BroadcastMessage does not work when the target is deactivated. How do tweak this to make it work in such situation.
Apparently, This EventOnMonoCallback.cs script is attached to the TOOTHPANEL, and it will trigger on OnEnable() but the _Food gameobject itself is inactive.
Seems like, BroadcastMessage not work for deactivated child ?
For some reason, the TOOTHPANEL can't be in active state until other script set TOOTHPANEL gameobject to true.

EventOnMonoCallback.cs
public class EventOnMonoCallback : MonoBehaviour
{
    public enum MonoCallbackType
    {
        Awake,
        Start,
        Update,
        OnEnable,
        OnDisable,
        OnDestroy
    }

    public MonoCallbackType Type;
    public UnityEvent Do;

    void Awake()
    {
        if (Type == MonoCallbackType.Awake)
        {
            Do.Invoke();
        }
    }

    void Start()
    {
        if (Type == MonoCallbackType.Start)
        {
            Do.Invoke();
        }
    }

    void Update()
    {
        if (Type == MonoCallbackType.Update)
        {
            Do.Invoke();
        }
    }

    void OnEnable()
    {
        if (Type == MonoCallbackType.OnEnable)
        {
            Do.Invoke();
        }
    }

    void OnDisable()
    {
        if (Type == MonoCallbackType.OnDisable)
        {
            Do.Invoke();
        }
    }

    void OnDestroy()
    {
        if (Type == MonoCallbackType.OnDestroy)
        {
            Do.Invoke();
        }
    }
}

A: There is a difference between activating/deactivating and enabling/disabling in Unity. You can activate  and deactivate GameObjects. You can enable and disable scripts. Do not confuse these two.
The BroadcastMessage function will always work even when the script with the target function is disabled but it will not work when the GameObject that script is attached to is deactivated.

There are two easy workarounds:
1.Use Unity's builtin Invoke function. Use GetComponentsInChildren to get all MonoBehaviour then call Invoke on each one. Invoke will always work even when the GameObject is deactivated. Use the overload version of GetComponentsInChildren that take List as parameter so that it does not create garbage each time it is called.
List<MonoBehaviour> monoList = new List<MonoBehaviour>();

void BroadcastMessageExt(string methodName)
{
    targetObj.GetComponentsInChildren<MonoBehaviour>(true, monoList);
    for (int i = 0; i < monoList.Count; i++)
    {
        monoList[i].Invoke(methodName, 0);
    }
}

The only bad thing about this is that you cannot pass a parameter to it. See #2 for workaround.

2.Do the-same thing as #1 but use C# MethodInfo.Invoke function instead of the version from Unity API. This should let you pass a parameter to the function you are calling.
List<MonoBehaviour> monoList = new List<MonoBehaviour>();

void BroadcastMessageExt(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver)
{
    targetObj.GetComponentsInChildren<MonoBehaviour>(true, monoList);
    for (int i = 0; i < monoList.Count; i++)
    {
        try
        {
            Type type = monoList[i].GetType();

            MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance |
                                            BindingFlags.NonPublic |
                                             BindingFlags.Public |
                                             BindingFlags.Static);

            method.Invoke(monoList[i], new object[] { value });
        }
        catch (Exception e)
        {
            //Re-create the Error thrown by the original SendMessage function
            if (options == SendMessageOptions.RequireReceiver)
                Debug.LogError("SendMessage " + methodName + " has no receiver!");

            //Debug.LogError(e.Message);
        }
    }
}

You can turn these into extension methods to make them more easier to use.

A: You are correct, BroadcastMessage does not work for inactive objects. You will have to enable it some way other than by BroadcastMessage or SendMessage.
If you have a reference to the object, you could enable with that.
If your goal is to just call a function in all applicable children, you could try something like:
void Call_YOURFUNCTION_OnChildren(){
    Transform[] transforms = GetComponentsInChildren<Transform>(true);
    foreach (Transform t in transforms){
        if (t.GetComponent<YOURCLASS>()){
            t.GetComponent<YOURCLASS>().YOURFUNCTION();
        }
    }
}

Note: this assumes that all of your objects have transforms


text:
Q: MongoDB aggregate - using $filter with $in condition for projection db.getCollection('regions').aggregate([
    { $match: { 'status': 1 },
    { $project: {
        names: { $filter: {
            input: '$names',
            as: 'name',
            cond: {$or: [
                { $eq: ['$$name.lang', 'de'] },
                { $eq: ['$$name.lang', 'en'] },
                { $eq: ['$$name.lang', 'es'] },
                ]}
        }}
    }}
])

Is it possible to replace the $or condition with a single $in: ['de', 'en', 'es'] condition ?
This does not work:
db.getCollection('regions').aggregate([
{ $match: { 'osm.parent': 0, 'osm.admin_level': 2 }},
{ $project: {
    osm: 1,
    names: { $filter: {
        input: '$names',
        as: 'name',
        cond: { $in: [ '$$name.lang', ['de','en','es'] ]}
    }}
}}

])

A: You could try:
{ $unwind : "$name" }
{ $match : { "$name.lang" : { "$in" : [ "de", "en", "es"] } }}

Rather than use $filter inside your projection.
db.getCollection('regions').aggregate([
    { $match: { 'osm.parent': 0, 'osm.admin_level': 2 } },
    { $unwind : "$name" },
    { $match : { "$name.lang" : { "$in" : [ "de", "en", "es"] } } },
    { $project: { osm: 1, "name.lang": 1 } }
])


text:
Q: Android toolbar navigation icon and menu icon look different I'm developing app according material design guidelines. I am using toolbar, which is 56dp and icons for toolbar which are 48dp.
When i'm setting exactly the same icon as navigation icon and as menu item icon they look different.

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_toolbar_cross);
    }

and in menu
<item
    android:id="@+id/action_settings"
    android:icon="@drawable/ic_toolbar_cross"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="ifRoom" />

Why navigation button becomes bigger?
Also I noticed that in Google IO 32dp buttons used for toolbar but according to material design specs they should be 48dp


text:
Q: Maximum points for heat flux density I have a function $u(x,y)$ describing a certain temperature distribution that looks like

$u(x,y) = -\dfrac{q}{4\pi \lambda} [\ln((x-a)^2+(y-a)^2)-\ln((x+a)^2+(y-a)^2)+\ln((x+a)^2+(y+a)^2)-\ln((x-a)^2+(y+a)^2)], \quad \text{for} \:x>0,y>0$

and it is given that $u(0,y) = 0$, $u(x,0) =0$.
Now I am interested in finding the maximum points for the heat flux density $\textbf{j} =-\lambda\nabla u$ going out from the boundaries. So I thought that shouldn't be a problem, we just solve the equations $|\nabla_y u(x,y)|_{y=0} = 0$ and $|\nabla_x u(x,y)|_{x=0} = 0$ (this would give us the magnitudes of the normal derivatives at the boundaries, if you disagree then I am interested to hear why). But according to my calculations, both of these expressions lead to $0=0$ (which is probably obvious in some way and if not then it is obvious my calculations are inaccurate). So I ask you, the reader, for a push in the right direction.

A: you will get
$$\frac{\partial f(x,y)}{\partial x}=-1/4\,{\frac {q}{\pi \,\lambda} \left( {\frac {2\,x-2\,a}{ \left( x-a
 \right) ^{2}+ \left( y-a \right) ^{2}}}-{\frac {2\,x+2\,a}{ \left( x+
a \right) ^{2}+ \left( y-a \right) ^{2}}}+{\frac {2\,x+2\,a}{ \left( x
+a \right) ^{2}+ \left( y+a \right) ^{2}}}-{\frac {2\,x-2\,a}{ \left(
x-a \right) ^{2}+ \left( y+a \right) ^{2}}} \right) }
$$
and $$\frac{\partial f(x,y)}{\partial y}=-1/4\,{\frac {q}{\pi \,\lambda} \left( {\frac {2\,y-2\,a}{ \left( x-a
 \right) ^{2}+ \left( y-a \right) ^{2}}}-{\frac {2\,y-2\,a}{ \left( x+
a \right) ^{2}+ \left( y-a \right) ^{2}}}+{\frac {2\,y+2\,a}{ \left( x
+a \right) ^{2}+ \left( y+a \right) ^{2}}}-{\frac {2\,y+2\,a}{ \left(
x-a \right) ^{2}+ \left( y+a \right) ^{2}}} \right) }$$


text:
Q: meteor js how to create rest api to regsiter user using Accounts.createUser? I have created web app in meteor js and now i need to create api's for mobile native app . My app is using this route for login on web app.
Path of web app login route
myapp\myappv1\app\lib\routes.js
Router.route('login', {
  name: 'login',
  controller: 'LoginController',
  where: 'client'
});

And to create api I have created server.js file in _myapp\myappv1\app\server_ directory and I'm trying to create api to register a user.
Router.route('/register/',{where: 'server'})

 .post(function(){
//console.log(this.request.body);
//return false;
let user = {
email : this.request.body.email,
username : this.request.body.username,
password : this.request.body.password,
countrycode : this.request.body.countrycode,
mobileno : this.request.body.mobileno,
};

});
   Meteor.call('registerForm', user, function(error, response1) {
        if (error) {
             response = {
                            "error" : true,
                            "message" : error,
                        }
        }
        if (response1) {
            response = {
                            "error" : false,
                            "UserID" : response1,
                        }
        }
    });
    this.response.setHeader('Content-Type','application/json');
    this.response.end(JSON.stringify(response));
   });

It's showing error in callback. How I can get response with Accounts.createUser. It's inserting data into database but
in response returns error "Accounts.createUser with callback not supported on the server".


text:
Q: Tricky module import with late init I have such a simple module's structure:
mod1/
    __init__.py
    clsOne.py
    clsN.py

Where code looks like this:
__init__.py:
     # module init
     from clsOne import MyFirstCLass
     from clsN import NThCLass

     clshnd = MyFirstClass()
     ...
     nhnd = NThClass()

clsOne.py:
     class MyFirstClass( object ):
         pass
clsN.py:
     classNThClass( object ):
         pass

Now I use them as follows:
Way #1)
    from mod1.clsOne import MyFirstClass

or:
Way #2)
    from mod1 import clshnd

Is it possible to import name clshnd but in such a way that other handlers (i.e. nhnd) are initialized only on demand (when explicitelly imported)?
For now both: Way #1 and Way #2 cause module initialization call, means: also NThClass object is created. I would like to avoid it, because I have a lot of such classes and would like to avoid long init, however I would like to have simple access (Way #2) as well.
Is it possible at all or I have to redesign modules and files (remove from init)?
Zbigniew

A: You just put the relevant code into a separate module.
mod1/
    __init__.py
    clsOne.py
    clsN.py
    foo.py

And then in foo.py:
from clsOne import MyFirstCLass
from clsN import NThCLass

clshnd = MyFirstClass()
...
nhnd = NThClass()


text:
Q: Can I Write Aspect for my Junit Test Cases in SpringBoot I have a branch of Test cases that are using the same code repeatedly for different test scenarios/methods. It's like infra related maintenance code. Suppose need to validate some business logic before we need to perform some infra-related operation. Same after the execution of business logic like cleaning all the infra-related configs. Thought we can use Aspects. As our main services are written in spring boot.
@TestInstance(Lifecycle.PER_CLASS)
@TestMethodOrder(OrderAnnotation.class)
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class RegressionTest{

    @Test
    @Order(1)
    public void Test1(){

    }

    @Test
    @Order(2)
    public void Test2(){

    }

    @Test
    @Order(3)
    public void Test3(){

    }

    @Test
    @Order(4)
    public void Test4(){

    }

    @Test
    @Order(5)
    public void Test5(){

    }

    @Test
    @Order(6)
    public void Test6(){

    }

}

In the above example suppose want to run some common code before and after some test cases with the different values( 1 , 5 use some maintenance code with a different activity, and 2,6 use some different ). Depends on the test case. I planning to use Aspect so that no need to write same code repeatedly. Please suggest if you have a better suggestion or how can I use aspect-oriented programming in this scenario.

A: You can only apply Spring AOP to Spring beans/components. I.e., your test would need to e.g. have a @Component annotation in order to be picked up by a correspondingly configured component scan or be instantiated in a @Bean factory method. I am not a Spring user, i.e. I do not have much experience in using Spring from tests either. But what I do know is that you could simply use native AspectJ, either applied by compile-time or load-time weaving, in order to achieve what you want. That would be pretty straightforward to implement. I can certainly help you, if you present an MCVE on GitHub, so I do not have to start from scratch.
If you want to use a non-AOP solution, why not simply use the existing @BeforeAll and/or @BeforeEach annotations, just like @asafb suggested before? I see no reason why that would not work.


text:
Q: Why does var test = false become true when you do test = !test? Javascript newbie here and my mind is bending now.
var test = false
test = !test
// returns true

I know that the ! is a bang operator and changes a Boolean value to the opposite of what it currently is.
But I can't grasp what is going on in
test = !test

The variable test is pointing to the value false at first, but is this variable getting set to itself? It seems that the test variable is getting set to itself and then the bang operator applies making it true. But could both sides of a assignment operator be set the same variable?

A: Let's do this step by step.
test =

You are now assigning test a new value
= ![...]

Which is the logical opposite of...
= !test

... the current value in test. What this code does in summary is to invert test and apply the result of that operation back on the variable itself, effectively changing it.
What might help understanding the whole operation is that testis not pointing at false but is false.

A: It returns true. Maybe you should put a ; at the end of the statements.
https://jsfiddle.net/dtpx1d5m/

A: var test = false; // test = false
test = !test; // test = true (because `test` was `false`, now it's equal to opposite value: `true`)

And don't ignore semicolons at the end of rows.

A: var test = false
Here you are setting the value of test to be false.
test = !test
First evaluated is the right side. So by reffering to test you receive its value.
Ultimatelly test is the same as false. So !test becomes !false, which is evaluated to true.
Thus your test = !test is the same as test = !false and finally becomes test = true

A: You just assign variable test with new value, and the new value is !test.

var test = false;
test = !test; //you assign new value to test, and old value will be replaced
document.getElementById('tes').value = test;
<input type='text' id='tes'>


text:
Q: How do I link variables inside another object in scaladocs? To link another class, I can use [[package.Classname]].
Linking functions defined by def works as well, but trying to link variables doesn't work.
What I've tried:
object Foo {

  val BAR = 0
}

object Example {

  /**
  * Does the thing with [[Foo.BAR]]
  */
  def doTheThing(): Unit = {

  }
}

I've also tried [[Foo#BAR]] (from another post) instead of [[Foo.BAR]], which fails as well.
What's the proper way to link variables in scaladoc?

A: The right way to go is what you have already tried:
/**
* Does the thing with [[Foo.BAR]]
*/

Please note that if this is just an example to a more complicated scenario, you need to include the whole package path of Foo.BAR. For example, if Foo is under:
package a.b.c.d

Then you need to do:
/**
* Does the thing with [[a.b.c.d.Foo.BAR]]
*/

You can find in the scaladocs docs:

Create links to referenced Scala Library classes using the square-bracket syntax, e.g. [[scala.Option]]

For more information you can read SCALADOC FOR LIBRARY AUTHORS
You can see here and example how the akka library is using it.


text:
Q: How can I check if it includes more than one things? Is there way to check if something includes more than one thing?
My code didn't work when I did this:
if(variable.includes("a" || "e")) {...}
I thought it would work because of "||" but it only worked with "a", only checked if theres "a" and if there isn't stopped the code.
Sorry if any grammar mistakes or bad explanation.

A: It is most likley not a great solution but if your variable is an array (eg. array = [a, h, a])
then you could try:
items=0;
numbers.forEach(function(){ //does a function for every item
items+=1; //will add one for every item
});

then do:
if (items>1) {
   //code that would run if there is more than one item
}

A: You need an iteration and check with includes with the optional values.
variable.some(v => ["a", "e"].includes(v))

A: You could use the following code:
if (['a', 'e'].some(v => variable.includes(v))) {...}


text:
Q: Socket.io listeners in React class component not working The socket.io event listener in the below code isn't working. Any ideas?
class Foo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      socket: io("localhost:5000")
    }
  }
  componentDidMount() {
    this.state.socket.on("event", data => {console.log("event logged.")})
  }
  render() {
    return (

Hello World!

    )
  }
}

It might be worth noting that "foo" here is the child of a functional component which is also using socket.io listeners, but with hooks (useEffect). The socket.io event listeners in the parent component are working just fine.


text:
Q: Calculate mean for each group, many groups, huge group_id, in R I have a big dataset in R, containing: items(item id) and review scores by clients. It is groupped by item code, each item appears one or more times in dataset. How can I mutate one column that has the mean of the review scores for each item?
looks like
   gt3dskh     4
   gt3dskh     3
   o1gsjnv     5
   abg56ji     4
   abg56ji     1
   ...

but, many more rows, item id unpredictable, do not know how many rows each group has.
Thank you in advance!

A: Try this base R approach with aggregate
aggregate(score ~ id, df, mean)
       id score
1 abg56ji   2.5
2 gt3dskh   3.5
3 o1gsjnv   5.0

Data
df <- structure(list(id = c("gt3dskh", "gt3dskh", "o1gsjnv", "abg56ji",
"abg56ji"), score = c(4L, 3L, 5L, 4L, 1L)), class = "data.frame", row.names = c(NA,
-5L))

A: @shawn-hemelstrand has the right answer, but I'll just add that if you truly had a big dataset, you should use data.table not tidyverse
library(data.table)
setDT(df)
df[,.(mean_val = mean(score,na.rm=T)), by=id]

Output:
       id mean_val
1: gt3dskh      3.5
2: olgsjnv      5.0
3: abg56ji      2.5

A: You can do this fairly easily with the tidyverse package:
Load tidyverse here:
library(tidyverse)

Then I'll just recreate your data frame here:
Dataframe
id <- c("gt3dskh",
        "gt3dskh",
        "olgsjnv",
        "abg56ji",
        "abg56ji")
score <- c(4,3,5,4,1)
df <- data.frame(id,score)

Finally, you just need to use the this code to group each id and then summarize the mean for each.
Summarize scores:
df %>%
  group_by(id) %>%
  summarize(mean = mean(score))

This should produce this output:
  id       mean
  <chr>   <dbl>
1 abg56ji   2.5
2 gt3dskh   3.5
3 olgsjnv   5

Observing a large dataset
Also just to piggyback off your issue of dealing with large datasets...there are multiple ways to get a cursory look at the data.
Here is one:
glimpse(df)

Which gives you this output showing the rows, columns, variables, and values attributed:
Rows: 5
Columns: 2
$ id    <chr> "gt3dskh", "gt3dskh", "olgsjnv", "abg56ji", "abg56ji"
$ score <dbl> 4, 3, 5, 4, 1

There is also a nice function from the skimr library that can be helpful for summarizing a lot of data.
library(skimr)
skim(df)

Which gives you a lot of valuable output as well if you want it:
-- Data Summary ------------------------
                           Values
Name                       df
Number of rows             5
Number of columns          2
_______________________
Column type frequency:
  character                1
  numeric                  1
________________________
Group variables            None

-- Variable type: character ---------------------------------------------
# A tibble: 1 x 8
  skim_variable n_missing complete_rate   min   max empty n_unique
* <chr>             <int>         <dbl> <int> <int> <int>    <int>
1 id                    0             1     7     7     0        3
  whitespace
*      <int>
1          0

-- Variable type: numeric -----------------------------------------------
# A tibble: 1 x 11
  skim_variable n_missing complete_rate  mean    sd    p0   p25   p50
* <chr>             <int>         <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 score                 0             1   3.4  1.52     1     3     4
    p75  p100 hist
* <dbl> <dbl> <chr>
1     4     5 ▃▁▃▇▃


text:
Q: Mongodb Connection not defined trying to follow tutorial with my own database I'm trying to follow along with the tutorial in the Mongo docs here: https://www.mongodb.com/languages/express-mongodb-rest-api-tutorial
So I have a file called mongodb-connect.js
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let dbConnection;

module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      if (err || !db) {
        return callback(err);
      }

      dbConnection = db.db("GardeningSite");
      console.log("connection", dbConnection);
      console.log("Successfully connected to MongoDB.");

      return callback();
    });
  },

  getDb: function () {
    return dbConnection;
  },
};

And another called db-manager.js that I want to use that connection in to export some basic functions:
module.exports = {
  /*Get an array of items from a collection
        ASYNC
        Parameters:
            collectionName: The collection to retrieve items from
        Returns:
            An object of format
            { success: boolean, data: data returned from db, error: string }
    */
  getItemsFromCollection: async function (collectionName) {
    const connection = getDb();
    console.log("conn", connection);
    const collection = connection.collection(collectionName);
    try {
      const items = await collection.find({}).toArray();
      return { success: true, data: items, error: "" };
    } catch (err) {
      console.log(err.message);
      return { success: false, data: null, error: err.message };
    }
  },

But whenever I try to run this, I get the error that 'connection is not defined' and I'm not sure where I'm missing a step. The tutorial doesn't show how the client is imported, so I'm not sure if I've maybe got that wrong?


text:
Q: string match using awk I have a tab separated file that has rows like this:
field1 field2 field3 field4 field5 field6
1 abc 2 word:add,word:remove text string
2 xyz 2 word:replace,word:modify msg string
3 lmn 1 word:add msg numeric
4 cncn 2 phone:add,phone: remove msg numeric
5 lmn 2 word:add msg text

I want to write an awk program/oneliner that gives me the rows where
field3 ==2 and field4 contains either "add" or "remove"
In other words it should have first filtered out these and,
1 abc 2 word:add,word:remove text string
2 xyz 2 word:replace,word:modify msg string
4 cncn 2 phone:add,phone:remove msg numeric
5 lmn 2 word:add msg text

In the second step should have filtered out these
1 abc 2 word:add,word:remove text string
4 cncn 2 phone:add,phone:remove msg numeric
5 lmn 2 word:add msg text

I can get the first step right using : cat test.tsv | awk -F '\t' '$3 == 2'
How do I match the substrings for the second part?
Thanks in advance

A: You could match the field using ~:
awk -F '\t' '$3==2 && $4 ~ /add|remove/' filename

would produce the desired result:
1 abc 2 word:add,word:remove text string
4 cncn 2 phone:add,phone: remove msg numeric
5 lmn 2 word:add msg text

Quoting from the manual:
   ~ !~        Regular  expression match, negated match.  NOTE: Do not use
               a constant regular expression (/foo/) on the left-hand side
               of  a  ~  or !~.  Only use one on the right-hand side.  The
               expression /foo/ ~ exp has  the  same  meaning  as  (($0  ~
               /foo/) ~ exp).  This is usually not what was intended.


text:
Q: cakephp foreach sort with titles Hello
i'm started to learning cakephp framework.And just for start i wanted to write some simple game.
I have user controller wited already (not finished but works :D) and now i started to write equipment. But i stuck at the moment i'm trying to sort foreach by type (helmet, armor, shield etc) and now script output table like this:
Id  Owner   Name                    Status  Type    Cost
1    23      Krasnoludzka Salada     B       H       100
2    23      Jakieś spodnie          B       L       10
3    23      Zbroja                  B       A       123

But i wanna to make it like this:
Id  Owner   Name                    Status  Type    Cost
Helmets:
1    23      Krasnoludzka Salada     B       H       100
4    23      Smocza Salada           B       H       100
Legs:
2    23      Jakieś spodnie          B       L       10
Armors:
3    23      Zbroja                  B       A       123

Mine equipments_controller.php:
<?php
class EquipmentsController extends AppController {

    var $name = 'Equipments';
    var $helpers = array('Html', 'Form');

    function index() {
        $this->set('equipments', $this->Equipment->find('all', array('conditions' => array('owner='.$this->Session->read('Auth.User.id'), 'status=\'B\''))));
        //$this->set('equipments', $this->Equipment->find('owner='.$this->Session->read('Auth.User.id')));
    }

    function view ($id = null) {
        $this->Equipment->id = $id;
        $owner = $this->Equipment->read('owner');
        if ($owner['Equipment']['owner']==$this->Session->read('Auth.User.id')) {
            $this->redirect(array('controller' => 'equipments', 'action' => 'index'));
            $this->Session->setFlash('To nie twój przedmiot!');
        } else {
        $this->set('equipment', $this->Equipment->read());
        }
    }

}

And equipments/index.ctp:

Plecak

        Id
        Owner
        Name
        Status
        Type
        Cost

<?php foreach ($equipments as $equipment): ?>

        <?php echo $equipment['Equipment']['id']; ?>
        <?php echo $equipment['Equipment']['owner']; ?>
        <?php echo $equipment['Equipment']['name']; ?>
        <?php echo $equipment['Equipment']['status'];?>
        <?php echo $equipment['Equipment']['type']; ?>
        <?php echo $equipment['Equipment']['cost']; ?>

<?php endforeach; ?>

Can anyone help me?

A: You can add a 'group' option to your find()...
$this->set(
  'equipments',
  $this->Equipment->find(
    'all',
    array(
      'conditions' => array(
        'Equipment.owner' => $this->Session->read('Auth.User.id'),
        'Equipment.status' => 'B'
      ),
      'group' => array(
        'Equipment.type'
      ),
      'order' => array(
        'Equipment.type',
        'Equipment.name',
      ),
    )
  )
);

Hopefully you've actually got a Model for those types, and can use that model instead of those Equipment.type values, something like EquipmentType.name would be useful in your view. If you had that, then you'd be able to output a new heading row each time the EquipmentType.id changed.

A: I I'm understanding you correctly, you'd like to be able to sort your table of data by the titles in the table head tags.
If this is the case, I'd suggest using cake's built in paginator.
Your controller should look like:
class EquipmentsController extends AppController {

    var $name = 'Equipments';
    var $helpers = array('Html', 'Form');

    public $paginate = array(
        'Equipment' => array(
            'limit' => 25,
            'order' => array(
                'Equipment.id' => 'ASC'
            )
        )
    );

    function index() {
        $owner = $this->Session->read('Auth.User.id');
        $equipments = $this->paginate('Equipment', array(
            'Equipment.owner' => $owner,
            'Equipment.status' => 'B'
        ));
        $this->set(compact('equipments'));
    }

}

Then in your views/equipments/index.ctp:

Plecak

        <?=$this->Paginator->sort('Id', 'Equipment.id')?>
        <?=$this->Paginator->sort('Owner', 'Equipment.owner')?>
        <?=$this->Paginator->sort('Name', 'Equipment.name')?>
        <?=$this->Paginator->sort('Status', 'Equipment.status')?>
        <?=$this->Paginator->sort('Type', 'Equipment.type')?>
        <?=$this->Paginator->sort('Cost', 'Equipment.cost')?>

<?php foreach ($equipments as $equipment): ?>

        <?php echo $equipment['Equipment']['id']; ?>
        <?php echo $equipment['Equipment']['owner']; ?>
        <?php echo $equipment['Equipment']['name']; ?>
        <?php echo $equipment['Equipment']['status'];?>
        <?php echo $equipment['Equipment']['type']; ?>
        <?php echo $equipment['Equipment']['cost']; ?>

<?php endforeach; ?>

Using the paginator this way will generate links in your table headers that will automatically sort the data coming out of the db.


text:
Q: Using jQuery to load page into a div element and remove current loaded page I'm trying to load content/pages dynamically without having to leave the page, or, the page changing. Assume the following:
I have four pages: index.php, about.php, contact.php, products.php and when a visitor visits the website, by entering "http://mysite.com" they are greeted with the "index.php" page.
If they click onto a link, let's say "about" then the "index" page is removed and the contents of "about.php" is displayed inside the div content-loaded I have tried the following:
jQuery:
$(document).ready(function() {

   $("#content-loaded").load("index.php");

   $('.about').click(function() {

       $("#content-loaded").load("about.php");
   });

   //....
});

HTML:

   Home
   About

But this does not work. It displays both the index page AND the about page. Could anyone suggest any improvements/answers or a more elegant way to structure this?
Thanks

A: Try cleaning the previous content. See if this works:
$(document).ready(function() {

   $("#content-loaded").load("index.php");

   $('.about').click(function(evt) {
       $("#content-loaded").empty();
       $("#content-loaded").load("about.php");
       evt.preventDefault();
   });

   //....
});

A: Using jQuery 1.9.1 and the following source code, worked for me.


text:
Q: Facebook Login Swift I wrote a basic Swift Class for Facebook login handling.
I want to check if the user already authorised the App, because in my case, the user gets asked everytime if he authorises the app - it switches to safari everytime instead of simply logging in. Sometimes the login completely fails - no error message, but also no success.
Here is my code:
class FacebookLogin{

private var data : NSMutableData? = nil

init(){

}

let facebookReadPermissions = ["public_profile", "email", "user_friends"]

    func loginToFacebookWithSuccess(successBlock: () -> (), andFailure failureBlock: (NSError?) -> ()) {

        if FBSDKAccessToken.currentAccessToken() != nil {
            return
        }

        FBSDKLoginManager().logInWithReadPermissions(self.facebookReadPermissions, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
            if error != nil {
                // Process error
                FBSDKLoginManager().logOut()
                failureBlock(error)
            } else if result.isCancelled {
                // Handle cancellations
                FBSDKLoginManager().logOut()
                failureBlock(nil)
            } else {
                // If you ask for multiple permissions at once, you
                // should check if specific permissions missing
                var allPermsGranted = true

                let grantedPermissions = Array(result.grantedPermissions).map( {"\($0)"} )

                for permission in self.facebookReadPermissions {
                    if !contains(grantedPermissions, permission) {
                        allPermsGranted = false
                        break
                    }
                }

                if allPermsGranted {
                    // Do work
                    let fbToken = result.token.tokenString
                    let fbUserID = result.token.userID

                    println(fbUserID)
                    successBlock()
                } else {
                    //The user did not grant all permissions requested

                    failureBlock(nil)
                }
            }
        })
    }

func login() -> Void{
    if(self.alreadyLoggedIn() == false){
        self.performLogin()
    }else{
        self.getFBUserData()
    }
}

private func performLogin() -> Void {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager();
    fbLoginManager.loginBehavior = FBSDKLoginBehavior.SystemAccount

    println(FBSDKAccessToken.currentAccessToken())
    fbLoginManager.logInWithReadPermissions(["email"], handler: { (result, error) -> Void in
        if (error == nil){
            var fbloginresult : FBSDKLoginManagerLoginResult = result
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.getFBUserData()
                fbLoginManager.logOut()
            }
        }
    })
}

private func alreadyLoggedIn() -> Bool {
    if (FBSDKAccessToken.currentAccessToken() != nil)
    {
        return true
    }else{
        return false
    }
}

private func getFBUserData() -> Void{
    if((FBSDKAccessToken.currentAccessToken()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
            if (error == nil){
                println(result)
            }
        })
    }
}
}

Thanks

A: In your view controller viewDidLoad() you can add this code :
if (FBSDKAccessToken.currentAccessToken() == nil)
    {
        // User is not already logged
        println("No Logged")
    }
    else
    {
        // User is already logged
        println("Already Logged")
    }


text:
Q: Why is a deductive closure an intersection of maximally consistent sets? Full Question:
Show that if $\Delta(\Gamma)$ is the deductive closure of a consistent $\Gamma$ then $\Delta(\Gamma)$ is the intersection of all maximal consistent sets of formulas $\Lambda$ with $\Gamma \subseteq \Lambda$.
I'm really stuck with this question, I honestly don't know how to even start. Can someone please provide some assistance?

A: You have two things to prove: (1) that $\Delta(\Gamma)$ is a subset of any maximal consistent superset of $\Gamma$; (2) that if $\phi \not\in \Delta(\Gamma)$ then there is a maximal consistent superset of $\Gamma$ that does not contain $\phi$.
For (1), if $\chi \in \Delta(\Gamma)$ and $\Lambda$ is a consistent superset of $\Gamma$, then so is $\Lambda \cup \{\chi\}$. So if $\Lambda$ is a maximal consistent superset, then $\chi \in \Lambda$.
For (2), use Zorn's lemma: consider the set $\cal C$ of all consistent supersets of $\Gamma$ that do not contain $\phi$. There is at least one member of $\cal C$, namely $\Gamma$ itself. The union of a chain of elements of $\cal C$ is also a member of $\cal C$, so by Zorn's lemma $\cal C$ has a maximal element.


text:
Q: how to get both json data and template response in fastapi? @router.post('/boards',status_code =status.HTTP_201_CREATED)
async def create_user(request:Request,board_name:str = Form(. . .), db:Session= Depends(get_db)):
    types = boards. Boards(board_name = board_name)
    db. add(types)
    db. commit()
    db. refresh(types)
    types = db. query(boards. Boards).all()
    return templates.TemplateResponse("boards.html",{"request":request,"types":types})

I want to get both json data and templateResponse


text:
Q: Consensus Algorithms for multi-agent systems What are the best web resources available to start learning about consensus algorithms? I tried reading IEEE research papers but couldn't understand it because of the level of mathematics used in it.

A: Consensus is typically a problem solved in a layer below multi-agent systems, it is the fundamental problem in distributed systems, an abstraction-level below multi-agent systems. Consensus is the essential problem in distributed systems, and is required for implementing reliable communication, replication, leader election, agreement etc.
Multi-agent system literature typically reason about behavior and protocol of agents through more high-level protocols than consensus algorithms. Often the protocols on multi-agent system level talks about "coordination", "auctions", etc. rather than consensus. E.g in multi-agent system literature it is common to not even explicitly mention how consensus, and means of communication is managed, those are assumed to be implemented on a lower level.
If you are interested about consensus in distributed systems you can see the following literature.

*

*Paxos: https://en.wikipedia.org/wiki/Paxos_(computer_science), or the paper by the author of the algorithm: https://lamport.azurewebsites.net/pubs/paxos-simple.pdf

*Raft: https://raft.github.io/

*2PC: https://en.wikipedia.org/wiki/Two-phase_commit_protocol

*View synchrony: https://en.wikipedia.org/wiki/Virtual_synchrony
Those are four different algorithms/approaches for consensus, the most fundamental one is Paxos. However, the papers might include some math so if you are not comfortable with that, try the wiki pages first, or try googling and you'll find blogposts.
If you want to read a shorter book on distributed systems as a general subject, including some chapters on consensus, I can recommend: http://book.mixu.net/distsys/ , this book contains minimal math as far as I remember.
If you are looking for any specific literature let met know, I've read quite a lot on this subject.
Best regards;


text:
Q: ошибка при запуске docker sudo docker ps

в ответ получаю
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

При проверке - sudo service docker status
Выдает результат
docker start/pre-start, process 1357

Значит сервис запущен
Пробывал sudo usermod -aG docker $USER - не помагает
/etc/default/docker -
# Docker Upstart and SysVinit configuration file

# Customize location of Docker binary (especially for development testing).
#DOCKER="/usr/local/bin/docker"

# Use DOCKER_OPTS to modify the daemon startup options.
#DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"

# If you need Docker to use an HTTP proxy, it can also be specified here.
#export http_proxy="http://127.0.0.1:3128/"

# This is also a handy place to tweak where Docker's temporary files go.
#export TMPDIR="/mnt/bigdrive/docker-tmp"


text:
Q: How to Autocomplete in ct-vue-light-bootstrap-dashboard template form How to disable autocomplete in the current form?
   <fg-input
                            v-validate="'required|min:3'"
                            data-vv-name="Login"
                            label="Login"
                            type="text"
                            placeholder="Login"
                            v-model="form.login"
                            autocomplete="none">
                        </fg-input>
                        {{ errors.first("Login")
    }}

                        <fg-input
                            data-vv-name="Description"
                            label="Description"
                            type="text"
                            placeholder="Description"
                            v-model="form.description"
                            autocomplete="none">
                        </fg-input>
                        {{ errors.first("Description") }}

                        <fg-input
                            label="Password"
                            type="password"
                            placeholder="Password"
                            data-vv-name="Password"
                            v-validate="form.id ? '' : 'required|min:3'"
                            v-model="form.password"
                            autocomplete="off">
                        </fg-input>

Now it looks  like this:

Used template
https://github.com/creativetimofficial/ct-vue-light-bootstrap-dashboard-pro

A: just add autocomplete="new-password" attribute to your password input and everything will work as you want.
Example
                        <fg-input
                            label="Password"
                            type="password"
                            placeholder="Password"
                            data-vv-name="Password"
                            v-validate="form.id ? '' : 'required|min:3'"
                            v-model="form.password"
                            autocomplete="new-password">
                        </fg-input>

hrome no longer supports autocomplete="off"


text:
Q: Notion of good supersingular reduction for proper smooth variety over a $p$-adic field Let $X$ be a proper smooth variety over a $p$-adic field $K$. Let $\mathcal{O}_K$ be the ring of integers of $K$ and $k$, its residue field. We say that $X$ has good ordinary reduction if there is a smooth proper model $\mathfrak{X}$ of $X$ over $\mathcal{O}_K$ such with special fibre $Y$ satisfying $H^r (Y, d\Omega_Y^s) = 0$ for all $r$ and $s$, where $d\Omega_Y^s$ is the sheaf of exact differentials on $Y$. This definition is due to Kato, following his paper with S. Bloch [$p$-adic etale cohomologies]. When $X$ is a $d$-dimensional abelian variety, the above definition coincides with the classical definition of ''ordinary" for abelian varieties: that the group of $\bar{k}$-points killed by $p$ on $Y$ has order $p^d$.
Now, for an elliptic curve $E$, we say it has good supersingular reduction if the group of $\bar{k}$-points of the reduction of $E$ killed by $p$ is trivial. (I don't know if this definition is the same for abelian varieties; I would be grateful if somebody will confirm or correct me on this).
Question: Is there a general notion of good supersingular reduction for a proper smooth variety $X$ over a $p$-adic field $K$ as above?


text:
Q: Sobrescrever first-child css Bom dia, estou trabalhando com cards do bootstrap e preciso substituir o border radius do header, porém quando tento modificar pelo css eu não consigo devido ao :first-child que tem na classe do bootstrap, alguem sabe como Sobrescrever essa propriedade?
elemento inspecionado do bootstrap
.card-header:first-child {
  border-radius: calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0;
}

A: resolução do problema:
.card-header{
border-radius: 20px !important;

}


text:
Q: I got to go to the party I need to know the literal meaning of this "I got to go to the party."
Did someone actually go to the party (as in I went to the party) or he had the opportunity of going to the party regardless of the fact whether he went to the party or not?

A: The "literal" meaning of the rather "slangy" construction to get [to do something] is to have the opportunity [to do it] - always with the implication of taking up that opportunity (actually doing it).
In respect of future actions, if a 17-year-old Brit says I get to vote after my next birthday, that very strongly implies he intends to vote when he becomes eligible. If instead he'd said I will be able to vote... that strong implication of intending to vote wouldn't be there. So the be able to... version could reasonably be followed by ...but I doubt if I actually will vote, but that would be "unusual / acceptable" after the get to... version.
Note that [to] get [to] often just functions as an "auxiliary" verb in English, with little or no semantic content, so it's actually optional in the following example - which means the same regardless of whether get to is present or not...

1: I [get to] sleep easily when I avoid coffee

But with the "have the opportunity" idiomatic usage being asked about here, it makes a significant difference whether get to is present or not...

2: I [get to] sleep with my girlfriend when her parents are away

In #2 above, including get to forces the implication I am able to... [do something that I want to do]. If those two words aren't present, it's simply a neutral statement about what happens in that situation.
Finally, note that with OP's exact example, got is definitely a Past Tense usage (I was able to go to the party). But there's also the "Present" Tense / Infinitive usage to have [got] to do something, meaning to be obliged to do it. With that usage, auxiliary have is often omitted in casual speech, and go to is often transcribibed as a single word...

3: I gotta go to the party
(I must go to the party - but with the strong implication that I don't actually want to go)


text:
Q: Kafka log & index files are modified when broker is stopped We are currently running with 2 Kafka clusters, version 0.9.0.0, and in both we've noticed the following behavior: when a broker is stopped (kafka-server-stop.sh), all the log & index files of all of its topics are being modified (we simply see that the modification time of all the files is updated).
The problem with this is that it damages the retention policies once the broker is started again (as far as I understand, the retention policy relies on the file's modification time). Thus, if, for example, my retention policy is set for 24 hours and the broker is restarted every 23 hours, old logs will never be deleted.
Did anyone encounter this behavior? Any idea why this happens and how to fix this?
Thanks


text:
Q: Update a value in a table which has a foreign which requires a join, what is the elegant solution (efficient) I have two tables X and Y:

*

*X has columns ID (primary key), Name

*Y has a foreign key to X referencing the ID column.

I can only get the Name value from an input as related to X.
I need to update Y a value in Y
I do not want to hit the database twice; that is : to get the ID value in X by matching the name value and return this to be used in the update of Y  via WHERE
How do I write this SQL query, is there a complex query I can write ?
Any help would be great.

A: I'm not sure I understand your question, but:
update Y
set ...
where Y.X_ID in (select X.ID from X where X.Name = '...');

This would update those rows of Y whose X_ID references a row of X with a matching Name value.

A: one way to update in single query is following
     UPDATE
    Table_A
SET
    Table_A.col1 = Table_B.col1

FROM
    Y AS Table_A
    INNER JOIN X AS Table_B
        ON Table_A.id = Table_B.id
WHERE
    Table_A.col3 = 'cool'