text:
Q: Android Question (for game) I have a game, at the end i show a "Game Over" if the player does not follow some instructions.... the problem is android seems to stay on that state, when i go back to the menu and come back in.. i still dont have a way to play again, the game is coded in the main activity and has Runnables and OnTouch events, also I have a splash screen that when click it goes to the other activity where the game starts.... I am new to Android, what is the best way to terminate the Thread and then send them to the first Activity or splash screen?
Thank you in advance

A: It's very difficult to help without seeing any code. However, an Activity can self-terminate by calling finish(), if that's what you're asking.

A: If you use static variables they will be 'remembered' unless explicitly set in the View constructor or onSizeChanged etc. For example  x = x + 5, can increase x every time you start the same game if x is static, because it 'remembers' x from the previous play - one needs to be aware of this.


text:
Q: r-base-core build on ubuntu 10.04 failing because of missing libjpeg8 package So the libjpeg8 package on 10.04 has reached EOL.
Is there a way to locate and install the legacy package for this?
$ sudo apt-get install r-base-core
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
  r-base-core: Depends: libc6 (>= 2.15) but 2.11.1-0ubuntu7.13 is to be installed
               Depends: libjpeg8 (>= 8c) but it is not installable
               Depends: liblzma5 (>= 5.1.1alpha+20110809) but it is not installable
               Depends: libpcre3 (>= 8.10) but 7.8-3build1 is to be installed
               Recommends: r-recommended but it is not going to be installed
E: Broken packages

A: You can try the following commands.
sudo apt-get install -f
This would install any dependencies that your previous installs missed.
If that doesn't help, please refer to the following link:
https://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies

redpajama_set_name: RedPajamaStackExchange


text:
Q: Broadcom 4312 wireless issues
Possible Duplicate:
How to Install Broadcom / STA Wireless card (BCM43XX)

I know theres a plethora of other questions and some are "Solved" out there for this same issue but I've run through all that I can find to no avail.
I solved this problem once but then I went on to troubleshoot an injection issue fora nother program and I messed up the wireless so I reinstalled and now I can't get it working again!  On this reload of Ubuntu 11.10 ive already tried a couple things so ill post as much relevant info as I know.
I'm new to Linux entirely having only used it for about a week now.
LSPCI:
00:00.0 Host bridge: Intel Corporation Mobile 4 Series Chipset Memory Controller Hub (rev 07)
00:02.0 VGA compatible controller: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller (rev 07)
00:02.1 Display controller: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller (rev 07)
00:1a.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #4 (rev 03)
00:1a.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #5 (rev 03)
00:1a.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #6 (rev 03)
00:1a.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #2 (rev 03)
00:1b.0 Audio device: Intel Corporation 82801I (ICH9 Family) HD Audio Controller (rev 03)
00:1c.0 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 1 (rev 03)
00:1c.1 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 2 (rev 03)
00:1c.2 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 3 (rev 03)
00:1c.3 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 4 (rev 03)
00:1c.4 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 5 (rev 03)
00:1c.5 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 6 (rev 03)
00:1d.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #1 (rev 03)
00:1d.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #2 (rev 03)
00:1d.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #3 (rev 03)
00:1d.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #1 (rev 03)
00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev 93)
00:1f.0 ISA bridge: Intel Corporation ICH9M LPC Interface Controller (rev 03)
00:1f.2 SATA controller: Intel Corporation ICH9M/M-E SATA AHCI Controller (rev 03)
00:1f.3 SMBus: Intel Corporation 82801I (ICH9 Family) SMBus Controller (rev 03)
08:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 03)
0e:00.0 Network controller: Broadcom Corporation BCM4312 802.11b/g LP-PHY (rev 01)
1a:00.0 FireWire (IEEE 1394): O2 Micro, Inc. Device 10f7 (rev 01)
1a:00.1 SD Host controller: O2 Micro, Inc. Device 8120 (rev 01)
1a:00.2 Mass storage controller: O2 Micro, Inc. Device 8130 (rev 01)

iwconfig:
lo        no wireless extensions.

eth0      no wireless extensions.

eth2      IEEE 802.11  Access Point: Not-Associated
          Link Quality:5  Signal level:0  Noise level:0
          Rx invalid nwid:0  invalid crypt:0  invalid misc:0
ifconfig:
eth0      Link encap:Ethernet  HWaddr 00:24:e8:bb:67:b9
          inet addr:192.168.5.109  Bcast:192.168.5.255  Mask:255.255.255.0
          inet6 addr: fe80::224:e8ff:febb:67b9/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13807 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9503 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:15997294 (15.9 MB)  TX bytes:1087286 (1.0 MB)
          Interrupt:46 Base address:0xc000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:64 errors:0 dropped:0 overruns:0 frame:0
          TX packets:64 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:4672 (4.6 KB)  TX bytes:4672 (4.6 KB)

If any other information is needed please let me know. Again thank you for your time!
Additional information:
sudo ifconfig wlan0 up;iwconfig;
wlan0: ERROR while getting interface flags: No such device
lo        no wireless extensions.

eth0      no wireless extensions.

eth2      IEEE 802.11  Access Point: Not-Associated
          Link Quality:5  Signal level:0  Noise level:0
          Rx invalid nwid:0  invalid crypt:0  invalid misc:0

lspci -nnk | grep -i net -A2:

08:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller [10ec:8168] (rev 03)
    Subsystem: Dell Device [1028:02c0]
    Kernel driver in use: r8169
--
0e:00.0 Network controller [0280]: Broadcom Corporation BCM4312 802.11b/g LP-PHY [14e4:4315] (rev 01)
    Subsystem: Dell Wireless 1397 WLAN Mini-Card [1028:000c]
    Kernel driver in use: wl

rfkill list:
0: brcmwl-0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: dell-wifi: Wireless LAN
    Soft blocked: yes
    Hard blocked: yes

