Q: Issue using position dodge vertically in ggplots with geom_linerange in R I'm relatively new to R, and I am having issues with avoiding overlapping line ranges using geom_linerange and position_dodge with ggplot. I am comparing 2 different sets of age ranges for each individual in the study data. I would like to show the two ranges side-by-side, rather than display on the same ID line. Here is the data:
> dput(data)
structure(list(ID = c("A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z"), Age_Range1_Start = c(39L, 21L, 28L,
35L, 35L, 20L, 21L, 28L, 20L, 29L, 28L, 20L, 49L, 20L, 39L, 21L,
39L, 21L, 20L, 28L, 30L, 29L, 21L, 28L, 29L, 35L), Age_Range1_End = c(69L,
42L, 52L, 57L, 57L, 43L, 42L, 52L, 43L, 44L, 52L, 43L, 65L, 43L,
69L, 42L, 69L, 42L, 43L, 52L, 54L, 44L, 42L, 52L, 44L, 57L),
    Age_Range2_Start = c(46L, 43L, 49L, 46L, 48L, 34L, 37L, 45L,
    44L, 46L, 37L, 43L, 51L, 45L, 48L, 36L, 53L, 44L, 24L, 43L,
    45L, 49L, 34L, 45L, 22L, 30L), Age_Range2_End = c(87L, 80L,
    92L, 86L, 90L, 64L, 69L, 83L, 81L, 85L, 68L, 80L, 97L, 84L,
    89L, 68L, 100L, 83L, 45L, 82L, 83L, 92L, 64L, 84L, 42L, 56L
    )), class = "data.frame", row.names = c(NA, -26L))
>

Here is the R code I used
ggplot(data) + theme_minimal() + coord_flip() +
geom_linerange(aes(x=ID, ymin=Age_Range1_Start, ymax=Age_Range1_End, color="Method 1", size=1.5)) +
geom_linerange(aes(x=ID, ymin=Age_Range2_Start, ymax=Age_Range2_End, color="Method 2", size=1.5), position=position_dodge(width=1)) +
labs(x="ID", y="Age Range", title="Method Age Range Comparison")

It produces the following plot:

Is it possible to shift (or dodge) the line ranges for Method 2 such that they appear slightly below or inferior to the age ranges for Method 1? I do not understand why the position_dodge code does not shift the values.
Thank you in advance for any help or suggestions.

A: If you organize your data in another format you can do the trick, as follows:
library(ggplot2)

data = data.frame(
  ID = rep(c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), 2),
  Start = c(39, 21, 28, 35, 35, 20, 21, 28, 46, 43, 49, 46, 48, 34, 37, 45),
  End = c(69, 42, 52, 57, 57, 43, 42, 52, 87, 80, 92, 86, 90, 64, 69, 83),
  Method = c(rep(1, 8), rep(2, 8))
)
data$Method = as.factor(data$Method)

ggplot(data) +
  theme_minimal() +
  coord_flip() +
  geom_linerange(aes(x = ID, ymin = Start, ymax = End, colour = Method),
                 size = 1.5, position = position_dodge2(width = 0.5)) +
  labs(x = 'ID', y = 'Age Range', title = 'Method Age Range Comparison')

Here is the output:

Note that I gather the starts together and the ends together. Then, I labeled each of them as method 1 or 2.
Also remember using position_dodge2() when you flip the coordinates.


Q: display an image when dropdown is selected I am trying to display an image when a dropdown is selected with the code below.By default dropdown value will be "None".Initially when the page is loaded it is not displaying image.when i select field2 or field image is diaplaying.But when i select none again the image is still diaplaying.The code i used is:
<select id="dropdown" name="dropdown">
<option value="field1" selected="selected">None</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>

$(document).ready(function() {
  $("#image").hide();
  $('#dropdown').on('change', function() {
   if ( this.value == 'field2')
   {
      $("#image").show();
   }
   elsif(this.value == 'field3')
   {
       $("#image1").show();
   }
  else
   {
      $("#image").hide();
      $("#image1").hide();
   }
 });

});
#image img {
    padding-left:554px;
    position:absolute;
    padding-top: 774px;
  }

A: This should do it. Use the .indexOf() on an array of the good values and check if the value is in the array. To ensure that the handler fires at page load trigger the change event with .change().:
$(document).ready(function() {
    $('#dropdown').on('change', function() {
        if ( ['field2', 'field3'].indexOf( this.value ) > -1 )
        {
            $("#image").show();
        }
        else
        {
            $("#image").hide();
        }
    })
    .change();
});

$(document).ready(function() {

  $('#dropdown').on('change', function() {
   if ( ['field2', 'field3'].indexOf( this.value ) > -1 )
   {
      $("#image").show();
   }
  else
   {
      $("#image").hide();
   }
 })
  .change();
});
#image img {
    padding-left: 60px;
    position:absolute;
    padding-top: -10px;
  }

<select id="dropdown" name="dropdown">
<option value="field1" selected="selected">None</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>

Update
Note: For the purpose of continuity, it is good practice to retain the original question and include any new updates. When the question is drastically different, it's advisable to create a new question.

$(document).ready(function() {
  $('#dropdown').on('change', function() {
    $('#image,#image1').hide();
   if ( this.value === 'field2')
   {
      $("#image").show();
   }
   else if(this.value === 'field3')
   {
       $("#image1").show();
   }
  else
   {
      $("#image").hide();
      $("#image1").hide();
   }
 })
  .change();
});
#imagex img {
    padding-left:554px;
    position:absolute;
    padding-top: 774px;
  }

<select id="dropdown" name="dropdown">
<option value="field1" selected="selected">None</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>
#image
#image1


