text:
Q: Router can connect to internet but clients intermittently can't get beyond the router Currently working with a small business which is using an ISP supplied domestic ADSL modem/router to connect their internal setup to the internet and this is also being used for DHCP.
They're having repeated problems where 1 or more clients lose internet connectivity.  During these times all clients/servers can connect internally without issue, all clients and servers can ping the modem/router but can't connect out over any protocol (web, email or ping).
Unfortunately this domestic modem/router doesn't have much of an interface but during these episodes I can ping to a public IP from the router web console.
The customer had been restarting everything every time to resolve but the issue is actually resolved by performing a DHCP renew on the affected device.
In summary during the fault time all 192.168.1.0/24 hosts can connect with each other and to the gateway (192.168.1.1). That gateway can connect to the internet but the hosts can't.
I suspect that this is related to DHCP lease expiry but wouldn't that stop internal network traffic too?
How can I get my customer back online reliably?
(I'd love to recommend that they invest in some proper business grade tech but they don't have the budget so I am left to try and resolve with what they have.)

A: Looks like the router loses its routing / NAT configuration when a DHCP lease expires.
Since this is a software problem in the router, you need to find if there are upgrades for the software for the router. If there aren't any upgrades available, they need to buy some corresponding device.


text:
Q: Preserve coherence while shuffling queues in Tensorflow I have 3 queues, one is a FileReader supplied by a string_input_producer, two are slice_input_producers fed by a vector of int32 and a matrix of int32 respectively. They are all ordered such that, when read in sequence, they provide an image, question, and answer that forms one example.
What I want to do is shuffle them, while preserving the relations between them.
I've tried using shuffle_batch, but this does not preserve the relations - making it useless.
My current code (the relevant bits):
def load_images(self,images,q_name):
    filename_queue = tf.train.string_input_producer(images,shuffle=False,name=q_name)
    reader = tf.WholeFileReader()
    key, value = reader.read(filename_queue)
    imagedata = tf.image.decode_png(value)
    imagedata = tf.cast(tf.image.resize_images(imagedata,[224,224],tf.image.ResizeMethod.NEAREST_NEIGHBOR),tf.float32)
    imagedata = tf.div(imagedata,tf.reduce_max(tf.abs(imagedata)))
    imagedata.set_shape([224,224,3])
    return key,imagedata

keys[testfile],imagedata[testfile] = self.load_images(imagefiles[testfile],'test')
keys[trainfile],imagedata[trainfile] = self.load_images(imagefiles[trainfile],'train')

s_train_answer_batch,s_train_question_batch,s_train_image_batch = tf.train.batch([tf.train.slice_input_producer([answers[trainfile]],shuffle=False)[0],tf.train.slice_input_producer([questions[trainfile]],shuffle=False)[0],imagedata[trainfile]],batch_size=batch_size,capacity=batch_size*2,enqueue_many=False)

feed_dict = {self.x_image:s_train_image_batch.eval(), self.x_question: s_train_question_batch.eval(), self.y_:s_train_answer_batch.eval(),self.keep_prob:keep_prob}

_,ce, summary, image_summary, accuracy= sess.run([self.train_step,self.cross_entropy, self.summary_op, self.image_summary_op, self.accuracy],feed_dict=feed_dict)

So, to be absolutely clear: if the image, question, and answer matrices where just vectors of the numbers one to ten, I'd want the feed dictionary to look like:
q:[4,1,8,2,3,9,6,5,7],a:[4,1,8,2,3,9,6,5,7],i:[4,1,8,2,3,9,6,5,7]

but currently they'd look like:
q:[4,1,8,2,3,9,6,5,7],a:[7,3,1,5,6,2,4,9,8],i:[9,8,3,5,4,6,7,1,2]

A: I solved it! Don't use .eval() to get the output, call sess.run([image_batch,question_batch,answer_batch]). This preserves ordering and does the shuffling. I have no idea why.

A: Why do not use a single queue, like tf.train.range_input_producer with shuffle, to extract an integer used to access the different data?
In other words, you use a single queue to extract an integer that you use to index all your three data structures.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Archivos subidos a hosting en Firebase Acabo de subir con éxito una pagina web (HTML y CSS unicamente) al Hosting de Firebase. La pagina se visualiza correctamente, pero me gustaría saber si existe algun tipo de CPanel o algo por el estilo que me permita saber cuantos archivos tengo subidos, o si puedo eliminar o editar alguno de ellos, o consultar la fecha de subida de algún archivo concreto...
Y aprovecho la pregunta para consultaros: ¿Para subir archivos a Firebase solo puede hacerse mediante el CLI, es decir, la consola de Firebase? ¿No existe una interfaz mas amigable para tener mayor control de los archivos subidos?
¿Me recomendáis algún hosting gratuito con una interfaz gráfica amigable para subir los archivos y redireccionar la pagina a un dominio adquirido?
Muchas gracias por vuestro tiempo.
Un saludo!!

A: En el caso de Firebase, no contas con un cPanel como contarias con otros servicios de hosting, lo que deberias hacer es contratar un servicio de hosting tercero y enlazarlo con Firebase para poder hacer la redirección, en mi caso en una app que estamos usando firebase hosting usamos Hostinger como hosting aparte y luego lo enlazamos a Firebase hosting, de esta forma mantenemos por separado ambas partes


text:
Q: Read classic ASP's cookies with PHP How do I obtain the asp cookie's name and value using PHP so i may assign it to a variable? PHP and ASP are on the same domain.
Classic Asp Create Cookie
response.cookies("apple")("red")="reddelicious"
response.cookies("apple")("yellow")="gingergold"
response.cookies("apple")("green")="grannysmith"
response.cookies("apple").expires = dateadd("d",2,Now())

Classic ASP Read Cookie
strRed = request.cookies("apple")("red")
strYellow = request.cookies("apple")("yellow")
strGreen = request.cookies("apple")("green")

Reading The ASP cookies with PHP echo
echo $_COOKIE["apple"];

In firebug, after expanding the 'apple' cookie within the console, 'echo $_COOKIE["apple"]' outputs:
red=reddelicious&yellow=gingergold&green=grannysmith

Tried:
$strRed = $_COOKIE["apple"]["red"]; //doesn't work

A: You could use the parse_str function in php
<?php

parse_str($_COOKIE["apple"], $apple);

echo($apple["red"]);

?>

A: To get the string red=reddelicious&yellow=gingergold&green=grannysmith to the format of a multi dimensional array try this:
$itemArray = explode('&', $_COOKIE['apple']);  // Split variables at '&'
foreach($itemArray as $item){ // for each variable pair 'key=value'
    $itemParts = explode('=', $item); // split string to '[key, value]'
    $apple[$itemParts[0]] = $itemParts[1]; // set each item to $apple[key] = value;
}

Then you can use the variable like this:
$strRed = $apple["red"]; //should work :)


text:
Q: Parse Facebook feed datetime in python?
*

*I am reading a Facebook updates feed using the python library 'feedparser'.

*I loop through the collection of entries in my Django templates, and display the results.

*The updated field is returned in a big long string, of some format I am unfamiliar with.
Tue, 01 Dec 2009 23:55:52 +0000
How can I...
A) Use a Django filter to clean the date time in the for loop on the template.
...or...
B) Parse the date and format the updated date in the view, esentially cleaning the date in the collection of entries before it is iterated over in the view.
NOTE: I have tried both approaches. Django's date filter does't recognize it, and the iso8601 library I tried to parse the string didn't either.
Anybody have any experience with this? Thanks for your help!
UPDATE:
Using the updated_parsed value from feedparser in a Django template didn't work so well. But a Django snippet of a filter for this very thing already exists!**
Django Snippet: http://www.djangosnippets.org/snippets/1595/

A: Use entries[i].updated_parsed instead of entries[i].updated, and feedparser will return a parsed 9-tuple for you. (Documentation)
Then build a datetime object and pass it to Django or format to a string by yourself.
There is a similar question here.

A: This worked but wasn't what my final solution ended up becoming.
This solution iterates over the feed entries collection I get back from Facebook. I then parse the datetime and set the updated property to that new datetime. (Also, ignoring the +0000)
for entry in feed.entries:
        entry.updated = datetime.strptime(entry.updated, "%a, %d %b %Y %H:%M:%S +0000")

The entries collection is returned to the template which I can now use the Django 'date' filter to format the date.


text: Q: Auto load mp4 video to browser cache. I want to load a mp4 video from server to my browser cache and after full video is loaded to the browser cache,then play it with the HTML5 video tag. Is it posible ?


text:
Q: When does convergence in distribution of discrete random variable lead to convergence of associated PMFs to density of limit distribution Consider a sequence of real-valued discrete random variables, $\left\{X_n\right\}_{n \in \mathbb{N}}$ with an associated sequence of CDFs given by $\left\{F_n(x)\right\}_{n \in \mathbb{N}}$. Suppose that $\left\{F_n(x)\right\}_{n \in \mathbb{N}}$ uniformly converges to $F(x)$, which is a Normal distribution with mean equal to $0$ and variance equal to $\nu > 0$.
When does such uniform convergence in distribution imply uniform convergence of PMFs to the density of this limiting Normal distribution?
In my understanding of "On a Converse to Scheffe's Theorem," Sweeting (1985) shows that uniform convergence of PMFs to the density of this limiting Normal distribution would hold when the sequence of PMFs, $\left\{g_n\right\}_{n \in \mathbb{N}}$, is (1) uniformly bounded and (2) asymptotically uniformly equicontinuous.
It seems intuitively obvious that $\left\{g_n\right\}_{n \in \mathbb{N}}$ is uniformly bounded since $g_n(x)$ cannot take on a value greater than $1$ for every $n = 1, 2, 3, \dots$.
But what would it mean for PMFs of a discrete random variable to be asymptotically uniformly equicontinuous? And how could one show asymptotic uniform equicontinuity given knowledge about the mean of the limiting distribution (0) and finite variance ($\nu > 0$)? Finally, assuming one can establish asymptotic uniform equicontinuity, how do uniform boundedness and asymptotic uniform equicontinuity together then imply convergence of a sequence of PMFs to the density of limit distribution (or do I misunderstand the results from Sweeting, 1985)?
Many thanks to all for any insights!


text:
Q: How to auto focus browser tab when clicking on browser notification in Chrome? I am trying to setup browser notification for a project I'm working on. The code I have so far is:
// Notification permissions logic handled before...
var notification = new Notification('Title', { body: 'Message' });
notification.onclick = function (e) {
    window.focus();
    // this.cancel();
};
setTimeout(notification.close.bind(notification), 5000);