If I do put on the proprietary driver (which I've read in several forums to remove) it still doesn't let me use my wireless. As it currently stands I have it activated and I still have for my rfkill:
0: dell-wifi: Wireless LAN
Soft blocked: yes
Hard blocked: yes

1: brcmwl-0: Wireless LAN
Soft blocked: no
Hard blocked: no

I tried the solutions here and they did not work:

*

*Dell inspiron 1545 wired and wireless do not work
Additional Information: If you have the interface Eth2 or something similar and can't set your card to monitor mode then

*

*Open your package manager and search for bcm

*Uninstall that crap

*Make sure you have the firmware-b43-lpphy-installer and b43-fwcutter while youre  there.

*Type into terminal
 cat /etc/modprobe.d/* | egrep 'bcm'

and see if the term blacklist bcm43xx is there.

*If it is, type
cd /etc/modprobe.d/
sudo gedit blacklist.conf

put a # in front of the line: blacklist bcm43xx then save the file (you might get some funky messages saying that it isnt saving, it should be ok)

*Reboot

*You may have to re-apply the previous command:
sudo rmmod dell-laptop

I believe you have to blacklist wl as well as it wont let you get into monitor mode and you want it replaced by the kernel driver b43-pci-bridge as stated in the following code:
     lspci -nnk | grep -i net -a2
Subsystem: Dell Device [1028:02c0]
    Kernel modules: i2c-i801
08:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller [10ec:8168] (rev 03)
    Subsystem: Dell Device [1028:02c0]
    Kernel driver in use: r8169
    Kernel modules: r8169
0e:00.0 Network controller [0280]: Broadcom Corporation BCM4312 802.11b/g LP-PHY [14e4:4315] (rev 01)
    Subsystem: Dell Wireless 1397 WLAN Mini-Card [1028:000c]
    Kernel driver in use: b43-pci-bridge

A: I just figured this one out again. Now again >.< I'm now fairly certain as to what fixed this.
Actually there's still one step I question the relevance of, though I'm sure in the end it's worth doing regardless and that is to get all possible updates through your software manager.
Next if you don't already have Synaptic Package Manager get it. In Synaptic, make sure you have
bcm-kernel-source, b43-fwcutter, and depending on your chipset (in this case) firmware-b43-lpphy-installer.
Next you want to go to terminal and put in gksudo gedit /etc/modprobe.d/blacklist.conf and scroll right on down to
## # replaced by b43 and ssb.
##blacklist bcm43xx

So you can put a # right next to blacklist bcm43xx so you end up with:
## #blacklist bcm43xx

Go ahead and reboot to get all this loaded up. After the reboot you go to terminal and your rfkill list should produce Hard or soft blocked to some degree (both were blocked for me). To fix this type in:
#sudo -s
#rmmod dell-laptop

Putting yourself in sudo -s I've found makes root actions easier.
Rebooted this piece and stuff lit all up and wireless is blazing! I did notice that my proprietary driver that Linux wanted to install initially is activated.

A: That's the LP-PHY model like on my dell 1747, so you'll need the lp-phy b43 driver, which looks like you might have already.
Make sure you remove any b43 driver previously installed through 'additional drivers' or via apt.
sudo apt-get autoremove --purge b43-fwcutter
sudo apt-get install bcmwl-kernel-source
sudo modprobe wl
ifconfig eth2

If that doesn't work then purge that driver, sudo apt-get purge bcmwl-kernel-source.
Then install this one sudo apt-get install firmware-b43-lpphy-installer
Some say that one works for them where the bcmwl does not.

A: I think that the network card switches are inhibiting your connection.

*

*Make completely sure there is not a hardware switch keeping your network card off.

*Run sudo rfkill unblock wifi. This should remove every soft block related to your network card.
Please check this and report back. If this doesn't happen, perhaps your computer doesn't let both wireless virtual devices to be active at the same time.

*I recommend you to blacklist your dell_laptop module. This was giving me wireless connection problems once too.
sudo echo dell_laptop >> /etc/modprobe.d/blacklist-<username>.conf

*Make sure you only have one network card driver loaded at a time. The drivers that are used for your network card popularly are: wl, b43 and ssb. Find out how to do this in more detail at the bcm43xx article @ Ubuntu Community Documentation Wiki.

*

*Load drivers with sudo modprobe <driver>

*Unload drivers with sudo modprobe -r <driver>

*Check for a loaded driver with lsmod | grep <driver>

*Once you have a working configuration, be sure to add the working driver to the /etc/modules/ file:
sudo echo <driver> >> /etc/modules, where driver can be either of wl, b43 and ssb

*Blacklist the modules that didn't work:
sudo echo <driver> >> /etc/modprobe.d/blacklist-<username>.conf


text:
Q: How do I remove non-English words in R for most frequent words? I need help to remove non_English words.
I used the following codes but when I get to view the head and tail of the text, the tail has non-English words. That means the non-English words were not removed.
When I used this code,
for (i in seq(hotel2)) {
    hotel2[[i]] <- gsub('[^a-zA-Z|[:blank:]]', "", hotel2[[i]])
}

and run this code for frequent word
 hotel2<-as.matrix(TermDocumentMatrix(hotel2))
I got an error when I get to view the most frequent words using tdm

Error in UseMethod("meta", x) :    no applicable method for 'meta'
  applied to an object of class "character"

When I used this code:
removenonenglish <- gsub("[^\x20-\x7E]", "", hotel2)

hotel2 <- tm_map(hotel2, content_transformer(removenonenglish))

I got the error below it.

Error in FUN(content(x), ...) : could not find function "FUN"


text:
Q: Applying a Combination of Runge-Kutta and Midpoint Rule for this IVP For a time step $h=0.5$, how can we apply a $RK2-M$ method to solve the following IVP?
\begin{cases}
y^{\prime}(t)=-1.2 y(t)+7 e^{-0.3 t}=f(t, y(t)), \quad t \in[0,1.5] \\
y(0)=3
\end{cases}
Now the problem I am facing is in the transition of this IVP into the desired scheme. I know that $K_{1}=f(t_{i},y_{i})$ but I always get lost in computing $K_{2}$ and thus my computations are wrong. Any help is much appreciated.

A: You have
$$
K_2=f(t_i+h/2,y_i+hK_1/2)
$$
and then
$$
y_{i+1}=y_i+hK_2
$$
This should not be hard to implement.

A: As indicated by @Lutz Lehmann, the implementation is not hard at all (a matter of practicing), The full $RK2-M$ scheme is given by :
$$
\left\{\begin{array}{l}
K_{1}=f\left(t_{i}, y_{i}\right)=-1.2 y_{i}+7 e^{-0.3 t_{i}} \\
K_{2}=f\left(t_{i}+\frac{h}{2}, y_{i}+\frac{h}{2} K_{1}\right)=-1.2\left(y_{i}+\frac{h}{2} K_{1}\right)+7 e^{-0.3\left(t_{i}+\frac{h}{2}\right)} \\
y_{i+1}=y_{i}+h K_{2}
\end{array}\right.
$$
By proceeding with computing $K_{1}$, $K_{2}$, and $y_{i+1}$ for different time intervals, we are able to recursively obtain a solution for the IVP, I have constructed this table that shows the obtained values :
$$
\begin{array}{|c|c|c|c|c|c|}
\hline \mathrm{i} & t_{i} & y_{i} & K_{1}=-1.2 y_{i}+7 e^{-0.3 t_{i}} & K_{2}=-1.2\left(y_{i}+\frac{h}{2} K_{1}\right)+7 e^{-0.3\left(t_{i}+\frac{4}{2}\right)} & y_{i+1}=y_{i}+h K_{2} \\
\hline 0 & 0 & 3 & -1.2 * 3+7=3.4 & -1.2 *\left(3+\frac{3.4}{4}\right)+7 e^{-0.075} & 3+1.8742 * 0.5 \\
& & & & =1.8742 & =3.9371 \\
\hline 1 & \frac{1}{2} & 3.9371 & -1.2 * 3.9371+7 e^{-0.15} & -1.2\left(3.9371+\frac{1}{4} 1.3004\right)+7 e^{-0.3\left(\frac{4}{4}\right)} & 3.9371+0.47497 * 0.5 \\
& & & =1.3004 & =0.47497 & =4.1746 \\
\hline 2 & 1 & 4.1746 & -1.2 * 4.1746+7 e^{-0.3} & -1.2 *\left(4.1746+\frac{1}{4} 0.17621\right)+7 e^{-0.3\left(\frac{5}{4}\right)} & 4.1746-0.25136 * 0.5 \\
& & & =0.17621 & =-0.25136 & =4.0489 \\
\hline 3 & \frac{3}{2} & 4.0489 & \mathrm{x} & \mathrm{x} & \mathrm{x} \\
\hline
\end{array}
$$
The exact solution is hence :
$$
\boxed{y(t)=-\frac{43}{9}e^{-1.2t}+\frac{70}{9}e^{-0.3t}}
$$


text:
Q: Parent for a single (single.php) Is it posible to get the parent ID of an single page.... I mean not a Page I mean an is_single()... page.
I have a page witch contains some custom posts and when I click on one of these i came to the single page of these entree. I would like to get the permalink of the parent page, the page i come from.

A: For a hierarchical post type, you can use $post->post_parent and get_permalink(), perhaps like so:
<?php
global $post;
$parent_permalink = get_permalink( $post->post_parent );
?>
<a href="<?php echo $parent_permalink; ?>">Parent Post


text:
Q: making background inactive when a button is pressed When i click a user name on twitter background it becomes inactive and dark.just like that:

I want to make my website's background inactive when a button is pressed, how can i do that?
Note: and i want to now which solution should i use make a box appear/disappear middle of my site when a button is pressed?i am doig something like this.
//in css
.visible{
    display: inline;
}
.hidden {
    display: none;
}

//in jquery
$("#div1").click(function() {
    $('#div2').removeClass("visible").addClass("hidden");
}

A: This is called a lightbox.
First hit should make you happy: https://www.google.nl/search?q=lightbox

A: You are trying to build lightbox. Just show fullscreen div with semi-transparent background color for this.
Simple solution:
CSS:
.lightbox {
    display:none;
    position: absolute;
    z-index:10;
    background-color: rgba(255,255,255,0.7);
}

HTML:
Show lightbox

JQuery:
$("a").on("click",function(){
$(".lightbox").css({'width':$(document).width()+'px','height':$(document).height()+'px'});
$(".lightbox").show();
return false;

});


text:
Q: Crashlytics shows crash in _queueForDealloc: [NSManagedObject release] I've got some crashes in Crashlytics with this information, unfortunately I don't know what to do with it:

I have really no idea where to start, I don't get any other information... In an other thread I see something like [GAI threadMain:] but I don't think that that's an issue.
I'm using MagicalRecord for my CoreData stuff, don't know what else I could say to get any information...


text:
Q: Ruby preloading classes in initializer I have a highly modified Rails repository. None of the classes use ActiveRecord. I'm finding that I have to specify many file and gem requirements at the top of each class. I want to have the requirements for each class preloaded in an initializer rather than it being specified in the class. How do I do this? Is this a bad idea? Is it necessary?

A: There are several ways to do this.
The obvious one is to require a single file, and then inside that file have all of your requirements listed.
For example in list_of_requirements.rb you could have
require 'thin'
require 'x'
require 'y'

Then in your  class_that_requires_stuff.rb you could have
require 'list_of_requirements'

This way in your indvidual classes you only need one require statement and you don't need to require all these gems in every file. You also don't need an initializer.


text:
Q: How to query by age in Mongodb? If I have a dob (date of birth) field in MongoDB, how can I query all records where date of birth is less than 1/1/1990 (it's a string) or less than a certain age?

A: You can store your DOB dates in ISO format - yyyymmdd - as a simple number, i.e.
db.col.insert( { dob: 19910412 } )
db.col.insert( { dob: 19900708 } )
db.col.insert( { dob: 19880511 } )
db.col.insert( { dob: 19870225 } )

Then, to find all the dates before a particular date, do this:
db.col.find( { dob: { $lt: 19900101 } } )

Adding an index to this field will speed up these queries:
db.col.ensureIndex( { dob: 1 } )

A: Either store the data as Date() object or as string in ISO format. In both cases you can use the standard $gt or $lt operators.

A: I suggest storing a 'real' date object rather than a string. You may then use the usual comparison operators. If you cannot do that, an alternative would be storing an age integer. The latter is less useful as it must be updated every year but it's worth considering.
EDIT: An alternative that will allow you to work with your existing data would be to pass a match function to collection.find(). Obviously this has performance implications as the function must be evaluated for each object in the collection. See $where docs. For example...
var date =  function() {
    return new Date(this.dob) < new Date('1/1/1990');
}

db.mycollection.find(date);


text:
Q: SVG not displaying properly in Node.js Recently switched over from Django to Node.js and my svg html isn't loading properly, all other static files seem to be fine.
Here you can find my html:
<svg class="svg-features-top" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
   <path position="fixed" d="M55,0 L68,35 Q72,45 80,40 L100,30 100,0 Z" fill="#2b016d"/>
</svg>

background image in css that I'm trying to vector:
.section--intro{
    min-width:100%;
    height:100%;
    -webkit-background-size: 100%;
    -moz-background-size: 100%;
    -o-background-size: 100%;
    background-size: 100%;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    background-position:center bottom;
    background-image:url(images/bg.jpg);
    position:relative;
    overflow:hidden;
}

The background image isn't loading at all, and I would really appreciate any help I can get

A: Probably, you don't serve your static files (images in this case) properly with Node.js. When you are trying to get images for example like: /images/bg.jpg, here is what happening:

*

*Your browser makes a request to the server

*Your server (or web application) accepts the request and should explicitly know what to do with it. Otherwise, it returns 404.

If you are using Express as your Node.js framework, you can tell your Node.js to handle such requests very easily:
const path = require('path');
app.use('/images', express.static(path.join(__dirname, 'images')))

Also, you can check the docs here: https://expressjs.com/en/starter/static-files.html
After that, your Node.js app should be able to return image content for any /images/ requests. If you use a different framework for your app, it's not a problem, you just need to find the right hint in the docs, search by keywords like: static files or serve files
PS. SVG images content is not HTML, but XML


text:
Q: Let user view file only once with PHP Got a request that I'm not even sure is feasible:  The plan is to only allow users to see a PDF in their browser after they have filled out a form.
I can't think of a way to redirect to a PDF in browser in a way that makes it viewable only once.
The best thing I can think of is forcing a download of the PDF after they submit the form.

A: What do you mean by "only once" ?
You can redirect to the URL linking to that PDF once the form is completed.
Or, you can reload the page (or part of it) with an appropriate link to that PDF file.
To do things "once" you either recognize the user using PHP Sessions (but it's good only until the user closes the connection to your server) or you could persist the fact that the current user is not to receive the PDF again by writing a record in a database.

A: Actually, this is pretty easy:

*

*for each download you wish to allow, create a hash and store it in a table

*in download.php, evaluate that hash:

*

*if it's not there, return a 501 or 503

*if it's there, set your mime type to application/pdf and return the contents of the file


text:
Q: discrete values supplied to continuous scale I am plotting a linear mixed effects model using ggplot2 in R. I keep receiving this error with regards to including the mean rating per trial.

Error: Continuous value supplied to discrete scale

I have localized the problem to geom_point as geom_line and geom_ribbon work just fine. Here is the code I am currently using
p2 <- ggplot(td_mean_pref_plot_groups, aes(x, td_mean_pref_plot_groups$predicted, col = group)) +
      geom_line(size=1.5) +
      scale_color_manual(values = c("blue","red")) +
      geom_ribbon(aes(ymin=conf.low,ymax=conf.high, fill=group),alpha=.2,colour=NA) +
      scale_fill_manual(values = c("blue","red")) +
      geom_point(data=summStats_td_mean,aes(trial,mean, col = condition),size=2) +
      scale_color_manual(values = c("blue","red")) +
      theme_bw() +
      xlab('Trial') +
      ylab('Prediction Error') +
      ylim(1,2.2) +
      ggtitle('TD learning about TD vs. TD \n learning about ASD') +
      theme(text=element_text(size=20),
        plot.title = element_text(hjust = 0.5),
        panel.border = element_blank())
p2

geom_point reads the data below
structure(list(condition = c(1L, 1L, 1L, 1L, 1L, 1L), trial = 1:6,
    n = c(80L, 93L, 92L, 94L, 94L, 94L), mean = c(1.225, 1.39784946236559,
    1.25, 1.40425531914894, 1.24468085106383, 1.29787234042553
    ), sd = c(1.01849976541573, 1.08487411558084, 1.00137268424261,
    1.11025666834073, 1.00199983058361, 1.09573746202196)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
    condition = 1L, .rows = structure(list(1:6), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L), .drop = TRUE))

As you can see, the options for condition for condition are 1 or 2 but R seems to be reading those as continuous. I have used this code many times before and never run into this issue so I'm not sure why it's suddenly acting up. Thank you!

A: As mentioned in the comment the condition in your data is an integer therefore the scale in continuous, you can easily change this by calling as.factor() on your condition:
library(ggplot2)
p1 = ggplot()+
  geom_point(data= df, aes(trial, mean, col = condition))+
  labs(subtitle = "Continuous scale")

p2 = ggplot()+
  geom_point(data= df, aes(trial, mean, col = as.factor(condition)))+
  scale_color_manual(values = c("blue","red"))+
  labs(subtitle = "Discrete scale")

library(ggpubr)
ggarrange(p1,p2)


text:
Q: Can Ubuntu use a flash drive to increase performance like ReadyBoost?
Possible Duplicate:
Is there any way that an external hard drive can be used to boost performance?

This might be a silly question but is there any way to use a flash drive to optimize the memory on lubuntu 12.04? Kinda like how you can in win7?

A: To answer your question, No.  ReadyBoost is a disk cache component of Windows, works by using flash memory, a USB flash drive, as cache, NOT as swap.  Plus too much I/O operations in a flash drive can damage it in a long run.
Nowadays RAM is cheap, so you'd better off using RAM, since USB is slower than RAM.  Or you can use SSD.


text:
Q: String split on specific characters I have a string like;
'[abc] [def] [zzz]'

How would I be able to split it into three parts:
abc
def
zzz

A: You can use re.findall:
>>> from re import findall
>>> findall('\[([^\]]*)\]', '[abc] [def] [zzz]')
['abc', 'def', 'zzz']
>>>

All of the Regex syntax used above is explained in the link, but here is a quick breakdown:
\[      # [
(       # The start of a capture group
[^\]]*  # Zero or more characters that are not ]
)       # The end of the capture group
\]      # ]

For those who want a non-Regex solution, you could always use a list comprehension and str.split:
>>> [x[1:-1] for x in '[abc] [def] [zzz]'.split()]
['abc', 'def', 'zzz']
>>>

[1:-1] strips off the square brackets on each end of x.

A: Another way:
s = '[abc] [def] [zzz]'
s = [i.strip('[]') for i in s.split()]


text:
Q: Apache reverse proxy converting json to html I will be amazed if anyone can answer this as I have found a few questions with no conclusive answers for the same but its worth a try.
I have an IBM IHS server fronting a websphere commerce 6 environment. In front of this on a separate server I have an Apache instance which is reverse proxying the requests to the Websphere box.
The reason for this is to manage certs etc..
Anyway the problem is that response from IHS in JSON are being converted by Apache to HTML. Subsequently the code cannot parse the data.
The 443 virtual host proxy is as per the below:
ProxyHTMLStripComments off
ProxyHTMLFixups reset
ProxyHTMLEnable on
ProxyRequests off
SetOutputFilter INFLATE;proxy-html;DEFLATE
ProxyHTMLDoctype XHTML
SSLEngine on
SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
ProxyRequests off
ProxyPreserveHost On
<proxy *>
    Order deny,allow
    Allow from all
</proxy>
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

ProxyPass / https://xx.xx.xx.xx/ retry=1 acquire=3000 timeout=600 Keepalive=On
ProxyPassReverse / https://xx.xx.xx.xx/
ProxyPassReverseCookiePath / https://xx.xx.xx.xx/

This works absolutely fine however for responses from the websphere server coming back as JSON they are being surrounded by HTML tags - html, body and p. I need to stop this - any ideas!? Will be forever in your debt!

A: just in case anyone else has this after messing about with several options for several days, my latest combination seems to have worked.
Disabling the "ProxyRequests off" directive seems to resolve it.
Time for a beer! Thanks for people who offered tips!


text:
Q: Power Auatomate/Flow - Attach a Flow to a SharePoint List/Library to trigger or create/update I would like to create a new Flow that should trigger on SharePoint item/document create/edit event.
This flow will be a common flow for many SharePoint sites and I would like to programmatically attach these flows to the required lists/libraries across many SharePoint sites.
Is this possible?
How do I go about creating a common flow to be used across multiple SharePoint sites? and can I use CSOM, Rest API, Powershell to attach the flow to the libraries/lists on those sites?

A: Flow trigger based on site address, so you can't create a common flow to be used across multiple SharePoint sites.
Reference:
https://powerusers.microsoft.com/t5/General-Power-Automate/One-Flow-Multiple-Sites/td-p/402223


text:
Q: Пропадает интернет на сервере При завершении соединения с удаленным столом на windows 10, на нем как будто пропадает интернет? Почему думаю, что не работает интернет: скрипт который должен работать с сайтами не срабатывает, если я не подключен к серверу (в открывшемся браузере ошибка "Опаньки..." как обычно бывает при отсутствии интернета), если подключен, то все ок. С teamviewer такая же проблема, если не подключен, то ошибка "у вашего партнера нет доступа к интернету" Подскажите в чем может быть проблема, в каком направлении копать?

A: Попробуйте отключиться от сервера с помощью создания файла .bat и запуска от имени администратора следующего скрипта:
for /f "tokens=4 delims= " %%G in ('tasklist /FI "IMAGENAME eq tasklist.exe" /NH') do SET RDP_SESSION=%%G
tscon %RDP_SESSION% /dest:console
exit

После выполнения скрипта вас выкинет с RDP

A: "Опаньки..." это не отсутствие интернета, а сбой при нехватке ОЗУ, либо же потеря дисплея при отключении от рдп. К примеру в консоли линукса с помощью Xvfb можно сделать виртуальный дисплей, либо запускать браузер с аргументом --headless.


text:
Q: Not able to access the ID while deleting the row from GridView I am using a Gridview containing an ID. I want to write a Row_deleting event in which I access the ID from my .aspx page, but I am not getting it.
How can I do that?
Here is my Gridview Code
<asp:LinkButton ID="lnkDelete"
    runat="server" CssClass="gridLink"
    CommandArgument='<%# Eval("Serial_key") %>'
    CommandName="Delete">
    <b>Delete</b>
</asp:LinkButton>

A: first in your gridview set AutoGenerateDeletebutton=true then use this link
How to use the GridView AutoGenerateDeletebutton
protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)
{

var PN = GridView1.DataKeys[e.RowIndex].Values["Part_Number"];// this is how you get the right row to delete e.rowindex is used to do this
string PN = pn.ToString;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
con.Open();
string str = "DELETE * FROM XML WHERE ([Part_Numbber] = " + PN + ")";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Button1_Click(sender, e);
con.Close();
}

A: For Deleting any record from your database you need unique or Primary key column. If you want to delete record using column "Serial_key" . Then  put the following code to Delete.
<ItemTemplate>
<asp:Label ID="lblSerial_key" runat="server" Text='<%# Eval("Serial_key") %>'></asp:Label>
<asp:Button ID="deleteButton" runat="server" CommandName="Delete" Text="Delete"  /></ItemTemplate>

Now you can use the lblSerial_key to delete a row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string Serial_key = string.Empty;
        Label lblId = (Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblSerial_key");
        Serial_key = lblId.Text.ToString();
        string selectSQL = "delete from tablename where id='" + Serial_key + "'";

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        // Create the command object
        con.Open();
        SqlCommand cmd = new SqlCommand(selectSQL , con);
        cmd.ExecuteNonQuery();
        con.Close();
    }


text:
Q: How to make my carousel active for each item?
I want to make one image active each when it is selected, but right now all items are active
<?php foreach($project_images as $image) {?>

    <?php
        if($image['project_image_name'] != '') {
            $images = '';
        } else {
            $images = '

        <?php echo $images; ?>

<?php }?>

A: This sounds like a job for JavaScript, not PHP.
I'm assuming PHP doesn't know if the image is active or not, it just displays the image.
I'm assuming you want the image to be active when it's clicked.  That's JavaScript.
Step 1: Don't make anything active.
Remove 'active' from the div.

    <?php echo $images; ?>

Step 2: Give each div a unique identifier so JavaScript knows what element you're referring to.
<?php
   $id = 0;
   foreach($project_images as $image) {
     $id++;
 ?>

    <?php
         // .. code is the same
    ?>

    <div id="carousel_<?php echo $id ?>" class="carousel-item">
        <?php echo $images; ?>

<?php }?>

That should give each div a unique id.
Step 3: Create a JavaScript function that will toggle the 'active' class of the selected item.
Ex:
function ToggleClass(elemID){
  // Get selected element
  selElement = document.getElementById(elemID);

   //Use selElement to change class.  Code goes here
}

Step 4: Add the JavaScript function to the div.
Note the quotes -- use the double and singles as needed.
Ex:
<div id="carousel_<?php echo $id ?>" class="carousel-item active" onclick="ToggleClass('carousel_<?php echo $id ?>')">
      <?php echo $images; ?>


text:
Q: How to extract functions used in a python code file? I would like to create a list of all the functions used in a code file. For example if we have following code in a file named 'add_random.py'
`
import numpy as np
from numpy import linalg

def foo():
    print np.random.rand(4) + np.random.randn(4)
    print linalg.norm(np.random.rand(4))

`
I would like to extract the following list:

    [numpy.random.rand, np.random.randn, np.linalg.norm, np.random.rand]

The list contains the functions used in the code with their actual name in the form of 'module.submodule.function'. Is there something built in python language that can help me do this?

A: You can extract all call expressions with:
import ast

class CallCollector(ast.NodeVisitor):
    def __init__(self):
        self.calls = []
        self.current = None

    def visit_Call(self, node):
        # new call, trace the function expression
        self.current = ''
        self.visit(node.func)
        self.calls.append(self.current)
        self.current = None

    def generic_visit(self, node):
        if self.current is not None:
            print "warning: {} node in function expression not supported".format(
                node.__class__.__name__)
        super(CallCollector, self).generic_visit(node)

    # record the func expression
    def visit_Name(self, node):
        if self.current is None:
            return
        self.current += node.id

    def visit_Attribute(self, node):
        if self.current is None:
            self.generic_visit(node)
        self.visit(node.value)
        self.current += '.' + node.attr

Use this with a ast parse tree:
tree = ast.parse(yoursource)
cc = CallCollector()
cc.visit(tree)
print cc.calls

Demo:
>>> tree = ast.parse('''\
... def foo():
...     print np.random.rand(4) + np.random.randn(4)
...     print linalg.norm(np.random.rand(4))
... ''')
>>> cc = CallCollector()
>>> cc.visit(tree)
>>> cc.calls
['np.random.rand', 'np.random.randn', 'linalg.norm']

The above walker only handles names and attributes; if you need more complex expression support, you'll have to extend this.
Note that collecting names like this is not a trivial task. Any indirection would not be handled. You could build a dictionary in your code of functions to call and dynamically swap out function objects, and static analysis like the above won't be able to track it.

A: In general, this problem is undecidable, consider for example getattribute(random, "random")().
If you want static analysis, the best there is now is jedi
If you accept dynamic solutions, then cover coverage is your best friend. It will show all used functions, rather than only directly referenced though.
Finally you can always roll your own dynamic instrumentation along the lines of:
import random
import logging

class Proxy(object):
    def __getattr__(self, name):
        logging.debug("tried to use random.%s", name)
        return getattribute(_random, name)

_random = random
random = Proxy()


text:
Q: Django: within html reference foreign key from user models.py:
class Banking(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    available_credits = models.PositiveIntegerField()

base.html:
{{ user.banking.available_credits }}

Can I use the user object to reference the available_credits in the banking table?
I'm using this base.html as a template which all other templates extend and ideally don't want to pass the specific instance in. I was hoping there was a way to reference it in a similar way to
{{ user.username }}

A: You can do this with functions and then pass it to the template
 get_available_credits = Banking.objects.filter(user = request.user)

A: It seems to me, that if each user must only have one banking, one should use  OneToOneField instead of ForeignKey. This way, user.banking.something will work. However, note, that it is still possible that User won't have a banking, and a Banking.DoesNotExist will be raised when accessing user.banking.


text:
Q: How to merge multiple data frames into panel data frame? I can't imagine this question wasn't asked before, but I spend 2 hours of searching and didn't found anything.
Let's suppose I have 5 separate data frames that contains the same four variables for different years. There is one common variable called 'ID' in each data frame. All data frames are already in the long format (so the observations are listed underneath each other) for further analysis.
Each data frame consists of a various amount of observations, so not all IDs are included in every data frame. The aim is to merge these data frames into panel data. Thereby, only complete cases should be considered. If one ID is missing for one year, it should be dropped out.
Here is some example code for better understanding:
#2010
df1=data.frame(ID=c(111,112,113,114),"year"=c(2010, 2010, 2010, 2010),"income"=c(3800, 2200, 1500, 2700),"state"=c("NI", "SH", "BY", "NI"))
df1

ID year income state
1 111 2010   3800    NI
2 112 2010   2200    SH
3 113 2010   1500    BY
4 114 2010   2700    NI

#2011
df2=data.frame(ID=c(112,113,114,115,116),"year"=c(2011, 2011, 2011, 2011, 2011),"income"=c(2300,1500,2500,4200,6000),"state"=c("BY", "BY", "SH", "BY", "HH"))
df2

  ID year income state
1 112 2011   2300    BY
2 113 2011   1500    BY
3 114 2011   2500    SH
4 115 2011   4200    BY
5 116 2011   6000    HH

#2012
df3=data.frame(ID=c(109,112,113,114),"year"=c(2012,2012,2012,2012),"income"=c(1200,2500,1500,3000),"state"=c("BW", "BY", "NI", "SH"))
df3

   ID year income state
1 109 2012   1200    BW
2 112 2012   2500    BY
3 113 2012   1500    NI
4 114 2012   3000    SH

#Desired result
df_final=data.frame(ID=c(112,112,112,113,113,113,114,114,114),"year"=c(2010,2011,2012,2010,2011,2012,2010,2011,2012),"income"=c(2200,2300,2500,1500,1500,1500,2700,2500,300),"state"=c("SH", "BY", "BY", "BY", "BY", "NI", "NI", "SH", "SH"))
df_final

 ID year income state
1 112 2010   2200    SH
2 112 2011   2300    BY
3 112 2012   2500    BY
4 113 2010   1500    BY
5 113 2011   1500    BY
6 113 2012   1500    NI
7 114 2010   2700    NI
8 114 2011   2500    SH
9 114 2012    300    SH

I found a similar question where the panel data function from the reshape2 package was recommended. Although it worked fine, unfortunately it did not exclude cases.
Does anybody know a solution?
I appreciate any kind of help.
Thanks in advance!

A: We can get the datasets in a list, find the common ids with intersect, subset the list elements and rbind in base R
lst1 <- list(df1, df2, df3)
commonIds <- Reduce(intersect, lapply(lst1, `[[`, "ID"))
out <- do.call(rbind, lapply(lst1, subset, subset = ID %in% commonIds))
out <- out[order(out$ID),]
row.names(out) <- NULL

-output
> out
   ID year income state
1 112 2010   2200    SH
2 112 2011   2300    BY
3 112 2012   2500    BY
4 113 2010   1500    BY
5 113 2011   1500    BY
6 113 2012   1500    NI
7 114 2010   2700    NI
8 114 2011   2500    SH
9 114 2012   3000    SH


text:
Q: Why isn't G++ compiler treating these two functions the same way? I have an array A with zeros and ones. I want to find the sum of all numbers in A. I want to test two functions:
First function
void test1(int curIndex){
    if(curIndex == size) return;
    test1(curIndex+1);
    s+=A[curIndex];
}

Second function
void test2(int curIndex){
    if(curIndex == size) return;
    s+=A[curIndex];
    test2(curIndex+1);
}

I used the PAPI library to count the number of instructions, here is the entire experiment:
#include <iostream>
#include <fstream>
#include "Statistics.h"

using namespace std;

int size;
int *A;
int s;

void test3(int curIndex){
    if(curIndex == size) return;
    test3(curIndex+1);
    s+=A[curIndex];
}

int main(int argc, char* argv[]){

    size = atoi(argv[1]);
    if(argc!=2){
        cout<<"type ./executable size{odd integer}"<<endl;
        return 1;
    }
    if(size%2!=1){
        cout<<"size must be an odd number"<<endl;
        return 1;
    }
    A = new int[size];
    int i;
    for(i=0;i<size;i++){
        if(i%2==0){
            A[i] = false;
        }
        else{
            A[i] = true;
        }
    }

    Statistics stat(1);
    stat.start();
    test3(0);
    stat.stop();
    stat.printWithHelp();
    cout<<s<<endl;

    return 0;
}

Here is the Statistics.h file:
#ifndef TRIPLETPARSER_STATISTICS_H
#define TRIPLETPARSER_STATISTICS_H

#include <time.h>
#include <unistd.h>
#include <fstream>
#include <papi.h>
#include <iostream>
#include <iostream>

#define BILLION  1000000000LL

using namespace std;

class Statistics {

private:
    timespec s, e;
    /*
    PAPI_BR_CN  Conditional branch instructions
    PAPI_BR_INS     Branch instructions
    PAPI_BR_MSP     Conditional branch instructions mispredicted
    PAPI_BR_NTK     Conditional branch instructions not taken
    PAPI_BR_PRC     Conditional branch instructions correctly predicted
    PAPI_BR_TKN     Conditional branch instructions taken
    PAPI_BR_UCN     Unconditional branch instructions
    PAPI_BRU_IDL    Cycles branch units are idle
    PAPI_BTAC_M     Branch target address cache misses

    PAPI_TLB_DM     Data translation lookaside buffer misses
    */
    int events[10];  // , PAPI_L2_TCA,PAPI_L3_TCM,PAPI_L3_TCA PAPI_BR_CN, PAPI_BR_PRC}; //type of events we are interested in
    int num_hwcntrs;  //total amount of events stored in 'events' array
    long long values[10];
    long long counters[10];

    void handle_error(int err){
        std::cerr << "PAPI error: " << err << std::endl;
    }

public:
    Statistics(int papi){
        for(size_t i = 0; i< 10; i++)
            counters[i]=0.0;

        switch(papi){
            case 0:
                num_hwcntrs = 0;
                break;
            case 1:
                num_hwcntrs = 6;
                events[0] = PAPI_L2_TCA;
                events[1] = PAPI_L3_TCA;
                events[2] = PAPI_L3_TCM;
                events[3] = PAPI_TOT_INS;
                events[4] = PAPI_BR_INS;
                events[5] = PAPI_BR_MSP;
                break;
        }

    }

    void start(){

        for(size_t i = 0; i< 10; i++)
            counters[i]=0.0;

        if (num_hwcntrs != 0 && PAPI_start_counters(events, num_hwcntrs) != PAPI_OK)
            handle_error(1);
    }

    void start(float ratio){

        if (num_hwcntrs != 0 && PAPI_start_counters(events, num_hwcntrs) != PAPI_OK)
            handle_error(1);
    }

    void stop(){
        if (num_hwcntrs != 0 && PAPI_stop_counters(values, num_hwcntrs) != PAPI_OK)
            handle_error(1);
        update();
    }

    void stop(float ratio){
        if (num_hwcntrs != 0 && PAPI_stop_counters(values, num_hwcntrs) != PAPI_OK)
            handle_error(1);
        update();
    }

    void update(){
        for(size_t i = 0; i < num_hwcntrs; i++)
            counters[i] += values[i];
    }

    void print(){
        for(int i=0;i<num_hwcntrs;i++)
            std::cout << counters[i] << "\t";
        //cout<<"L2 cache miss ratio: "<<counters[1]/(double)counters[0]<<endl;
        //cout<<"L3 cache miss ratio: "<<counters[3]/(double)counters[2]<<endl;
    }

    void printWithHelp(){
        cout<<"L2 accesses: "<<counters[0]<<endl;
        cout<<"L2 miss/access ratio: "<<(double)counters[1]/counters[0]<<endl;
        cout<<"L3 accesses: "<<counters[1]<<endl;
        cout<<"L3 misses: "<<counters[2]<<endl;
        cout<<"L3 miss/access ratio: "<<(double)counters[2]/counters[1]<<endl;
        cout<<"Instructions: "<<counters[3]<<endl;
        cout<<"Branches: "<<counters[4]<<endl;
        cout<<"Branch mispredictions: "<<counters[5]<<endl;
        cout<<"Branch miss/predict ratio: "<<(double)counters[5]/counters[4]<<endl;
    }

    void print(float avg_ratio){
        for (int i = 0; i<num_hwcntrs; i++)
            std::cout << (double)(avg_ratio*counters[i]) << "\t";
    }

};