Q: Easiest way to test vim regex? I'm trying to write a vim syntax file, one problem I'm dealing with is vim's regex syntax is different from most other languages(I think the one called "perl compatible regex", Python, JavaScript etc. uses mostly the same regex syntax) and so I can't use regex testers like regexpal.
What is the easiest way to try vim regexes ? Ideally what I want is two splits, in one I'll write vim regex, and the other one will have the text, and matched parts should be highlighted.
Thanks in advance.
EDIT: I added a modified version of Ingo Karkat's answer to my .vimrc:
nnoremap <F5> mryi":let @/ = @"<CR>`r

This version also puts cursor back where it was when pressed F5 with the cost of losing mark r.

A: Use vim to test the regex. By typing / in vim you can search for stuff and the search uses regex.
For help on syntax have a look on vimregex

A: We can access Vim's registers in Ex mode or in searching mode by pressing Ctrl+R and then the register you want to paste.
In your situation we can use this to copy the text we want to test and then paste this in our search.
yi"/Ctrl+R0CR
Explanation:
yi" -> Yank inside of double quotes "
/ - > Open the search field
Ctrl+R0 -> paste the last yanked text

A: Do this in Vim. For syntax files, you often deal with start="^begin" stuff. Yank the regexp via yi", then highlight it via:
:let @/ = @"

Of course, if you need this often, bind this to a mapping (and :set hlsearch), like:
:nnoremap <F5> yi":let @/ = @"<CR>

A: Ideal solution:

https://github.com/bennypowers/nvim-regexplainer
But it seems that it only work on javascript regex, not vim's, so far.
Nice website (but no vim's regex engine)

Convert magic to very magic (to avoid backslashits):
https://github.com/sisrfeng/VimRegexConverter
Split to pieces of strings by hand:
if file_name =~# '\v^(' .. '[\%#~]' .. '|' .. '\.?[/\\]\a+:' .. '|' ..  '^\d+' .. ')$'

vs
if file_name =~#  '^\.\=[\\/]\|^\a\+:\|^[%#~]\|^\d\+$'

A: You can also try RegExr
It's a good tool to learn RegEx and try them in real time.


Q: Add mouse event listener to OBJMTL object - three.js I have created a OBJMTL 3D object with:
                    var loader = new THREE.OBJMTLLoader();
                    loader.addEventListener('load', function (event) {
                        Barrel = event.content;

                        side: THREE.DoubleSide;

                        scene.add(Barrel);
                    });

                    loader.load( '3D/Barrel/barrel.obj', '3D/Barrel/barrel.mtl');

I want to add an mouse event listener like in this :
link
Any other example of creating mouse listeners i found around the web does not work with OBJMTL loaded objects.
Any idea?


Q: Convert foreach to lambda Just started with Lambda in c# and I got stumbled by this.How can I convert following code block to lambda expression, adding all the values in headers get added to DefaultRequestHeaders.
var client = new HttpClient();
foreach (var header in headers)
{
    client.DefaultRequestHeaders.Add(header.Name, header.Value);
}

A: This is no use case for a Lambda expression (as the discussion on Sim's answer shows), but it could be if you wanted to leverage parallel processing:
using System.Threading.Tasks;

Parallel.ForEach(headers, header =>
    client.DefaultRequestHeaders.Add(header.Key, header.Value)
);

I wouldn't do that in this case though. The class might not be thread-safe and there is nothing to be gained here in terms of performance.


Q: tc don't see marked packets Server has 2 interfaces:

*

*eth1 with address 13.0.0.254/24

*eth0 with address 172.20.203.4/24.

It's routing traffic between this two networks. Task is to limit bandwidth between this two networks to 1Vbit/sec, but not to limit bandwidth between server and network hosts(i. e. limit all packets going though FORWARD)
iptables -t mangle -A POSTROUTING -s 13.0.0.0/24 -d 172.20.203.0/24 -j MARK --set-mark 0x0001
iptables -t mangle -A POSTROUTING -s 172.20.203.0/24 -d 13.0.0.0/24 -j MARK --set-mark 0x0002

# eth1
tc qdisc add dev eth1 root handle 1:0 htb default 2

tc class add dev eth1 parent 1:0 classid 1:1 htb rate 1000mbps ceil 1000mbps
tc class add dev eth1 parent 1:1 classid 1:2 htb rate 999mbps ceil 1000mbps
tc class add dev eth1 parent 1:1 classid 1:3 htb rate 1mbps

tc qdisc add dev eth1 parent 1:2 handle 2:0 sfq perturb 10
tc qdisc add dev eth1 parent 1:3 handle 3:0 sfq perturb 10

tc filter add dev eth1 parent 1:0 handle 1 fw flowid 1:3
tc filter add dev eth1 parent 1:0 handle 2 fw flowid 1:3

# eth0
tc qdisc add dev eth0 root handle 1:0 htb default 2

tc class add dev eth0 parent 1:0 classid 1:1 htb rate 1000mbps ceil 1000mbps
tc class add dev eth0 parent 1:1 classid 1:2 htb rate 999mbps ceil 1000mbps
tc class add dev eth0 parent 1:1 classid 1:3 htb rate 1mbps

tc qdisc add dev eth0 parent 1:2 handle 2:0 sfq perturb 10
tc qdisc add dev eth0 parent 1:3 handle 3:0 sfq perturb 10

tc filter add dev eth0 parent 1:0 handle 2 fw flowid 1:3
tc filter add dev eth0 parent 1:0 handle 1 fw flowid 1:3

This doesn't work. If I use this at the beginning:
tc qdisc add dev eth1 root handle 1:0 htb default 3
tc qdisc add dev eth0 root handle 1:0 htb default 3

it works. So problem is in filter settings.
iptables -L -v -n -t mangle

shows, that packets are going though MARK rules. I tried to mark packets not in POSTROUTING, but in FORWARD or PREROUTING - this does not work too. What am I doing wrong?
Here is some diagnostics:
# tc -s -d -r filter show dev eth0
filter parent 1: protocol [768] pref 49151 fw
filter parent 1: protocol [768] pref 49151 fw handle 0x1 classid 1:3
filter parent 1: protocol [768] pref 49152 fw
filter parent 1: protocol [768] pref 49152 fw handle 0x2 classid 1:3
# tc -s -d -r filter show dev eth1
filter parent 1: protocol [768] pref 49151 fw
filter parent 1: protocol [768] pref 49151 fw handle 0x2 classid 1:3
filter parent 1: protocol [768] pref 49152 fw
filter parent 1: protocol [768] pref 49152 fw handle 0x1 classid 1:3

A: modprobe xt_mark

If module is not loaded, iptables gives no f***ing error, but rules "-j MARK" do not work


Q: Kendo UI Ajax Request I'm using Kendo UI Grid with an action link into a client-template column. This action link call an data edit view. See example:
 c.Bound(p => p.sID).ClientTemplate(@Html.ImageActionLink(Url.Content("~/Content/images/edit3.png"), "Edit", "Edit", new { id = "#= sID #" }, new { title = "Edit", id = "Edit", border = 0, hspace = 2 }).ToString()
                           ).Title("").Width(70).Filterable(false).Groupable(false).Sortable(false);

My question is how can I configure the grid in order to show an ajax loader when the action link is clicked, until the edit view is rendered?

A: you can create relative div and insert there your grid and loader wrapper:

    @(Html.Kendo().Grid()....)

css:
.grid-wrapper {
    position: relative;
}
.loading-wrapper {
    display: none;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1000;
}
.loading {
    position: absolute;
    height: 4em;
    top: 50%;
}

add to imageActionLink in htmlAttributes object class named "edit" (for example), and write click event handler:
$(document).on('click', '.edit', function (e) {
    $('.loading-wrapper').show();
    $.ajax({
        // ajax opts
        success: function(response) {
             // insert your edit view received by ajax in right place
             $('.loading-wrapper').hide();
        }
    })
});

A: you can do this like :
c.Bound(p => p.sID).Template(@Edit).Title("Edit").Encoded(false);
//encoded false = Html.Raw


Q: Broken ubuntu distibution I am running Ubuntu 14.04 as my main distro. Recently I installed several additional desktop environments, including:
Cairo, Cinnamon, Pantheon, Deepin, and most recently Xubuntu.
I always had trouble booting into Pantheon and Deepin so I wanted to uninstall them. So, for Deepin I went to the file in my sources file and deleted to lines I had added, and subsquently went into Synaptic and deleted everything with "Deepin" in its name. Then for Pantheon I did (i think):
sudo apt-get purge pantheon

Upon rebooting into Ubuntu itself, I saw a blank blue home page, but no unity interface at all, I could do nothing but press and hold the power button and restart.
How can I make Ubuntu boot again?

A: My recommendation is that you attempt to reconfigure/reinstall some packages. try running sudo apt-get install --reinstall ubuntu-desktop lightdm pantheon deepin then sudo dpkg reconfigure ubuntu-desktop lightdm. If that doesn't work you may need to fix a few corrupt packages or something. Try using sudo apt-get -f install along with the usual autoclean, clean, update, upgrade, and autoremove commands.

A: Sounds like you've got some leftover Xubuntu packages messing with your configs. Try this in a terminal:
sudo apt-get purge abiword abiword-common abiword-plugin-grammar abiword-plugin-mathview alacarte bison blueman brltty-x11 catfish espeak exo-utils flex fonts-droid fonts-lyx gigolo gmusicbrowser gnome-system-tools gnome-time-admin gstreamer0.10-gnomevfs gthumb gthumb-data gtk2-engines-pixbuf indicator-application-gtk2 indicator-sound-gtk2 leafpad libabiword-3.0 libbison-dev libdigest-crc-perl libexo-1-0 libexo-common libexo-helpers libfl-dev libgarcon-1-0 libgarcon-common libgdome2-0 libgdome2-cpp-smart0c2a libglade2-0 libgnomevfs2-0 libgnomevfs2-common libgnomevfs2-extra libgsf-1-114 libgsf-1-common libgstreamer-perl libgtk2-notify-perl libgtk2-trayicon-perl libgtkmathview0c2a libgtkspell0 libido-0.1-0 libindicate-gtk3 libintl-perl libjpeg-progs libjpeg-turbo-progs libkeybinder0 liblink-grammar4 libloudmouth1-0 libnet-dbus-perl liboobs-1-5 libotr5 libots0 librarian0 libsexy2 libtagc0 libthunarx-2-0 libtidy-0.99-0 libtie-ixhash-perl libtumbler-1-0 libunique-1.0-0 libvte-common libvte9 libwv-1.2-4 libxfce4ui-1-0 libxfce4ui-utils libxfce4util-bin libxfce4util-common libxfce4util6 libxfcegui4-4 libxfconf-0-2 libxml-parser-perl libxml-twig-perl libxml-xpath-perl lightdm-gtk-greeter link-grammar-dictionaries-en m4 orage parole pastebinit pavucontrol pidgin pidgin-data pidgin-libnotify pidgin-microblog pidgin-otr plymouth-theme-xubuntu-logo plymouth-theme-xubuntu-text python-configobj rarian-compat ristretto screensaver-default-images scrollkeeper shimmer-themes system-tools-backends tcl8.5 thunar thunar-archive-plugin thunar-data thunar-media-tags-plugin thunar-volman tumbler tumbler-common xbrlapi xchat xchat-common xfburn xfce-keyboard-shortcuts xfce4-appfinder xfce4-cpugraph-plugin xfce4-dict xfce4-indicator-plugin xfce4-mailwatch-plugin xfce4-netload-plugin xfce4-notes xfce4-notes-plugin xfce4-notifyd xfce4-panel xfce4-places-plugin xfce4-power-manager xfce4-power-manager-data xfce4-quicklauncher-plugin xfce4-screenshooter xfce4-session xfce4-settings xfce4-systemload-plugin xfce4-taskmanager xfce4-terminal xfce4-verve-plugin xfce4-volumed xfce4-weather-plugin xfce4-xkb-plugin xfconf xfdesktop4 xfdesktop4-data xfwm4 xscreensaver xscreensaver-data xscreensaver-gl xubuntu-artwork xubuntu-default-settings xubuntu-desktop xubuntu-docs xubuntu-icon-theme xubuntu-wallpapers && sudo apt-get install --reinstall ubuntu-desktop
and then reboot.


Q: How long does Apple provide support for Mac OS X? I am currently using Apple 10.6 (Snow Leopard). How long will Snow Leopard be supported for? Does Apple provide an end-of-life policy in writing?
I have read that Apple tends to only provide security updates for the latest two versions of Mac OS X (an 'n-2' support policy, where 'n' is the latest version of the OS. Since Lion and Mountain Lion are out, Apple might drop security updates Snow Leopard.
According to "Mac users left wondering if OS X Snow Leopard's retired" from Computerworld and "Where are the Safari security updates for Windows and Snow Leopard? Users left exposed" on Sophos's blog, some believe that Apple has already, quietly retired Snow Leopard. However, those pages have some contradictory information (Tiger was updated in 2009).
However, the articles above seem to cite rumor. Does Apple provide their support policy in writing?

A: Apple don't provide any end of life information unfortunately, and you're correct that they only support the current and previous versions, although they do still release security patches for the one before that from time to time for another release cycle after this.
So you'll get up to 3 years out of an OS release, and that usually an Apple computer will be supported by new OS releases for around the same time.

A: Haven't yet come across a support policy in writing, but this page would seem to contradict the notion that older products stop receiving current updates.  There are updates for 10.5 and XP as recently as June, 2012.

A: support lasts approximately 40 months.
OSX 10.9 is no longer receiving security updates:
support.apple.com/en-us/HT201222

http://www.computerworld.com/article/2950580/operating-systems/the-end-is-near-for-os-x-mountain-lion-support.html


Q: Core data attribute not being made I've decided to add an NSNumber attribute to one of my entities in core data. I Cleaned the code and deleted the app from the simulator. I then added the following code in my appDelegate and it tells me that my NSNumber attribute doesn't exist.
People *PeopleA = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context];
PeopleA.name = @"Paul";
PeopleA.number = [NSNumber numberWithInt:12];

The name attribute works just fine, that was made before and it's always worked. But when it gets to PeopleA.number it crashes with :
-[People setNumber:]: unrecognized selector sent to instance 0x4d5eeb0

So I did a po 0x4d5eeb0 and saw that there is a name attribute but not one for number. My core data class should be good because I had XCode make it for me.
What could possibly be the issue?
Here is my People.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Group;

@interface People : NSManagedObject {
@private
}
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) id image;
@property (nonatomic, retain) NSNumber * number;
@property (nonatomic, retain) Group * group;

@end

People.m
#import "People.h"
#import "Group.h"

@implementation People
@dynamic name;
@dynamic image;
@dynamic number;
@dynamic group;

@end

po 0x4d5eeb0 gets me:
<People: 0x5932290> (entity: People; id: 0x59322f0 <x-coredata:///People/t83A9C7D9-4F7A-4189-9EC5-7695968A29552> ; data: {
    group = nil;
    name = Paul;

A: Printing the object in the debugger should give you all the properties defined in the class regardless of whether it is a NSManagedObject subclass held by a context or just a plain vanilla custom class. The debugger printout is not only missing the number property but the image one as well.
Really, the only way that could happen was if you didn't have the new version of the class file added to the target but were actually using the old version that lacked the new properties.
Check the target for the old files and/or check that the new version has been properly added to the build target.

A: Try naming the number attribute something different, such as theNumber. There are several known reserved words in Core Data attributes, and an unknown number (no pun intended) which are not documented - you may have stumbled onto another one.

A: When in doubt, delete it out.
I ended up deleting my two xcdatamodel files and the xcdatamodeld file. Also deleted them in their respective folders. Then I created a new one. Had some issues at first but it actually works now.
I have a little issue with xcode thinking that my Group.h file doesn't have an addPeople method, which it does. So it says that it may not respond to that method, or any of its other methods. It also throws me a Lexical or Preprocessor Issue: 'Group.h' file not found error at build-time, but everything seems to still work.
I still have no idea what was going on. Thanks to everyone for their suggestions.


Q: What are good linux programming environments for windows? Especially for Rails, I've found that development on Linux is generally a lot nicer than on Windows. However, I still prefer Windows as my main OS.
So far I've tried 2 options.
Dual-Booting with Ubuntu: The problem with this is I don't like having to reboot just to use Ubuntu, like if someone just asked me a quick question about a project.
Virtualizing Ubuntu with VirtualBox: This is pretty damn slow and freezes up at times, even if I'm doing basic stuff like text editing.
Basically, I'm looking for something that doesn't need to be full-featured, but where I can fetch repository packages that I need such as programming libraries. I was thinking maybe there's a Linux distro that's less demanding than Ubuntu that I can use, or some way to run a decent Linux within Windows without virtualizing. Any suggestions?

A: Did you consider using Cygwin? I didn't test this myself but there are several resources mentioning this combo:

*

*Get Cygwin => Rails Wiki

*Setting up Rails on Windows with Cygwin

*Ruby on Rails Development in Windows via Cygwin

*Rails Development and Cygwin on Windows XP

A: Have a look at what cygwin can offer you for a Linux- like experience on Windows.
Or: virtualize Windows (tm) inside Linux.

A: If you want Linux on Windows without virtualization, that sounds like coLinux to me.

A: You can install Ubuntu using a windows installer using Wubi. The result is a standard dual boot setup, but with a simplified method for installing ubuntu if you already have windows pre-existing on your machine. Switching between windows and ubuntu requires a reboot.

A: Perhaps you need to upgrade your PC. Ubuntu+text editing shouldn't be a problem for VirtualBox or VMWare.
However, if you want a resource-lite distro, try Arch Linux + Xfce desktop.

A: I'd try to find another PC to put Ubuntu on. A relatively older one should run it fine.
You can join them together and share the keyboard/mouse with win2vnc or x2vnc.

A: You may be able to tweak VirtualBox to speed it up significantly. If you have a recent CPU, you can enable VT-x (Intel) or AMD-V, and possibly also nested paging. If your processor supports both of these, you should see a significant speed increase. As mentioned by others, you could always try making linux less demanding - use a lighter window manager, or use a distro like DSL or Puppy linux.

A: I've found virtualizing Windows XP pretty sluggish with a full dev environment running, but maybe that's just because I do that for Flex development which requires Flex Builder which almost instantly consumes all of my VM's allocated RAM. Virtualization is really demanding on your hardware, my next build is going to have 16GB of RAM so that I can virtualize in peace.
I think it would be faster to run a minimal Linux distro like Arch in VirtualBox and use that for running the servers and things like the console commands that generate your skeletons. I use git for all my source control and just push and pull from a remote repo to share code between my VMs, it's just easier that way than setting up something special.
Good luck. I think this approach is much more reliable and straightforward than cygwin or other POSIX implementations on Windows; it generally takes significant fiddling to get those things to work correctly for more than a couple of applications, and I assume if you're going to be running a server you'll have some issues with it.

A: Boxes are cheap, especially something to run Linux on. I have a wimpy little garage server that has only 256MB on it and it runs Ubuntu 9.04 server just fine. You can always network the filesystem so you can use whatever on your Win box to edit, but when you run the code, you are actually running in a Linux environment, no games, no compromises.
Once you've taken the plunge (please return it by Tuesday) you'll find that Linux is far more interesting as a server environment. You can try out nginx, or play around with iptables, or ... The point is, just get a separate Linux box and all of the problems are "solved." And you will be building marketable skills in the process.

A: Try VMWare player. It's free and really nice. You can drag and drop between your windows environment and Linux. It's quite easy to use aswell. I'm running Ubuntu and OpenSUSE on top of my Windows XP.

A: Download and run the POSIX subsystem for Windows. It's kinda like Linux.

A: You could stick with Ubuntu in a VM (keep the benefits of broad community support etc.) and try a less demanding windowing environment than Gnome or KDE.  Wmii and awesome are, from what I've heard, pretty good.  (edit) Forgot about Fluxbox, there's an intro to using it on Ubuntu here.

A: If you're just looking for a "linux-like" development environment, MSYS provides a bash shell and a good handful of development tools that run natively in Windows.  Combined with MinGW, lets you compile and install plenty of open source packages.
Alternatively, Cygwin provides an emulation layer which lets you compile and run most linux programs.  A bit slower than the native Windows programs you get with MSYS, but better selection of libraries/software that have don't have good Windows ports yet.

A: Why not just develop in windows. Most of the standard opend source tooling Apache, perl, php, ruby, sqlite, Mysql, vim, Eclipse etc. etc. come nicely packed as windows ".exe" install files (in may cases much more nicely packaged!).
The only real pain is occasionally you may have to write a ".bat" file which I thought was pretty awful attempt at a shell for an 8 bit machine and has not improved one bit in the last 20 years.

A: I personally can get by with msysgit, which is a fork of msys, which is a fork of cygwin. Depending on what exactly you need I'd say one of those. it's unfortunate that I've noted incompatibilities between msys and msysgit. I'm not sure if there's a binary incompatibility  with mingw and msysgit, but in theory they should work together so I would go with that. Given it doesn't have a package manager... but is enough unix for me on windows... depending on what you really want/need. Otherwise go with a virtualization product.

A: I recommend using Lubuntu http://lubuntu.net/ instead of Ubuntu when running Ubuntu in a VM environment.
I also do not like the speed of normal Ubuntu. Lubuntu is faster especially in a VM. It also just needs about 256MB of RAM to run good.
Only downside: There are no long term releases of Lubuntu. That means you need to upgrade Lubuntu maybe once/twice a year (which is easy with Ubuntu based systems).


Q: How can I calculate the difference between 2 numbers How can I calculate the diffrence between 2 Numbers in % in c? I have written my own exp funktion and want to compare it with the original one from the math.h.
this is my exp funktion and I want to compare the result with the exp() from math.h and print the difference in percent.
double expo(double zahl)
{
    int schleifendurchlaeufe = 1;
    double exp = 1;//Variable in der das Ergebnis steht
    double sum = 1;//Summant, der auf exp raufaddiert wird

    do
    {
        sum = sum * (zahl / schleifendurchlaeufe);
        exp = exp + sum;
        schleifendurchlaeufe++;
    } while (exp != exp + sum);

    return exp;
}

A: "difference between 2 Numbers in %" sounds strange, perhaps you want percentage difference (see explanation at https://www.mathsisfun.com/percentage-difference.html)
For case of comprising only results of exp function (two positive values) you can use the following function:
double percdiffcalc(double a, double b)
{
    double difference = abs(a - b);
    double average = (a + b) / 2.0;
    return difference * 100.0 / average;
}

You can call this function for any two values, e.g. percdiffcalc(myexp(x), exp(x));


Q: PHP ChromeDriver, multiple instances How to run multiple threads with multiple instances of chrome, is it possible? probably there is possibiity to operate via custom port?


Q: Shell Script for Flip Canvas Vertical I have M1.jpg M2.jpg ....... M100.jpg in /Users/KanZ/Desktop/Project/Test/
I would like Flip Canvas Vertical them, save and replace them instead of old files. How can I write the script for this problem?

A: You can do that with convert, with a little help from find so you don't have to write a loop:
find /Users/KanZ/Desktop/Project/Test/ -type f -name "M*.jpg" -exec convert {} -flip {} \;

Explanation:

*

*find /Users/KanZ/Desktop/Project/Test/ - Invoke find tool and specify the base directory to perform the search for files recursively.

*-type f - Find only files

*-name "M*.jpg" - Find only files with names that start with M and end with .jpg

*-exec ... \; - For each such file found, perform the command in ...

*convert {} -flip {} - This is the actual command that flips your images. The {}'s are syntax as part of the find command, they represent where the found files from find would be substituted into. So here we are saying to use convert to flip the images vertically with the -flip option, but keep the file names unchanged.

Alternatively:
You can also do it with a loop and globbing:
for file in /Users/KanZ/Desktop/Project/Test/M*.jpg; do convert "$file" -flip "$file"; done


Q: Multi-dialog program in PyQT will not close For my project, I require multiple dialogs to be linked to each other.  One button would go to one level, another button would go back two levels.  To get a basic idea of what I'm looking for without showing all my code, here is a compilable example:
'''
Created on 2010-06-18

@author: dhatt
'''

import sys
from PyQt4 import QtGui, QtCore

class WindowLV3(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 120, 150)
        self.setWindowTitle('LV3')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))  # this will close entire program

class WindowLV2(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.Window3 = WindowLV3()

        self.setGeometry(300, 300, 120, 150)
        self.setWindowTitle('LV2')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        next = QtGui.QPushButton('Lv3', self)
        next.setGeometry(10, 50, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('reject()'))  # this doesn't work

        self.connect(next, QtCore.SIGNAL('clicked()'),
            self.nextWindow)

    def nextWindow(self):
        self.Window3.show()

class WindowLV1(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.Window2 = WindowLV2()

        self.setGeometry(300, 300, 120, 150)
        self.setWindowTitle('LV1')

        next = QtGui.QPushButton('Lv2', self)
        next.setGeometry(10, 50, 60, 35)

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(next, QtCore.SIGNAL('clicked()'),
            self.nextWindow)

    def nextWindow(self):
        self.Window2.show()

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('reject()'))  # this doesn't work

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    Window1 = WindowLV1()
    Window1.show()
    sys.exit(app.exec_())

The problem is that I cannot close from a window and show the previous window. For instance, if I clicked on the 'CLOSE' button inside from a LV3 window, it will transfer control back to a LV2 window.  I can call QtCore.SLOT('quit()')), but it will shut down the entire program, and I don't want that.
What am I doing wrong here?

A: there are two things that need to be addressed here.

*

*You can simply call QDialog.close in the connect method.

*In def nextWindow(self): you are trying to connect a local variable quit. So it won't work. You need to define quit as an instance variable (self.quit)
self.connect(self.quit, QtCore.SIGNAL('clicked()'),
                self.close)  # this should work
Here is the modified code:
import sys
from PyQt4 import QtGui, QtCore

class WindowLV3(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 120, 150)
        self.setWindowTitle('LV3')

        self.quit = QtGui.QPushButton('Close', self)
        self.quit.setGeometry(10, 10, 60, 35)

        self.connect(self.quit, QtCore.SIGNAL('clicked()'),
            self.close)  # this will close entire program

class WindowLV2(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.Window3 = WindowLV3()

        self.setGeometry(300, 300, 120, 150)
        self.setWindowTitle('LV2')

        self.quit = QtGui.QPushButton('Close', self)
        self.quit.setGeometry(10, 10, 60, 35)

        next = QtGui.QPushButton('Lv3', self)
        next.setGeometry(10, 50, 60, 35)

        self.connect(self.quit, QtCore.SIGNAL('clicked()'),
            self.close)  # this should work

        self.connect(next, QtCore.SIGNAL('clicked()'),
            self.nextWindow)

    def nextWindow(self):
        self.Window3.show()

class WindowLV1(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.Window2 = WindowLV2()

        self.setGeometry(300, 300, 120, 150)
        self.setWindowTitle('LV1')

        next = QtGui.QPushButton('Lv2', self)
        next.setGeometry(10, 50, 60, 35)

        self.quit = QtGui.QPushButton('Close', self)
        self.quit.setGeometry(10, 10, 60, 35)

        self.connect(next, QtCore.SIGNAL('clicked()'),
            self.nextWindow)

    def nextWindow(self):
        self.Window2.show()

        self.connect(self.quit, QtCore.SIGNAL('clicked()'),
            self.close)  # this should work

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    Window1 = WindowLV1()
    Window1.show()
    sys.exit(app.exec_())


Q: gstreamer: gst/app/gstappsrc.h no such file or directory I have installed gstreamer1.0-plugins-base use command:
$ sudo apt-get install gstreamer1.0-plugins-base

but when I compile my code, it still gives me an error

gst/app/gstappsrc.h: no such file or directory

And I even can't find the directory /app at the directory /usr/include/gstremer1.0/gst

A: You will need the development header files. The package is probably named libgstreamer-plugins-base1.0-dev or close to that.

A: You need the include (headers) and link (libs) directories for gstreamer-app-1.0, part of the gstreamer base-plugins.
If you are using pkg-config, try the following command to get all the compilation flags you need:
pkg-config --cflags --libs gstreamer-app-1.0

In case of CMake with pkg-config:
# pkg-config
find_package(PkgConfig)
pkg_check_modules(GSTREAMER REQUIRED gstreamer-1.0)
pkg_check_modules(GSTREAMER_APP REQUIRED gstreamer-app-1.0)

# including header files directories
include_directories(
  ${GSTREAMER_INCLUDE_DIRS}
  ${GSTREAMER_APP_INCLUDE_DIRS}
)

# linking library directories
link_directories(
  ${GSTREAMER_LIBRARY_DIRS}
  ${GSTREAMER_APP_LIBRARY_DIRS}
)

# linking gstreamer library with target executable
target_link_libraries(${PROJECT_NAME} ${GSTREAMER_LIBRARIES})
target_link_libraries(${PROJECT_NAME} ${GSTREAMER_APP_LIBRARIES})


Q: critical point, increasing/decreasing function and local extremum If $f ' (x) =(x-1)^2 (x+2)$ is given and we're asked to find the 3 things in the title:
for critical points we put $f ' (x)=0$ and the values of x we get are critical points
for increasing/decreasing functions we will divide intervals according to critical point and take a test point to see sign of x and thus conclude if it's increasing or decreasing
for local extremums we can use second derivative test?
Are these three approaches correct or am i doing anything wrong?

A: Some corrections, for technical correctness:

for critical points we put $f ' (x)=0$

*

*Critical points are where $f'(x)$

*

*either doesn't exist $(y=|x|$ at $0)$

*or equals $0.$

for local extremums we can use second derivative test

*For local extrema that are stationary turning points, the sign test is one alternative (among others) to the second-derivative test.

*But a local extremum might also be

*

*a non-stationary turning point $(y=|x|$ at $0),$ or

*a stationary non-turning point $(y=3$ at $0),$ or

*neither stationary nor turning $(y=\sqrt x$ at $0)$ !

A: If you are going to divide the interval according to whether $f$ is increasing/decreasing anyway, then you don't need the second derivative test. Just look at the monotonicity of $f$ near its critical points to decide local extremums.
In your example, $x=-2$ is a critical point of $f$. Note that $f'(x) < 0$ for $x < -2$ and $f'(x) > 0$ for $-2 < x < 1$. This means $f$ is strictly decreasing on the left of $x=-2$ and strictly increasing on the right of $x=-2$. Thus, $x=-2$ is a strict local minimum of $f$.
You can do a similar analysis for another critical point $x=1$.

A: Yes, you are right!
The first derivative test uses the derivatives of a function to locate the critical points of a function. To calculate the critical points we need to solve the equation $f^{'}(x)=0$. The computed values of the parameter $x$ will be critical.
The second-derivative test uses the value of the second derivative at those points to determine whether such points are a local maximum or a local minimum. If the function f is twice-differentiable at a critical point x (i.e. a point where $f^{'}(x)=0$), then:

*

*If $f^{''}(x)<0$, then f has a local maximum at x.

*If $f^{''}(x)>0$, then f has a local minimum at x.

*If $f^{''}(x)=0$, the test is inconclusive.
Good luck!


Q: Window owner in WPF without always-on-top behaviour Is it possible to get some of the functionality of Window.Owner without getting all of it?
There are two windows, window A and window B.  I want to make it so that selecting either one will bring them on top of other applications, but either one can overlay the other.  (In reality there more than just two, but they should all behave similarly.)
If I set window B's Owner to A, then switching to either window will bring both in front of other applications (which I want), but will also force B to always sit on top of A (which I don't want).
I actually already have code which is tracking the window hierarchy independently of Owner/OwnedWindows, so I can probably extend that to sort out the activation problem.  So if that simplifies the problem, an alternative answer I'm looking for is:
How do I actually do "when this window is activated by the user, bring a specific set of windows (all the others in the app) to the Z-order just below me, while preserving their existing Z-orders relative to each other"?

A: One possible solution would be to have a hidden window that owns all the windows in your app.
You would declare it something like:
<Window
    Opacity="0"
    ShowInTaskbar="False"
    AllowsTransparency="true"
    WindowStyle="None">

Be sure to remove StartupUri from your App.xaml. And in your App.xaml.cs you would override  OnStartup to look something like:
protected override void OnStartup(StartupEventArgs e)
{
    HiddenMainWindow window = new HiddenMainWindow();
    window.Show();

    Window1 one = new Window1();
    one.Owner = window;
    one.Show();

    Window2 two = new Window2();
    two.Owner = window;
    two.Show();
}

Another difficulty will be how you want to handle closing the actual application. If one of these windows is considered the MainWindow you can just change the application ShutdownMode to ShutdownMode.OnMainWindowClose and then set the MainWindow property to either of those windows. Otherwise you will need to determine when all windows are closed and call Shutdown explicitly.


Q: Adding a custom domain in PythonAnywhere does not work I added my application to pythonanywhere, now I'm trying to add a custom domain but I can not get a positive result.
My change I've added in pythonanywhere looks like this. Under my hidden field is my domain name.

According to the documentation, I added a CNAME record (at my domain provider, it looks like this.).

But after entering in the address www.ka ....pl I am not being redirected to my django application in pythonanywhere.
This is my first time when i added my domain, how to fix this error (so that my application will appear after entering the domain), any help will be appreciated.

A: When setting up your CNAME, you need to end its value with a dot. to be absolute
CNAME: webapp-*****.pythonanywhere.com.

Otherwise it will be relative to your custom domain and end up like this :
webapp-*****.pythonanywhere.com.$DOMAIN

See Domain names with dots at the end


Q: Cannot read property of undefined angular2 ngif I am now able to get the object in the view however I cannot run an if statement.  Per previous answer this is how I am bringing in the object.
public getPosts$(category, limit) {
  return this.cartService.getPosts(category, limit).map(response => {
    return response && response.data && response.data.children;
  };
}

ngOnInit() {
  this.getPosts$(this.category, this.limit).subscribe(cart => {
    this.cart = cart;
  }
}

I am trying to run but get cannot get property vegetable.

{{cart.vegetable}}

{{cart.vegetable}}

The error is

Cannot read property 'vegtable' of undefined

A: The cart object is null until the service getPosts$ returns (callback). Therefore, the code *ngIf="cart.vegetable ... is equal to *ngIf="null.vegetable ... until that happens. That is what is happening.
What you could do is put a DOM element with *ngIf="cart" containing the other *ngIf. For example:

{{cart.vegetable}}

*Edit: As it is said in the next answer, a good alternative (and good practice) is the following:

{{cart.vegetable}}

A: Use the safe-navigation operator to guard against null or undefined for async fetched data:

{{cart.vegetable}}

A: I used {{ }} while they are not needed. Getting rid of them fixed it for me.
So this

Should be


Q: How can I close dropdown if another dropdown is open I have some dynamic contents like sort of a news-feed and each element has a dropdown menu.
I am able to toggle the dropdown-menu of the exact element I click on and when I click outside or anywhere else on the window it closes the menu which is nice.
but problem arise when I click on another dropdown element. The previously clicked menu doesn't close instead it stays on the same page.
what I am trying to say is
when I click multiple dropdown elements, I have them all showing,
it only closes or disappears when I click outside of element.
For instance
When I click on dropdown-1, then click on dropdown-2, they both display at the same window. How do I close dropdown 1 while dropdown 2 is open instead of having them both open.
How can I toggle each dropdown as I click. I am unable to attach video to this post, but I have added an image to help clarify my question.

This is an example of my JQuery code to toggle dropdown.
/* toggle dropdown options */
$(document).on("click", ".dropdown-toggle", function (e) {
 e.stopPropagation();
 $(this).siblings().toggleClass('show');
});

/* // Close the dropdown if the user clicks outside of it */
$(window).click(function (e) {
 if (!e.target.matches('.dropbtn') ) {
    var dropdowns = $('.dropdown-content');
    var i;
    for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if ($(openDropdown).hasClass("show") ) {
            $(openDropdown).removeClass("show");
        }
    }
 }

});

A: I have been able to solve this problem.
what I did was to hide all divs that may be visible then toggle the dropdown I clicked to show its content.
$(document).on("click", ".dropdown-toggle", function (e) {
        e.stopPropagation();

        // hide all dropdown that may be visible
        var i;
        var dropdowns = $('.dropdown-content');
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if ($(openDropdown).hasClass("show")) {
                $(openDropdown).removeClass("show");
            }
        }

        // toggle the dropdown
        $(this).siblings().toggleClass('show');
    });


Q: Javascript global variable not updating outside any functions I'm trying to get the following code to work (the console.log are just to see what's going on). I've declared the global variables outside of any functions, but it only seems to be updating them inside functions.
<script type="text/javascript">

var map;
var geocoder;
var address;

function initialize(){
    geocoder = new google.maps.Geocoder();

    var mapOptions = {
        center:new google.maps.LatLng(-76.146294, 43.052081),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 15,
        streetViewControl: false
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    loadAddress();
    console.log("initialize function: " + address); //this correctly returns the updated address
}

function loadAddress(){
    var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
    var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
    address = property + "," + zipCode;
    geocoder.geocode({'address': address}, function(result, status){
        if(status === "OK"){
            map.setCenter(result[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: result[0].geometry.location
            });
        }
        else {
            alert("Failed to geocode: " + status);
        }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

The above works fine - the 'address' variable updates properly, and when I log it to the console at the end of the initialize() function, it displays properly. The problem is if I try to log that same variable to the console further down the page:
<script type="text/javascript">
console.log("further down page: " + address); //this comes back as 'undefined'
</script>

When I try to do that, I just get 'undefined'. I'm pretty new to javascript, but my understanding was that if the variable is declared outside of any functions, it is a global variable, and it should be accessible anywhere. I feel like I'm missing something pretty obvious, but I don't know what (and I've spent quite a bit of time searching!).
My hunch is that it has to do with the initialize() not being called until after the page loads, but 'address' is trying to be logged before the page has finished loading. If that's the issue, I don't know how to fix it.
Also, I'm sure the above code is not the best way to do things, but this is really more of a learning experience. Thanks!

A: The problem is that the geocoder.geocode function is asynchronous : it doesn't block the code, the following lines are executed, but the inner callback isn't called until the server responds.
This means that you must put your console.log line inside the callback or in a function called from the callback :
geocoder.geocode({'address': address}, function(result, status){
    if(status === "OK"){
        map.setCenter(result[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: result[0].geometry.location
        });
    } else {
        alert("Failed to geocode: " + status);
    }
    otherFunc();
});

function otherFunc(){
    console.log("further down page: " + address);
}

A: Your hunch is correct.  The code further down the page is executing in place before your initialize method is called.  window.load is not fired until the DOM is loaded, including images:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

A simple fix here would be to define address right away.  Its components are static on the page, there's no reason to have that happen inside the function.
    var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
    var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
    var address = property + "," + zipCode;

    function loadAddress() {
      // ...
    }

A: The problem is that the second <script>-element is executed right away when the browser loads the page. In your first block you add the DOM-listener for the load-event, which should call initialize(). However, that is executed later when the browser has fully loaded and built the page.
If you log the value after it has been determined in the callback to geocoder.geocode() it should print the proper value.


Q: Navicat 8/9 crashes my Debian/Linux I run Debian 5 + Gnome and it seems that after I made certain updates with aptitude, whenever I run a query in Navicat ( sql program that runs on WINE ), as the results are being presented linux goes into the command line and the GUI dies and it restarts and it asks me to login again ( all my programs crash ).
Has anyone experienced this before? Or does anyone have a clue as to how I could go about debugging this? I suspect it's some issue with Gnome and WINE, but I'm not sure.

A: I'd try reinstalling wine. It could be some navicat configuration files stored in wine, navicat does seem particularly temperamental. Are you running the windows version under your own wine install or is it the one that's been packaged by them? If you need a fresh copy I could email one over.


Q: Query MYSQL - mysql query distinct count I have the following table:
ID_PERSON   NAME_PERSON
001         JHON SLAVE
002         BRUCE WILLIAN
001         PAUL BYLING

I would like to know, for example, how many cases the ID_PERSON 001 is linked to different names (distinctly)
My current query:
SELECT ID_PERSON, COUNT(DISTINCT(NAME_PERSON))
GROUP BY ID_PERSON
HAVING COUNT(DISTINCT(NAME_PERSON)>1

The output I expect are 2 records: 001 from Jhon and 001 from Paul
As my table has millions of records, it is not performing

A: SELECT t1.*
FROM src_table t1
JOIN ( SELECT ID_PERSON
       FROM src_table t2
       GROUP BY ID_PERSON
       HAVING COUNT(DISTINCT(NAME_PERSON) > 1 ) t3 USING (ID_PERSON)

SELECT *
FROM src_table t1
WHERE EXISTS ( SELECT NULL
               FROM src_table t2
               WHERE t1.ID_PERSON = t2.ID_PERSON
                 AND t1.NAME_PERSON <> t2.NAME_PERSON )

There are more variants.


Q: Sniffing content of web pages in a network - experiment I want to sniff the web content. Don't worry, no vicious intentions, it is an experiment : )
So the scenario is: I have my host machine, and multiple guest virtual machines running on it. All VMs go to random URLs. I would like to sniff and store the content that the VMs access (I am interested in capturing raw HTML, I would like to skip images, video streams etc.)
One solution would be to setup a sniffer on my host machine (like tcpdump) and later process what is captured. The inconvenience here is that I would need to work on raw .pcap dumps :(
Other solution would be to setup a proxy server and configure it in the way that the content is dumped to a file... but I am no expert in proxies. Can it be done with, e.g., squid?
Any other ideas?


Q: Get consecutive nodes with following-sibling and condition My XML file looks like this, but bigger:
<w><forme>la</forme><lemme>le</lemme><categorie>DETDFS</categorie></w>
<w><forme>grande</forme><lemme>grand</lemme><categorie>ADJFS</categorie></w>
<w><forme>douleur</forme><lemme>douleur</lemme><categorie>NCFS</categorie></w>
<w><forme>du</forme><lemme>du</lemme><categorie>DETDMS</categorie></w>
<w><forme>père</forme><lemme>père</lemme><categorie>NCMS</categorie></w>
<w><forme>duchesne</forme><lemme>duchesne</lemme><categorie>NCMS</categorie></w>
<w><forme>exemple.</forme><lemme>exemple.</lemme><categorie>NCMS</categorie></w>
<!-- ... -->

I would like to get every <w> node recursively to get words to create sentences with.
For example, the final word here is "exemple.". So I would like to get every <forme> until .
to generate a sentence.
For now I can only match the node with the full stop. I don't know how to select the first <w> node (first word of the sentence) until the last <w> node (final word).
following-sibling::w[contains(forme, '.')][1]

My goal is to select every <w> node (or <forme>) until the word with the full stop, and recursively.
I started to write a template to concatenate strings:
<xsl:template name="concat">
  <xsl:param name="liste" />
  <xsl:param name="result" select="''"/>
    <xsl:choose>
      <xsl:when test="$liste">
        <xsl:call-template name="concat">
          <xsl:with-param name="liste" select="$liste[position() > 1]" />
          <xsl:with-param name="result" select="concat($result, ' ', $liste[1])" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$result" disable-output-escaping="no" />
      </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Thx for the help. It's very important.

A: One approach would be to use an <xsl:key> in the following way.
Keys let you index nodes by a certain property, for example you could index all nodes by some attribute value. But you could also index them by a calculated value.
In your case you have many <w> nodes like this:
<doc>                                                                              <!-- Sentence # -->
  <w><forme>le</forme><lemme>le</lemme><categorie>DETDFS</categorie></w>           <!-- 0 -->
  <w><forme>grand</forme><lemme>grand</lemme><categorie>ADJFS</categorie></w>      <!-- 0 -->
  <w><forme>test.</forme><lemme>test.</lemme><categorie>NCMS</categorie></w>       <!-- 0 -->
  <w><forme>la</forme><lemme>le</lemme><categorie>DETDFS</categorie></w>           <!-- 1 -->
  <w><forme>grande</forme><lemme>grand</lemme><categorie>ADJFS</categorie></w>     <!-- 1 -->
  <w><forme>douleur</forme><lemme>douleur</lemme><categorie>NCFS</categorie></w>   <!-- 1 -->
  <w><forme>du</forme><lemme>du</lemme><categorie>DETDMS</categorie></w>           <!-- 1 -->
  <w><forme>père</forme><lemme>père</lemme><categorie>NCMS</categorie></w>         <!-- 1 -->
  <w><forme>duchesne</forme><lemme>duchesne</lemme><categorie>NCMS</categorie></w> <!-- 1 -->
  <w><forme>exemple.</forme><lemme>exemple.</lemme><categorie>NCMS</categorie></w> <!-- 1 -->
  <w><forme>phrase</forme><lemme>phrase</lemme><categorie>NCMS</categorie></w>     <!-- 2 -->
  <w><forme>suivante</forme><lemme>suivante</lemme><categorie>NCMS</categorie></w> <!-- 2 -->
</doc>

The ones with the full stop demarcate a sentence end. The preceding siblings up to the previous full stop are words of the same sentence.
We could say: "All words belong to the same sentence that are preceded by the same number of full stops."
The numbers in the comments above represent exactly that number. We can calculate it with count(preceding-sibling::w[substring(forme, string-length(forme), 1) = '.']). And we can create an <xsl:key> that indexes <w> nodes by this number.
And then it's a matter of going over each node that marks a sentence end and using key() to retrieve all the <w> nodes that belong to the same sentence:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes" />

  <xsl:key
    name="kSentence"
    match="w"
    use="count(preceding-sibling::w[substring(forme, string-length(forme), 1) = '.'])"
  />

  <xsl:template match="/*">
    <sentences>
      <xsl:for-each select="w[substring(forme, string-length(forme), 1) = '.']">
        <xsl:variable
          name="sentenceNum"
          select="count(preceding-sibling::w[substring(forme, string-length(forme), 1) = '.'])"
        />
        <sentence>
          <xsl:copy-of select="key('kSentence', $sentenceNum)/lemme" />
        </sentence>
      </xsl:for-each>
    </sentences>
  </xsl:template>
</xsl:stylesheet>

gives this result:
<sentences>
  <sentence>
    <lemme>le</lemme>
    <lemme>grand</lemme>
    <lemme>test.</lemme>
  </sentence>
  <sentence>
    <lemme>le</lemme>
    <lemme>grand</lemme>
    <lemme>douleur</lemme>
    <lemme>du</lemme>
    <lemme>père</lemme>
    <lemme>duchesne</lemme>
    <lemme>exemple.</lemme>
  </sentence>
</sentences>

The "phrase suivante" is not part of the result because it did not end with a full stop in my example.

A: Either use classical sibling recursion where you in the template matching the parent/container node of the w siblings start with <xsl:apply-templates select="w[1]"/> and then process <xsl:apply-templates select="following-sibling::w[1]"><xsl:with-param name="previous-ws" select="$previous-ws | ."/></xsl:apply-templates/> and have two template matches for e.g. <xsl:template match="w[not(substring(forme, string-length(forme)) = '.')]"> and <xsl:template match="w[substring(forme, string-length(forme)) = '.']"> or use a key <xsl:key name="siblings" match="w[not(substring(forme, string-length(forme)) = '.')]" use="generate-id(following-sibling::w[substring(forme, string-length(forme)) = '.'][1])"/>, then process all <xsl:apply-templates select="w[substring(forme, string-length(forme)) = '.']"/> and in the template matching w you can collect the preceding siblings simply with key('siblings', generate-id()).

A: This is very simple to do in XSLT 2.0 using xsl:fer each group with group-ending-with.
There are several methods to accomplish the same thing in XSLT 1.0 - among them "sibling recursion" or using a key to link each word to its nearest following sibling that ends with a period (both of these have been mentioned by Martin Honnen in his answer above).
The method you have attempted, using a recursive named template, is also an option. Here is a simplified example:
XML
<root>
    <word>Joe</word>
    <word>waited</word>
    <word>for</word>
    <word>train.</word>
    <word>The</word>
    <word>train</word>
    <word>was</word>
    <word>late.</word>
    <word>Mary</word>
    <word>and</word>
    <word>Samantha</word>
    <word>took</word>
    <word>the</word>
    <word>bus.</word>
    <word>Orphan</word>
</root>

XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/root">
    <output>
        <xsl:call-template name="combine-words">
            <xsl:with-param name="words" select="word"/>
        </xsl:call-template>
    </output>
</xsl:template>

<xsl:template name="combine-words">
    <xsl:param name="words" />
    <xsl:param name="accumulated" select="/.."/>
    <xsl:if test="$words">
        <xsl:variable name="word" select="$words[1]" />
        <xsl:variable name="isLast" select="substring($word, string-length($word), 1)='.'" />
        <xsl:if test="$isLast">
            <sentence>
                <xsl:for-each select="$accumulated | $word">
                    <xsl:value-of select="." />
                    <xsl:if test="position()!=last()">
                        <xsl:text> </xsl:text>
                    </xsl:if>
                </xsl:for-each>
            </sentence>
        </xsl:if>
        <xsl:call-template name="combine-words">
            <xsl:with-param name="words" select="$words[position() > 1]"/>
            <xsl:with-param name="accumulated" select="$accumulated[not($isLast)] | $word[not($isLast)]"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

Result
<?xml version="1.0" encoding="UTF-8"?>
<output>
   <sentence>Joe waited for train.</sentence>
   <sentence>The train was late.</sentence>
   <sentence>Mary and Samantha took the bus.</sentence>
</output>


Q: can we write that function in c form When I read some question to write random nuber generator ,I saw that function and it
efficient but it is written in C#. I want see that function in form of c
language,can anyone help?
IEnumerable<int> ForLargeQuantityAndRange(int quantity, int range)
{
    for (int n = 0; n < quantity; n++)
    {
        int r = Random(range);

        while (!used.Add(r))
            r = Random(range);

        yield return r;
    }
}

A: Questions regarding number generators for C have been asked before here on SO, such as in the article "Create Random Number Sequence with No Repeats".
I'd suggest looking at the above article to see if anything is suitable and provides a useful alternative to the standard rand() function in C, assuming that you've already looked at the latter and rejected it.

A: This is not quite a function, as function in C or C++. This is a co-routine, which may be resumed.
To implement it in C, you will need to maintain external state, and provide a "next value" func.
The advantage of this function is that it guarantees unique values. Do you really need it? If not, use stdlib's rand, multiplied by proper factors.

A: Do you just want random numbers? If so, why don't you use one of the many libraries out there that can do it for you in a cross platform fashion? Here's one.

A: To write a co-routine in C, you need to maintain state.  This simplest way to do this is to use a static variable.  For this example, it would look something like:
int ForLargeQuantityAndRange(int init_quantity, int init_range)
{
    static int n;
    static int quantity, range;

    if (init_quantity > 0)
    {
        n = 0;
        quantity = init_quantity;
        range = init_range;
    }

    if (n++ < quantity)
    {
        int r = Random(range);

        while (!used_add(r))
            r = Random(range);

        return r;
    }

    /* Quantity exceeded */
    return -1;
}

...where you would call it with (quantity, range) to intialise a new sequence, and (0, 0) to continue the previous sequence.
Note that you will have to supply implementations of the Random() and used_add() functions.


Q: RecyclerView - How to select items by dpad/keyboard How can you select items of a RecyclerView using the dpad and/or keyboard?

A: Make your items focusable. It will let you navigate it via dpad. Then you'll need to add your logic to "select" focused item on press. (whatever your select key is)


Q: How to get openCL library for Hi3536 Mali GPU We are using Hi3536 Soc, which has Mali T720 core. The SDK of Hi3536 does not provide examples for OpenCL nor the library. Any suggestions how to get the cross-compiled SDK libraries for Mali T720?


Q: Difference between downscaling 1080p to 720p in real time and downscaling during encoding? Suppose a high quality, uncompressed video is re-encoded twice, with almost identical encoding settings at a relatively low bitrate of 4mbps, but at different resolutions, first at 1080p, and then at 720p.
So we now have two videos: One is 1080p and the other one is 720p. Both have identical bitrates.
I know that 4mbps is considered a low bitrate for 1080p, and the video will look bad on a full-HD display due to the compression artifacts.
However, during playback on a 720p display, the 1080p video will obviously be downscaled to 720p.
My question is: On the 720p display, will the 1080p video (which is being downscaled to 720p in real time during playback) look as good as the 720p video (which has the same bitrate)? Or will the 720p video (which was downscaled from 1080p to 720p by the encoder) look better? Or will both of them look the same?
I would run some tests to see this for myself, but my system isn't powerful enough for 1080p encoding. I'm looking for some expert views on this.

A: When I stream at 720p have my game running at 3820x2160 and the playback is definetly noticeably better on the playback than if I was playing the game a 1920x1080p while streaming 720p.


Q: LINQ two Where clauses does anybody know how I can chain my where clauses?
I would like to filter the items in my main list by the items found in the second result.
I have the following example code
@foreach (var artikel in Controller.Artikel
    .Where(x => x.LieferantenArtikel
                .Where(y => y.Lieferant.LieferantId == bestellung.LieferantId)
)
{
    <option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}

The first .Where is just to access the list of my object, which has the real check I need.

A: Your way of chaining .Where() into .Where() is technically correct. The problem is that the outer .Where() under the current situation does not evaluate to boolean. However, that's a requirement. The purpose of a .Where() is to define a filter for a collection that results in a subset of that collection. You can check whether .Any() item fulfills that condition:
@foreach (var artikel in Controller.Artikel
    .Where(x => x.LieferantenArtikel
                .Any(y => y.Lieferant.LieferantId == bestellung.LieferantId))
)
{
    <option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}

.

A: To add a bit more context to the other answers, which hopefully helps you to understand how to efficiently use LINQ:
What you tried to program using .Where() is technically "where exists". Translated into LINQ naively, that would be
Controller.Artikel
    .Where(x =>
        x.LieferantenArtikel
            .Where(y => y.Lieferant.LieferantId == bestellung.LieferantId)
            .Count() > 0 // naive "exists", but bad; for reasons see below
    )

.Count() > 0 however is very inefficient, since this would require the execution of .Count() to evaluate the statement, which in turn requires to determine the accurate result set.
This is where .Any() steps in: it only determines if there is at least one element in the IEnumerable by checking them and immediately returning true when the first item matches. So only if there is no match, all items of "LieferantenArtikel" have to be enumerated and checked, otherwise a smaller subset will do.

A: I find non-nested LINQs to be much more readable. Flatten things out with SelectMany, and then use Where. Note that you need to make sure Equals() is implemented in Artikel so Distinct() does its job properly.
var artikels = Controller.Artikel
    .SelectMany(x => x.LieferantenArtikel, (x, l) => (Artikel: x, Lieferant: l))
    .Where(x => x.Lieferant.LieferantId == bestellung.LieferantId)
    .Select(x => x.Artikel)
    .Distinct();

@foreach(var artikel in artikels)
{
    <option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}


Q: Align tables to each others side I have created two tables with bootstrap 4, which show on the one hand specifications and on the other hand earning statistics.
I put both tables in a col-xs-6-class and want one table aligned to the left and the other table to the right. However, currently the tables are somehow clued to each other. Please find below my minimum viable example:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

Specifications

          Price :

            100

          Manufacturer:

            Gigabyte

          Wattage:

            150

          Product:

            Product 1

Earning

          Period
          Rev
          Cost
          Profit

          Hour
          $

                          0.022

          $

                          0.006

          $

                          0.016

          Day
          $

                          1.34

          $

                          0.36

          $

                          0.98

          Week
          $

                          9.37

          $

                          2.52

          $

                          6.85

          Month
          $

                          37.48

          $

                          10.08

          $

                          27.40

          Year
          $

                          449.77

          $

                          120.96

          $

                          328.81

Any suggestions how to align the Specification table to the left and the Earnings table to the right?
I appreciate your replies!

A: One ruleset:
table.table.stats {display:inline-table}

display: inline-table behavior is simply a table that will sit inline with elements instead of the default behavior of occupying the whole width and pushing everything at its left and right -- up and down.
you might have a more complicated environment with your real code so you can
Chain the classes to get higher specificity  which may be overkill but with Bootstrap it is common necessity.
table.table.stats.table.stats {display:inline-table}

Demo

table.table.stats {
  display: inline-table
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

Specifications

          Price :

            100

          Manufacturer:

            Gigabyte

          Wattage:

            150

          Product:

            Product 1

Earning

          Period
          Rev
          Cost
          Profit

          Hour
          $

                          0.022

          $

                          0.006

          $

                          0.016

          Day
          $

                          1.34

          $

                          0.36

          $

                          0.98

          Week
          $

                          9.37

          $

                          2.52

          $

                          6.85

          Month
          $

                          37.48

          $

                          10.08

          $

                          27.40

          Year
          $

                          449.77

          $

                          120.96

          $

                          328.81

A: Add the container-fluid class div around the row.
There is no such class as col-xs-6 instead use col-6
Added another div in col-6 and add padding to it for making some space between them.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

Specifications

              Price :

                100

              Manufacturer:

                Gigabyte

              Wattage:

                150

              Product:

                Product 1

Earning

              Period
              Rev
              Cost
              Profit

              Hour
              $

                            0.022

              $

                            0.006

              $

                            0.016

              Day
              $

                            1.34

              $

                            0.36

              $

                            0.98

              Week
              $

                            9.37

              $

                            2.52

              $

                            6.85

              Month
              $

                            37.48

              $

                            10.08

              $

                            27.40

              Year
              $

                            449.77

              $

                            120.96

              $

                            328.81


Q: Reaction Delete channel | Discord.js I am making a ticket system with discord.js
I tried to when a member reacts to the message with the emoji, the ticket will close, but after running it, it shows an error
if (reaction.emoji.name == '') {
    if(!reaction.channel.name.includes("ticket")) return;
    channel.delete()
}

A: Even though you didn't specify the error I can see that you never defined "channel".
If you want to delete the channel in which the reaction was added use:
reaction.message.channel.delete();


Q: pyspark dataframe filter using variable list values I have a requirment to filter the pyspark dataframe where user will pass directly the filter column part as a string parameter. For example:
Sample Input data: df_input

|dim1|dim2|  byvar|value1|value2|
| 101| 201|MTD0001|     1|    10|
| 201| 202|MTD0002|     2|    12|
| 301| 302|MTD0003|     3|    13|
| 401| 402|MTD0004|     5|    19|

Ex 1: filter_str = "dim2 = '201'"
I will filter the data as: df_input = df_input.filter(filter_str)

Output: (**I'm able to get the output**)

|dim1|dim2|  byvar|value1|value2|
| 101| 201|MTD0001|     1|    10|

But, for multiple filter condition I'm getting error and not able to filter.
Scenario where I'm not able to filter the input dataframe:
valid Scr 1:
filter_str = "dim1 = '101' and dim2 in '['302', '402']'"
df_inp = df_inp.filter(filter_str)
Getting Error

valid Scr 2:
value_list = ['302', '402']
filter_str = "dim1 = '101' or dim2 in '(value_list)'"
df_inp = df_inp.filter(filter_str)
Getting Error

Could you please help in acheiving the scr 1 and 2 and how to modify the filter section if i get the filter_str string as mentioned I example.

A: Use & (or) | operators in your filter query and enclose each statement with brackets ().
df.filter((col("dim1") == '101') | (col("dim2").isin(['302','402']))).show()
#+----+----+-------+------+------+
#|dim1|dim2|  byvar|value1|value2|
#+----+----+-------+------+------+
#| 101| 201|MTD0001|     1|    10|
#| 301| 302|MTD0003|     3|    13|
#| 401| 402|MTD0004|     5|    19|
#+----+----+-------+------+------+

df.filter((col("dim1") == '101') & (col("dim2").isin(['302','402']))).show()
#+----+----+-----+------+------+
#|dim1|dim2|byvar|value1|value2|
#+----+----+-----+------+------+
#+----+----+-----+------+------+

Using expr:
Here we need to convert list to tuple to perform in on value_list
#using filter_str
value_list = ['302', '402']
filter_str = "dim1 = '101' or dim2 in {0}".format(tuple(value_list))
filter_str
#"dim1 = '101' or dim2 in ('302', '402')"
df.filter(expr(filter_str)).show()
#+----+----+-------+------+------+
#|dim1|dim2|  byvar|value1|value2|
#+----+----+-------+------+------+
#| 101| 201|MTD0001|     1|    10|
#| 301| 302|MTD0003|     3|    13|
#| 401| 402|MTD0004|     5|    19|
#+----+----+-------+------+------+

filter_str = "dim1 = '101' and dim2 in {0}".format(tuple(value_list))
df.filter(expr(filter_str)).show()
#+----+----+-----+------+------+
#|dim1|dim2|byvar|value1|value2|
#+----+----+-----+------+------+
#+----+----+-----+------+------+


Q: Multiple API Resources in one call using laravel I am using API Resources for laravel to transform resource to array for an API call,and its working fine,Is is possible that i can retrieve data of multiple models in one call ? As to get JSON data of users along with Pages JSON ? Or i need a separate call for this.
Here what i have tried so far
//Controller
public function index(Request $request)
{
    $users = User::all();
    $pages = Page::all();
    return new UserCollection($users);
}

//API Resource
public function toArray($request)
    {
        return [
            'name' => $this->name,
            'username' => $this->username,
            'bitcoin' => $this->bitcoin,
        ];
    }

Any help will be highly appretiated

A: You can do the following:
public function index(Request $request)
{
    $users = User::all();
    $pages = Page::all();
    return [
        'users' => new UserCollection($users),
        'pages' => new PageCollection($pages),
    ];
}

A: laravel 6..
This should work 100% if you do like the below, you actually helped me sort out a problem i was having and this is a return on that favour :3.
changes the below:
'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),

to
(Will work with a vatiable or just the strait db query)
'advertisements' => AdvertisementCollection::collection(Advertisement::latest()->get())

class HomeController extends Controller
{
    public function index()
        {
           $ads = Advertisement::latest()->get();
           $banners = Banner::latest()->get();
           $sliders = Slider::latest()->get()
            return [
                'advertisements' => AdvertisementCollection::collection($ads),
                'banners' => BannerCollection::collection($banners),
                'sliders' => SliderCollection::collection($sliders),
                ];
        }
}

A: I am using laravel 6.x, And i don't know laravel is converting the response or doing something but i am getting the response as JSON in following condition also:
class HomeController extends Controller
{
    public function index()
        {
            return [
                'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),
                'banners' => new BannerCollection(Banner::latest()->get()),
                'sliders' => new SliderCollection(Slider::latest()->get())
                ];
        }
}


Q: woocommerce UPS rates to have USD converted rates from INR on plugin Hi I am using woocommerce to build a ecommerce site and I use UPS shipping to do shipping, the ups I have signed is from India so the returned rates are in Indian Currency. Is there a way to convert the currency from INR to convert to USD and display the price to the customers of my site. Thanks in advance.

A: As per my knowledge if your woocommerce by default currency is dollar then currency always comes in same the currency.Can you please share your site Url then I can check what is the problem?


Q: Compress files in a directory in a zip file with the shell I want to compress files from the filesystem to a directory within a new zip archive or update an old one. So here is my example:
directory/
  |-file1.ext
  |-file2.ext
  |-file3.ext

in the zip archive it should look like this:
new_directory/
  |-file1.ext
  |-file2.ext
  |-file3.ext

I could copy the files to a new directory and compress them from there but i do not want to have that extra step. I haven't found an answer to that problem on google. The man page doesn't mention anything like that aswell so I hope somebody can help me.

A: I don't think the zip utility supports this sort of transformation. A workaround is to use a symbolic link:
ln -s directory new_directory
zip -r foo.zip new_directory
rm new_directory

If other archive formats are an option for you, then this would be a bit easier with a tar archive, since GNU tar has a --transform option taking a sed command that it applies to the file name before adding the file to the archive.
In that case, you could use (for example)
tar czf foo.tar.gz --transform 's:^directory/:new_directory/:' directory


Q: Variable 'c' set but not used [-Wunused-but-set-variable] I have searched and haven't really found and understood this error. It's weird that I only get the error for c, d, e and not for a and b or them all.
Program is about Dooubly Link List.
This happens when I compile with:
gcc -Wall -g -c program.c

Error part:
void try_mymem(int argc, char** argv) {
strategies strat;
void *a, *b, *c, *d, *e;
if (argc > 1)
    strat = strategyFromString(argv[1]);
else
    strat = First;

/* A simple example.
   Each algorithm should produce a different layout. */

initmem(strat, 500);

a = mymalloc(100);
b = mymalloc(100);
c = mymalloc(100);
myfree(b);
d = mymalloc(50);
myfree(a);
e = mymalloc(25);

print_memory();
print_memory_status();

}
What am I doing wrong?

A: They're not used, just like the compiler says. You assign but never read. a and b are used as arguments, the others are not.


Q: Android talkback element type announcement I am trying to make my app more accessible. I am having a hard time finding helpful things because there isn't a lot of documentation (at least I could not find it).
In my app, Talkback does not announce the element type for ImageViews. What I basically want is for Talkback to announce my contentDescription for the ImageView and follow it up with ", Image".
This link states that " Many accessibility services, such as TalkBack and BrailleBack, automatically announce an element's type after announcing its label, so you shouldn't include element types in your labels. For example, "submit" is a good label for a Button object, but "submitButton" isn't a good label." but it does not specify which element types it announces and which it does not.
https://developer.android.com/guide/topics/ui/accessibility/apps.html

*

*Does anyone have any idea if Talkback announces "Image" after the contentDescription for ImageViews?

*When does Talkback announce a link as a "Link"? Or is it the developer's responsibility to add it at the end of the contentDescription? Can I make talkback announce clickable text as a "Link"?

Any help/information/pointers is greatly appreciated. Thanks in advance.

A: A: don't add stuff to the end of the content description.  It is an accessibility violation and in almost ALL circumstances just makes things less acessible (will explain more later).
B: A lot of contextual things are communicated to TalkBack users via earcons (bips, beeps, etc), you may just not be noticing.
C: Yes, this is confusing and difficult to determine, no images are not announced, though I think this is for good reason.  For example, an image with a click listener may just be a fancy styled button.  In iOS there are traits for you to change for this, Android has omitted this highly useful feature, so we're stuck with odd workarounds.  The ideal solution would be for the Accessibility APIs to allow the developer to communicate this information.
As for links, typically inline links in text views are announced (basically anything android detects and underlines automatically), but otherwise are not.  So, in practice A LOT of links are missed.
Now, as for when you should/should not supply this information yourself.  If unsure, just don't and you'll obtain a reasonably high level of accessibility by following the above guidelines.  In fact, any of the considerations below are really just fighting the Android OS limitations, and are their problem!  However, the Android Accessibility Ecosystem is very weak, and if you want to provide a higher level of accessibility, it is understandable, however, difficult!  In your attempts you can actually end up working against yourself.  Let me explain:
In Accessibility there is a line between providing information and consistency.  By adding contextual information to a content description you are walking along this line.  What if Google said "We're not going to share contextual information, add it yourself!".
You would have buttons in music players across different music playing apps that announce in TalkBack like this:
App1: "Play, Button"
App2: "Play, Actionable"
App3: "Play, Clickable"
Do we have consistency here?  Now a final example!
App4: "Play, Double Tap to click if you're on TalkBack, Hit enter if you're a keyboard user, use your select key for SwitchAccess users....."
Notice how complicated App4's Play Button is, this is illustrating that the information that TalkBack is using is NOT JUST FOR TALKBACK.  The accessibility information from you app is consumed by a multitude of Accessibility services.  When you "Hack" contextual information onto a content description, sure it might sound better for a TalkBack user, but what have you done to Braille Back users?  To SwitchAccess users?  In general, the content description of an element should describe the element, and leave contextual information for TalkBack to calculate/users to figure out given proximity to other controls.
TO ANSWER YOUR TWO PARTICULAR ISSUES (Images and Links):
What I recommend for images is in the content description make it obvious that the thing your describing is an image.
Let's say you have a picture of a kitten.
BAD: A kitten, Image
Good: A picture of a kitten.
See here, if TalkBack fails to announce this as an image (which it will) the user still gets the idea that it is a picture.  You have added contextual information to the content description in a way that has ACTUALLY BETTER DESCRIBED THE CONTROL.  This is actually the most accessible solution!  Go figure.
Links:
For links this gets a bit tricky.  There is a great debate in Accessibility about what constitutes a link vs a button.  In the web browser world, this is a good debate.  However, in native mobile I think we have a very clear definition:
Any button that when activated takes you away from your current Application Context, is a link.
The fact that the Context (Capital C Context!!!) is going to change significantly when a user interacts with a control is EXCEPTIONALLY important information.
TalkBack fails to recognize links A LOT, and as such, for this very important piece of information, if you find that TalkBack is not sharing this information, go ahead and append ", link" to your content description for this element.  THIS IS THE ONLY EXCEPTION TO THIS RULE I HAVE FOUND, but believe it is a good exception.  Reason being, YES it does add a violation or two for other Assistive Technologies, but it conveys important enough information to justify doing so.  YOU CANNOT create a WCAG 2.0 compliant application of reasonable complex User Interface using the Android Accessibility APIs.  They have too many limitations, you simply can't do everything you need to do to accomplish this without "hacks".  So, we have to make judgement calls sometimes.


Q: How to change network in metamask using react js I am developing my first Dapp, I am using metamask and web3 for this. As far now, I am able to get my wallet balance and connect account to metamask. Now I am trying switch between two networks, I am using handleChainChanged, also I am passing chainId and Networkversion but, it is giving me error. I am uncertain about returning anything from changeNetwork function or I only have to pass  chainId and Networkversion.

import { useStoreApi } from "./storeApi";
import { useState } from "react";
import useWeb3 from "./useWeb3";
import { Button, TextField } from "@material-ui/core";

import "./App.css";

function App() {
  const { balance, address, message, setAddress, setBalance } = useStoreApi();
  const web3 = useWeb3();

  // get user account on button click
  const getUserAccount = async () => {
    if (window.ethereum) {
      try {
        await window.ethereum.enable();
        web3.eth.getAccounts().then((accounts) => {
          setAddress(accounts[0]);
          updateBalance(accounts[0]);
          console.log(accounts);
        });
      } catch (error) {
        console.error(error);
      }
    } else {
      alert("Metamask extensions not detected!");
    }
    web3.eth.getChainId().then(console.log);
  };

  const updateBalance = async (fromAddress) => {
    await web3.eth.getBalance(fromAddress).then((value) => {
      setBalance(web3.utils.fromWei(value, "ether"));
    });
  };

  const changeNetwork = async () => {
    if (window.ethereum) {
      try {
        await window.ethereum.enable();
        window.ethereum._handleChainChanged({
          chainId: 0x1,
          networkVersion: 1,
        });
      } catch (error) {
        console.error(error);
      }
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        {address ? (
          <>
            <p> Balance: {balance} </p>
          </>
        ) : null}
        <Button
          onClick={() => getUserAccount()}
          variant="contained"
          color="primary"
        >
          Connect your account
        </Button>
        <Button onClick={changeNetwork} variant="contained" color="primary">
          Switch to mainnet ethereum
        </Button>

      </header>
    </div>
  );
}

export default App;

A: You can use wallet_switchEthereumChain  method of RPC API of Metamask
Visit: https://docs.metamask.io/guide/rpc-api.html#wallet-switchethereumchain

A:   const changeNetwork = async () => {
if (window.ethereum) {
  try {
    await window.ethereum.request({
    method: 'wallet_switchEthereumChain',
      params: [{ chainId: Web3.utils.toHex(chainId) }],
    });
    });
  } catch (error) {
    console.error(error);
  }
}
changeNetwork()

A: What if the user doesn't have the required network added? Here is an expanded version which tries to switch, otherwise add the network to MetaMask:
const chainId = 137 // Polygon Mainnet

if (window.ethereum.networkVersion !== chainId) {
      try {
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: web3.utils.toHex(chainId) }]
        });
      } catch (err) {
          // This error code indicates that the chain has not been added to MetaMask
        if (err.code === 4902) {
          await window.ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [
              {
                chainName: 'Polygon Mainnet',
                chainId: web3.utils.toHex(chainId),
                nativeCurrency: { name: 'MATIC', decimals: 18, symbol: 'MATIC' },
                rpcUrls: ['https://polygon-rpc.com/']
              }
            ]
          });
        }
      }
    }

A: export async function switchToNetwork({
library,
chainId,
}: SwitchNetworkArguments): Promise<null | void> {
if (!library?.provider?.request) {
return
}
const formattedChainId = hexStripZeros(
BigNumber.from(chainId).toHexString(),
)
try {
await library.provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: formattedChainId }],
})
} catch (error) {
// 4902 is the error code for attempting to switch to an unrecognized chainId
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((error as any).code === 4902) {
const info = CHAIN_INFO[chainId]
        await library.provider.request({
            method: 'wallet_addEthereumChain',
            params: [
                {
                    chainId: formattedChainId,
                    chainName: info.label,
                    rpcUrls: [info.addNetworkInfo.rpcUrl],
                    nativeCurrency: info.addNetworkInfo.nativeCurrency,
                    blockExplorerUrls: [info.explorer],
                },
            ],
        })
        // metamask (only known implementer) automatically switches after a network is added
        // the second call is done here because that behavior is not a part of the spec and cannot be relied upon in the future
        // metamask's behavior when switching to the current network is just to return null (a no-op)
        try {
            await library.provider.request({
                method: 'wallet_switchEthereumChain',
                params: [{ chainId: formattedChainId }],
            })
        } catch (error) {
            console.debug(
                'Added network but could not switch chains',
                error,
            )
        }
    } else {
        throw error
    }
}

}


Q: Apply `dplyr::rowwise` in all variables I have a data:
df_1 <- data.frame(
  x = replicate(4, runif(30, 20, 100)),
  y = sample(1:3, 30, replace = TRUE)
)

The follow function work:
library(tidyverse)

df_1 %>%
  select(-y) %>%
  rowwise() %>%
  mutate(var = sum(c(x.1, x.3)))

But, the follows functions (for all variables) dooesn't work:
with .:
df_1 %>%
  select(-y) %>%
  rowwise() %>%
  mutate(var = sum(.))

with select_if:
df_1 %>%
  select(-y) %>%
  rowwise() %>%
  mutate(var = sum(select_if(., is.numeric)))

The both methods return:
Source: local data frame [30 x 5]
Groups: <by row>

# A tibble: 30 x 5
     x.1   x.2   x.3   x.4   var
   <dbl> <dbl> <dbl> <dbl> <dbl>
 1  32.7  42.7  50.1  20.8 7091.
 2  75.9  71.3  83.6  77.6 7091.
 3  49.6  28.7  97.0  59.7 7091.
 4  47.4  96.1  31.9  79.7 7091.
 5  54.2  47.1  81.7  41.6 7091.
 6  27.9  58.1  97.4  25.9 7091.
 7  61.8  78.3  52.6  67.7 7091.
 8  85.4  51.3  38.8  82.0 7091.
 9  27.9  72.6  68.9  25.2 7091.
10  87.2  42.1  27.6  73.9 7091.
# ... with 20 more rows

Where 7091 is a incorrect sum.
How adjustment this functions?

A: This can be done using purrr::pmap, which passes a list of arguments to a function that accepts "dots". Since most functions like mean, sd, etc. work with vectors, you need to pair the call with a domain lifter:
df_1 %>% select(-y) %>% mutate( var = pmap(., lift_vd(mean)) )
#         x.1      x.2      x.3      x.4      var
# 1  70.12072 62.99024 54.00672 86.81358 68.48282
# 2  49.40462 47.00752 21.99248 78.87789 49.32063

df_1 %>% select(-y) %>% mutate( var = pmap(., lift_vd(sd)) )
#         x.1      x.2      x.3      x.4      var
# 1  70.12072 62.99024 54.00672 86.81358 13.88555
# 2  49.40462 47.00752 21.99248 78.87789 23.27958

The function sum accepts dots directly, so you don't need to lift its domain:
df_1 %>% select(-y) %>% mutate( var = pmap(., sum) )
#         x.1      x.2      x.3      x.4      var
# 1  70.12072 62.99024 54.00672 86.81358 273.9313
# 2  49.40462 47.00752 21.99248 78.87789 197.2825

Everything conforms to the standard dplyr data processing, so all three can be combined as separate arguments to mutate:
df_1 %>% select(-y) %>%
  mutate( v1 = pmap(., lift_vd(mean)),
          v2 = pmap(., lift_vd(sd)),
          v3 = pmap(., sum) )
#         x.1      x.2      x.3      x.4       v1       v2       v3
# 1  70.12072 62.99024 54.00672 86.81358 68.48282 13.88555 273.9313
# 2  49.40462 47.00752 21.99248 78.87789 49.32063 23.27958 197.2825

A: A few approaches I've taken in the past:

*

*use a pre-existing row-wise function (e.g. rowSums)

*using reduce (which doesn't apply to all functions)

*complicated transposing

*custom function with pmap
Using pre-existing row-wise functions
set.seed(1)
df_1 <- data.frame(
  x = replicate(4, runif(30, 20, 100)),
  y = sample(1:3, 30, replace = TRUE)
)

library(tidyverse)

# rowSums
df_1 %>%
  mutate(var = rowSums(select(., -y))) %>%
  head()
#>        x.1      x.2      x.3      x.4 y      var
#> 1 41.24069 58.56641 93.03007 39.17035 3 232.0075
#> 2 49.76991 67.96527 43.48827 24.71475 2 185.9382
#> 3 65.82827 59.48330 56.72526 71.38306 2 253.4199
#> 4 92.65662 34.89741 46.59157 90.10154 1 264.2471
#> 5 36.13455 86.18987 72.06964 82.31317 3 276.7072
#> 6 91.87117 73.47734 40.64134 83.78471 2 289.7746

Using Reduce
df_1 %>%
  mutate(var = reduce(select(., -y),`+`))  %>%
  head()
#>        x.1      x.2      x.3      x.4 y      var
#> 1 41.24069 58.56641 93.03007 39.17035 3 232.0075
#> 2 49.76991 67.96527 43.48827 24.71475 2 185.9382
#> 3 65.82827 59.48330 56.72526 71.38306 2 253.4199
#> 4 92.65662 34.89741 46.59157 90.10154 1 264.2471
#> 5 36.13455 86.18987 72.06964 82.31317 3 276.7072
#> 6 91.87117 73.47734 40.64134 83.78471 2 289.7746

ugly transposing and matrix / data.frame conversion
df_1 %>%
  mutate(var = select(., -y) %>% as.matrix %>% t %>% as.data.frame %>% map_dbl(var)) %>%
  head()
#>        x.1      x.2      x.3      x.4 y       var
#> 1 41.24069 58.56641 93.03007 39.17035 3 620.95228
#> 2 49.76991 67.96527 43.48827 24.71475 2 318.37221
#> 3 65.82827 59.48330 56.72526 71.38306 2  43.17011
#> 4 92.65662 34.89741 46.59157 90.10154 1 878.50087
#> 5 36.13455 86.18987 72.06964 82.31317 3 520.72241
#> 6 91.87117 73.47734 40.64134 83.78471 2 506.16785

Custom function with pmap
my_var <- function(...){
  vec <-  c(...)
  var(vec)
}

df_1 %>%
  mutate(var = select(., -y) %>% pmap(my_var)) %>%
  head()
#>        x.1      x.2      x.3      x.4 y      var
#> 1 41.24069 58.56641 93.03007 39.17035 3 620.9523
#> 2 49.76991 67.96527 43.48827 24.71475 2 318.3722
#> 3 65.82827 59.48330 56.72526 71.38306 2 43.17011
#> 4 92.65662 34.89741 46.59157 90.10154 1 878.5009
#> 5 36.13455 86.18987 72.06964 82.31317 3 520.7224
#> 6 91.87117 73.47734 40.64134 83.78471 2 506.1679

Created on 2019-04-30 by the reprex package (v0.2.1)

A: I think this is tricky because the scoped variants of mutate (mutate_at, mutate_all, mutate_if) are generally aimed at executing a function on a specific column, instead of creating an operation that uses all columns.
The simplest solution I can come up with basically amounts to creating a vector (cols) that is then used to execute the summary operation:
library(dplyr)
library(purrr)

df_1 <- data.frame(
  x = replicate(4, runif(30, 20, 100)),
  y = sample(1:3, 30, replace = TRUE)
)

# create vector of columns to operate on
cols <- names(df_1)
cols <- cols[map_lgl(df_1, is.numeric)]
cols <- cols[! cols %in% c("y")]

cols
#> [1] "x.1" "x.2" "x.3" "x.4"

df_1 %>%
  select(-y) %>%
  rowwise() %>%
  mutate(
    var = sum(!!!map(cols, as.name), na.rm = TRUE)
  )
#> Source: local data frame [30 x 5]
#> Groups: <by row>
#>
#> # A tibble: 30 x 5
#>      x.1   x.2   x.3   x.4   var
#>    <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1  46.1  28.9  28.9  50.7  155.
#>  2  26.8  68.0  67.1  26.5  188.
#>  3  35.2  63.8  62.5  28.5  190.
#>  4  31.3  44.9  67.3  68.2  212.
#>  5  52.6  23.9  83.2  43.4  203.
#>  6  55.7  92.8  86.3  57.2  292.
#>  7  56.9  50.0  77.6  25.6  210.
#>  8  95.0  82.6  86.1  22.7  286.
#>  9  62.7  26.5  61.0  88.9  239.
#> 10  65.2  23.1  25.5  51.0  165.
#> # … with 20 more rows

Created on 2019-04-30 by the reprex package (v0.2.1)
NOTE: if you are unfamiliar with purrr, you can also use something like lapply, etc.
You can read more about these types of more tricky dplyr operations (!!, !!!, etc.) here:
https://dplyr.tidyverse.org/articles/programming.html

A: This is a tricky problem since dplyr operates column-wise for many operations. I originally used apply from base R to apply over rows, but apply is problematic when handling character and numeric types.
Instead we can use (the aging) plyr and adply to do this simply, since plyr lets us treat a one-row data frame as a vector:
df_1 %>% select(-y) %>% adply(1, function(df) c(v1 = sd(df[1, ])))

Note some functions like var won't work on a one-row data frame so we need to convert to vector using as.numeric.