The notifications work fine with this code except for one thing. In Chrome clicking on the notification does not set the focus on the browser window. In Firefox this behavior is native out of the box and it works fine without on click handler defined above. I have looked for the solution for this for Chrome and found these:
How to get focus to the tab when a desktop notification is clicked in Firefox?
How to get focus to a Chrome tab which created desktop notification?
However the suggested accepted solutions do not work for me - the event is triggered but the focus is not set.
Does anyone have any suggestions how to make this behave properly?
Chrome version: Version 44.0.2403.130 m
Firefox version: 40.0

A: It's an hacky solution, but if you registered a service worker you could do something like this.
In the client page:
yourServiceWorkerRegistration.showNotification('Title', {
  body: 'Message',
});

In the service worker:
self.addEventListener('notificationclick', event => {
  event.notification.close();

  event.waitUntil(
    clients.matchAll({
      type: "window",
    })
    .then(clientList => {
      if (clientList.length) {
        clientList[0].focus();
      }
    })
  );
});

A: Now, my chrome version is 100.0.4896.127. And window.focus() works perfect in onclick of notification callback! It would be helpful to anyone who sees this issue.


text:
Q: Changing data returned from service changes data in service too When I store data returned from a service in my controller and then edit it, it also changes the data in the service.
JSFiddle Demo
 /* The backend connection part and the actual markdown editor JS have been removed because it would just make the code huge and is irrelevant to the problem */

var myApp = angular.module('myApp', []);

// In my app, this service caches blog post data from my server on the client side and returns single posts from it
myApp.factory('PostService', function ($log, $filter, $http) {
    var data;

    // Just an example for data pulled from server
    data = [{
        id: 99999,
        text: "Hello"
    }];

    // Function for returning a post out of the data array loaded from the server
    var getData = function (id) {
        if (id !== undefined) {
            var arr = $filter('filter')(data, {
                id: id
            });
            if (arr.length === 0) {
                $log.error('PostService:: getData(' + id + '):: Post Not Found');
                return 'not_found';
            } else {
                $log.debug('PostService:: getData(' + id + '):: Post returned');
                return arr[0];
            }
        } else {
            return data;
        }
    };
    return {
        getData: getData
    };
});

function ctrl($log, $scope, PostService) {
    var edit = this;

    // Sample post id
    edit.editingId = 99999;

    // "Copy" (apparrently more "bind") the blog post data to edit.data
    edit.data = PostService.getData(edit.editingId);

}

This is used for a markdown editor. I wanted to load the data from the service into the controller, then edit it, and give the service the new version on pressing a "Save" button.
If the aforementioned behaviour is correct in the sense of Angular's databinding, what is a better solution to achieve what I want?
Update
Based on PSL's comment and Thibaud Sowa's answer I changed the getData() function to return a copy using angular.copy(). However, it seems not to be possible to copy one object out of an array (like angular.copy(arr[0])), as it will still return the whole array. See the updated JSFiddle.
Update 2
Well, I was dumb. I corrected it in the fiddle. Thank you for your answers.

A: This is because you are returning an object. In javascript when you do that it's like if you are passing a pointer.
You should use angular.copy to copy the object field by field, like this:
        return angular.copy(data);

See the doc here https://docs.angularjs.org/api/ng/function/angular.copy
Response to your update
Well, I edited your fiddle, to show you that you can copy an item of an array. Actually it's seems that every thing works like you want... (Or I didn't understand your need!)
The updated fiddle:
https://jsfiddle.net/thibaudsowa/aybLwa2L/3/

A: There is a very simple solution to your problem:
If you dont want to change the data you get from the service make a copy
There are plenty of threads on SO discussing the fastes or most elegant way to deep copy a Javascript object. A simple and rather fast solution is using json parse and stringify like this:
var copyOfA = JSON.parse(JSON.stringify(a));

Apply this to the data you get from your service and you are good to go :)