#endif //TRIPLETPARSER_STATISTICS_H

This is the output that I get from the first function when the size of A is 111,111
L2 accesses: 24126
L2 miss/access ratio: 0.131559
L3 accesses: 3174
L3 misses: 587
L3 miss/access ratio: 0.18494
Instructions: 1022776
Branches: 178113
Branch mispredictions: 6976
Branch miss/predict ratio: 0.0391661

This is the output that I get from the second function when the size of A is 111,111
L2 accesses: 7090
L2 miss/access ratio: 0.163752
L3 accesses: 1161
L3 misses: 507
L3 miss/access ratio: 0.436693
Instructions: 555860
Branches: 111189
Branch mispredictions: 25
Branch miss/predict ratio: 0.000224842

Why the difference in the results? The instructions reduce by half, the branch mispredictions are almost eliminated. What is happening here?

A: Your second function is tail-recursive. That means the compiler can optimize it to something like:
void test2(int curIndex){
  while(true)
  {
    if(curIndex == size) return;
    s+=A[curIndex];
    curIndex = curIndex + 1;
  }
}

That reduces the number of instructions significantly. It also reduces the number of stack frames needed to (at most) one. As a result, it uses a lot less memory, which results in the reduction of cache misses.
The compiler is not able to make this optimization for the first function.
UPDATE:
Some people have asked why the compiler cannot make that optimization on the first function.
Let's start by observing the function is not tail-recursive. A function is tail recursive if the very last thing that happens is a recursive call to the same function, followed by returning the result of that recursive call (if any).
Clearly, that is not the case for the first function, s+=A[curIndex]; is executed after the recursive call.
So then people have asked why the compiler cannot turn the first function into the second one.
The question is "why does G++ not have this feature?" The answer to that question is always the same. Features are unimplemented by default; G++ does not have that feature because no one designed, implemented and shipped the feature to customers.
That should be the end of it, but of course people will want to know why nobody designed, implemented and tested this feature. Well, maybe nobody thought of doing it. But more importantly, the feature would be far from trivial.
First of all, the compiler would have to understand that
test1(curIndex+1);
s+=A[curIndex];

and
s+=A[curIndex];
test1(curIndex+1);

are equivalent. That is a non trivial observation, given that from a mechanical point of view they are not equivalent! Indeed, the first one effectively loops from the end of the array to the start, whereas the second one loops from the start to the end. Is that the same? It yields the same result when A is an int* (and s in an int), but it doesn't in other cases (e.g. when A is a double* and s is a double). Do we expect a compiler to be that smart?
So here we have a potential feature with a high cost to implement. But the cost may be worth it, if the benefit is high. Is the benefit high? I would guess that this happens very little in real code, i.e. developers are likely to write the second form anyway. So there you have it: an expensive feature with little benefit. IMHO, compiler developers are wise to spend their valuable time on more useful features.


text:
Q: How to set onClick event in ASP Menu MenuItem I have a dynamically generated menu (C#), like this:
MenuItem(string text, string value, string imageUrl, string navigateUrl, string target)

MenuItem AdminLevel1 = new MenuItem("Admin", "Admin");
MenuItem AdminPedidosRegisto = new MenuItem("Questions", "AdminQ");

NavigationMenu.Items.Add(new MenuItem("Messages Received", "AdminMessagesR", "", "./Admin/Messages.ascx", "ContainerIframe"));

AdminPedidosRegisto.ChildItems.Add(new MenuItem("Pending", "AdminPending", "", "./Admin/Pedidos.ascx", "ContainerIframe"));`

Where ContainerIframe is the iframe's ID and NavigationMenu is the (asp:Menu)'s ID.
I want to set some JavaScript to be executed when I click a MenuItem.
Is there a way?

A: Try putting the following code inside head tag of your .aspx page:
   <script type="text/javascript"> window.onload = function(){

    var menuTable = document.getElementById("<%=Menu1.ClientID%>");  //specify your menu id instead of Menu1 var menuLinks = menuTable.getElementsByTagName("a");
        for(i=0;i<menuLinks.length;i++)
        {
            menuLinks[i].onclick = function(){return confirm("u sure to postback?");}
        }
        setOnClickForNextLevelMenuItems(menuTable.nextSibling); } function setOnClickForNextLevelMenuItems(currentMenuItemsContainer){

        var id = currentMenuItemsContainer.id;
        var len = id.length;
        if(id != null && typeof(id) != "undefined" && id.substring(0,4) == "Menu" && id.substring(parseInt(len)-5,parseInt(len)) == "Items")
        {
            var subMenuLinks = currentMenuItemsContainer.getElementsByTagName("a");
            for(i=0;i<subMenuLinks.length;i++)
            {
                subMenuLinks[i].onclick = function(){return confirm("u sure to postback?");}
            }
            setOnClickForNextLevelMenuItems(currentMenuItemsContainer.nextSibling);
        } } </script>

Note that  you do not need to write any code in code behind file for this solution to work. I've tested the code in IE7 & FF2.0
Hope it works for you.
cheers!!

A: AdminLevel1.NavigateUrl = "javascript:callSomeFunction();";

A: Thanks to @Manibhadra (this is enough for parent items and child items)
window.onload = function ()
{
    var menuTable = document.getElementById("<%=NavigationMenu.ClientID%>");
    var menuLinks = menuTable.getElementsByTagName("a");
    for (i = 0; i < menuLinks.length; i++)
    {
        menuLinks[i].onclick = function () { setInnerHTML('ContainerTittle', this.innerHTML); }
    }
}

A: Hahns answer seems to make all items the same.
I use the following:

*

*Make the menu item non-selectable so it wont postback

*Add the following code where appropriate:

Page.ClientScript.RegisterStartupScript(typeof(Page), "123", string.Format("$('#MenuDiv').find('a').filter(':contains(\"{0}\")').css('cursor', 'pointer').click(function(){{ {1} }});", Title, Script), true);

Where:
"123" is a unique key for your script
MenuDiv is your menu client id
Title is the text you assigned to the menu item
Script is the javascript you want to run.


text:
Q: Time Complexity of three nested for loops There are three nested for loops, and I can find complexity if the loop increment by 1 but if the loop increment like this i+=c, I got confused?
    for (int i = 0; i < n; i+=c)
        for (int j = 0; j < i; j++)
             for (int k=0; k < m; k++)
                 result[i,j]= x[j]-y[k]

The complexity of the third for loop is m but for the first for loop I think is n/c and for the second for loop is n ==> multiply ranges together: n/c * n * m = n^2/c * m ==> the worst case is O(n^2). is this correct?
How to find the total number of iterations using the sum form?

A: The time complexity depends on two parameters in your case: m and n as the middle loop can be expressed as a function of the first.
If you consider the total number of iterations they are of the order of:
1/2 * m * n * (n-1) = O(mn^2)

The left part assumes c=1. However, given c as a constant the overall time complexity would not change.
If c is not given as a constant the resulting time complexity would be O(mn^2)/c


text:
Q: 401 (Unauthorized) while fetching user using laravel Sanctum with api token authentication I watched this tutorial for api token authentication with laravel sanctum. When logging in, I retrieve a Bearer token which I add to the axios header. But when trying to fetch the user via /api/user, I get a 401. Notice that I don't use CSRF tokens since I'm using Sanctum Api Token Authentication and not SPA authentication.
I have an api file for all axios requests that looks like
let axiosInstance = axios.create({
  baseURL: 'http://some-url.local/api',
})

let api = function () {
  let token = localStorage.getItem('token');
  if (token) {
    axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }
  return axiosInstance;
}

export { api }

Some auth functions
import {
  api
} from 'boot/axios'

export default {
  register(form){
    return api().post('/register', form)
  },
  login(form) {
    return api().post('/login', form)
  },
  logout(){
    return api().post('/logout')
  },
  auth(){
    return api().get('/user')
  }
}

LoginController
class LoginController extends Controller{
  public function login(Request $request){
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required',
        'deviceName' => 'required'
    ]);

    $user = User::where('email', $request->email)->first();

    if (!$user || !Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }
    return $user->createToken($request->deviceName)->plainTextToken;
  }

  public function logout(Request $request)
  {
    $request->user()->tokens()->delete();

    return response()->json('logout successful', 201);
  }
}

Route in routes/api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
  return $request->user();
});

I use HasApiTokens in my User Model, have 'prefix' => 'api' in config/sanctum.php, 'paths' => ['api/*'] in config/cors.php and have 'api' => ['driver' => 'sanctum',...] in my config/auth.php
I watched that tutorial twice and copied everything exactly the same (except that I'm using Quasar framework), searched all over google and stackoverflow... I don't understand, please help! I do recieve a Bearer token, so the app thinks I'm logged in, but can't fetch my user data. In part 1 of the tutorial mentioned above, the same is done, but with SPA authentication (csrf) and this one did work!
UPDATE
It seems it works with php artisan serve on http://127.0.0.1:8000/, but not with MAMP serving on http://some-domain.local or on a public domain
Why...

A: SOLVED!
For anyone else with this problem:
It seemed that my Bearer token was removed from the request on the laravel endpoint for some reason (I still don't know why).
Adding a custom header (X-Authorization) to axios and resolving server side with a middleware fixed it! More info here


text:
Q: How can I loop through multiple files and process them using SSIS package? We have a situation where we are importing a number of files with the same format, using the same SSIS package.  The package is being loaded and executed from a .net assembly.  Currently the package is being reloaded for each file.
I would like to load the package once during the initialisation of the .net process, and then execute it for each file, to save the overhead of re-loading the package for each file.  Is this a safe process to follow?

A: I understand that you have found the answer to your question by using Foreach Loop Container. I think that is the best approach in my opinion if the files are of the same format. I am posting the following example so other users can find it useful.
One possible way of achieving this is by using ForEach Loop container in the Control Flow tab and then placing a Data Flow task within the Control Flow task. I have explained the process in the below example. This example uses SQL Server back-end as the destination and Excel 97-2003 format .xls as the source files. Please note that the Excel files should be of same format.
Step-by-step process:

*

*Create a table named dbo.Location as shown in screenshot #1. This example will populate this table by reading three different Excel files having the same layout. The screenshot shows an empty table before the package execution.

*Create two Excel files in path c:\temp\ as shown in screenshots #2 - #4. Notice that both the Excel files have the same layout but different content.

*On the SSIS package, create three variables as shown in screenshot #5. Variable FolderPath will contain the path where the Excel files are located; FileExtension will contain the Excel file extension (here in this case it is *.xls) and FilePath should be configured to point to one valid Excel file (this is required only during the initial configuration of the Excel connection manager).

*Create an Excel connection in the connection manager pointing to one valid Excel file as shown in screenshot #6.

*Create an OLE DB Connection in the connection manager pointing to the SQL Server.

*On the SSIS package, place a ForEach Loop container and a Data Flow task within the ForEach loop container as shown in screenshot #7.

*Configure ForEach loop container as shown in screenshots #8 and #9. By doing this, variable User::FilePath will contain the full path Excel files located in the folder c:\temp\ with the help of variables FolderPath and FileExtension configured on the Collection section.

*Inside the data flow task, place an Excel source to read Excel file data and OLE DB destination to insert data into SQL Server table dbo.Location. Data flow task should look like as shown in screenshot #10.

*Configure the Excel source as shown in screenshots #11 and #12 to read the data using Excel connection.

*Configure the OLE DB destination as shown in screenshots #13 and #14 to insert the data into SQL Server database table.

*On the Excel connection in the connection manager, configure the Expressions ExcelFilePath and ServerName as shown in screenshot #15.

*Sample execution of the data flow task is shown in screenshot #16.

*Screenshot #17 displays the data in the table dbo.Location after package execution. Please note that it contains all the rows present in Excel files shown in screenshots #3 and #4.

*On the Data Flow task properties, Set the DelayValidation to True so that the SSIS doesn't throw errors when you open the package.
Hope that helps.
Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Screenshot #6:

Screenshot #7:

Screenshot #8:

Screenshot #9:

Screenshot #10:

Screenshot #11:

Screenshot #12:

Screenshot #13:

Screenshot #14:

Screenshot #15:

Screenshot #16:

Screenshot #17:

Screenshot #18:

A: In the end, I used a foreach loop in the package to process each file in term.  This was very fast!  I still have a lot to learn about SSIS!

A: It seems like it would be safe to me.  But I would run some controlled tests on the process, perhaps with a very simple SSIS package first, then your more complex one.
I can't say that I have done this exact scenario myself.


text:
Q: Let $f$ be holomorphic on $\mathbb{D}=\{z\in\mathbb{C} | |z|\leq 1\}$. Prove the following. I'm doing this exercise:

Let $f$ be holomorphic on $\mathbb{D}=\{z\in\mathbb{C} | |z|\leq 1\}$. Prove that:
a) $\frac{1}{2\pi i}\cdot \displaystyle\int_{|z|=1}{\frac{\bar{f}(z)}{z-a}dz}=\bar{f}(0)\ $ if $|a|<1$
b)  $\frac{1}{2\pi i}\cdot \displaystyle\int_{|z|=1}{\frac{\bar{f}(z)}{z-a}dz}=\bar{f}(0)-\bar{f}(1/\bar{a})\ $ if $|a|>1$

I know that if we call $\gamma=\partial D(0,1)$ the unit disk boundary, we have:
$$ \frac{1}{2\pi i}\cdot \int_{\gamma}{\frac{\bar{f}(z)}{z-a}dz}=\bar{f}(a)Ind(\gamma,a)$$
and we know that $Ind(\gamma,a)=1$, so
$$ \frac{1}{2\pi i}\cdot \int_{\gamma}{\frac{\bar{f}(z)}{z-a}dz}=\bar{f}(a)$$
But how can I prove that $\bar{f}(a)=\bar{f}(0)$?
Thanks for your time.

A: Because $|a|<1$ then $\left|\frac{a}{z}\right|<1$ for $|z|=1$ and we can write
$$\frac{1}{z-a}=\frac{1}{z}\frac{1}{1-\frac{a}{z}}=
\frac{1}{z}\left(\sum\limits_{k=0}\left(\frac{a}{z}\right)^k\right)=
\sum\limits_{k=0}\frac{a^k}{z^{k+1}}$$
Now $\forall n>0$
$$\int\limits_{|z|=1}\frac{1}{z^{n}(z-a)}dz=
\sum\limits_{k=0}\left(a^k\int\limits_{|z|=1}\frac{1}{z^{n+k+1}}dz\right)=0 \tag{1}$$
which is easy to see from Cauchy's integral formula for $g^{(k)}(0)=\frac{k!}{2\pi i}\int\limits_{|z|=1}\frac{g(z)}{z^{k+1}}dz$ for $g(z)=1$ constant. As a result (from @glofatics comments)
$$\int\limits_{|z|=1}\frac{\overline{f(z)}}{z-a}dz=
\int\limits_{|z|=1}\left(\sum\limits_{n=0}\frac{\overline{a_n}}{z^n}\right)\left(\sum\limits_{k=0}\frac{a^k}{z^{k+1}}\right)dz \overset{(1)}{=}
\int\limits_{|z|=1}\overline{a_0}dz=
2\pi \overline{f(0)}$$

Because $|a|>1$ then $\left|\frac{z}{a}\right|<1$ for $|z|=1$ and we can write
$$\frac{1}{z-a}=-\frac{1}{a}\frac{1}{1-\frac{z}{a}}=
-\frac{1}{a}\left(\sum\limits_{k=0}\left(\frac{z}{a}\right)^k\right)=
-\sum\limits_{k=0}\frac{z^k}{a^{k+1}}$$
Now $\forall n>0$
$$\int\limits_{|z|=1}\frac{1}{z^{n}(z-a)}dz=
-\sum\limits_{k=0}\left(\frac{1}{a^{k+1}}\int\limits_{|z|=1}z^{k-n}dz\right)=
-2\pi \frac{1}{a^n}\tag{2}$$
(more details here) and it's $0$ for $n=0$ since $1=|z|<|a|$. As a result
$$\int\limits_{|z|=1}\frac{\overline{f(z)}}{z-a}dz=
-\int\limits_{|z|=1}\left(\sum\limits_{n=0}\frac{\overline{a_n}}{z^n}\right)\left(\sum\limits_{k=0}\frac{z^k}{a^{k+1}}\right)dz \overset{(2)}{=}
-2\pi \sum\limits_{n=1}\frac{\overline{a_n}}{a^n}=\\
2\pi \overline{f(0)}-2\pi \sum\limits_{n=0}\frac{\overline{a_n}}{a^n}=
2\pi \overline{f(0)}-2\pi \overline{\sum\limits_{n=0}\frac{a_n}{\overline{a}^n}}=
2\pi \overline{f(0)}-2\pi \overline{f\left(\frac{1}{\overline{a}}\right)}$$

A: No series developments are needed. Let
$$Q:={1\over 2\pi i}\int_\gamma{\overline{f(z)}\over z-a}\>dz\ .$$
Then
$$\bar Q={-1\over 2\pi i}\int_\gamma{f(z)\over\bar z-\bar a}\>d\bar z\ .$$
Now along $\gamma$ we have $\bar z={1\over z}$ and therefore $d\bar z=-{1\over z^2}\>dz\ .$ It follows that
$$\bar Q={1\over2\pi i}\int_\gamma{f(z)\over z(1-\bar a z)}\>dz={1\over2\pi i}\int_\gamma f(z)\left({1\over z}-{1\over z-1/\bar a}\right)\>dz\ .$$ From this we conclude that  $$|a|<1\ \Rightarrow \ \bar Q =f(0),\qquad |a|>1\ \Rightarrow \ \bar Q =f(0)-f(1/\bar a)\ .$$

A: Following up on a comment by @glofatics.
$f$ is holomorphic, so it is analytic and you can write $f(z)=\sum_n a_n z^n$ and so $\overline{f}(z)=\sum_n \overline{a_n} \cdot \overline{z}^n$.
By uniform convergence, $$\int_{|z|=1} \frac{\overline{f}}{z-a}=\sum_n \overline{a_n}\int_{|z|=1}\frac{\overline{z}^n}{z-a}dz$$
Take a look at $g_n(z)=\frac{\overline{z}^n}{z-a}$.
For $|z|=1$, $\overline{z}=\frac{1}{z}$, and so $\int_{|z|=1}g_n dz=\int_{|z|=1}h_n(z)dz$ for $h_n(z)=\frac{1}{z^n(z-a)}$.
$h_n$ is holomorphic, up to some poles, and so we can apply the residue theorem.
If $|a|<1$ then we have two poles in $B(0,1)$ which are $0,a$ of order $n,1$ respectively.
Let us calculate residues.

*

*First, $Res_{z=a} h_n =a^{-n}$, for all $n\geq0$.

*It is not too difficult to see that for $n\geq1$ we have $$Res_{z=0} h_n =(-1)^{n-1}\cdot\frac{1}{(-a)^n}=-a^{-n}$$
This is because $$Res_{z=0} h_n=\frac{1}{(n-1)!}\frac{d^{n-1}}{dz^{n-1}}(z^n h_n(z))$$ for pole of order $n$.
For $n=0$, it is clear that $\int_{|z|=1|}h_n(z)dz=2\pi i$ by Cauchy's formula.
So, to sum up, $\int_{|z|=1}h_n(z)=2\pi i (Res_{z=0}+Res_{z=a})$ which is $0$ if $n\geq1$ and $2\pi i$ if $n=0$.
Therefore, we obtained that the integral from the beginning is
$$\sum_n \overline{a_n}\int_{|z|=1}h_n dz=\overline{a_0} \cdot 2\pi i=\overline{f(0)} \cdot 2\pi i$$
which is what you wanted in $1$. Similar solution will probably give $2$.


text:
Q: Is it ok to use ticks to pass datetime using ticks between pages of an application I'm currently passing some date-time info to a web page using url parameters, which are ticks of date times, and then converting the ticks back into date times when I need to at the other end.
Is there a better way to do this, and why.
for example
http://localhost:57765/dinners/updatedinner/38?startDate=633917664000000000

A: that's fine, in fact that the standard format for encoding dates for JSON. only concern is timezones, as your tickcount doesn't encode that. you can either always assume the timzone, and do offset calculations based on that, or encode the timezone in the value (eg sD=12343245345-0500)

A: Representing datetime in human readable format would be much better for developers (troubleshooting etc.) and potential customers of your site.

A: Given that Ticks is defined as the number of 100-nanosecond intervals that have passed since 12 midnight, January 1, 0001, I can't see there being any functional issues, as long as you either convert to UTC before passing (and from UTC after) or otherwise deal with timezone issues.
That said, there are more human-friendly ways to pass the information, for example passing it as yyyyMMddThhmmss.nnn will be more friendly if anyone wants to manually enter the URL, although it's not quite as precise (if you need better than millisecond precision).


text:
Q: Antd v4: How to add nesting in ? I am trying to create a custom grid like structure.
The structure will consist of various rows and each row can have multiple columns. And each column will have 1-2 form fields.
With Antd v4.2.0, we have <Form.List /> component with helps us to create dynamic form.
I tried using it and it was fine for the dynamic row part, but I am unable to figure out how can I create mutliple columns ie <Form.List> inside <Form.List>
I can create this grid manually as well but I want to leverage the form validation as well within this grid.
Visual representation for what I am trying to create:

A: To add a nested <Form.List> element inside another <Form.List> just add the nested list inside the outer list loop like any other nested <Form.Item>. The trick is to set the nested <Form.List> name property correctly, using the format: <Form.List name={[field.name, 'nested-input-name']}>.
As an example, let's extend the dynamic form example from the official documentation (https://ant.design/components/form/#components-form-demo-dynamic-form-item) with a nested list. The original example adds fields for "first name" and "last name", so we'll add a nested list for "nicknames".
import { Form, Input, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

const Demo = () => {
  const onFinish = values => {
    console.log('Received values of form:', values);
  };

  return (
    <Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
      <Form.List name="users">
        {(fields, { add, remove }) => {
          return (

              {fields.map(field => (
                <>
                    <Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="start">
                      <Form.Item
                        {...field}
                        name={[field.name, 'first']}
                        fieldKey={[field.fieldKey, 'first']}
                        rules={[{ required: true, message: 'Missing first name' }]}
                      >
                        <Input placeholder="First Name" />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        name={[field.name, 'last']}
                        fieldKey={[field.fieldKey, 'last']}
                        rules={[{ required: true, message: 'Missing last name' }]}
                      >
                        <Input placeholder="Last Name" />
                      </Form.Item>

                      <MinusCircleOutlined
                        onClick={() => {
                          remove(field.name);
                        }}
                      />
                    </Space>

                    <Form.List name={[field.name, 'nicknames']}>
                        {(nicknames, { add, remove }) => {
                          return (

                              {nicknames.map(nickname => (
                                <Space key={nickname.key} align="start">
                                  <Form.Item
                                    {...nickname}
                                    name={[nickname.name, 'nickname']}
                                    fieldKey={[nickname.fieldKey, 'nickname']}
                                    rules={[{ required: true, message: 'Missing nickname' }]}
                                  >
                                    <Input placeholder="Nickname" />
                                  </Form.Item>

                                  <MinusCircleOutlined
                                    onClick={() => {
                                      remove(nickname.name);
                                    }}
                                  />
                                </Space>
                              ))}

                              <Form.Item>
                                <Button
                                  type="dashed"
                                  onClick={() => {
                                    add();
                                  }}
                                  block
                                >
                                  <PlusOutlined /> Add nickname
                                </Button>
                              </Form.Item>

                          );
                        }}
                    </Form.list>
                </>
              ))}

              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => {
                    add();
                  }}
                  block
                >
                  <PlusOutlined /> Add field
                </Button>
              </Form.Item>

          );
        }}
      </Form.List>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, mountNode);

I'm keeping with the single component style of the official documentation, but you would probably want to break this up into smaller components in a real application.


text:
Q: What is the correct file extension I should use for a newly created PostgreSQL schema that I created? I have created a new schema for a new PostgreSQL DB that I want to create (IF NOT EXISTS).
What should the file extension be for this document so that I can run it from psql, .dbu or .sql?

A: .dbu is used as a "Database Utility" file
You need to use .sql
Then from psql you can use something like:
SET search_path = schemaName, something_else;
SELECT * FROM tableName;        -- schemaName.tableName

or something to that effect depending on what you're trying to accomplish...


text:
Q: iOS Google Silent Sign In provides a (valid) token with missing profile info I've integrated Google SignIn SDK (v4.0.1) to my iOS app.
The normal authentication process is working fine via:
GIDSignIn.sharedInstance().signIn()

The retrieved idToken is valid and includes both email and the user's basic info:
given_name
family_name
picture

*

*Google provide this URL for reviewing token data:
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=
Problem is, after relaunching the app, I perform silent login on didFinishLaunchingWithOptions like so:
if GIDSignIn.sharedInstance().hasAuthInKeychain() {
    GIDSignIn.sharedInstance().signInSilently()
}

The delegate function sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) is being called. And the authentication seem to have completed successfully. However, the idToken retrieved (from user.authentication.idToken) is missing the info of the "profile" scope. Only email field is provided.
Sending this idToken to our backend server results in a valid login but with missing info populated into our db. frustrating.
It feels like GIDSignIn.sharedInstance().signInSilently() does not respect GIDSignIn.sharedInstance().shouldFetchBasicProfile even if set true beforehand.
Attempt to refresh the token at this stage by running user.authentication.refreshTokens:handler produces a new token, again, with missing profile scope.


text:
Q: TextView in my getView() inside a adapter class throws null pointer exception I'm trying to create a android application, in which I try to setText() for a textview dynamically. But it throws null pointer exception
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder1 holder1;

    // LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    Log.i("&&&&& convert view is null", "&&&&& convert view is null");
    LayoutInflater inflater = activity.getLayoutInflater();

    if(convertView == null){
        convertView = inflater.inflate(R.layout.searchlist_repeat_items, parent, false);
        Log.i("@@@@@ convert view is null", "@@@@@ convert view is null");
        holder1 = new ViewHolder1();
        holder1.companyName_textView = (TextView) convertView.findViewById(R.id.companyName_textView);
    }else{
        holder1 = (ViewHolder1) convertView.getTag();
    }

     holder1.companyName_textView.setText("Checking text");

    return convertView;

}
static class ViewHolder1 {
    TextView companyName_textView;
}

A: you missed convertView.setTag(holder1) in the if clause. When convertView is not null, you are calling convertView.getTag() which is returning null
if(convertView == null){
        convertView = inflater.inflate(R.layout.searchlist_repeat_items, parent, false);
        Log.i("@@@@@ convert view is null", "@@@@@ convert view is null");
        holder1 = new ViewHolder1();
        holder1.companyName_textView = (TextView) convertView.findViewById(R.id.companyName_textView);
        convertView.setTag(holder1);
}


text:
Q: (html) How do I hide my navbar when my website is viewed on mobile? Is there a way to do this with html and css or can I only do it with javascript/bootstrap? I'm fairly new to coding so detailed explanations if possible would be nice!

A: Yes you can.
There several approaches to do that

*

*Detect device is touchable (e.g. with Modernizr like tools) - I do not recommend, cause nowadays event laptops provided with touch displays.

*By device's viewport - here's the good table list with most popular devices viewports by Adobe

I prefer second approach
So the solution comes in hand with CSS media-queries
And read about mobile first techniques
Example (press the Full page button after running snippet to look how it's gonna look in desktops)

A: You can do that with css media query. If you are begineer here is a small tutorial on that CSS media query.
According to mobile device size you can hide the navbar.
EXAMPLE:
@media only screen and (max-width: 600px) {
  .navbar{
      display:none;
  }
}

A: You can hide show with the help of @media screen to show or hide the code in different devices sizes.
Examples:
@media screen and (max-width: 767px) {
  .hide_on_mobile {
    display: none;
  }
}
@media screen and (min-width: 768px) {
  .hide_on_mobile {
    display: block;
  }
}


text:
Q: How to cleanly uninstall anaconda via terminal. I am having trouble getting coremltools to found as a module in Spyder Image of installed Anaconda Directories OK, long story short. I just started learning about CoreML for iOS. So from what i gathered, theres only about 4 trained models on Apple's website. In the search of some more robust models, i found Caffe was a hugely mentioned one. You need to use python to be able to translate some of these other 'external' models. I installed Anaconda via the continuum website for mac and am using the only supported 2.7 python language with keras/scikit/and a few other modules....... So from what I think it could be is after I installed anaconda at Applications level on my mac, it should of been originally installed at the User level. I reinstalled it at the User level, so technically I have two instances of anaconda on my system. Neither will work and inside Anaconda, i cannot import coremltools.
I have a hunch that maybe i need to change some pointers. Or just uninstall it completely from the machine and reinstall it at the User level from the start. I have about a year of swift experience, so im much more confident in my swift ability vs terminal ability. If anyone could coach me through how to cleanly remove it from my macbook pro, and explain the commands, I would greatly appreciate it. Or give any insight about whats going on or what im not doing. I can go into more detail if need be. Cheers in advance


text:
Q: case insensitive in cassandra while filtering the user email Hello guys i have a query where I'm getting the user email from the web services where i want to filter the user email either it is(lower/upper case) provided by the user while login:
user = User.objects.filter(email_id=v1_api.payload['email_id']).first()

here "v1_api" is blueprint in flask-restplus this code work fine if the user enters the email address which is same as the database but its throws an exception when I write "CAPSLOCK@gmail.com" in place of "capslock@gmail.com"
I want it to make case insensitive either the email in lower/uppper it should always considered it as a lower case...
In other database like SQLAlchemy we can do this in such a way:
from sqlalchemy import func
user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first()

But in cassandra I'm not able to do it please suggest me how to do this .....thanks

A: It's not possible to do this in Cassandra - Cassandra queries by precise value that you provided, it couldn't apply any function during the query. So you need to do the "normalization" of email when you're inserting data into database.


text:
Q: Database for storing files and their metadata I have decided to develop an EDMS in Java as an end of year project for my last year in IT studies and i'm currently researching into database solutions for uploading and storing files with different formats as well as their metadata.
I would like to be able to query file metadata and file content (I.E : return all documents created after june 2012, by the user John and that contain the string "finance").
I understand that Databases are for data and File Systems are for files as explained in this article, but some of my teachers have suggested that I look into XML databases, Apache Cocoon or Apache Jackrabbit and I have to admit that I am at a loss as to which approach I should take.
This article seems to suggest that MongoDB would be my best bet?
Thank you for your patience and help.
Sebastien

A: Without having the features you plan on implementing it is hard to say.  Assuming that your system will:

*

*allow uploading of documents

*allow searching of documents based on various metadata

*allow downloadig

consider either:

*

*Keeping the files in a filesystem but the metadata in a database such as mysql

*Keeping the files in a filesystem but use a search engine like Elasticsearch to
store the metadata.

Both of the solutions would work depending on how you want to search.  The flow of your application would be:
Uploading Documents

*

*User uploads new document

*Assign document internal ID

*Store document in filesystem based on that ID

*Store metadata in database/elasticsearch using ID to reference the file

Retrieving Documents

*

*User enters search criteria

*You generate query for either database or elasticsearch

*Display results. The result will have a link with the internal ID you created

*User selects result.  You use the ID to get the document


text:
Q: Trigger LogStash pipeline from Kibana Is there any easy way to configure it from Kibana? I have full control of the LogStash server and running Kibana on Elastic cloud
The only possible route I can think of is to create a custom button on Kibana that call a web service, setup a web service on LogStash server that manually start logstash on call
Is there any other way around this?


text:
Q: Treeview Header in WPF xaml I am having a treeview in my wpf application which dynamically binds data from my viewmodel.
<TreeView Grid.Column="0"
          Grid.Row="0"
          ItemsSource="{Binding Main}"
          HorizontalAlignment="Stretch"
          Name="treeView1"
          VerticalAlignment="Stretch"
          Height="auto"
          Width="auto"
          SelectedItemChanged="treeView1_SelectedItemChanged"
          HorizontalContentAlignment="Stretch"
          VerticalContentAlignment="Top"
          Margin="0,0,5,5">
  <TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
      <Setter Property="IsExpanded"
              Value="{Binding IsExpanded, Mode=TwoWay}" />
      <Setter Property="IsSelected"
              Value="{Binding IsSelected, Mode=TwoWay}" />
      <Setter Property="FontWeight"
              Value="Normal" />
      <Style.Triggers>
        <Trigger Property="IsSelected"
                 Value="True">
          <Setter Property="FontWeight"
                  Value="Bold" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </TreeView.ItemContainerStyle>
  <TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:MViewModel}"
                              ItemsSource="{Binding Children}">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Mname}" />
      </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="{x:Type local:FViewModel}"
                              ItemsSource="{Binding Children}">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding FName}" />
      </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="{x:Type local:CViewModel}"
                              ItemsSource="{Binding Children}">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Com}" />
      </StackPanel>
    </HierarchicalDataTemplate>
    <DataTemplate DataType="{x:Type local:LViewModel}">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Lo}" />
      </StackPanel>
    </DataTemplate>
  </TreeView.Resources>
</TreeView>

I need to add the header to the whole treeview say "Family" whose childs are the above treeview elements.
How can i add header to the whole treeview.so that when i click that header it should display all Mname and so on.
Please help me with this issue.
Edit:
i have used
  <HierarchicalDataTemplate  DataType="{x:Type TextBlock}" ItemsSource="{Binding Children}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Family" />
                        </StackPanel>
  </HierarchicalDataTemplate>

in my TreeviewResource. But still i can't assign the parent for the tree.
Edit 2:
<TreeView>
   <TreeViewItem ItemsSource="{Binding Main}" Header="Family">
      <TreeViewItemContainerStyle>
      //..
      </TreeViewItemContainerStyle>
      <TreeView.Resources>
      //..
      </TreeView.Resources>
   </TreeViewItem>
</TreeView>

Its showing error.
But when i do like below,
<TreeView>
       <TreeViewItemContainerStyle>
      //..
      </TreeViewItemContainerStyle>
      <TreeView.Resources>
      //..
      </TreeView.Resources>
   <TreeViewItem ItemsSource="{Binding Main}" Header="Family"/>
</TreeView>

The root item has been set. But Only the first set of child are displayed. Childs of child elements are not displaying.

A: You can wrap your TreeView with Expander element:
<Expander Header="Family">
    <TreeView>
        ...
    <TreeView>
</Expander>

But it is not clear from your question which element you want to use as a Header.
Edit:
So, if you need a root element for a tree, you can add it explicitly in xaml:
<TreeView> <!--ItemsSource you should set on a TreeViewItem-->
    <TreeViewItem ItemsSource="{Binding Main}" Header="Family">
        <TreeViewItem.ItemContainerStyle>
            ...
        </TreeViewItem.ItemContainerStyle>
        <TreeViewItem.Resources>
            ...
        </TreeViewItem.Resources>
    </TreeViewItem>
<TreeView>


text:
Q: IBM Bluemix Watson visual recognition authorization issue under my IBM Bluemix account, I have registered a Watson Visual Recognition service.
My intention is to call the service from Bizagi BPMS as REST service.
Bizagi brings an "unauthorized" error.
The URL for the REST Service is
https://gateway.watsonplatform.net/visual-recognition-beta/api/v2/classify
The Service URL is
https://gateway.watsonplatform.net/visual-recognition-beta/api/?username=xxxxxxxxxxxxxxxxxxx&password=yyyyyyyyyyy
(x and y are the credentials from the service instance in Bluemix.
When entering the Service URL directly into the browser, I can enter the authentication credentials in a popup window, but the response is
"Error 404: SRVE0190E: File not found: / "

A: The service uses Basic Authorization so you need to send the username and password Base64 encoded.
On the other hand, the Visual Recognition service requires you to send the image you want to recognize. If you use a browser you need to point to a GET call. Open a browser using this url: https://gateway.watsonplatform.net/visual-recognition-beta/api/v2/classifiers?version=2015-12-02
That should return the list of classifiers.
Example Output:
{
  "classifiers": [
    {
      "classifier_id": "nightvsday_11138698",
      "name": "night vs day"
    },
    {
      "classifier_id": "tiger_458617357",
      "name": "tiger"
    },
    {
      "classifier_id": "Black",
      "name": "Black"
    },
    {
      "classifier_id": "Blue",
      "name": "Blue"
    }
 ]
}

For more examples look at the Visual Recognition API Reference.


text:
Q: Error starting MongoDB in windows 7 [32-bit] I followed a blog(link) to install and configure MongoDB in my system[Windows 7 32 bit].
As per blogger said, I have download mongodb-win32-i386-2.6.5 and extract to D:/mongodb/ and followed the blog
Upto installation everything alright, but when I try to start service using following command,
 D:\mongodb\bin>net start MongoDB

I got error response as,
System error 2 has occurred.

The system cannot find the file specified.

How to solve this ?

Update : Log File

2014-11-19T16:43:25.356+0530 [DataFileSync] flushing diag log
2014-11-19T16:43:25.403+0530 [initandlisten] MongoDB starting : pid=5128 port=27017 dbpath=D:\mongodb\data 32-bit host=AVVENIRE-JAVA
2014-11-19T16:43:25.403+0530 [initandlisten]
2014-11-19T16:43:25.403+0530 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
2014-11-19T16:43:25.403+0530 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).
2014-11-19T16:43:25.403+0530 [initandlisten] **       See http://dochub.mongodb.org/core/32bit
2014-11-19T16:43:25.404+0530 [initandlisten]
2014-11-19T16:43:25.404+0530 [initandlisten] targetMinOS: Windows XP SP3
2014-11-19T16:43:25.404+0530 [initandlisten] db version v2.6.1
2014-11-19T16:43:25.404+0530 [initandlisten] git version: 4b95b086d2374bdcfcdf2249272fb552c9c726e8
2014-11-19T16:43:25.404+0530 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB_VERSION=1_49
2014-11-19T16:43:25.404+0530 [initandlisten] allocator: system
2014-11-19T16:43:25.404+0530 [initandlisten] options: { config: "d:\mongodb\mongo.config", diaglog: 3, net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "D:\mongodb\data", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "D:\mongodb\log\mongo.log", quiet: true } }
2014-11-19T16:43:25.483+0530 [initandlisten] journal dir=D:\mongodb\data\journal
2014-11-19T16:43:25.484+0530 [initandlisten] recover : no journal files present, no recovery needed
2014-11-19T16:43:25.770+0530 [initandlisten] waiting for connections on port 27017
2014-11-19T16:44:25.439+0530 [DataFileSync] flushing diag log
2014-11-19T16:45:25.361+0530 [DataFileSync] flushing diag log
2014-11-19T16:46:25.360+0530 [DataFileSync] flushing diag log
2014-11-19T16:46:31.869+0530 [conn1] terminating, shutdown command received
2014-11-19T16:46:31.869+0530 [conn1] dbexit: shutdown called
2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to close listening sockets...
2014-11-19T16:46:31.869+0530 [conn1] closing listening socket: 540
2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to flush diaglog...
2014-11-19T16:46:31.869+0530 [conn1] flushing diag log
2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to close sockets...
2014-11-19T16:46:31.870+0530 [conn1] shutdown: waiting for fs preallocator...
2014-11-19T16:46:31.870+0530 [conn1] shutdown: lock for final commit...
2014-11-19T16:46:31.870+0530 [conn1] shutdown: final commit...
2014-11-19T16:46:31.873+0530 [conn1] shutdown: closing all files...
2014-11-19T16:46:31.873+0530 [conn1] closeAllFiles() finished
2014-11-19T16:46:31.873+0530 [conn1] journalCleanup...
2014-11-19T16:46:31.889+0530 [conn1] removeJournalFiles
2014-11-19T16:46:31.891+0530 [conn1] shutdown: removing fs lock...
2014-11-19T16:46:31.891+0530 [conn1] dbexit: really exiting now
2014-11-19T16:47:08.985+0530 ***** SERVER RESTARTED *****
2014-11-19T16:47:08.985+0530 Trying to install Windows service 'MongoDB'
2014-11-19T16:47:08.985+0530 There is already a service named 'MongoDB', aborting

Update 2(result of @disposer's suggestion):

A: Run Command window as administrator and run net delete MongoDB
For running mongo as a service use this:
C:\mongodb\bin\mongod --bind_ip  0.0.0.0 --logpath  "C:\Data\db\log.txt"  --logappend  --dbpath  "C:\Data\db"  --port 27017 --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install

then run Command window as administrator and run net start MongoDB

A: Download from this link @ http://downloads.mongodb.org/win32/mongodb-win32-i386-v3.2-latest-signed.msi?_ga=1.10304565.1436936475.1490595203
After installation in E: drive, run mongod command with options
 @ E:\Program Files\MongoDB\Server\3.2\bin>
mongod --storageEngine=mmapv1 --dbpath C:\data\db
Observe, two options are necessary to be installed without errors, specially for 32-bit, --storageEngine=mmapv1 and create a directory in OS drive(c:) only as --dbpath C:\data\db
Keep your server running at command prompt, install mongobooster from http://s3.mongobooster.com/download/3.5/mongobooster-3.5.3.exe for GUI to manage mongodb.
and connect to local database..try samples @ https://www.youtube.com/playlist?list=PL6gx4Cwl9DGDQ5DrbIl20Zu9hx1IjeVhO

A: I got it working like this..

*

*Install the latest msi version.

*Create the folders c:\data\db

*In my bin directory (C:\Program Files\MongoDB\Server\3.2\bin), I ran mongod --storageEngine=mmapv1 --dbpath C:\data\db using CMD.

*Opened up a new CMD window (Keeping the one from 1st step still running) and traveled to the same bin directory (C:\Program Files\MongoDB\Server\3.2\bin) and then ran mongo.exe
Hope it helps

A: in log file if it shows this"There is already a service named 'MongoDB', sleeping and retrying" that mean you are reinstalling mongodb.for resolve this problem just run

*

*mongod --remove in command prompt in bin folder.it will remove service MongoDB.

*then run mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongo.log --logappend --install.

*and the last command net start MongoDB will run MongoDB service.

A: I got the same error with MongoDB 3.2 for 32 bit.

*

*Try to make new db folder

*Copy-paste your database from old db folder ( there are 2 files )

*Connect it with new db folder using cmd
You won't loss your database. It had happened with me twice. I don't why it happened


text:
Q: WP_query show specific category and its subcat I need to change the behavior of WP_query. Currently it shows all main categories and their subcategories, and I need to have specific category and its categories.
For example: Category A with ID1 has 10 subcategories and I need to display (filter the category A and 10 subcats).
<?php
    $the_query = new WP_Query( array("post_type"=>"project_post") );
    while ( $the_query->have_posts() ) : $the_query->the_post();
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'project_preview_big' );
    $image = $image[0];
    $categories = wp_get_post_terms($post->ID,"projects_category");
    $category = array();
    if(count($categories)){
        foreach($categories as $categ){
            array_push($category,$categ->name);
        }
        $category = implode(",",$category);
    }
    else{
        $category = "";
    }
    $cats = array();
    foreach($categories as $cat){
        array_push($cats,$cat->term_id);
    }
    $cats = implode(",",$cats);
?>
<div class="project" style="overflow:hidden;" data-categories='<?php echo $cats; ?>'>
    <img src="<?php echo $image; ?>" width="100%"/>

<?php echo $category; ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

        <?php
            $content = excerpt(strip_tags($post->post_content),16,"...");
            echo $content;
        ?>

        <a class="read_more" href="<?php the_permalink(); ?>"><?php _e("Prohlédnout projekt","um_lang"); ?>

<?php
    endwhile;
?>


text:
Q: Rosencrantz is Routing DELETE Method not working? my using Rosencrantz to Api Server.
but
DELETE method set is run compile to error
not working?
i Document copy and path , message, http method to Edited only
nim versin : 0.19.6
rosencrantz : 0.3.8
import
  asyncdispatch,
  asynchttpserver,
  strutils,
  rosencrantz

let handler = get[
  path("/api/users")[
    ok("Get Users")
  ] ~
  pathChunk("/api/users")[
    intSegment(proc(id: int): auto =
      ok("Get User by " & intToStr(id) & "!")
    )
  ]
] ~ delete[
  pathChunk("/api/users")[
    intSegment(proc(id: int): auto =
      ok("Delete User by " & intToStr(id) & "!")
    )
  ]
]

let server = newAsyncHttpServer()
waitFor server.serve(Port(8080), handler)

Error Message
     :
     :
    ... api.nim(16, 3) Error: type mismatch: got <Handler, proc (x: var seq[Handler], i: Natural){.noSideEffect, gcsafe, locks: 0.}>
    ... but expected one of:
    ... proc `~`(h1, h2: Handler): Handler
    ...   first type mismatch at position: 2
    ...   required type: Handler
    ...   but expression 'delete' is of type: proc (x: var seq[Handler], i: Natural){.noSideEffect, gcsafe, locks: 0.}
    ... expression: (get ->
    ...     (path("/api/users") -> ok("Get Users")) ~
    ...     (pathChunk("/api/users") ->
    ...     intSegment(proc (id: int): auto = result = ok(
    ...     `&`("Get User by ", intToStr(id, 1), "!"))))) ~ delete

A: Yo have to qualify the delete method:
] ~ rosencranz.delete[
  pathChunk("/api/users")[
    intSegment(proc(id: int): auto =
      ok("Delete User by " & intToStr(id) & "!")
    )
  ]

Or you will call the system.delete.


text:
Q: enable send button on rightclick and paste i have write a function to disable my send button in chat area while there is no invalid data input.
    _validateChatDraft: function() {
    var chat = this.input.value.trim();
    var isFileSelected = we.useNativeUpload ? this.uploadImageData : !!this.uploadInput.value;
    if (isFileSelected) {
      this.btn.removeAttribute('disabled');
      return;
    }
    if (chat === '') {
      this.btn.setAttribute('disabled', 'disabled');
    } else {
      this.btn.removeAttribute('disabled');
    }
  },

but right now my send button is disabled in paste event.
i have also used these 3 lines that seems 3th one doesn't work:
        this.input.addEventListener('keyup', this._validateChatDraft.bind(this));
    this.uploadInput.addEventListener('change', this._validateChatDraft.bind(this));
    this.input.addEventListener('paste', this._validateChatDraft.bind(this));

A: actually my problem is solved with  just changing 'keyup' to 'input' , that is more general and includes all cases
    this.input.addEventListener('input', this._validateChatDraft.bind(this));


text:
Q: XPages: How to use data in client JS as data source of dataview control? I use client JS to collect some data and want to use these data as data source of some common xpages controls, any suggestion?

A: I assume you mean a data source for a ViewPanel, DataTable, or Repeat?

*

*Put the data in a hidden field with client js.

*Execute a server side action. (Within the server side action you can place the data from the hidden field into a scope variable, if desired)

*Execute a partial refresh from the server side action and make sure you are refreshing the control that needs to use the client side data as a data source.

*Point the data source of the control to the hidden field (or scope variable if that's what you used)

*Manipulate the data as necessary.  For example, if your field contains "one,two,three" as a value you need to turn that into an array with string.split().