text:
Q: Can not boot raspberry pi 3b from USB Drive with UBoot + Grub I have successfully installed Ubuntu 18.04 onto an SD card. I did this by creating an msdos partition table (pi doesn't support guid), then putting U-Boot onto the SD Card on partition 1 (fat32, pi doesn't support anything else). Then I pasted the pi-bootloader onto partition 1 /. And then I copied the files from the net installer (mini-iso) onto that partition as well.
The whole process is laid out here.
Everything works perfectly well from the SD Card. UBoot starts, then it loads the grub2 that came with the net installer mini iso. that in turn i have changed the config so it loads the linux kernel from partition 3 (p2 is swap, in my case).
So I pulled an image of that, put it on an usb drive (usb to m2 sata adapter), which should just behave like any other flash drive. So, I turn it on. U boot starts, I don't see anything different from normal. Then it loads grub. But instead of displaying a nice menu with the option to boot ubuntu or install it (because the net installer stuff is still on there), it dumps me straight into the grub console.
typing ls I get (memdisk), and nothing else. It doesn't seem to find the usb drive it actually loaded from itself. on that memdisk is a single file at (memdisk)/boot/grub/grub.cfg, but I have no way of knowing what's actually in there.
Edit: (memdisk) is there on the sd card also, same content, it just lists the partitions on the sd card also, while it does not on the flash drive.
There are no grub modules, no nothing. I think it ever so briefly flashes an error at me, but then the grub console opens and I have no time to read those messages.
I'm at a loss as to what to do.
Perhaps if I made my own grub image with usb modules like it is described here (using grub-mkimage to create a grub image with modules in the memdisk)? Although I have no idea which modules I need, or if that's even the right approach.
Any help would be greatly appreciated.
Edit: I have found this:
Basically you need grub modules (which I don't have) for grub to recognize the usb drive.

the short answer is:
insmod usbms
  insmod ehci
  insmod uhci
  insmod ohci
Only one of the *hci line is needed (usually ehci), but older machines
  may need either uhci or ohci Inserting all 3 works fine.
Those lines should be added to either grub.cfg or custom.cfg (I
  recommend the latter) in the /boot/grub/ folder on the non-USB drive.

I got my modules from here, however usbms is not among them and neither is [e,u,o]hci. I have found this about writing grub modules, but it confuses me. And I can't find the source code. Using something odd like the armhf 64bit processor doesn't make things easy to find compatible software.
Edit2: I have downloaded the grub source code from http://git.savannah.gnu.org/git/grub.git/ and compiled it on my raspberry pi. However the usbms.c and ehci.c source code files are there, it did not compile them into grub modules.
I have found this information on how to build grub modules here but it just doesn't work for me. I tried changing Makefile.core.am and removed the if statement around usbms.module, then running autogen and configure. No dice.
I tried manually building in grub-core with make usbms.module, but it says gcc: fatal error: no input files.
I don't need grub. I just want to boot my Ubuntu arm64. If I can somehow skip from u boot directly to there it's fine.
My current ideas:

*

*Compile usbms.mod, ehci.mod, uhci.mod and ohci.mod, make a new grub image with those modules linked in, and it should just work with the current grub config.

*Make a new grub image with the modules, the config and the linux kernel and initramfs built in as a memdisk. boot the kernel from there with the command line indicating that the rootfs is on partition 3

*Somehow tell uboot to boot my linux kernel from partition3 with the command line that partition 3 is root.

*use the black magic boot loader that comes with the raspberry pi firmware thing. I have not the slightest idea how that stuff works, but if someone can make it boot my ubuntu x64 then I'd be all too happy to ignore the fact that I don't know how it works.

I have no idea how to do any of them.

A: You can install ubuntu to an sd card and then swap out uboot (kernel8.img) with a new kernel like https://github.com/sakaki-/bcmrpi3-kernel
now you configure a cmdline.txt like in raspbian, for example
dwc_otg.lpm_enabled=0 root=PARTUUID=12345678-03 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait

then you can copy the raspbian config.txt, for example
# For more options and information see
# http://rpf.io/configtxt
# Some settings may impact device functionality. See link above for details

# uncomment if you get no picture on HDMI for a default "safe" mode
#hdmi_safe=1

# uncomment this if your display has a black border of unused pixels visible
# and your display can output without overscan
#disable_overscan=1

# uncomment the following to adjust overscan. Use positive numbers if console
# goes off screen, and negative if there is too much border
#overscan_left=16
#overscan_right=16
#overscan_top=16
#overscan_bottom=16

# uncomment to force a console size. By default it will be display's size minus
# overscan.
#framebuffer_width=1280
#framebuffer_height=720

# uncomment if hdmi display is not detected and composite is being output
#hdmi_force_hotplug=1

# uncomment to force a specific HDMI mode (this will force VGA)
#hdmi_group=1
#hdmi_mode=1

# uncomment to force a HDMI mode rather than DVI. This can make audio work in
# DMT (computer monitor) modes
#hdmi_drive=2

# uncomment to increase signal to HDMI, if you have interference, blanking, or
# no display
#config_hdmi_boost=4

# uncomment for composite PAL
#sdtv_mode=2

#uncomment to overclock the arm. 700 MHz is the default.
#arm_freq=800

# Uncomment some or all of these to enable the optional hardware interfaces
#dtparam=i2c_arm=on
#dtparam=i2s=on
#dtparam=spi=on

# Uncomment this to enable the lirc-rpi module
#dtoverlay=lirc-rpi

# Additional overlays and parameters are documented /boot/overlays/README

# Enable audio (loads snd_bcm2835) dtparam=audio=on

program_usb_boot_mode=1

add
dtoverlay=rpi-backlight
dtoverlay=rpi-ft5406

to the end if you have the ft5406 touchscreen and load the kernel modules in
/etc/modules-load.d/ft5406.conf
rpi_backlight
rpi_ft5406

and it just works


text:
Q: mvn exec:java throws ClassNotFoundException when executed on Jetbrains TeamCity I ran into issue with executing maven exec:java on Jetbrain's TeamCity. The configuration works without any issues locally but on TC it throws constantly:
java.lang.ClassNotFoundException: "…"
    at java.net.URLClassLoader.findClass (URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass (ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass (ClassLoader.java:357)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:270)
    at java.lang.Thread.run (Thread.java:748)
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project …: An exception occured while executing the Java class. "…"

TC configuration is fairly simple:

*

*goals: clean install exec:java

*additional commandline args: -DskipTests  -Dexec.mainClass="…" -Dexec.args="…"
Basically what I'm using locally. However using TC it throws above exception.
I tried explicitly setting current artifact as dependency and configuring compile dependencies as classpath:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <dependencies>
        <dependency>
            <groupId>…</groupId>
            <artifactId>…</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
    <configuration>
        <classpathScope>compile</classpathScope>
    </configuration>
</plugin>

But without any luck. Any help would be appreciated.

A: Try to add <mainClass> in the <configuration> tag, like this :
<configuration>
    <mainClass>com.category.main.Master</mainClass>
    <classpathScope>compile</classpathScope>
</configuration>

Then run with the command mvn exec:java -Dexec.mainClass=src.com.category.main.Master

A: Everything boiled down to quotes in Additional Maven command line parameters: - TC passes them as parameters so -Dexec.mainClass="some.package.Class" became"some.package.Class"in maven (instead ofsome.package.Class`)
I finally noticed it when I was comparing debug from local na remote run:

*

*remote:

[DEBUG] joining on thread Thread["my.package.SummaryGenerator".main(),5,"my.package.SummaryGenerator"]

*

*local:

[DEBUG] joining on thread Thread[my.package.SummaryGenerator.main(),5,y.package.SummaryGenerator]


text:
Q: What is the right way to map an object to database i have the object below represented by this JSON:
"page":{

"pageId":"123123",
"pageUrl":"www.page.com",
"pageCode":"13123128098e"

"news":{
    "header":{
       "headerId":4413123,
       "headerRef":"On-line",
       "headerName":"On-line Ref.",
    },
    "writerList":[
       {
          "writerId":1,
          "writerName":"Mega Thunder"

       },
       {
          "writerId":2,
          "writerName":"Rain Forest"
       }
    ]

The Java object is an news object that contains an header and an writeList. Right here ok.
But, my doubt is.. when a i map this using hibernate, I'm thinking about if is necessary to have the news object mapped to be an table, because the news object will have only  one id, a reference to header and the writeList object will have one reference to news. Is the news object really necessary to exists on database? can i create only the header and writerList linked to page?

A: You will need the following:
Page, News, Header, ArrayList<WriterList>.
The rest will be strings or integers. Make sure you public static class your inner classes.


text:
Q: Django error in creating model I'm having an issue with creating a user profile with a foreign object.
I have a user and I want to attach an account type to that user.
model.py
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    account = models.ForeignKey(Account, unique=True)

class Account(models.Model):
    reports = models.IntegerField(default=3)
    accounttype = models.CharField(default='Free', max_length=250)
    description = models.CharField(default='N/A', max_length=250)
    monthlycost = models.FloatField(default=0.0)

    def __str__(self):
        return self.user.username + " - " + self.accounttype

The issue is I'm getting the below error:
account = models.ForeignKey(Account, unique=True)
NameError: name 'Account' is not defined

How do I call the Account class for the foreign key?

A: from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    account = models.ForeignKey("app_name.Account", unique=True)

class Account(models.Model):
    reports = models.IntegerField(default=3)
    accounttype = models.CharField(default='Free', max_length=250)
    description = models.CharField(default='N/A', max_length=250)
    monthlycost = models.FloatField(default=0.0)

    def __str__(self):
        return self.user.username + " - " + self.accounttype

You can use "app_name.Account"instead of Account. Replace app_name with the name of your app.

A: As per  John Gordon comment, I moved Account above UserProfile and it worked
class Account(models.Model):
    reports = models.IntegerField(default=3)
    accounttype = models.CharField(default='Free', max_length=250)
    description = models.CharField(default='N/A', max_length=250)
    monthlycost = models.FloatField(default=0.0)

    def __str__(self):
        return self.user.username + " - " + self.accounttype

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    account = models.ForeignKey(Account, unique=True)

Thanks guys :)


text:
Q: Why can't I make my div 100% height if I use an HTML5 doctype? How do I get it 100% height I am working on getting the layout sorted for a pretty simple gallery webapp, but when I use an HTML5 doctype declaration, the height of some of my divs (which were 100%) get shrunk right down, and I can't seem to plump them back up using CSS.
My HTML is at https://dl.dropbox.com/u/16178847/eyewitness/b/index.html and css is at https://dl.dropbox.com/u/16178847/eyewitness/b/style.css

*

*If I remove the HTML5 doctype declaration, all is as I want it to be,
but I really want to use the proper HTML5 doctype declaration.

*If I set the doctype to HTML5 and make no changes, the div with the photo and the footer divs are not visible, presumably because they are 0px high.

*If I set the doctype to HTML5 and make the body { height: 100px } and .container { height: 100px } or .container { height: 100% }, it becomes visible, but what I need is it to be is full height rather than a height in pixels.

*If I try to do the same as above, but with the body { height: 100% } the photo and footer divs are not visible again.

What do I need to do to get it 100% in height so that my photo and footer divs are full height?

A: Indeed, to make it work do as follow:
<!DOCTYPE html>

  <title>Vertical Scrolling Demo</title>

About

Portfolio

Contact

about

    About page content goes here.

portfolio

    Portfolio page content goes here.

contact

    Contact page content goes here.

A: Only if the parent element has a defined height, i..e not a value of auto. If that has 100% height, the parent's parent height must be defined, too. This could go until to the html root element.
So set the height of the html and the body element to 100%, as well as every single ancestor element of that element that you wish to have the 100% height in the first place.
See this example, to make it clearer:

html, body, .outer, .inner, .content {
  height: 100%;
  padding: 10px;
  margin: 0;
  background-color: rgba(255,0,0,.1);
  box-sizing: border-box;
}

      Content

This wouldn't work, if I didn't give 100% height to—say html element:

body, .outer, .inner, .content {
  height: 100%;
  padding: 10px;
  margin: 0;
  background-color: rgba(255,0,0,.1);
  box-sizing: border-box;
}

      Content

… or .inner

html, body, .outer, .content {
  height: 100%;
  padding: 10px;
  margin: 0;
  background-color: rgba(255,0,0,.1);
  box-sizing: border-box;
}

      Content

A: I got stuck into a similar problema to size a canvas, so here is what i did and worked perfectly.
Besides doing the:
body{ width: 100%; height: 100%;}

Set the desired element like this:
.desired-element{ width: 100vw; height: 100vh}

In that way you are assured to have 100% of the view port in width and height.
vw stands for viewwidth
and
vh stands for viewheight
I hope this helps someone


text:
Q: JSONObject returns null in Android 10? I have a private app for work installed on a phone running Android 8 and a tablet running Android 8.1 and it's working fine on both but when I installed it on my new phone running Android 10, it gives me an JSON error. The rest of the app works fine but it's showing a JSONObject as null. Is this just a setting or has something changed with Android 10?
@Override
        protected Void doInBackground(Void... arg0) {

            HttpJsonParser httpJsonParser = new HttpJsonParser();
            Map<String, String> httpParams = new HashMap<>();

            JSONObject jsonObject = httpJsonParser.makeHttpRequest(GET_VERSION_URL, "GET", httpParams);

            if (jsonObject != null) { // <- Returns fine on Android 8.1 but not Android 10

                try {
                    ...
                } catch (final JSONException e) {
                    ...
                }

            } else {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"Error.", Toast.LENGTH_LONG).show(); // <-Goes to this everytime
                    }
                });
            }

            return null;

        }

A: I don't think your problem is with JSONObject itself. More probably is has to do with changes and restrictions with how HTTP calls are made in Android. Some changes are introduced with newer version like:

*

*Requiring all request to be made using HTTPS.

*Deprecation of old HTTP Clients like Apache's one.

Some of those restrictions can be bypassed enabling a config flag, this will give you more time to update your implementation. But the recommended approach is to follow the new guidelines as stop using deprecated stuff.
Go here, and check the "Behavior changes for all apps" and "Behavior changes for apps targeting API XX+" pages for the version of Android where your app doesn't work. That will give you a clue about if this is the problem.


text:
Q: How to Label Multiple Geocode Locations I have a page in my application that's trying to display a number of addresses on the map. I'd like to be able to label them in numerical order and display the relevant data about the location in an InfoWindow. Here's my code
//init info window
var infoWindow = new google.maps.InfoWindow;
var onMarkerMouseover = function() {
    var marker = this;
    infoWindow.setContent(marker.details);
    infoWindow.open(map, marker);
}

var form = document.getElementById('routeOptions');
    var i;
    var post_data = '';
    var wo_count = 1;
    var bounds = new google.maps.LatLngBounds();
    var geocoder = new google.maps.Geocoder();
    var addressMap = {};

    for (i = 0; i < form.elements.length; i++) {
        if (form.elements[i].id.indexOf('maploc') == '0') {
            if (form.elements[i].id.indexOf('[start]') > 0
                || form.elements[i].id.indexOf('[end]') > 0) {
                continue;
            }

            var values = form.elements[i].value.split('::');
            var address = values[0] + ', ' + values[1] + ', ' + values[2] + ', wo_count:' + wo_count
            var latLng;

            geocoder.geocode({
                'address': address
            }, function(results, status) {
                if (status == 'OK') {
                    var content = 'WO#: ' + jq('#wo_number_'
                        + wo_count).html() + '
'
                        + $('#address_'+ wo_count).html()+' '
                        + $('#city_'+ wo_count).html()+', '
                        + $('#state_'+ wo_count).html()+' '
                        + $('#zip_'+ wo_count).html()+'
'
                        + $('#work_type_'+wo_count).html();

                    //draw the marker
                    var marker = new google.maps.Marker({
                        position: results[0]['geometry']['location'],
                        map: window.map,
                        label: wo_count+"",
                        details: content
                    });
                    google.maps.event.addListener(marker, 'mouseover', onMarkerMouseover);

                    bounds.extend(marker.getPosition());
                    map.fitBounds(bounds);
                } else {
                    alert("Unable to find address. Contact Support if the problem persists");
                    return;
                }
            });

            wo_count++;
        }
    }

The main issue with this code is that although wo_count as a variable is available to the callback function as defined the value of it will be wrong every time. For example, if I have 3 addresses then the value of wo_count will always be 4 for each location because the code to increment it finishes faster than google can respond. I can't just assign the number in the order the responses come back either because google might not return my responses in order. Is there a way I can get my wo_count variable to be correct on each iteration to assign the correct index to the icon and retrieve the correct address data for the Info Window on each location?

A: Creating a closure around your counter would allow you to keep a persistent reference to it. Something like this might work:
var form = document.getElementById('routeOptions');
var i;
var post_data = '';
var wo_count = 1;
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var addressMap = {};

for (i = 0; i < form.elements.length; i++) {
    if (form.elements[i].id.indexOf('maploc') == '0') {
        if (form.elements[i].id.indexOf('[start]') > 0
            || form.elements[i].id.indexOf('[end]') > 0) {
            continue;
        }

        geocodeWrapper(form.elements[i].value.split('::'), wo_count)

        wo_count++;
    }
}

function geocodeWrapper(values, wo_count) {
    var address = values[0] + ', ' + values[1] + ', ' + values[2] + ', wo_count:' + wo_count
    var latLng;

    geocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == 'OK') {
            var content = 'WO#: ' + jq('#wo_number_'
                + wo_count).html() + '
'
                + $('#address_'+ wo_count).html()+' '
                + $('#city_'+ wo_count).html()+', '
                + $('#state_'+ wo_count).html()+' '
                + $('#zip_'+ wo_count).html()+'
'
                + $('#work_type_'+wo_count).html();

            //draw the marker
            var marker = new google.maps.Marker({
                position: results[0]['geometry']['location'],
                map: window.map,
                label: wo_count+"",
                details: content
            });
            google.maps.event.addListener(marker, 'mouseover', onMarkerMouseover);

            bounds.extend(marker.getPosition());
            map.fitBounds(bounds);
        } else {
            alert("Unable to find address. Contact Support if the problem persists");
            return;
        }
    });
}


text:
Q: Android: Rendering real time values Is there any open source engine available to render real time values in the shape of line chart and other types of chart. As the data passed using the web it will dynamically update itself and plot.

A: I am using AChartEngine to draw line charts.
It only provides plotting functionality.
Implementing real time data binding is your job.
ADDED
JFreeChart is the most famous one in Java, but it does not support Android since it uses Swing.
AFreeChart is a port of JFreeChart for android supprts.
http://code.google.com/p/afreechart/
Screenshots: http://afreechart.googlecode.com/svn/doc/screenshot/index.html
I am not sure it provides types of charts you want to use, but I think there are not many alternatives and this one may be the best.

A: GraphView: http://www.jjoe64.com/p/graphview-library.html
It supports only line chart and barchart for now, but it has really small footprint and support dynamic data as well. Not very complex.
They have dynamic data example in their demos.


text:
Q: It was meme city I know it's silly but, Elon Musk once said it during his meme review: "It was meme city". So we've got an argument with my friend about the 'meme city' part.
I say it's a compound adjective used as subject complement, so it's like saying "It was hilarious",  "It was hysterical", "It was very entertaining" that's why no article is needed
My friend says 'city' is a noun so it has no be qualified as a noun
Who's right? Is there an article I can refer to to prove my point if I'm right? Can't seem to find any. Thank you


text:
Q: How to pass a file as a parameter of a procedure I am trying to write a sub procedure to read from a "grocery.txt" file. The format is as follow:
12 7.2 Orange
The first column is an integer, the second is a float. The third one is a String till the end of line. How should I declare the parameter and how can I pass the file variable as a parameter for the sub procedure?
 PROCEDURE Read_File(Ada.Text_IO.File_Type => in_Item,
  Item : out Grocery_Item) IS
 BEGIN
  Ada.Integer_Text_IO.Get(File => In_Item,
     Item => Grocery_Item.Quantity,
        Width => 3);
  Ada.Float_Text_IO.Get(File => In_Item, Item => Grocery_Item.Cost_Per_Item,
     Width => 3);
  Ada.Text_IO.Get_Line(Item => Grocery_Item.Item.Item_Name,
     Last => Grocery_Item.Item.Item_Name_Length);
 END Read_File;

I keep getting an error saying I am missing a "," on the PROCEDURE line.
Thank you very much.

A: => is used only when calling procedures or functions.  When you declare them, the syntax is parameter-name : [in/out/in out/access] type, just like you did with Item : out Grocery_Item:
procedure Read_File (In_Item : in Ada.Text_IO.File_Type;  -- the "in" keyword is optional
                     Item    : out Grocery_Item) is
...

(Just to avoid any possible confusion, => is also used in contexts that have nothing to do with procedures or functions (subprograms).  The point is that when you're using subprograms, you may use => when you call them, but not when you declare them.)
Also, I'm not sure which one is the type and which one is the parameter name: Item or Grocery_Item?  If Grocery_Item is the type, the parameter declaration is fine, but it doesn't make sense to use Grocery_Item.Quantity, Grocery_Item.Item.Item_Name_Length, etc., in the body, because that's not a place for a type name.  Maybe you want to say Item.Quantity, etc.  I can't tell.  If Item is actually the type, and Grocery_Item will be the name of the parameter, then you need to switch them at the top of the procedure:
procedure Read_File (In_Item      : in Ada.Text_IO.File_Type;  -- the "in" keyword is optional
                     Grocery_Item : out Item) is
...

But to know for sure, we'd have to see what the declaration of either type Item or type Grocery_Item is.
Finally, one other thing: why do the first two Get calls use a file, but the last Get_Line doesn't?  This will cause two reads from your file, and third read will be from the keyboard (probably).  You probably want to add the File parameter to the last Get_Line too.


text:
Q: How to add a null terminator in string? say i have a loop i want to add the first value "this" by the command
strcat(l->value,l->db.param_value.val);

now i want to append a null and move it one more space to the right so i can have
"this"'\0'"is"'\0'

if i do strcat continuously in a loop it just gives me "thisis", anyone have a suggestion on how to do this ?
Ive tried the statement below it didn't work
      l->value=  l->value[1 + strlen(l->db.param_value.val)];

Thank you!

A: Try
l->value += strlen(l->db.param_value.val) + 1;

Assigning l->value[1 + strlen(l->db.param_value.val)] essentially means treating the small value of a character as an address. Which is most definitely not what you want.
Also, make sure there is enough space and all that.


text:
Q: Change git base branch I have a release branch from which MO-1334 is branched off. MO-3119 is a branch of MO-1334. Now that MO-1334 is merged back into the release branch, I want to not have all commits on it show up in my MO-3119 pull request (I tried creating a PR draft on the Github UI, selecting the release branch as base and saw commits from MO-1334 as well which is not what I want - those were already reviewed!).
Note that I tried to follow Git change base branch and got this in Android Studio's git view:

Here - when looking at it from the Github UI - "release/7.1.0" actually contains not only remove 86 megabytes of junk from the code base but also these commits from the merged MO-1334 pull request:

Now that is way too confusing so I went ahead to the Github UI and tried to create a pull request for MO-3119, getting this:

Note that:
1. commits from MO-1334 are still there and I explicitely wanted to "hide" them (essentially basing my MO-3119 on the release branch that already has MO-1334 merged in)
2. my MO-3119 commits are duplicated for some weird reason
Please, help me resolve this mess as well as document what should I do next time step by step.

A: What I ended up doing:

*

*cloned the repo fresh, checked out the release branch

*created a new branch, MO-3119_fixed

*cherry picked the MO-3119 commits on it

*pushed MO-3119_fixed and deleted MO-3119
Nice and simple and worked like a charm.


text:
Q: Can anyone recommend a beginner DBA course in London My organisation is in need of a SQL Server DBA and as the companies only "SQL Guy" my boss has suggested me to take SQL Server DBA course.  My general T-SQL knowledge is fairly good, I can write fairly complicated queries, have done stuff with stored procedures etc.  But when it comes to proper DBA knowledge, is where I fall down.  All my previous role had a DBA team who guarded their knowledge jealously so I am missing lots of best practice knowledge on how to deal with SQL server.
Can anyone recommend a good beginner SQL Server 2012 DBA course in London (UK)?
Thanks
Ian

A: Ask your boss to get you a pluralsight subscription.
Additionally, read answers from people like Paul White, Aaron Bertrand, Remus, etc and try to answer questions on this site.
Read blogs from sqlskills.com, brentozar.com, mssqltips.com, sqlperformance.com.
Also folks from sqlskills and brentozar are giving inperson training in LD.
Sqlbits event in UK and the videos on it are extremely helpful and don't forget virtual academy from Microsoft.


text:
Q: Orchard CMS or Other Calendar I am working on a site and we need a calendar exactly like on this page: http://www.houseofblues.com/concert-events
The site seems developed in Orchard CMS, do you know which type of plugin, module they are using for calendar? From where we can get this calendar ?


text:
Q: iphone app settings I would like to be able to show the app settings to some users and to others no. I have created the settings bundle (the default settings bundle outside the app), it works fine and I know how to access the settings value pragmatically.
What I would like to do is either:
***if(user logged) do nothing else make settings disappear
or:
***if(user logged) create settings pragmatically and make them show
   else make settings disappear/delete
I know I can't make the whole settings invisible is it possible to make one of the pref invisible???
How could I do that?

A: A setting bundle is totally static. You can't run some code in it, like checking if the user is connected.
I pretty sure that you cannot, in your app, activate or deactivate the setting bundle. If I'm wrong, I would be glad to know how.
EDIT :
You should create an in-app settings view controller to control dynamically some entries.
There's no automated way to make that kind on settings but I think you should create an UITableViewController.
Here's the documentations : https://developer.apple.com/library/IOs/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html#//apple_ref/doc/uid/TP40007451
And a good sample code : https://developer.apple.com/library/IOs/#samplecode/TableViewSuite/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007318


text:
Q: Is javascript injection of password in form safe? I want to use javascript injection in my programming to make my company work more efficiently. What I worried about is leaking of password due to javascript injection. Here's my question, is the code below are safe? Here's the code I am going to using.
document.getElementById("user_input").value="company_user_id";
document.getElementById("pwd_input").value="company_password";
document.getElementById("submit_input").click();

I understand that javascript is client side script and maybe the code above wouldn't do anything related to network. I have do checking traffic by using WireShark and browser network console. Both show me the result of code above didn't do any sending or receive task.
Why I am asking such question is I really want to make myself easy that javascript code above is safe.

A: Safe from what?
(whatever it is, probably not)
You're including a plaintext password in a javascript file. If this file is accessible to anyone that isn't supposed to know the password, you're basically making it useless.


text:
Q: How to identify that a specific text was sent by socket, to activate a command, with if ==? I have a code that sends a pre-established text by socket. If the default text sent is "hi", I want that in addition to receiving the hi, print that the text sent was hi. I'm a beginner, I tried doing if msg == hi: but it didn't work. How do I do it please?
Server
from socket import *
host = gethostname()
port = 8889

print(f'HOST: {host} , PORT {port}')
serv = socket(AF_INET, SOCK_STREAM)
serv.bind((host, port))
serv.listen(5)

con, adr = serv.accept()

msg = con.recv(1024)
print(msg.decode())

if msg == "hi":
    print('A mensagem foi hi')

Client
from socket import *
host = gethostname()
port = 8889
cli = socket(AF_INET, SOCK_STREAM)
cli.connect((host, port))

msg = ("hi")
cli.send(msg.encode())

A: You aren't actually updating your msg variable to the decoded string, you are just printing the string. When comparing msg to "hi", msg still contains encoded bytes. You should add
msg = msg.decode()

or you might as well put it earlier:
msg = con.recv(1024).decode()


text:
Q: Safari Bug: rotateY and rotateX element under fixed element
The gray image with the hands scrolls up using translate. It has a fixed position. The dog image cutting through has the following styles:
transform: scale(1.025) rotateY(..) rotateX(..)
Only happens in Safari. Seems like the rotated dog image doesn't like being under fixed elements. This also happens when the image is scrolled beneath the nav bar (also fixed position).
Anyone know a fix for this? I've tried putting different transform properties on different elements, no fix yet.

A: Adding translate3d(...) to the fixed element above the dog image fixed the problem.
I also added perspective: 9999 to the parent element containing the grid of images.

A: I suffered from the same issue. After few try, I fixed it by add tranlateZ(some value which is important) which separate these two layer into two level.


text:
Q: Is it possible to style 2 halves of 1 div in separately? So for instance one half is skewed at one angle, the other is skewed at another, using only 1 div.
Reason being is that I will have text across the Div, so I can not just split it into two.
Any information or ideas that you can provide are much appreciated.

A: Refer this as an example as you have not added any codes, it impossible to guess your approach. But you could do that by adding background:linear-gradient to parent div.

div{
  width:300px;
  height:300px;
  background:linear-gradient(90deg, red 50%, green 50%);
}
div h1{
  text-align:center;
}

Hello !!!

Add vendor prefixes for other browser support.

A: You cannot have in general two different styles on one element with rule of applying under conndition, for example "apply style nr.2 if width is over 50%"
Rather than that, create some simple structure (snippet below).
!!I DO NOT RECOMMEND THIS, but you can also in a limited way display 2 different colours on one div by using gradient, check this tool http://www.colorzilla.com/gradient-editor/
But rather than that, you should do some structure, because if you need more styling than only a 2 colors, it is simply necessary.

.container, .container2{position:absolute; top:0; left:0; margin:auto; width:200px; height:200px; background:black;}
.bg-1, .bg-12
{height:100%; width:50%; position:absolute; top:0; left:0; background:#CCF;}

.bg-2, .bg-22{height:100%; width:50%; position:absolute; top:0px; left:50%; background:#FCC;}
.text{width:100%; height:100%; position:absolute; top:0; left:0; font-size:80px; text-align:center; vertical-align:middle; line-height:200px;}
.container2{left:230px !important;}

.bg-12{box-shadow: inset 0px 0px 52px 0px rgba(0,0,0,0.75);}
.bg-22{box-shadow: inset 0px 0px 52px 0px rgba(0,255,0,0.75);}

Text

Text


text:
Q: MYSQL How to use a variable for the OutFile I can't find how to use a variable as an an Outfile.
DECLARE wOutFile CHAR(256);
SET wOutFile = CONCAT('c/data/',wDateStr,'.csv');
SELECT * FROM sometable
INTO OUTFILE wOutFile;

The above renders an error on the last line.  The syntax parser in MySQL Workbench doesn't like the wOutFile on the last line.
Is there a way to tell the parser to use the contents of the variable?
I tried to search for a while but I must not be phrasing my question well.

A: If you want to make new statement from the strings, then you should use prepared statements -
DECLARE wOutFile CHAR(256);
SET wOutFile = CONCAT('c/data/',wDateStr,'.csv');

SET @var = CONCAT('SELECT * FROM sometable INTO OUTFILE ', wOutFile);
PREPARE stmt FROM @var;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


text:
Q: Chrome Ignoring autocomplete='off' I've created a web FROM but Chrome autocomplete is populating the info in the wrong places. Chrome (Version 41.0.2272.89 (64-bit))
Despite both the input field AND the form field having the autocomplete="off" attribute, Chrome insists on showing a drop down history of previous entries for the field.
Sample From
<form accept-charset="UTF-8" action="/something" autocomplete="off" id="something_form" method="post">

  <input name="utf8" type="hidden" value="✓" />
  <input name="authenticity_token" type="hidden" value="xxxxxxxxxxxx" />

    Name:

      <input id="from-name" inlineeditable-column="0" type="text" name="o_name" class="form-control custom-form_control required sensitive long "  autocomplete="off"  >

</form>

A: On the input fields that you want to stop from auto complete this will work. Make the fields read only and on focus remove that attribute like this
<input readonly onfocus="this.removeAttribute('readonly');" onblur="this.setAttribute('readonly');"  id="from-name" type="text" name="o_name" class="form-control custom-form_control required ">

A: In Chrome autocomplete="off" only works for fields other then password, email, username, mobile, zipcode, city, ...
If the field's name or id is like id="blabla-password" or name"email-blabla" or id="bla-username-bla" etc... then you have to use the following
id="bla-bla-some-password" autocomplete="new-password"
id="bla-email-bla"         autocomplete="new-email"
id="some-username-id"      autocomplete="new-username"
name="bla-password"        autocomplete="new-password"
name="bla-email-bla"       autocomplete="new-email"
name="some-username-id"    autocomplete="new-username"
...city                    autocomplete="nope"
...zipcode                 autocomplete="nope"
...mobile                  autocomplete="nope"
...

For all the other fields keep using autocomplete="off" !
It is still the best result
id="description" autocomplete="off"
id="date"        autocomplete="off"
id="some-text"   autocomplete="off"
...

And so on

A: Chrome has been ignoring autocomplete="off" for a while now, you have to trick chrome by doing the following: 1. Set the input type to text, and 2. reset the input type when on focus event is triggered
<input type="text" id="password" autocomplete="off" name="password">

$('#password').on('focus', function(){
    $('#password').attr('type', 'password');
});

Reset done using Jquery


text:
Q: Visual Studio C# Debug vs Release and Compilation debug="false" I have confused myself and am seeking clarification after reading and not finding an clear answer, that or I'm too sleep deprived to "get it":
I am testing Javascript/CSS bundling on my local machine using Visual Studio 2012.
I can not get this to work without having web.config
    <compilation debug="false"...

or setting
    protected void Application_Start()
    {
    BundleTable.EnableOptimizations = true;
    ...

So if I set the debug="false" then Visual Studio complains "The page cannot be run in debug mode... "
Am I missing a fundamental concept?  I want to run a test or two with the Bundling/Minification on.  Do I have to manually set either of the above two settings? Why does this not work automatically when I have debug="true" but use Ctrl+F5?
It seems like a pain to have to manually turn on/off the <compilation debug="true" setting when I want to see this feature on my local machine.
Am I missing something?

A: Try adding:
 BundleTable.EnableOptimizations = (!HttpContext.Current.IsDebuggingEnabled);

This gives you the benefit of including the full version of js while in debug mode and a minified version when in release mode.
Are you sure the prompt you are getting when you include compilation debug="false"... is not a warning such as ..."debugging is not turned on. Do you want to enable debugging?" type prompt?


text:
Q: C++ copying files. Short on data I'm trying to copy a file, but whatever I try, the copy seems to be a few bytes short.
_file is an ifstream set to binary mode.
void FileProcessor::send()
{
    //If no file is opened return
    if(!_file.is_open()) return;
    //Reset position to beginning
    _file.seekg(0, ios::beg);

    //Result buffer
    char * buffer;
    char * partBytes = new char[_bufferSize];
    //Packet *p;
    //Read the file and send it over the network

    while(_file.read(partBytes,_bufferSize))
    {
        //buffer = Packet::create(Packet::FILE,std::string(partBytes));
        //p = Packet::create(buffer);
        //cout<< p->getLength() << "\n";
        //writeToFile(p->getData().c_str(),p->getLength());
        writeToFile(partBytes,_bufferSize);
        //delete[] buffer;
    }

    //cout<< *p << "\n";
    delete [] partBytes;
}

_writeFile is the file to be written to.
void FileProcessor::writeToFile(const char *buffer,unsigned int size)
{
    if(_writeFile.is_open())
    {
        _writeFile.write(buffer,size);
        _writeFile.flush();
    }
}

In this case I'm trying to copy a zip file.
But opening both the original and copy in notepad I noticed that while they look identical , It's different at the end where the copy is missing a few bytes.
Any suggestions?

A: You are assuming that the file's size is a multiple of _bufferSize. You have to check what's left on the buffer after the while:
while(_file.read(partBytes,_bufferSize)) {
  writeToFile(partBytes,_bufferSize);
}
if(_file.gcount())
    writeToFile(partBytes, _file.gcount());

A: Your while loop will terminate when it fails to read _bufferSize bytes because it hits an EOF.
The final call to read() might have read some data (just not a full buffer) but your code ignores it.
After your loop you need to check _file.gcount() and if it is not zero, write those remaining bytes out.

A: You don't want to always do writeToFile(partBytes,_bufferSize); since it's possible (at the end) that less than _bufferSize bytes were read. Also, as pointed out in the comments on this answer, the ifstream is no longer "true" once the EOF is reached, so the last chunk isn't copied (this is your posted problem). Instead, use gcount() to get the number of bytes read:
do
{
    _file.read(partBytes, _bufferSize);
    writeToFile(partBytes, (unsigned int)_file.gcount());
} while (_file);

For comparisons of zip files, you might want to consider using a non-text editor to do the comparison; HxD is a great (free) hex editor with a file compare option.

A: Are you copying from one type of media to another?  Perhaps different sector sizes are causing the apparent weirdness.
What if _bufferSize doesn't divide evenly into the size of the file...that might cause extra bytes to be written.


text:
Q: How do I go back in webview? I am using the react-navigation package in react-native I installed the react-navigation  package in react-native
I have implemented tab navigation and one of them is implemented in webview format.
My problem is that if I press the back physical button on Android, I go from the app itself to the previous tab, not back from the webview.
I've already applied the back button for the webview on the internet, but I have not done that.
I tried to display the onNavigationStateChange log when debugging, but it was not updated when url was moved after it was loaded at first startup. Here is the code I implemented:
import React from "react";
import {BackHandler} from "react-native";
import {WebView} from "react-native-webview";

class SermonScreen extends React.Component {
    constructor(props) {
        super(props);
    }
    static navigationOptions = {
        header: null
    };

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
    }

    _onNavigationStateChange(navState) {
        console.log(navState);
        this.setState({
            canGoBack: navState.canGoBack
        });
    }

    handleBackButton = () => {
        console.log(this.state);
        if (this.state.canGoBack === true) {
            this.webView.goBack();
            return true;
        } else {
            return false;
        }
    };

    render() {
        return (
            <WebView
                source={{uri: 'https://m.youtube.com/channel/UCw3kP3qCCF7ZpLUNzm_Q9Xw/videos' }}
                ref={(webView) => this.webView = webView}
                onNavigationStateChange={this._onNavigationStateChange.bind(this)}
            />
        );
    }
}

export default SermonScreen;

A: Following the official webview documnentation you could try to do this: https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#intercepting-hash-url-changes
In general you were almost there, however the way the YT navigation works made it impossible to be caught via the onNavigationStateChange, that's why we inject a JS code that intercepts these hash changes and posts a message to the parent component, we then catch it inside the onMessage handler and set the state variable properly. Copying the injectedJavaScript and onMessage properties to your example should solve your problem.
I prepared a component for you that seems to do what is needed:
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Fragment } from "react";
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  BackHandler,
  StatusBar
} from "react-native";
import { WebView } from "react-native-webview";
import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions
} from "react-native/Libraries/NewAppScreen";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.startingUrl =
      "https://m.youtube.com/channel/UCw3kP3qCCF7ZpLUNzm_Q9Xw/videos";
    this.handleBackButton = this.handleBackButton.bind(this);
  }

  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton);
  }

  handleBackButton = () => {
    console.log(this.state);
    const { canGoBack } = this.state;
    if (canGoBack) {
      this.webView.goBack();
      return true;
    } else {
      return false;
    }
  };

  render() {
    return (
      <Fragment>
        <WebView
          source={{ uri: this.startingUrl }}
          style={{ marginTop: 20 }}
          ref={webView => (this.webView = webView)}
          injectedJavaScript={`
          (function() {
            function wrap(fn) {
              return function wrapper() {
                var res = fn.apply(this, arguments);
                window.ReactNativeWebView.postMessage('navigationStateChange');
                return res;
              }
            }

            history.pushState = wrap(history.pushState);
            history.replaceState = wrap(history.replaceState);
            window.addEventListener('popstate', function() {
              window.ReactNativeWebView.postMessage('navigationStateChange');
            });
          })();

          true;
        `}
          onMessage={({ nativeEvent: state }) => {
            if (state.data === "navigationStateChange") {
              // Navigation state updated, can check state.canGoBack, etc.
              this.setState({
                canGoBack: state.canGoBack
              });
            }
          }}
        />
      </Fragment>
    );
  }
}

export default App;

A: The response above was perfect. I set the state true for canGoBack though; I was getting a null error, so:
constructor(props) {
    super(props);
    this.startingUrl = "https://app.vethorcardpag.com.br/GIF/login/0/";
    this.state = {
        canGoBack : true
    }
    this.handleBackButton = this.handleBackButton.bind(this);
}

A: Here is a simple solution using the magic of React's State.
Hope this helps.
import React, { useRef, useState } from 'react'

export default function Component () {

    // This is used to save the reference of your webview, so you can control it
    const webViewRef = useRef(null);

    // This state saves whether your WebView can go back
    const [webViewcanGoBack, setWebViewcanGoBack] = useState(false);

    const goBack = () => {

        // Getting the webview reference
        const webView = webViewRef.current

        if (webViewcanGoBack)
            // Do stuff here if your webview can go back
        else
            // Do stuff here if your webview can't go back
    }

    return (
        <WebView
            source={{ uri: `Your URL` }}
            ref={webViewRef}
            javaScriptEnabled={true}
            onLoadProgress={({ nativeEvent }) => {
                // This function is called everytime your web view loads a page
                // and here we change the state of can go back
                setWebViewcanGoBack(nativeEvent.canGoBack)
            }}
        />
    )
}

Original answer
https://stackoverflow.com/a/74500469/7823800


text:
Q: Como puedo convertir un Arreglo de tipo String que contiene Horas a uno de tipo Float? Estoy intentando crear una aplicación en la que recupero una consulta de MySQL sobre horas y lo guardo en un arreglo de tipo String, este arreglo la quiero introducir en una gráfica pero la grafica requiere un arreglo de tipo float.
El arreglo que me recupera la consulta es algo como esto:
Hour = {"10:20:15","10:45:50"};
Habrá la posibilidad de convertir este arreglo a uno de tipo float o double?
He intentado hacer lo siguiente y para ser honesto soy nuevo en la programacion.
       float[] Hora = new float[Hour.size()];
       for (int h = 0; h< Hour.size();h++ ){
           Hora[h] = Float.parseFloat(Hour.get(h));
       }

O si lo puedo resolver desde esta parte:
ArrayList<String> Hour = new ArrayList<>();

JsonObjectRequest InformDay = new JsonObjectRequest(
                Request.Method.POST,
                URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response.length()>0) {
                            try {
                                    JSONArray jsonArray = response.getJSONArray("registro");
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject objeto = jsonArray.getJSONObject(i);
                                        String hora = objeto.optString("Hora");
                                        Hour.add(hora);
                                    }
                                } catch(JSONException e){
                                    e.printStackTrace();
                                }
                            }else{
                                Toast.makeText(getActivity(),"No fue posible obtener el registro",Toast.LENGTH_SHORT).show();
                        }
                    }
                    },
                            new Response.ErrorListener()
                    {
                        @Override
                        public void onErrorResponse (VolleyError error){
                    }
                    }
        );
        rq.add(InformDay);
    }

Espero haberme explicado

A: Puedes reemplazar el primer ":" por "." y los siguientes ":" eliminarlos, después de esto puedes realizar la conversión a float:
 String[] Hour = {"10:20:15","10:45:50"};

  float[] Hora = new float[Hour.length];

  for (int i = 0; i< Hour.length;i++ ){
       //System.out.println(Hour[i]);
       //Reemplaza el primer ":" por "." y  los siguientes ":" los elimina.
       String result = Hour[i].replaceFirst(":", ".").replaceFirst(":", "");
       //Convierte valores a float del array Hour y los agrega a array Hora.
       Hora[i] = Float.parseFloat(result);
   }

Al final tendrías un arreglo Hora de valores tipo Float conteniendo los siguientes valores:
10.2015
10.455


text:
Q: is ther any way carryout backward pagination in elasticsearch(with golang ) Pagination is done using scroll_api, as a result, is more than 10k
http://localhost:9200/all_assets/_search?scroll=10m

{

    "from": 0,
    "size": 10,
    "query": {
        "match_all": {}
    },
    "sort": [
        {
            "?.keyword": "?"
        }
    ]

To get next further result using this
localhost:9200/_search/scroll?pretty
{
    "from":10,
    "scroll": "10m",
    "scroll_id": "FGluY2x1ZGVfY29udGV4dF91dWlkDXF1ZXJ5QW5kRmV0Y2gBFFNmNUJLM1VCaFRQeUhJQlNPamRqAAAAAAAAAAIWNE0tSDZYY2tSanFyUk95VXl0enpsZw=="
}

1 ] If we execute this will get the next 10 records and 2] we execute again we will get the next 10 records,
is there is any way to get the previous 10 records, have tried using from and size.
Is there any way to make it with backward-compatible.
Not getting the previous result it's providing the next 10 records if we execute with scroll_id url and wanted to make pagination forward and backward compatible.

A: A scroll is one way, just forward. You cannot go back. If you want to have backward, you need to use search API with from and size parameters.


text:
Q: Emulating Button Press Using Kinect/SimpleOpenNI + Processing Depth I am using Kinect with Simple OpenNI and Processing, and I was trying to use the Z position of a hand to emulate a button press. So far when I try it using one hand it works really well, however, when I try to get it to work with a second hand, only one of the hands work. (I know it can be more efficient by moving everything except the fill out of the if statements, but I kept those in there just in case I want to change the sizes or something.)
irz and ilz are the initial Z positions of the hands when they are first recognized by onCreateHands and rz and lz are the current Z positions. As of now, the code works fine with one hand, but the other hand will either stay pressed or unpressed. If i comment one of the sections out, it works fine as well.
if (rz - irz > 0) {
 pushStyle();
 fill(60);
 ellipse(rx, ry, 10, 10);
 popStyle();
 rpressed = true;
}
else {
 pushStyle();
 noFill();
 ellipse(rx, ry, 10, 10);
 popStyle();
 rpressed = false;
}

if (lz - ilz > 0) {
 pushStyle();
 fill(60);
 ellipse(lx, ly, 10, 10);
 popStyle();
 lpressed = true;
}
else {
 pushStyle();
 noFill();
 ellipse(lx, ly, 10, 10);
 popStyle();
 lpressed = false;
}

I tried outputting the values of rz - irz and lz - ilz and the numbers range from small negative values to small positive values (around -8 to 8) for lz - ilz. But rz - irz outputs numbers from around 8-30 depending on each time I run it and is never consistent. Also, when I comment out the code for the lz-ilz, the values for rz-irz look just fine and it operates as intended. Is there a reason tracking both Z positions throws off one hand? And is there a way to get it to work?
Thanks!

A: I've a couple of ideas:

*

*Use the NITE "Click" gesture

*Use the z position of the hand as you are now, but also keep track of differences in z movements

SimpleOpenNI seems to like one hand better than two with NITE gestures like "Click"(you should see a message printed after the hand is picked up and then move your hand forward and backward).
Bellow is a quick example. Note that I'm keeping track of +/- differences on Z and using a threshold to only trigger based on a certain distance, this could be range for example.
import SimpleOpenNI.*;
SimpleOpenNI context;
boolean      handsTrackFlag = false;
PVector      handVec = new PVector();
PVector      handVec2D  = new PVector();//just for drawing
String       lastGesture = "";
float        lastZ = 0;
boolean      isPushing,wasPushing;
float        yourClickThreshold = 20;//set this up as you see fit for your interaction

void setup(){
  size(640,480);
  context = new SimpleOpenNI(this);
  context.enableDepth();
  // enable hands + gesture generation
  context.enableGesture();
  context.enableHands();
  // add focus gestures  / here i do have some problems on the mac, i only recognize raiseHand ? Maybe cpu performance ?
  context.addGesture("Wave");
  context.addGesture("Click");
  context.addGesture("RaiseHand");

}

void draw()
{
  context.update();
  image(context.depthImage(),0,0);
  // draw the tracked hand
  if(handsTrackFlag){
    context.convertRealWorldToProjective(handVec,handVec2D);
    float diff = (handVec.z-lastZ);
    isPushing = diff < 0;
    if(diff > yourClickThreshold){
      if(!wasPushing && isPushing) fill(255,0,0);
      if(wasPushing && !isPushing) fill(0,255,0);
    }else fill(255);
    lastZ = handVec.z;
    wasPushing = isPushing;
    ellipse(handVec2D.x,handVec2D.y,10,10);
  }

}

// -----------------------------------------------------------------
// hand events

void onCreateHands(int handId,PVector pos,float time){
  println("onCreateHands - handId: " + handId + ", pos: " + pos + ", time:" + time);

  handsTrackFlag = true;
  handVec = pos;
}

void onUpdateHands(int handId,PVector pos,float time){
  //println("onUpdateHandsCb - handId: " + handId + ", pos: " + pos + ", time:" + time);
  handVec = pos;
}

void onDestroyHands(int handId,float time){
  println("onDestroyHandsCb - handId: " + handId + ", time:" + time);
  handsTrackFlag = false;
  context.addGesture(lastGesture);
}

// -----------------------------------------------------------------
// gesture events

void onRecognizeGesture(String strGesture, PVector idPosition, PVector endPosition){
  if(strGesture == "Click") println("onRecognizeGesture - strGesture: " + strGesture + ", idPosition: " + idPosition + ", endPosition:" + endPosition);

  lastGesture = strGesture;
  context.removeGesture(strGesture);
  context.startTrackingHands(endPosition);
}

void onProgressGesture(String strGesture, PVector position,float progress){
  //println("onProgressGesture - strGesture: " + strGesture + ", position: " + position + ", progress:" + progress);
}

An alternative to get two hands is to use the SKEL_PROFILE_HEAD_HANDS when doing skeletal tracking, but note that the hand precision is lower.


text:
Q: Find that one string is substring of other or not   public class StringIsSubstring {

public static void main(String[] args) {
    String s1= new String("anurag");
    String s2=new String("anu");

    char a[]=s1.toCharArray();
    char b[]=s2.toCharArray();
    int i=0;
    int j=0;

    while(i<a.length && j<b.length)
    {
        if(a[i]==b[j])
        {
            i++;
            j++;
        }
        else
        {
            i++;
            j=0;
        }
        if(j == b.length)
        {
            System.out.println("we have found the substring");
        }
    }
}
 }

I have written following code to find that one String is substring of other or not. I dont want to use any library function. Is there any more efficient way to do the same

A: It is not possible to do any operations on a String without using a library function.  Your code uses String.toCharArray, for example.  And if you can use that, then you can also use String.indexOf and avoid reinventing the wheel.
People have suggested Boyer-Moore.  This is a good choice if you are going to search a large body of text (in String instances or in some other representation).  However, if you are only going to search a small chunk of text (as in your question), then the setup costs of Boyer-Moore mean that String.indexOf() will be faster.  The same applies for other sophisticated algorithms.

So, the only way this question makes sense is if this is a homework exercise which includes a constraint on what you are allowed to use to solve the problem.  In that case, unless you are doing an algorithmics course, I doubt that they expect you to research and implement a sophisticated algorithm.

A: Boyer-Moore has already been suggested, but let me also point out that your algorithm is actually broken. For example, if you want to test whether "coa" is a substring of "cocoa" (which is true), then you will match up to "co", then it will reset j on the next "c", but the problem is that now you have already "consumed" the "c" that starts the substring, and you don't get a match.

A: You can see Boyer-Moore  algorithm http://en.wikipedia.org/wiki/Boyer–Moore_string_search_algorithm and http://en.wikipedia.org/wiki/String_searching_algorithm . You can see also String.indexOf java implementation.

A: The previous comments have offered good reasons for applying a library function, however perhaps you are tasked with applying an alternate algorithm. From the sounds of your post, you are likely to be working with small s1s and s2s. For this purpose, the KnuthMorrisPratt algorithm yields good efficiency. You can implement this like so :
public class SOStringDemo {

    public static void main(String[] args) {

        SOStringIsSubstring pair = new SOStringIsSubstring();

        pair.text = "thequickbrownfoxanujumpedoverthelazydogs";
        pair.pattern = "anu";

        pair.KMPMatch();

        return;
    }
}

And the class file :
public class SOStringIsSubstring {

    public String text;
    public String pattern;
    private char[] textArray;
    private char[] patternArray;
    private int[] prefix;

    public void KMPMatch() {

        textArray = text.toCharArray();
        patternArray = pattern.toCharArray();
        int n = textArray.length;
        int m = patternArray.length;

        ComputePrefixFunction();
        int q = 0;

        for(int i = 0; i < n; i++) {
            while((q > 0) && (patternArray[q]) != textArray[i])
                q = prefix[q];
            if(patternArray[q] == textArray[i])
                ++q;
            if(q == m) {
                System.out.println("SubString is at index " + (i - m + 2));
                q = prefix[q-1];
            }
        }

        return;
    }

    public void ComputePrefixFunction() {

        int m = patternArray.length;
        prefix = new int [m];
        int k = 0;
        for(int q = 1; q < m; q++) {
            while((k > 0) && (patternArray[k] != patternArray[q]))
                k = prefix[k-1];
            if(patternArray[k] == patternArray[q])
                ++k;
            prefix[q] = k;
        }

        return;
    }
}


text:
Q: How to adapt a PHP library to Codeigniter? Good mor(eve)ning guys. My question is a bit general:
How can I adapt any PHP library (like facebook sdk for example) to use in CodeIgniter?
Generally, when you download a PHP library and look to the examples provided, you load the library using include or require_once. What are the adjustments (and ways) to use $this->load->library($name, $params)?
And how can I use the library after that: replacing $var = new Library($data) by ???
If my question is not yet clear, please notify me.
(bonus question: How to apply this to facebook-sdk ?)
Thanks in advance.

A: *

*create a folder to place a facebook-sdk files in it: /application/libraries/facebook/

*create a Facebook_lib.php in the libraries root with the content:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once 'facebook/facebook.php';
class Facebook_lib extends Facebook{}

*in controller:
$this->load->library('facebook_lib',$config); $this->facebook_lib->clearAllPersistentData();

A: For facebook sdk you just need to copy your files into ../application/libraries/ folder and in a controller you can call it in either ways:
$config = array('appId' => APP_ID, 'secret' => APP_SECRET);
$this->load->library('facebook', $config);

or
create a file named facebook.php in ./application/config folder and create an array in it
$config = array('appId' => APP_ID, 'secret' => APP_SECRET);

and in controller simply call your library like $this->load->library('facebook');

A: There is nothing stopping you from directly including classes include(APPPATH.'libraries/Facebook/base_facebook.php');
OR
Placing identically named versions in your application/libraries folder.
Classes should have this basic prototype (Note: We are using the name Someclass purely as an example):
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Someclass {

    public function some_function()
    {
    }
}

/* End of file Someclass.php */

From within any of your Controller functions you can initialize your class using the standard:
$this->load->library('someclass');

More read http://codeigniter.com/user_guide/general/creating_libraries.html


text:
Q: How to handle a Solidity uint array with web3 I am facing some problems when accessing elements of an array of uints, returned by a Solidity function, with web3 resp. Javascript.
The signature of my Solidity function looks like this
function getSomeIds() public view returns (uint[])

Now after I created some elements within my contract, and run above function in the interactive Truffle console I get the following (which is perfectly correct):
$ app.getSomeIds()
  [BigNumber {s:1, e:0, c[1]},
   BigNumber {s:1, e:0, c[0]}]

The problem with this is, that I cannot access elements of the returned array the common way, since web3 does not receive it as an array but as an object
$ array = app.getSomeIds()
$ array[0]
  undefined

$ typeof(array)
  'object'

So how can I access the elements of the array?


text:
Q: How to set the Ubuntu dock icon size to less then 16? In Ubuntu 20.04.1 settings, the minimum Dock icon size is 16:

How can I set this to less then 16?

A: Follow these steps:

*

*Install dconf editor from software center.

*open it and go to org/gnome/shell/extensions/dash-to-dock/.

*There you will find dash-max-icon-size.

*Set the value whatever you want (The default value is 48).

Or just run this command:
gsettings set org.gnome.shell.extensions.dash-to-dock dash-max-icon-size <VALUE>

for example -
gsettings set org.gnome.shell.extensions.dash-to-dock dash-max-icon-size 13


text:
Q: Massive: Using stored procedure I am trying to execute stored procedure using Massive micro-orm.
var tbl = new DynamicModel("Conn", tableName: "User", primaryKeyField: "UserID");
var result = tbl.Query("EXEC User_INSERT @0,@1,@2,@3", "7843bf9d-9cb8-495b-aaa5-785ac74b82a5", "7FBDDG58-B08E-4723-9477-C9E791CDF36E", "Admin", "11/20/2012");

While debugging it does not even go to Massive library. I also tried like...
var result = tbl.Query(@"EXEC ...);

and also
var result = tbl.Query("User_INSERT @0,...);

Nothing seems to be working. With same handle SELECT query works, but not the stored procedure. If I create a break point in the statement and load the same in "Quick watch" and expand dynamic result, it fires up stored procedure.

A: DynamicModel.Query returns an IEnumerable therefore the query (or stored procedure in this case) is never executed in SQL until the IEnumerable needs to be evaluated in your C# code.
You can force the evaluation of the IEnumerable by simply adding .ToList() to the end of your .Query() call:
var tbl = new DynamicModel("Conn", tableName: "User", primaryKeyField: "UserID");
var result = tbl.Query("EXEC User_INSERT @0,@1,@2,@3", "7843bf9d-9cb8-495b-aaa5-785ac74b82a5", "7FBDDG58-B08E-4723-9477-C9E791CDF36E", "Admin", "11/20/2012").ToList();

A: This is just a rough guess since I don't understand what your error message is and require more information but you can't pass your GUID's as a string (unless it is accepting it as a string type?). Perhaps try
var result = tbl.Query("EXEC User_INSERT @0,@1,@2,@3",
New Guid("7843bf9d-9cb8-495b-aaa5-785ac74b82a5"),
New Guid("7FBDDG58-   B08E-4723-9477-C9E791CDF36E"), "Admin", "11/20/2012");


text:
Q: How can I stub the controller_name method for a RSpec helper spec? I have a helper method that is dependent upon controller_name, and I want to write tests for it.
module NavigationHelper
  def show_navigation?
    !sessions_controller? && !registrations_controller?
  end

  private
    def sessions_controller?
      controller_name.eql?('sessions')
    end

    def registrations_controller?
      controller_name.eql?('registrations')
    end
end

These are the test setup steps i have tried:
RSpec.describe NavigationHelper, type: :helper do
  describe '#show_navigation?' do
    it 'is false for pages served by the sessions controller' do
      # controller.params[:controller] = 'sessions'
      # assign(:controller, 'sessions')
      # controller = SessionsController
      # helper.stub(:controller_name).and_return('sessions')
      # allow(helper).to receive(:controller_name) { 'sessions' }
      expect(show_navigation?).to eq(false)
    end
  end
end

How can I appropriately stub the call to controller_name?

A: the answer from Richard did not work for me.
I had to change from
let(:controller_name) { 'sessions' }

to
before do
  allow(helper).to receive(:controller_name).and_return 'sessions'
end

Now I can verify as usual in my helpers.

A: Here's a working solution:
require 'rails_helper'

RSpec.describe NavigationHelper, type: :helper do
  describe '#show_navigation?' do
    context 'SessionsController' do
      let(:controller_name) { 'sessions' }
      it { expect(show_navigation?).to eq(false) }
    end

    context 'RegistrationsController' do
      let(:controller_name) { 'registrations' }
      it { expect(show_navigation?).to eq(false) }
    end

    context 'other controllers' do
      it { expect(show_navigation?).to eq(true) }
    end
  end
end

How else might this problem be solved?


text:
Q: Having trouble with checkmouse I'm having trouble figuring out how to undraw something when there is a mouse click within a particular object (rectangle). I want the code to work in the way that when I click in the rectangle it erases the text (because I have to draw something else).
My professor doesn't like us to be importing a bunch of different libraries etc., so a simple method is much preferred.
The graphics library that we use from Zelle can be found here:
http://mcsp.wartburg.edu/zelle/python/graphics.py
Here is the code I have now.
#... is a game to celebrate the 150th anniversay of ...
#The aim of the game is for players to complete a maze , but only
#with the least number of moves possible, and crossing the least number of
#trip wires. BoilerMazer keeps track of the names, moves, and scores. Then
#will also display the top players and scores.

from graphics import *

#creating the game panel window
def panel():
    #grey window, with coordinates flipped, with banners etc
    win = GraphWin("Start Panel", 300,200)
    win.setCoords(0,0,300,200)
    win.setBackground("light grey")
    #drawing the BoilerMazer banner with text
    boilermazer = Rectangle(Point(0,200),Point(300,160))
    boilermazer.setFill("white")
    boilermazer.draw(win)
    #text inside
    banner1 = Text(Point(150,180),"BoilerMazer")
    banner1.setStyle("bold")
    banner1.setSize(20)
    banner1.draw(win)
    #initial game panel is going to have two buttons and a top scores object
    #top score "screen"
    toprec = Rectangle(Point(60,140),Point(240,50))
    toprec.setFill("white")
    toprec.draw(win)
    #text inside toprec
    topscores = Text(Point(150,130),"TOP SCORES")
    topscores.setSize(8)
    topscores.draw(win)
    border = Text(Point(150,120),"======")
    border.draw(win)
    bigmac = Text(Point(150,110),"Big Mac     21")
    bigmac.setSize(8)
    bigmac.draw(win)
    tt = Text(Point(150,90),"T.T     23")
    tt.setSize(8)
    tt.draw(win)
    cshell = Text(Point(150,75),"C-Shell     25")
    cshell.setSize(8)
    cshell.draw(win)
    macmac = Text(Point(150,55),"MacMac     27")
    macmac.setSize(8)
    macmac.draw(win)
    #new player button that will eventually be clicked
    new1 = Point(90,35)
    new2 = Point(210,0)
    newrec = Rectangle(new1,new2)
    newrec.setFill("chartreuse2")
    newrec.draw(win)
    #new player button text
    newplayer = Text(Point(150,18),"NEW PLAYER")
    newplayer.draw(win)
    #reset button
    resetrec = Rectangle(Point(240,35),Point(300,0))
    resetrec.setFill("red")
    resetrec.draw(win)
    #resettext
    reset = Text(Point(270,18),"RESET")
    reset.draw(win)
    #secondary panel window is the game panel after they click new player
    clicknew = win.checkMouse()

#defining the main function that will hold and call all other functions
def main():
    #calling the panel function that draws the window
    panel()

main()


text:
Q: Finding elements from one array within a certain range of elements of a different array I have two numpy arrays of unequal lengths:
a = numpy.array([108, 637, 1172, 1304, 2260, 2809])
b = numpy.array([109, 634, 2254, 2814])

I want to shorten a such that the corresponding elements in each array are similar. The criteria for this correspondence is when the element of b lies within the range: element a - 50 < element b < element a + 50. Hence, the element with value 108 from a is a match to the element with value 109 from b. The resulting output should be:
a_prime = numpy.array([108, 637, 2260, 2809])
b_prime = numpy.array([109, 634, 2254, 2814])

I can achieve this using a double for loop configuration:
a_prime = numpy.zeros(b.shape[0], dtype = int)
b_prime = numpy.copy(b)

for idx, element_b in enumerate(b):
  for element_a in a:
    if (element_a - 50) < element_b < (element_a + 50):
      a_prime[idx] = element_a

However, for large array lengths this will be very time consuming. What would be the fast and more pythonic way to achieve the same result?

A: Here's one way to obtain a_prime, where the closest values in a to a given value in b are set to the same index, regardless of the threshold, as you're looking for the closest values after all:
a_prime = a[np.abs(np.subtract.outer(b,a)).argmin(1)]
# array([ 108,  637, 2260, 2809])

Where np.substract.outer will give you the difference of each value in b with every other value in a, and taking its absolute value gives:
x = np.abs(np.subtract.outer(b,a))
print(x)
array([[   1,  528, 1063, 1195, 2151, 2700],
       [ 526,    3,  538,  670, 1626, 2175],
       [2146, 1617, 1082,  950,    6,  555],
       [2706, 2177, 1642, 1510,  554,    5]])

Now we only need the argmin value of each row, and to use it to index a:
x.argmin(1)
# array([0, 1, 4, 5], dtype=int64)


text:
Q: Adding CartoDB basemap in OpenLayers 3? I'm trying to add a CartoDB basemap to my OpenLayers map but I can't get it to work. Here is the code I use to declare the basemap variable:
const carto = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url:'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
    })
});

Any idea where the problem comes from?

A: const carto = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url:'http://{1-4}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
    })
});


text:
Q: iOS textures inverted, also it is rendered on only part of the texture?
After re-rendering all the data I am able to get the video streaming buffer on to openGL. But video is inverted and rendered only on part of the whole texture.
I am capturing frames from streaming video and rendering them to a texture. This is my vertex shader
    static const char *kVertexShaderString =
    "#version 100\n"
    "\n"
    "uniform mat4 uMVP; \n"
    "uniform vec3 uPosition; \n"
    "attribute vec3 aVertex; \n"
    "attribute vec4 aColor;\n"
    "varying vec4 vColor;\n"
    "varying vec3 vGrid;  \n"
"attribute vec2 v_TextCoord;\n"
"varying  vec2 texCoord;\n"
    "void main(void) { \n"
    "  vGrid = aVertex + uPosition; \n"
    "  vec4 pos = vec4(vGrid, 1.0); \n"
    "  vColor = aColor;"
    "  gl_Position = uMVP * pos; \n"
"   texCoord = v_TextCoord;\n"
    "    \n"
    "}\n";

and fragment shader
static const char *kPassThroughFragmentShaderString =
    "#version 100\n"
    "\n"
    "#ifdef GL_ES\n"
    "precision mediump float;\n"
    "#endif\n"
    "varying vec4 vColor;\n"
"uniform sampler2D v_Texture;\n"
"varying lowp vec2 texCoord;\n"
    "\n"
    "void main(void) { \n"
    "gl_FragColor = texture2D(v_Texture, texCoord);\n"
    "}\n";

After updates my vertices as below
-1.0f, -1.0f, -2.0f,
1.0f, -1.0f, -2.0f,
1.0f, 1.0f, -2.0f,
-1.0f, -1.0f, -2.0f,
1.0f, 1.0f, -2.0f,
-1.0f, 1.0f, -2.0f,

To create video texture I have used
     - (GLuint)createVideoTexture
{
    GLuint handle;
    glGenTextures(1, &handle);
    glBindTexture(GL_TEXTURE_2D, handle);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    return handle;
}

And to draw on screen I am using
CVPixelBufferRef pixelBuffer;

// If we have a valid buffer, lock the base address of its pixel buffer
//        if (NULL != latestSampleBuffer) {
//            pixelBuffer = CMSampleBufferGetImageBuffer(latestSampleBuffer);
pixelBuffer = [self.mOutput copyPixelBufferForItemTime:_player.currentItem.currentTime itemTimeForDisplay:nil];
unsigned char* pixelBufferBaseAddress = NULL;

CVPixelBufferLockBaseAddress(pixelBuffer, 0);
/// Address where image buffer starts
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(pixelBuffer);

/// Read image parameters
size_t width = CVPixelBufferGetWidth(pixelBuffer);
size_t height = CVPixelBufferGetHeight(pixelBuffer);
// CVPixelBufferRef rotatedBuffer = [self correctBufferOrientation:pixelBuffer];
pixelBufferBaseAddress = (unsigned char*)CVPixelBufferGetBaseAddress(pixelBuffer) ;

const size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
if(pixelBufferBaseAddress != NULL){

    if (0 == _floorTexture) {
        _floorTexture = [self createVideoTexture];
    }

    glBindTexture(GL_TEXTURE0, _floorTexture);
    GLsizei bufferHeight =  (GLsizei) CVPixelBufferGetHeight(pixelBuffer);
    GLsizei bufferWidth =  (GLsizei) CVPixelBufferGetWidth(pixelBuffer);
    if (bytesPerRow / BYTES_PER_TEXEL == videoSize.width) {
        // No padding between lines of decoded video

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixelBufferBaseAddress);
    }
    else {
        // Decoded video contains padding between lines.  We must not
        // upload it to graphics memory as we do not want to display it

        // Allocate storage for the texture (correctly sized)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, NULL);

        // Now upload each line of texture data as a sub-image
        for (int i = 0; i < videoSize.height; ++i) {
         GLubyte* line = pixelBufferBaseAddress + i * bytesPerRow;
         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, (GLsizei) videoSize.width, 1, GL_BGRA, GL_UNSIGNED_BYTE, line);
         }

        //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bufferWidth/BYTES_PER_TEXEL,bufferHeight, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixelBufferBaseAddress);
    }
}

//glVertexAttribPointer(_texCoordSlot, 2, GL_FLOAT, GL_FALSE,sizeof(float) * 4, 0);
glVertexAttribPointer(_texCoordSlot, 2, GL_FLOAT, 4*2, false, (GLvoid*) (sizeof(float) * 4));

glDrawArrays(GL_TRIANGLES, 0, NUM_CUBE_VERTICES / 3);
glBindTexture(GL_TEXTURE0, 0);
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);

if (pixelBuffer) {
    CFRelease(pixelBuffer);
}

I have also tried different vertices and also different glVertexAttribPointer for _texCoords.
Can anyone help identify problems in my approach?


text:
Q: Make  take up entire height I'm using an <embed> element so I can render a PDF inline.  It works well in all browsers, but I can't figure out how to have the <embed> take up the entire, available height in my Bootstrap column.  Here is a Plunker.  You'll need to widen the preview pane to see the columns next to each other.
This is my markup:

            <embed width="100%" type="application/pdf" src="http://pdf.pdf">

        Other stuff here

And here is the CSS that isn't completely working:
#pdf-container {
    bottom: 20px;
    left: 20px;
    position: absolute;
    right: 20px;
    top: 0;
}
#pdf-container #pdf {
    height: 100%;
    width: 100%;
}

What I'm challenged with is that it seems like you need to set the height directly on the '` element so they even render.  Setting the width on them to 100% is effective, but I can't get the height to take up 100% of the available height.
UPDATE: There appear to be a series of Bootstrap classes (.embed-responsive) that may be aimed at handling this, but when I apply it, my <embed> doesn't appear at all.  Here is a Plunker for that.

A: I put mine in responsive iframes. Change the padding-bottom and padding-top: 30px; to suit your needs

/* Flexible iFrame */

.Flexible-container {
  position: relative;
  padding-bottom: 56.25%;
  padding-top: 30px;
  height: 0;
  overflow: hidden;
}
.Flexible-container iframe,
.Flexible-container object,
.Flexible-container embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

  <object width="100%" data="https://modelica.org/events/modelica2012/authors-guide/example-abstract.pdf?scrollbar=0&toolbar=0&navpanes=0" type="application/pdf">
          <embed width="100%" type="application/pdf" src="https://modelica.org/events/modelica2012/authors-guide/example-abstract.pdf?scrollbar=0&toolbar=0&navpanes=0">
        </object>