Q: SSD full after swapping from Ubuntu (some kind of leak?) I'm working on an Acer Chromebook 15 with Ubuntu 16.04 installed. My SSD has ~10.5 GB total, with only 5 GB used. The last few times I've logged out of Ubuntu or had it fall asleep, it restarts into ChromeOS with the warning the device disk is full. There are 0 B remaining. Something has suddenly eaten 5+ GB of my disk.
Has anyone else heard of this? My google-fu hasn't yielded any solutions. The last couple times, I've been able to delete some download files, and it will eventually clear itself out. For some reason, swapping back to Ubuntu helps it realize the amount is disk space is actually used. This time, there's nothing to delete, and I'm having trouble figuring out what I can delete to have the room to switch over to Ubuntu.
Any help is appreciated.
Edit:
I poked around a bit, and it looks like the culprit is probably in /mnt/stateful_partition. I'm not sure where I should delve from here. Hopefully it helps narrow it down.
Output from df -h:
Filesystem               Size  Used Avail Use% Mounted on
/dev/root                1.7G  1.6G   86M  96% /
devtmpfs                 1.9G     0  1.9G   0% /dev
tmp                      1.9G  192K  1.9G   1% /tmp
run                      1.9G  548K  1.9G   1% /run
shmfs                    1.9G   19M  1.9G   1% /dev/shm
/dev/sda1                 11G   11G     0 100% /mnt/stateful_partition
/dev/sda8                 12M   24K   12M   1% /usr/share/oem
/dev/mapper/encstateful  3.2G   59M  3.1G   2% /mnt/stateful_partition/encrypted
media                    1.9G     0  1.9G   0% /media
none                     1.9G     0  1.9G   0% /sys/fs/cgroup
imageloader              1.9G     0  1.9G   0% /run/imageloader

Output from mount:
/dev/dm-0 on / type ext2 (ro,relatime,seclabel)
devtmpfs on /dev type devtmpfs (rw,nosuid,noexec,relatime,seclabel,size=1986368k,nr_inodes=496592,mode=755)
none on /proc type proc (rw,nosuid,nodev,noexec,relatime)
none on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)
none on /sys/fs/selinux type selinuxfs (rw,nosuid,noexec,relatime)
tmp on /tmp type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel)
run on /run type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,mode=755)
debugfs on /sys/kernel/debug type debugfs (rw,nosuid,nodev,noexec,relatime,seclabel,gid=605,mode=750)
shmfs on /dev/shm type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=000)
/dev/sda1 on /mnt/stateful_partition type ext4 (rw,nosuid,nodev,noexec,noatime,seclabel,commit=600,data=ordered)
/dev/sda8 on /usr/share/oem type ext4 (ro,nosuid,nodev,noexec,relatime,seclabel,data=ordered)
/dev/sda1 on /home type ext4 (rw,nosuid,nodev,noexec,noatime,seclabel,commit=600,data=ordered)
/dev/mapper/encstateful on /mnt/stateful_partition/encrypted type ext4 (rw,nosuid,nodev,noexec,noatime,seclabel,discard,commit=600,data=ordered)
/dev/mapper/encstateful on /var type ext4 (rw,nosuid,nodev,noexec,noatime,seclabel,discard,commit=600,data=ordered)
/dev/mapper/encstateful on /home/chronos type ext4 (rw,nosuid,nodev,noexec,noatime,seclabel,discard,commit=600,data=ordered)
run on /var/run type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,mode=755)
run on /var/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,mode=755)
media on /media type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel)
/dev/sda1 on /usr/local type ext4 (rw,nodev,noatime,seclabel,commit=600,data=ordered)
pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime,seclabel)
none on /sys/fs/cgroup type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,mode=755)
cgroup on /sys/fs/cgroup/cpu type cgroup (rw,nosuid,nodev,noexec,relatime,cpu)
/opt/google/containers/android/system.raw.img on /opt/google/containers/android/rootfs/root type squashfs (ro,nosuid,nodev,noexec,relatime,seclabel)
/usr/share/mount-passthrough/rootfs.squashfs on /opt/google/containers/arc-removable-media/mountpoints/container-root type squashfs (ro,nosuid,noexec,relatime,seclabel)
/opt/google/containers/arc-sdcard/rootfs.squashfs on /opt/google/containers/arc-sdcard/mountpoints/container-root type squashfs (ro,nosuid,noexec,relatime,seclabel)
/opt/google/containers/arc-obb-mounter/rootfs.squashfs on /opt/google/containers/arc-obb-mounter/mountpoints/container-root type squashfs (ro,nosuid,noexec,relatime,seclabel)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpuacct)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset,noprefix)
imageloader on /run/imageloader type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,mode=755)
debugfs on /run/debugfs_gpu type debugfs (rw,nosuid,nodev,noexec,relatime,seclabel,gid=605,mode=750)
/dev/sda1 on /home/chronos/user type ext4 (rw,nosuid,nodev,noexec,relatime,seclabel,commit=600,data=ordered)
/dev/sda1 on /home/user/02d44d5ef61df73bb9b079a0851db0426ccb854c type ext4 (rw,nosuid,nodev,noexec,relatime,seclabel,commit=600,data=ordered)
/dev/sda1 on /home/chronos/u-02d44d5ef61df73bb9b079a0851db0426ccb854c type ext4 (rw,nosuid,nodev,noexec,relatime,seclabel,commit=600,data=ordered)
/dev/sda1 on /home/root/02d44d5ef61df73bb9b079a0851db0426ccb854c type ext4 (rw,nosuid,nodev,noexec,relatime,seclabel,commit=600,data=ordered)

Edit2:
I think I've found the culprit but still have no idea how to proceed. Here's the output from lsblk.
NAME    MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda       8:0    0  14.9G  0 disk
├─sda1    8:1    0  10.8G  0 part /mnt/stateful_partition
├─sda2    8:2    0    16M  0 part
├─sda3    8:3    0     2G  0 part
├─sda4    8:4    0    16M  0 part
├─sda5    8:5    0     2G  0 part
├─sda6    8:6    0   512B  0 part
├─sda7    8:7    0   512B  0 part
├─sda8    8:8    0    16M  0 part /usr/share/oem
├─sda9    8:9    0   512B  0 part
├─sda10   8:10   0   512B  0 part
├─sda11   8:11   0     8M  0 part
└─sda12   8:12   0    16M  0 part
loop0     7:0    0   3.2G  0 loop
└─encstateful
  254:1    0   3.2G  0 dm   /mnt/stateful_partition/encrypted
loop1     7:1    0 449.2M  1 loop /opt/google/containers/android/rootfs/root
loop2     7:2    0     4K  1 loop /opt/google/containers/arc-removable-media/mou
loop3     7:3    0     4K  1 loop /opt/google/containers/arc-sdcard/mountpoints/
loop4     7:4    0     4K  1 loop /opt/google/containers/arc-obb-mounter/mountpo
zram0   253:0    0   5.6G  0 disk [SWAP]

The space held by zram0 is pretty much exactly the space that's missing. Some research tells it has something to do with external drives (I think?). With that in mind, I am using an SD card to run programs like IPython and Matlab. It might be a problem with it being improperly unmounted, but restarting my computer doesn't clear it out. If someone can help me reset zram0, I think that'll solve the issue.
The issue has been solved! It wasn't even an issue with swap files or anything like that. Running sudo du --max-depth=9 --human-readable / | sort --human-numeric-sort led me to the culprit: my vpn's manager log file. Clearing that out cleared out literally 7.5 GB.
Thanks to everyone that helped out!! I appreciate it greatly!!

A: It looks like the setup is using the /dev/zram0 device as a swap partition.
Here is a pretty good explanation on how that works:
https://wiki.gentoo.org/wiki/Zram
I'm not sure if this is actually the 'disk' flash memory or RAM that is being used.
You can try to disable the swap by doing :
swapoff /dev/zram0 and see if that fixes the issue (make sure to do it before it's full).
Then you can lookup on how to create and enable a different swap partition if needed and probably modify /etc/fstab
to not set it at boot. Good luck!


Q: Me who don't/doesn’t Now, I'm writing something quite important and confused whether don't can be used instead of doesn't in my sentence. I know that English natives usually treat that me as the third-person-singular pronouns, for example:

*

*It's me who is so generous that's bought you such a gift.

And if we use I in this case (which is also acceptable), then we treat it as the very pronoun I:

*It's I who am feeding your hamster now.

2.2. It's I who usually eat all the pizza.
But can I treat that me as the pronoun I, for example:

*Is it me who don't understand you?!

3.2. It's not me who am mending your roof up there.

A: So just as a native speaker of British English those last two sentences should be:
Is it me who doesn't understand you?!
It's not me who is mending your roof up there.
However to be honest none of the example sentences sound very natural. I'd rephrase them as:
I'm the one who's so generous to buy you such a gift.
I'm feeding your hamster now.
I usually eat all the pizza.
Saying 'It's I who' instead of just 'I' makes it sound like your deliberately being overly dramatic. Although for the full effect you'd want to say 'It is I who'.
I think this is because by using 'It's I who' you're talking about yourself in the third person, albeit using I instead of your name. Bare in mind this is me being a native speaker instead of someone who knows the technical ins and outs of the language, so using 'I' means you may not technically be using the third person but your certainly close.

A: Native American speaker here.
Sorry, these all sound unnatural to my ear.

It's me who is so generous that's bought you such a gift.

American: The construction sounds like the gift receiver has mistakenly thanked the wrong person for the gift, and the speaker is jealous of that attention. Hence,

"It was me that was so generous to buy you this gift!"

Now,

"It's I who am feeding your hamster now."

Again, sounds foreign, and like a case of mistaken identity. If you insist on using "I", I would say:

"It is I. I am feeding your hamster now."

I would never say "It is I who is...", I will always say "I am...".

"It's I who usually eat all the pizza."

Again, never "It is I", unless that is the complete sentence. So for example where that would work,

Commander: "Who is second in charge here?"
Harry: "It is I." (but more likely Harry would say, "I am.", as in "I am second in charge here.")

So, I'd write:

"I usually eat all the pizza."

Now,

But can I treat that me as the pronoun I, for example:

No. It is more like the pronoun "her" or "him".

For "Is it me who don't understand you?!"

I'd write

Is it me that doesn't understand you?!

You cannot write "me who do not", it is "me who does not". And even then, Americans will say "me that".
Which applies to the next one as well.

It's not me who am mending your roof up there.

I would say

It's not me that is mending your roof up there.

A: Okay, so as stated in the comments, "Me" is the first person singular objective pronoun, not third person.   The third person objective pronouns are "Him, Her, It."
"Don't" and "Doesn't" are contractions for "Do Not" and "Does Not".  Does is the third person conjugation of the verb "To Do" and should only follow a Sentance with a third person Subjective which are "He/She/It" in the singular and "They" in the plural.


Q: React Router, change path alternative of link element Is it possible to change route in react by react-router by other way than <Link></Link> ?
(e.g change route when onClick, or onKeydown event runs some function)

A: There is another way. You can use history.push in your code:
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
  const history = useHistory();

  return <button onClick={() => history.push('/profile')}>Profile</button>;
};


Q: Unit testing function XPath query results? I'm having a little bit of a dilemma. I have a very basic class with functions returning specific XPath query results.
Here is the code I'm currently using.
[TestFixture]
public class MarketAtAGlance_Test
{
    private XmlDocument document;
    private MarketAtAGlance marketAtAGlance;

    [SetUp]
    public void setUp()
    {
        this.document = new XmlDocument();
        // load document from file located in the project
        this.marketAtAGlance = new MarketAtAGlance(document);
    }

    [Test]
    public void getHourlyImport_Test()
    {
        Assert.AreEqual(100.0d, marketAtAGlance.getHourlyImport());
    }

    [Test]
    public void getHourlyExport_Test()
    {
        Assert.AreEqual(1526.0d, marketAtAGlance.getHourlyExport());
    }
}

public class MarketAtAGlance
{
    XmlDocument document;

    public MarketAtAGlance(XmlDocument document)
    {
        this.document = document;
    }

    public double getHourlyImport() {
        double value = Convert.ToDouble(document.SelectSingleNode("//information[@id=\"dat11\"]/new_val").InnerText);

        return value;
    }

    public double getHourlyExport() {
        double value = Convert.ToDouble(document.SelectSingleNode("//information[@id=\"dat12\"]/new_val").InnerText);

        return value;
    }
}

This is my first use of unit testing so I'm still unsure of many minor things. As you can see, I'm loading a static XML file located on my hard drive. Should I have the extra dependency or put the XML text in a big string? I'm loading an older XML file (with the same format) because I can test with already known values.
Also, how would I go about unit testing an XmlHttpReader (class that takes in an XML url and loads it as a document?
Any comments on my question or comments about the design?

A: I would construct the XML in the test setup, but limit the XML to only what you need for the test to pass. It looks like your XML document could be very simple in this case.
<someRoot>
   <someNode>
        <information id='dat11'><new_val>100.0</new_val></information>
        <information id='dat12'><new_val>1526.0</new_val></information>
   </someNode>
 </someRoot>

That XML would pass your test.
I also wouldn't test the XmlHttpReader, if that is a system class. You could mock a dependency to it. You might need to wrap it with something to help you easily decouple it as dependency from your class.

A: For your first question, whether you should have a big XML string or load it from a file.  I would say either works.  To be honest though since you are loading from a file inside the project I would keep it in the project as an embedded resource and load it via reflection.  That would take the mess of file structure out of the picture if any of your colleages run it from their pc's.  The only best practice I've really encountered with Unit Tests is to make sure you're testing properly and make sure others can run the test easily.
For your second question, about the XmlHttpReader.  It would depend on your output.  If you can test that you have valid XML then go for it.  I would reccommend negative testing as well.  Point it to http://stackoverflow.com, or a URL you know will error out and decorate the test with the appropriate expected error.


Q: Failed to initiate service connection to simulator? When i install  AFNetworking pod file for connecting web service. After installation pod then run my program Xcode show message "unable to contact local DTServiceHub to bless simulated connection".
I help this link for error from stackoverflow but not solve issue.
I used: Xcode 8.2.1, OSX 10.11.6 and Objective-C.
Thanks in Advance.


Q: How to change PATH priority for specified command in zsh I installed vim by using brew, but because /usr/bin have higher priority than /usr/local/bin/ the /usr/bin/vi is called by default.
which -a vi
/usr/bin/vi
/usr/local/bin/vi

I can create a alias in ~/.zshrc, but I'm using the init file also in other environment that doesn't have /usr/local/bin/vi.
If I change the priority of the paths /usr/bin/ and /usr/local/bin, some side effects may happen.
So I want to change the priority of paths only for vi command.
How can I do it? Or is there better way to solve this problem?

A: use hash: hash vi=/usr/local/bin/vi


Q: Connecting to a Windows server that has an active VPN connection In my company we connect to various customers using VPN.
We have a dedicated Windows server where the VPN clients are installed, and if we need to do customer support, we have to physically log in to this server and connect.
We cannot log in to this server using RDP or VNC because most VPN clients do not allow split tunnels, and therefore prevent any other traffic using TCP/IP.
To overcome this problem, we installed NetOp on our PC's, and used NetBEUI to connect to the server. This is actually working pretty well when using XP on the clients. However, now we are upgrading to Windows 7, and I'm not sure if we would be able to use NetBEUI anymore.
My question is: is there any other way of connecting to a server that will not allow TCP/IP traffic? Any alternative network protocol that we can use? Any remote admin software that would work?

A: *

*A dedicated management card like Dell DRAC, IBM SupII, or HP iLo would do this.

*An IP KVM would do this

*Virtualizing the server and using the VMware console would do this

*Using your network gear instead of this server to make the VPN connections to all of your clients would entirely sidestep the issue.


Q: Does $\hat{A} \cong \sigma(a)$? Suppose $A$ is a unital $C^{*}$-algebra and $a \in A$ is normal, with spectrum $\sigma(a)$. A common analysis in textbooks is the following. Let $B = C^{*}(a)$ the unital $C^{*}$-algebra generated by $1$ and $a$. This is an abelian algebra, so by Gelfand Isomorphism Theorem, we get $B \cong C(\hat{B})$, where $\hat{B}$ is the space of all nonzero $*$-homomorphisms $\chi: B \to \mathbb{C}$. Moreover, the function $\hat{a}: \hat{B} \to \mathbb{C}$ defined by $\hat{a}(\chi) := \chi(a)$ is a homeomorphism between $\hat{B}$ and $\sigma(a)$.
My question is: if $A$ is not only unital but also abelian, does the same analysis hold for $B$ replaced by $A$? In other words, is $\hat{a}$ a homeomorphism between $\hat{A}$ and $\sigma(a)$. I believe the usual analysis hold in this case too, since:
$$\operatorname{Im}(\hat{a}) = \{\chi(a): \chi \in \hat{A}\} = \sigma(a)$$
and this map is a homeomorphism if I am not mistaken. In short, do we still get $\hat{A} \cong C(\sigma(a))$ for $A$ abelian?

A: No, you don't. When you do the Gelfand transform business with an algebra that is bigger than $C^*(a)$, there is the possibility of having characters that are zero on $a$, so they don't exist as characters in $C^*(a)$. Consider $A=C[0,1]$ and $a(x)=\frac12\,x$. Then
$$
\hat A=[0,1],\qquad\qquad\text{ while }\qquad\qquad \sigma(a)=\big[0,\frac12\big]
$$
You can make this as extreme as you want, in the sense that it is possible to have a fixed $\sigma(a)$ and $\hat A$ any compact subset of the complex plane that contains $\sigma(a)$. Indeed, you can always form $A=B\oplus C(K)$. Then $\sigma(a,a)=\sigma(a)$, while $\hat A=K$.


Q: Maximum interval on react loop->addPeriodicTimer is 2147 seconds I'm running a timer using react\eventloop on my ratchet wamp app. I would like to have it run hourly at 3600 seconds, but for some reason if I set the interval higher than 2147 seconds I get this warning:
Warning: stream_select(): The microseconds parameter must be greater than 0 in C
:\wamp\www\vendor\react\event-loop\StreamSelectLoop.php on line 255

What's so special about 2147 seconds? And what can I do to bypass this contraint?
The Event Handler
class Pusher implements WampServerInterface, MessageComponentInterface {
    private $loop;
}

public function __construct(LoopInterface $loop) {
    $this->loop = $loop;

    $this->loop->addPeriodicTimer(2147, function() {
         //code
    });
}

public function onSubscribe(ConnectionInterface $conn, $topic) {}
public function onUnSubscribe(ConnectionInterface $conn, $topic) {}
public function onOpen(ConnectionInterface $conn) {}
public function onClose(ConnectionInterface $conn) {}
public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {}
public function onPublish(ConnectionInterface $conn, $topic, $event {}
public function onError(ConnectionInterface $conn, \Exception $e) {}

The Server
$loop = Factory::create();

$webSock = new Server($loop);
$webSock->listen(8080, '0.0.0.0');

new IoServer(
    new HttpServer(
        new WsServer(
            new SessionProvider(
                new WampServer(
                    new Pusher($loop)),
                $sesshandler
            )
        )

    ),
    $webSock
);

$loop->run();

A: It is because of the limit of PHP integers on 32-bit platforms.
2147 (seconds) * 1000000 (microseconds in one second) ~= PHP_INT_MAX on 32-bit platforms.
On 64-bit platforms the limit would be ~ 300k years.
The strange thing is that React's React\EventLoop\StreamSelectLoop calls stream_select() only with microseconds parameter, while it also accepts seconds. Maybe they should fix this issue. As a workaround you could override StreamSelectLoop implementation so that it make use of $tv_sec parameter in stream_select().

I created a pull request, let's see if it will be accepted


Q: How to create sharepoint 2013 statistical reports in SSRS? I wanna to create statistical reports for my sharepoint sites in SSRS. My sharepoint farm is 2013.
for wxample I try to create reports about how many user login in every site today, or last week, …
or which sites user1 browse today, or last week,… or how many times a special link had been clicked today, or last week,….
would you please guide me how to create statistical reports for sharepoint 2013 environment in SSRS??
or would you give me some links or articles about???
Thanks in advance!

A: I am going to assume that you don't have the framework for report creation in place, so I am going to give you information on how to get started which should hopefully also allow you to get an idea on how to create the reports when its all said and done.

*

*How to: Activate the Report Server Feature in SharePoint Central Administration

*How to: Configure Report Server Integration in SharePoint Central Administration

*Configuring Reporting Services for SharePoint 2010 Integration
Let me know if you need more help.
EDIT: Ok, so you have done the above and want to get to creating the actual reports, there are a few more things you need to do and here are a couple of resources that will be very useful to you. I don't want to recreate the wheel, so use this instead.

*

*How to Switch from SSRS Native Mode to SharePoint Integrated Mode

*Create SSRS Report with SharePoint 2010 Integrated Mode
Good luck, let us know how it goes.


Q: PHP Regex cut off space with preg_replace I have some string like this
Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300

I want to turn PC to Price
And this is result that I want
Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300

At first I use
$pattern = array('/(\s*)Product(\s*)/', '/(\s*)(Pc\.?|Pcs)(\s*)/');

But it came to change all of my PC to Price
Name xxx Product 1 Price 100
Name Price i Product 2 Price 200
Name Price x Product 3 Price 300

This is my code now.
$pattern = array('/(\s*)Product(\s*)/', '/[^a-z](Pc\.?|Pcs)[^a-z]/');
$replacement = array(' Product ', ' Price ');
$title = preg_replace($pattern, $replacement, $title, -1);

But it result like this
Name xxx Product 1 Price 100
Name Pci Product Price 00
Name Pcx Product 3 Price 00

Thanks you.

A: Regex:
(Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)

Replacement string:
$1 $2 Price $3

DEMO
$string = <<<EOT
Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300
EOT;
$pattern = "~(Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)~";
echo preg_replace($pattern, "$1 $2 Price $3", $string);

Output:
Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300

A: The reason your attempt is not working is because you are removing things that you don't want to.
You could use the following regular expression.
$title = <<<DATA
Name xxx Product 1 Pc 100
Name Pci Product2Pc.200
Name Pcx Product 3 Pcs300
DATA;

$title = preg_replace('/Product\K\s*(\d+)\D+(\d+)/', ' $1 Price $2', $title);
echo $title;

Output:
Name xxx Product 1 Price 100
Name Pci Product 2 Price 200
Name Pcx Product 3 Price 300


Q: Reading strings from file into dynamically allocated array in C I'm trying to learn C and can't seem to figure out how to read in strings from a file into an array.  I have a 2D array of chars as an array of strings and try to read those in by using malloc but I keep getting a SegFault.  Any tips on how to fix my code?
#include <stdio.h>
#define MAX_WORDS 10
#define MAX_WORD_SIZE 20

unsigned int getLine(char s[], unsigned int uint, FILE *stream);

int main( void ){

 FILE *infile1;
 unsigned int i = 0;
 unsigned int j = 0;
 unsigned int index;
 char c;

 char wordList[ MAX_WORDS+1 ][ MAX_WORD_SIZE + 1];

 infile1 = fopen("myFile.txt", "r");

 if (!(infile1 == NULL))
printf("fopen1 was successful!\n");

 while( (c = getc(infile1)) != EOF){
  while ((c = getc(infile1)) != ' '){
    wordList[i] = (char *)malloc(sizeof(char) );
        wordList[i][j] = getc(infile1);
        j++;
  }
  j = 0;
  i++;
}

printf("\nThe words:\n");
for (index = 0; index < i; ++index){
printf("%s\n", wordList[index]);
}

A: How are you compiling this.  The compiler should give you and error on the assignment:
wordList[i] = (char *)malloc(sizeof(char) );

The array wordlist is not of type char *
Also you are missing an include for malloc (stdlib.h probably) and you shouldn't be casting the return from malloc.

A: One obvious problem - you are allocating one char for wordList[i], then using it as if you had a character for each wordList[i][j].
You don't need to allocate any memory here, as you've defined wordlist as a 2 dimensional array rather than as an array of pointers or similar.
Next obvious problem - you are reading in characters and never providing an end of string, so if you ever got to the printf() at the end you are going to keep going until there happens to be a 0 somewhere in or after wordList[index] - or run off the end of memory, with a Segfault.
Next problem - do you intend to only detect EOF immediately after reading a space - AND throw away alternate characters?


Q: ListView - onContextItemSelected manipulate the item instead of toString As you can see in the code below, when I LongClick on an item in ListView, i get a popup menu with option to manipulate the item (delete, update, etc).
the problem is that I use my function on item.toString instead the item itself.
How can i get the item itself, and put it as an argument in my functions?
onCreateContextMenu:
public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    if (v.getId() == R.id.db_list_view) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list, menu);
    }
}

onContextItemSelected:
public boolean onContextItemSelected(android.view.MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    Object obj = lv.getItemAtPosition(info.position);
    String nameToString = obj.toString();

    if (item.getTitle().equals("Delete")) {
        deletePlayerFromLongClick(nameToString);
    } else if (item.getTitle().equals("Update")) {
        updatePlayerFromLongClick(nameToString);
    } else if (item.getTitle().equals("Change Host/Guest")) {
        changeMembership(nameToString);
    }
    return true;
}

A: do like:
yourAdapter.getItem(info.position);

or
((YourAdapter)lv.getAdapter()).getItem(position);

or even simpler,
listOfItem.get(info.position);


Q: Checking for a Discourse topic title I have a ruby function that creates a discourse topic if the title is not found.
def get_topic(user,title,created_at,bumped_at,last_posted_at,excerpt)

  title = title.gsub(/  /,' ')
  puts "get_topic.title:'#{title}' user.id:#{user.id} created_at:#{created_at} last_posted_at:#{last_posted_at} excerpt:#{excerpt}"
  result = Topic.find_by_title(title)
  if result == nil then
    result = Topic.create
    result.title = title
    result.fancy_title = title
    result.user_id = user.id
    result.last_post_user_id = user.id
    result.updated_at = last_posted_at
    result.created_at = created_at
    result.bumped_at = bumped_at
    result.last_posted_at = last_posted_at
    result.excerpt = excerpt
    result.save!
  else
      puts result
      puts created_at,bumped_at,last_posted_at
      if result.user_id != user.id then
        result.user_id = user.id
        result.last_post_user_id = user.id
      end
      if result.updated_at != last_posted_at then
        result.updated_at = last_posted_at
      end
      if result.created_at != created_at then
        result.created_at = created_at
      end
      if result.bumped_at != bumped_at then
        result.bumped_at = bumped_at
      end
      if result.last_posted_at != last_posted_at then
        result.last_posted_at = last_posted_at
      end
      if result.excerpt != excerpt then
        result.excerpt = excerpt
      end
      if result.changed.length > 0 then
        result.save!
        puts result.slug
        post = result.first_post
        post.created_at = created_at
        post.updated_at = result.updated_at
        post.baked_at = result.bumped_at
        post.last_version_at = result.last_posted_at
        post.user_id = result.user_id
        post.last_editor_id = result.user_id
        post.raw = result.excerpt
        post.save!
        puts post
        #puts user.id
      end
  end
  puts "get_topic.result.slug:#{result.slug}"
  return result
end

Before the code creates a topic it searches for the title.
title = title.gsub(/ /,' ') result = Topic.find_by_title(title)
If a nil result occurs it then creates a topic.
It works for most topics, however, for one title it’s throwing ActiveRecord::RecordInvalid: Validation failed: Title has already been used when the topic is being saved.
The valiation settings for topic.title is
validates :title, if: Proc.new { |t| t.new_record? || t.title_changed? },
                    presence: true,
                    topic_title_length: true,
                    censored_words: true,
                    quality_title: { unless: :private_message? },
                    max_emojis: true,
                    unique_among: { unless: Proc.new { |t| (SiteSetting.allow_duplicate_topic_titles? || t.private_message?) },
                                    message: :has_already_been_used,
                                    allow_blank: true,
                                    case_sensitive: false,
                                    collection: Proc.new { Topic.listable_topics } }

I’ve checked in the console using Topic.find_by_title(‘title’). No topics exist with the title. I checked using Topic.find_by_sql("select * from topics where title like ‘start of title%’). No topics exist with the first word of the title.
What other checks can done … what could be causing the error saying the topic title has already been used when there are no topics found with that title?
Further information
I tried turning on allowing duplicate titles. The code ran through without an error yet there were no topics with the title that was causing the error after the import. Feels like the error message is wrong.


Q: Way to share task and results between Azure website and workers We need to change our system to a two-tiered structure on azure with an Azure website handling requests and adding tasks to a queue which will then be processed in priority order by a set of Azure worker roles. The website will then return the results to the end user. The data and results sets for each task will be largish (several megabytes). What's the best way to broker this exchange of data.
We could do it via an Azure storage blob but they are quite slow. Is there a better way? Up until now we have been doing everything in scaled azure website which allows all instances access to the same disk.

A: If this is a long-running process I doubt that using blob storage would add that much overhead, although you don't specify what the tasks are.
On Zudio long-running tasks update Table Storage tables with progress and completion status, and we use polling from the browser to check when a task has finished. In the case of a large result returning to the user, we provide a direct link with a shared access signature to the blob with the completion message, so they can download it directly from storage. We're looking at replacing the polling with SignalR running over Service Bus, and having the worker roles send updates directly to the client, but we haven't started that development work yet so I can't tell you how that will actually work.


Q: pass current browser url address to bean I want to send the browser url address to bean,I found this
HttpServletRequest requestObj = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String url = requestObj.getRequestURL();

I did not get the right browser address,so I will use javasript window.location to get the browser address,but how can I send this to back bean?Every answers will be helpful,any ideas?

A: Use
FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer")

in the back bean, you can have the request url. This bothers me for a long long time, hope this will help someone.


Q: How to upload an artifact to an Azure DevOps build using the API Can anyone shed some light on how to use the ADO API to upload an artifact to a build. I can't find an example that shows how to do this.
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/artifacts/create
I know there is the vso task: ##vso[artifact.upload]local file path
But, I need to do this from another script and the vso task isn't available.
Thanks.


Q: Tkinter - the button I made doesn't work I have tried to make a following program: when opening the program, it shows an entry and a button labeled as '9'. Character '9' is added at the end of the entry when clicking the button '9'.
The code given below is I have written, but it doesn't work as I intended. The button doesn't work and the entry shows '09' rather than '0'.
# -*- coding : utf-8 -*-
import Tkinter as Tk
class calculator:
   def __init__(self, master):
       self.num = Tk.StringVar()
       self.opstate = None
       self.tempvar = 0

       # entry
       self.entry = Tk.Entry(root, textvariable = self.num, justify=Tk.RIGHT, width = 27)
       self.entry.pack(side = Tk.TOP)
       self.num.set("0")

       # Buttons
       self.numbuts = Tk.Frame(master)
       self.ins9 = Tk.Button(self.numbuts, text = "9", width = 3, command = self.fins(9))
       self.ins9.pack()

       self.numbuts.pack(side = Tk.LEFT)

   ##### Functions for Buttons #####
   def fins(self, x):
       self.entry.insert(Tk.END, str(x))

root = Tk.Tk()
calc = calculator(root)
root.mainloop()

I guess the part command = self.fins(9) is problematic but I don't know how to resolve it. Thanks for any help.

A: The code is passing the return value of the method call, not the method itself.
Pass a callback function using like following:
self.ins9 = Tk.Button(self.numbuts, text="9", width=3, command=lambda: self.fins(9))
                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^


Q: How I can access Class method variable in instance method OR Use a common variable for both? I have this Class method to create a hero object.
+(id)hero
{
    NSArray *heroWalkingFrames;
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    }
    heroWalkingFrames = walkFrames;
    //Create hero sprite, setup position in middle of the screen, and add to Scene
    SKTexture *temp = heroWalkingFrames[0];

    Hero *hero = [Hero spriteNodeWithTexture:temp];
    hero.name =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
    return hero;
}

and I have another instance method to perform run animation for my hero.
-(void)Start
{
        SKAction *incrementRight = [SKAction moveByX:10 y:0 duration:.05];
        SKAction *moveRight = [SKAction repeatActionForever:incrementRight];
        [self runAction:moveRight];
}

now  heroWalkingFrames variable in Start method so I can perform animation, I want to add this line in Start method
 [SKAction repeatActionForever:[SKAction animateWithTextures:heroWalkingFrames timePerFrame:0.1f resize:NO restore:YES]];

Is there any way I can use this variable for both ?

A: Sure, in Hero.h add:
@property (nonatomic, retain) NSArray *walkingFrames;

Then, in your +(id)hero method, instead of declaring a new array NSArray *heroWalkingFrames, use:
+(id)hero
{
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    }

    //We set hero texture to the first animation texture:
    Hero *hero = [Hero spriteNodeWithTexture:walkFrames[0]];
    // Set the hero property "walkingFrames"
    hero.walkingFrames = walkFrames;

    hero.name =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
    return hero;
}


Q: Creating an Atlas where polygons have the same attribute I am struggling to create the following Atlas :
I have a coverage layer containing polygons. I want to create an atlas where each map contains polygons that have the same attribute vale (blockname). The image should also be saved as the blockname.
I just cannot figure it out. By the way I am using QGIS 2.6.1. Also I am joining a csv file with attributes to the polygon layer.


Q: Function template argument deduction with variadic class template as function call parameter All the examples are from here and here.
Specifically,
template<class...> struct Tuple { };
template<          class... Types> void g(Tuple<Types ...>);        // #1
// template<class T1, class... Types> void g(Tuple<T1, Types ...>);    // #2
template<class T1, class... Types> void g(Tuple<T1, Types& ...>);   // #3

g(Tuple<>());                     // calls #1
g(Tuple<int, float>());           // calls #2
g(Tuple<int, float&>());          // calls #3
g(Tuple<int>());                  // calls #3

With #2 uncommented, g()'s are resolved as described in the comments. What surprises me is that if I comment out the #2 line, the g()'s calls are resolved as follows:
g(Tuple<>());                     // calls #1
g(Tuple<int, float>());           // calls **#1 ???? why not #3????**
g(Tuple<int, float&>());          // calls #3
g(Tuple<int>());                  // calls #3

From the following examples and explanations below I can't see why g(Tuple<int, float>()); can't resolved to #3. It is the direction application of the following two rules:

If a parameter pack appears as the last P, then the type P is matched against the type A of each remaining argument of the call. Each match deduces the template arguments for the next position in the pack expansion.

template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
const int z = x;
f(x, y, z); // P=Types&..., A1=x: deduces the first member of Types... to int
            // P=Types&..., A2=y: deduces the second member of Types... to float
            // P=Types&..., A3=z: deduces the third member of Types... to const int
           // calls f<int, float, const int>

If P has one of the forms that include a template parameter list <T> or <I>, then each element Pi of that template argument list is matched against the corresponding template argument Ai of its A. If the last Pi is a pack expansion, then its pattern is compared against each remaining argument in the template argument list of A. A trailing parameter pack that is not otherwise deduced, is deduced to an empty parameter pack.

A: There's a misconception here between your two examples. In the 2nd example with f, you are deducing reference arguments to a function. In the 1st example with g, you are deducing reference template parameters to an argument to a function. The latter must match exactly, but the former is deduced against the referred types. They are not the same.

In your fist example,
g(Tuple<int, float>());

cannot call g(Tuple<T1, Types&...>). The template deduction process is about picking a deduced argument type that is identical to the called argument type. There are some exceptions (for referenced cv-qualifications, pointers, derived classes, arrays, functions), but none of those apply here. We simply need to pick T1 and Types... such that Tuple<T1, Types&...> is the same type as Tuple<int, float>. This is impossible as there is no such pack Types... for which Types&... is {float}, since float is not a reference!
So once you comment out (2), there's only one viable candidate: (1).

On the other hand,
template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
    const int z = x;
    f(x, y, z);
}

Here, Types&... is actually the type of the parameter itself (rather than a template argument of it), so (temp.deduct.call):

If P is a reference type, the type referred to by P is used for type deduction.

We deduce Types... to match the arguments. This succeeds because all the arguments are lvalues, and we simply pick {int, float, const int}.


Q: Xamarin ListView item click animation For some reason, i have this animation/effect by default when I press any items of my ListView (chat). I dont have any codes for that, it is just present/default.

Why is that? How can I turn it off or on?

A: It called "Ripple effect".
there are many related question in SO, see this https://stackoverflow.com/a/27237195/3814729 .


Q: R - Looping through Values in Variable and Dropping Duplicates Based on Condition I would like to loop through each unique value in the variable "Item" (i.e. A, B, C), and only keep the rows with the lowest ID number for each item, deleting the other rows for each corresponding item.
So, I have a data frame that looks like this right now:
Item    Cost    ID

A        4       1
A                3
B       39      10
B               18
B               21
C       290     15
C

And I want something that looks like this:
Item    Cost    ID

A        4       1
B       39      10
C       290     15

How do I do this?
(Thanks in advance - I'm new to R!)

A: your task is quite easy with dplyr, but there is a variety of approaches.
library(dplyr)
df %>% group_by(Item) %>% filter(ID == min(ID, na.rm = TRUE))

Source: local data frame [3 x 3]
Groups: Item [3]

    Item  Cost    ID
  <fctr> <dbl> <dbl>
1      A     4     1
2      B    39    10
3      C   290    15

Data used:
structure(list(Item = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L), .Label = c("A",
"B", "C"), class = "factor"), Cost = c(4, NA, 39, NA, NA, 290,
NA), ID = c(1, 3, 10, 18, 21, 15, NA)), .Names = c("Item", "Cost",
"ID"), row.names = c(NA, -7L), class = "data.frame")


Q: jquery image change doesnt work The following code should work but I cant seem to find the problem why it doesnt work, I am testing it with google chrome

        <input id="unos" type="submit" name="change_src" value="change image" />

A:

        <input id="unos" type="submit" name="change_src" value="change image" />


Q: How to enable (or set up) MySQL to use "group commit"? I've read a lot of good reviews of MySQL Group Commit, which was broken in MySQL 4.x but was fixed in 5.1 and 5.5. See http://dev.mysql.com/doc/innodb/1.1/en/innodb-performance-group_commit.html
But I could not find any document showing how to enable (or set up) Group Commit in MySQL 5.5. The above link only says sync_binlog needs to be set to 0 for group commit to support binary log. But it does not mention any config variable to turn on group commit.
Maybe Group Commit is an internal optimization in MySQL that's always "enabled" without a user doing any explicit config change?


Q: Using MDX Correlation() function to find correlation of 2 dimentional members I'm trying to find the Pearson correlation of a single measure between two members of a dimension, but the msdn docs are a bit sparse.  Specifically I have a cube with a fact count measure, a date dimension, and a tool dimension and I'd like to find the correlation of tool X and tool Y over the date dimension.

A: take a look at the following script (Adventure Works DW 2008 R2):
It will return correlation of [Internet Sales Amount] measure for two different product subcategories ("Mountain Bikes"/"RoadBikes") for months of current date member on rows (Calendar Year 2007 quarters and Calendar Year 2007). I have left other comparable members in comments.
with
member ActualMeasure    AS  [Measures].[Internet Sales Amount]

member m1 AS
(
    [Product].[Product Categories].[Subcategory].&[1] -- Mountain Bikes
--  [Sales Territory].[Sales Territory].[Group].&[North America]
--  [Customer].[Gender].&[F]
    ,ActualMeasure
)
member m2 AS
(
    [Product].[Product Categories].[Subcategory].&[2] -- Road Bikes
--  [Sales Territory].[Sales Territory].[Group].&[Europe]
--  [Customer].[Gender].&[M]
    , ActualMeasure
)
member x as
Correlation
(
    {Descendants([Date].[Calendar].CurrentMember,[Date].[Calendar].[Month]) } as dates
    , m1
    , m2
), Format_String="Standard"

select
{   x,m1,m2 } on 0,
{
    Descendants
    (
        [Date].[Calendar].[Calendar Year].&[2007]
        , [Date].[Calendar].[Calendar Quarter]
    )
    ,[Date].[Calendar].[Calendar Year].&[2007]
} on 1
from [Adventure Works]

HTH,
Hrvoje Piasevoli


Q: find and replace string on a line I'm trying to make a find and replace on strings
?version(.*) -> ?versionMyVersionHere

ex :
<script src="js/script.js?versionSomeVersionHere"></script>
<script src="js/messages.js?version"></script>

<script src="js/script.js?versionMyVersionHere"></script>
<script src="js/messages.js?versionMyVersionHere"></script>

I've tried something like :
sed -i -e "s/\?version/?versionMyVersionHere/g" index.html

But it append the text to the one already present...
Thank you for taking the time to help me with this !

A: sed 's#\?version.*\"#\?versionMyVersionHere\"#g'

Demo :
$echo -e '<script src="js/script.js?versionSomeVersionHere"></script>
<script src="js/messages.js?version"></script>'  |  sed 's#\?version.*\"#\?versionMyVersionHere\"#g'
<script src="js/script.js?versionMyVersionHere"></script>
<script src="js/messages.js?versionMyVersionHere"></script>
$

A: You may use:
sed -i 's/?version"/?versionMyVersionHere"/' index.html

Details:

*

*? doesn't need to be escaped in default BRE.

*Make sure to match trailing " in order to avoid matching partial word.

A: If you want to substitute all all occurrences of ?version for substitute in your file index.html, then execute the following command:
sed -i 's/?version"/?versionMyVersionHere"/' index.html


Q: order_products column connected with Google Checkout transaction in osCommerce I am using Google Checkout with osCommerce and want to know which column of the order_products database table is connected with the transaction.
Google Checkout displays the price details of every product and I want to know from where in the code this detail comes from.

A: In osCommerce the payment modules have a method called process_button().
This method draws a form with the hidden fields the payment method needs. In the case of Google Checkout it will draw the fields needed by Google to show the information.
You can check in catalog/includes/modules/payment/<your Google Checkout module>.php that function to see which fields are sent to Google Checkout to show the information.


Q: NSIS - Detect drivers available and let the user decide where to install an specific file (the license of the software) What I need is:
After the software is installed, I need to identify the drivers available (Hard Disks, Pen Drives, etc), and the user can chose in which drive he wants to install the license of the software. When he chooses, a .txt file is created and it's written there the drive he choose (Example: C:).
My code without that feature is here:
  !include "MUI2.nsh"
  !define NOME "S-Monitor"

  Name "${NOME}"
  OutFile "${NOME}.exe"
  InstallDir "C:\${NOME}"

  ShowInstDetails show

;--- Paginas ---

  !define MUI_ICON Labels\SetupICO.ico

    !define MUI_HEADERIMAGE
    !define MUI_HEADERIMAGE_RIGHT
    !define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp
    !define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp

  !insertmacro MUI_PAGE_WELCOME
  !insertmacro MUI_PAGE_DIRECTORY
  !insertmacro MUI_PAGE_INSTFILES

  !define MUI_FINISHPAGE_NOAUTOCLOSE
    !define MUI_FINISHPAGE_RUN
    !define MUI_FINISHPAGE_RUN_CHECKED
    !define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho"
    !define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop"

  !insertmacro MUI_PAGE_FINISH

;--- Idiomas ---

!insertmacro MUI_LANGUAGE "Portuguese"
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Spanish"

Function .onInit

  !insertmacro MUI_LANGDLL_DISPLAY

FunctionEnd

;--------------------------------
;Arquivos a serem instalados

Section "Instalacao"

SetShellVarContext all

  SetOutPath "$INSTDIR"
  File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR

SectionEnd

Function AtalhoDesktop
createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe"
FunctionEnd

A: The user smilepleeeaz helped me at another question, and that can also be used to answered this.
The code with the feature that I wanted is down below:
!include "MUI2.nsh"
  !include FileFunc.nsh
  !insertmacro GetDrives

  var newCheckBox

  !define NOME "S-Monitor"

  Name "${NOME}"
  OutFile "${NOME}.exe"
  InstallDir "C:\${NOME}"

  ShowInstDetails show
  AllowRootDirInstall true

;--- Paginas ---

  !define MUI_ICON Labels\SetupICO.ico

    !define MUI_HEADERIMAGE
    !define MUI_HEADERIMAGE_RIGHT
    !define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp
    !define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp

  !insertmacro MUI_PAGE_WELCOME
  !insertmacro MUI_PAGE_DIRECTORY
  !insertmacro MUI_PAGE_INSTFILES
  Page Custom CustomCreate CustomLeave

  !define MUI_FINISHPAGE_NOAUTOCLOSE
    !define MUI_FINISHPAGE_RUN
    !define MUI_FINISHPAGE_RUN_CHECKED
    !define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho"
    !define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop"

!define MUI_PAGE_CUSTOMFUNCTION_SHOW showNewCheckbox
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE launchNewLink

  !insertmacro MUI_PAGE_FINISH

;--- Idiomas ---

!insertmacro MUI_LANGUAGE "Portuguese"
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Spanish"

Function .onInit

  !insertmacro MUI_LANGDLL_DISPLAY
  InitPluginsDir
         GetTempFileName $0
         Rename $0 '$PLUGINSDIR\custom.ini'

FunctionEnd

;--------------------------------
;Arquivos a serem instalados

Section "Instalacao"

SetShellVarContext all

  SetOutPath "$INSTDIR"
  File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR

  MessageBox MB_OK "O software BDE (Borland Database Engine) será instalado agora"
  ExecWait "Ficheiros\bde_install_Win7_32_e_64.exe"

  FileOpen $1 '$INSTDIR\S-monitor.cpy' w
  FileWrite $1 "CPY Location=C:\S-Monitor.cpy"
  FileClose $1

  writeUninstaller $INSTDIR\uninstall.exe

SectionEnd

Section "Uninstall"

MessageBox MB_YESNO "Deseja desinstalar o S-Monitor?" IDYES true IDNO false
true:
  SetShellVarContext all
  delete $INSTDIR\uninstall.exe
  RMDir /R /REBOOTOK $INSTDIR
  Goto +2
false:
MessageBox MB_OK "Desinstalação cancelada."
SectionEnd

Function AtalhoDesktop
createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe"
FunctionEnd

Function showNewCheckbox
${NSD_CreateCheckbox} 120u 110u 100% 10u "&Iniciar o S-Monitor ao terminar a instalação"
Pop $newCheckBox
FunctionEnd

Function launchNewLink
${NSD_GetState} $newCheckBox $0
${If} $0 <> 0
    Exec "C:\S-Monitor\Smonitor.exe"
${EndIf}
FunctionEnd

Function CustomCreate
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Settings' 'NumFields' '6'

         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Type' 'Label'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Left' '5'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Top' '5'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Right' '-6'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Bottom' '17'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Text' \
         'Selecione o drive a ser instalada a licensa do S-Monitor:'

         StrCpy $R2 0
         StrCpy $R0 ''
         ${GetDrives} "HDD+FDD" GetDrivesCallBack

         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Type' 'DropList'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Left' '30'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Top' '26'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Right' '-31'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Bottom' '100'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Flags' 'Notify'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'State' '$R1'
         WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'ListItems' '$R0'

         push $0
         InstallOptions::Dialog '$PLUGINSDIR\custom.ini'
         pop $0
         pop $0
FunctionEnd

Function CustomLeave
        ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Settings' 'State'
        StrCmp $0 '2' 0 next
        ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State'
        strcpy $R0  $0
        StrCpy $0 $0 3
        FileOpen $1 '$INSTDIR\S-monitor.cpy' w
        FileWrite $1 "CPY Location=$R0S-Monitor.cpy"
        FileClose $1

        Abort
     next:
        ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State'
        StrCpy '$INSTDIR' '$0'
FunctionEnd

Function GetDrivesCallBack
         StrCmp $R2 '0' 0 next
         StrCpy $R3 '$R4'
         StrCpy $R1 '$9'
         IntOp $R2 $R2 + 1
      next:
         StrCpy $R0 '$R0$9|'
         Push $0
FunctionEnd


Q: How to measure distance between apple watch and iPhone? I know that core bluetooth is not available in watchOS2 so there is no way to read RSSI. But app like lookout released watch app that has a distance indicator. How did they do that? Any thought?

A: Using interactive messing pass mobile location to apple watch and calculate distance to shown on watch
Refer below apple link for communicating with the counterpart app
https://developer.apple.com/documentation/watchconnectivity/wcsession


Q: How to have make a div take a minumum of 50% space but if no sibling is present take 100% Simply put I have:
#Container {
display:'flex';
flex-wrap:'wrap';
}

.item {
flex-basis: '50%'
}

Scenario one:

 33 %

 33 %

 33%

Scenario 2

 50 %

 50 %

scenario 3:

 100 %

What I want in general tems is this to be fluid, the more items I put in the less space each item will have but if there is only 1 then I want it to take full space.

A: First you have to add display: flex; to #Container
#Container{
  display: flex;
}

If you want to equally distribute the space between children then you can use flex property as
.item{
  flex: 1;
}

Above CSS is minimum required styles, rest is for demo

#Container {
  display: flex;
  margin-top: 1rem;
}

.item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
}

.item:nth-child(1) {
  background-color: red;
}

.item:nth-child(2) {
  background-color: blueviolet;
}

.item:nth-child(3) {
  background-color: aquamarine;
}

33 %

33 %

33 %

 50 %

 50 %

100 %

A: I think that this example could give you an idea of how to achieve what you want:
https://codepen.io/Eylen/pen/vYJBpMQ
.Container {
 display: flex;
 flex-wrap: wrap;
  margin-bottom: 8px;
}

.item {
  flex-grow: 1;
  margin: 0 12px;
  background: #f1f1f1;
}

Your main issue in the code that you gave, is that you're missing the flex item behaviour. I have just set that the item can grow to fill the space with the flex-grow:1.

A: You can make sure a flex child covers up the space if it can, you can provide flex-grow: 1

#Container {
  display:flex;
}

.item {
  width: 100%;
  flex-grow: 1;
  border: 1px solid;
  text-align: center;
}

 Scenario 1

33 %

33 %

33%

 Scenario 2

50 %

50 %

 Scenario 3

100 %

A: Added a demo below.

$( document ).ready(function() {
  $( "#add" ).click(function() {
    $('#container').append('

');
  });
   $( "#remove" ).click(function() {
    $('#container').children().last().remove();
  });
});
#container {
  width:100%;
  height:500px;
  background-color:#ebebeb;
  display:flex;
  flex-direction: column;
}

.item {
  width:100%;
  display: flex;
  flex: 1;
  border-bottom:1px solid #007cbe;
}
.item1 {
  background:#007cbe;
}
.item2 {
  background: #d60000;
}
.item3 {
  background: #938412
}

1

2

3

<button id="add"> Add

<button id="remove"> Remove

A: Apply to the below CSS to fulfill your requirement.
#Container {
    display: flex;
}

.item {
    width: 100%;
    min-height: 100px;
    border: 1px solid;
}


Q: Good practice for finding existing instance of a class from another class that is not a child I'm trying to develop simple TowerDefense game but
it seems like I miss the very basics of OOP as I encountered problem
must be somehow fixable as everyone programming in OOP must have
enountered it.
Here's very very basic structure
Game
|__ Map

Player
|__ UnitController

+ Block
+ Unit

So basically Map() controller creates 100 new Block() passing x and y coordinates to it
and stores information about those Blocks() inside a List<>. One of those Block is starting
position (it's still a Block object).
Now UnitController() has SpawnUnit() method. It creates new Unit() and it (here comes the problem)
has to put this unit instance ON the starting block. In order to do that, UnitController will have to
ask Map for starting position (that is a variable stored by Map) but.. How does the UnitController
can contact Map instance. The only way I see is that Map is a singleton and I simply can do Map.getStartingPos
otherwise if Map is not a singleton (thus instance) then how UnitController will find this instance?
I could pass this instance to UnitController when I was instantiating UnitController but that's not an option I guess
because there'll be tons of other examples in this game (for example Towers which attacks units, it has to find a unit and ...)
and I can't simply throw those instances all around the code?
thanks

A: Why are you against giving the UnitController a reference to its Map?
public UnitController {

    private final Map map;

    public UnitController(Map map) {
        this.map = map;
    }
}

Now your UnitController has a reference to the Map.  And this makes sense, if you think about it.  What units can be controlled without a map?  Shouldn't all UnitControllers have a Map on which they are controlling units?  It makes sense as a property, does it not?
You certainly don't want to make Map a singleton, as you suggest, as this sort of breaks the elegant object-orientedness of your model.  The whole point is to be able to have multiple Maps, on which multiple UnitControllers can be acting.  Restricting this to one run at a time, one Map at a time, makes the code much more procedural than object-oriented.
No matter what you do, the Map and the UnitController will have to have something in common in order to share data, even if you don't want them to have direct references to each other.
As far as "towers which attack the nearest unit" being a reason not to use this model, it doesn't make sense; a Tower ought to simply request the nearest unit from the Map object (i.e., map.getNearestUnit(int x, int y)).  No need for any more convoluted references, as long as everything can push and pull information from the Map.
For a more complicated example of the threaded Tower you're concerned with:
public class Tower extends Unit implements ActionListener {

    private final Timer fireTimer;
    private final Map map;
    private int damage;
    private int range;

    public Tower(Map map, int damage, int range, int fireRate) {
        this.map = map;
        this.damage = damage;
        this.range = range;
        fireTimer = new Timer(fireRate, this);
        fireTimer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == fireTimer) {
            map.damageNearestUnit(this, range, damage);
        }
    }

}

... where the signature for map.damageNearestUnit is something like damageNearestUnit(Unit unit, int range, int damage).  This should essentially take the passed in Unit, get its coordinates, and find the nearest unit in the int range.  If one exists in range, deal the int damage to that other unit.  Then if the damaged Unit has less than 1 health, it should be removed from the Map, trigger a UI change, etc.
Actually, if I had simple getters and setters in my Tower and had my damageNearestUnit method assume that one unit was damaging another, I could simply have its signature be damageNearestUnit(Unit attacker).
I hope this shows how the Map is the fabric that binds everything else together and controls that which exists on it.


Q: how to check if x-staticmap-api-warning response header exists? I'm working on a project for school using the google static map api. There is a table with a list of locations. When you click on a location it brings up a modal window with the google map. If the api cannot find the location it just shows a map of water with an error. I noticed in the developer console under network there is a response header under the staticmap call titled x-staticmap-api-warning which contains the error.
Is there a way in javascript that can check if this response header exists so I can display a "Location unknown" message instead?


Q: Swift 3 CollectionView scaling I recently implemented a collection view in a app, the only problem I'm experiencing is that the collection view goes from 2 column to 1 column on smaller devices with a lot of padding on both sides
heres on a display smaller then a iPhone 6:

and heres how it looks on a display bigger or equal to a iPhone 6:

I did try several method where if the display width was smaller then a certain number it would scale up the cells, but it failed to work out because the cells where indeed scaled up but where not centered and over-lapping themselves.

A: You need to calculate your sizes depending on the phone size - if two cell's width are larger then screen size ( including all offsets between them ) they will layout as in the first picture.
You have two options:
One is to deal with sizes and rescale cells according to device size
Two leave it as is - Make small changes for iphone6/6s/7.
If you opt out for first one, you will need to set up constraint for these sizes - aspect ratio or center horizontally ( which could crop the image a little ).
For changing sizes dynamically, take a look at:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout
More specific:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview

A:
You need to calculate the cell width.Try this code.

class YourClass: UIViewController {
        //MARK:-Outlets
        @IBOutlet weak var yourCollectionView: UICollectionView!

        //Mark:-Variables
        var cellWidth:CGFloat = 0
        var cellHeight:CGFloat = 0
        var spacing:CGFloat = 12
        var numberOfColumn:CGFloat = 2

        //MARK:-LifeCycle
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()

            yourCollectionView.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)

            if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
                cellWidth = (yourCollectionView.frame.width  - (numberOfColumn + 1)*spacing)/numberOfColumn
               cellHeight = cellWidth //yourCellHeight = cellWidth if u want square cell
                flowLayout.minimumLineSpacing = spacing
                flowLayout.minimumInteritemSpacing = spacing
            }
        }

     extension YourClass:UICollectionViewDelegateFlowLayout{
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                return CGSize(width: cellWidth, height: cellHeight)
            }
    }


Q: Outlook 2007 and Sharepoint Services Issue We have a Windows Sharepoint Services (WSS 3.0) Project Management site on one of our Windows 2003 servers.
We are trying to give our users access to forms showing them the status of their requests and a form to allow them to add projects through Outlook 2007 which runs on Exchange 2003.
We found a post on how to add a new folder item in Outlook and set the Home Page as the sharepoint URL for application pages (web part pages created through WSS).
This works very well, except where you try and use a Person Lookup button or edit the properties of a document in a document list. (i.e http://myserver.local/ProjectSite/Project1.aspx)
I have noticed that the address box in Outlook shows "Outlook:ITInformation\My Live Projects".
If you click on one of the Sharepoint Quick Menu or Top Menu items that appear Outlook Window, the address box changes to http:// address of the page on the Sharepoint and buttons and menus work.
Also if I create a folder linking to the main page site (http://myserver.local/ProjectSite/) and click on the links everything works fine.
I am trying to create a focused version for our users rather than them have to work their way through the whole site to get to the information relevant to them.
I have searched the web for information on this, but I have now reached a brick wall.
Can anyone help?

A: Looks Like there is no solutions so am closing the question off


Q: R How to take Median of Rows in Dataframe I am wondering if there is any way to a median of the rows in a data frame. I understand the function rowmeans exists, but I do not believe there is a row median function. I would like to store the results in a new column in the dataframe. Here is my example
I tried to look online. There was one mention of row medians, but I could not find the function in R.
 C1<-c(3,2,4,4,5)
   C2<-c(3,7,3,4,5)
   C3<-c(5,4,3,6,3)
   DF <- data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)

   DF

  # This is as far as I have gotten, but not streamlined

  MA <- median(C(3, 3, 5). na.rm = T)   # A
  MB <- median(C(2, 7, 4). na.rm = T)   # B
  MC <- median(C(4, 3, 3). na.rm = T)   # C
  MD <- median(C(4, 4, 6). na.rm = T)   # 4
  ME <- median(C(5, 5, 3). na.rm = T)   # E

  CM <- c(MA, MB, MC, MD, ME)C1<-c(3,2,4,4,5)

   ID C1 C2 C3
  1  A  3  3  5
  2  B  2  7  4
  3  C  4  3  3
  4  D  4  4  6
  5  E  5  5  3

   ID C1 C2 C3  CM
  1  A  3  3  5
  2  B  2  7  4
  3  C  4  3  3
  4  D  4  4  6
  5  E  5  5  3

Is there anyway I can streamline the process so it would be like DF$CM <- median(...

A: If you would like to use dplyr, you can find an example here, especially mpalanco's answer. Briefly, after using rowwise to indicate that the operation should be applied by row (rather than to the entire data frame, as by default), you can use mutate to calculate and name a new column off of a selection of existing columns. Check out the documentation on each of those functions for more details.
E.g.,
library(dplyr)

DF %>%
  rowwise() %>%
  mutate(CM = median(c(C1, C2, C3), na.rm = TRUE))

will yield the output:
# A tibble: 5 x 5
  ID       C1    C2    C3    CM
  <fct> <dbl> <dbl> <dbl> <dbl>
1 A         3     3     5     3
2 B         2     7     4     4
3 C         4     3     3     3
4 D         4     4     6     4
5 E         5     5     3     5

A: Just a little bit more flexible and up to date. We use c_across with rowwise function and it allows to use tidy-select semantics. Here we choose where to specify we only want the numeric column to calculate the median.
library(dplyr)

DF %>%
  rowwise() %>%
  mutate(med = median(c_across(where(is.numeric)), na.rm = TRUE))

# A tibble: 5 x 5
# Rowwise:
  ID       C1    C2    C3   med
  <chr> <dbl> <dbl> <dbl> <dbl>
1 A         3     3     5     3
2 B         2     7     4     4
3 C         4     3     3     3
4 D         4     4     6     4
5 E         5     5     3     5

A: To calculate the median of df, you can do the following
df$median = apply(df, 1, median, na.rm=T)

A: Oneliner that allows you to pick your desired columns:
apply(DF[, c("C1", "C2", "C3")], 1, median)

  ID C1 C2 C3 CM
1  A  3  3  5  3
2  B  2  7  4  4
3  C  4  3  3  3
4  D  4  4  6  4
5  E  5  5  3  5


Q: Akka-http: How do I map response to object Not sure if I'm getting this whole routing DSL thing right but here's the question. I want to do a post to external service such as:
val post = pathPrefix("somePath") {
  post {
    //get the response mapped to my Output object
  }
}

Then I want the response (which is a Json) to be mapped to an object matching the fields for example Output (assuming I have my JsonProtocol set up). How is this done?

A: You are using HTTP server directives to "retrieve" something "externally". This is what typically an HTTP client does.
For this sort of things, you can use akka http client api.
For example:
val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete {
  case Success(res) =>
    val entity = Unmarshal(res.entity).to[YourDomainObject]
    // use entity here
  case Failure(ex) =>  // do something here
}

However, this requires some Unmarshaller (to deserialize the received json). Take also a look at Json Support, as it helps you define marshallers easily:
case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)

A: I think what you are trying to ask is how to get the body i.e in JSOn format to the Case class that you have
Here is a quick example:
    path("createBot" / Segment) { tag: String =>
            post {
              decodeRequest {
                entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
                   val updatedAnswer = doSomeStuff(caseclassInstance)
                  complete {
                    "Done"
                  }
                }
          }

You can find more detailed example from here : https://github.com/InternityFoundation/Stackoverflowbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56
I hope it answers your question.


Q: Reading CSV file through Flask I'm currently trying to read through a CSV file that is being provided through Flask-WTF(orms) and I continue to run into issues when trying to load it through csv.DictReader or pandas.
The file (a FileStorage object) is not actually being uploaded anywhere, and I am trying to grab the data within the CSV to use within my code.
This is how I'm trying to grab it now using pandas
f = form.upload.data
data = pandas.read_csv(f.stream)
logger.debug(data)

However this returned the error pandas.errors.EmptyDataError: No columns to parse from file
When I tried grabbing it through csv.reader this way:
reader = csv.reader(f.read(), delimeter=',')

for row in reader:
    logger.debug(row)

I got this error instead: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
I received a similar error when trying out csv.DictReader as well.
Has anyone tried to do anything similar to this, or know if this is even possible without uploading the file anywhere? I've looked around but I can't seem to find a proper solution.
For reference, my CSV file has a pretty basic format:
C1,C2
Data,Data

Thanks!


Q: Create Resource Group with Azure Management C# API Is there a way to create a Resource Group with the Azure Management C# API?
Basically this REST API call:
https://msdn.microsoft.com/en-us/library/azure/dn790525.aspx
I found a way to create an Affinity Group by using client.AffinityGroups.Create, but that's the closest thing I've found.

A: I found the API call was hidden in a library which is only in preview mode at the moment. It's found in the following NuGet package, enable include prerelease in Visual Studio to find it in the NuGet client.
https://www.nuget.org/packages/Microsoft.Azure.Management.Resources/
Then to create a resource group I can use
var credentials = new TokenCloudCredentials("", "");
var client = new Microsoft.Azure.Management.Resources.ResourceManagementClient(credentials);
var result = c.ResourceGroups.CreateOrUpdateAsync("MyResourceGroup", new Microsoft.Azure.Management.Resources.Models.ResourceGroup("West US"), new System.Threading.CancellationToken()).Result;

There is another stack overflow post explaining how to do the authentication:
How to get Tags of Azure ResourceManagementClient object
The following blog post explains how to set up TokenCloudCredentials, required for the authentication part, in more detail, but only for command line apps:
http://www.bradygaster.com/post/using-windows-azure-active-directory-to-authenticate-the-management-libraries
If you want to use something other than a command line app the following can work for authentication:
http://www.dushyantgill.com/blog/2015/05/23/developers-guide-to-auth-with-azure-resource-manager-api/

A: Go to https://resources.azure.com - the ARMExplorer shows both the REST and the PowerShell commands to create a resource group.  All the APIs are REST based.  In C#, send a WebClient request.


Q: Download handler (php code) is called multiple times for a single request I have a PHP script which handles the download requests. this script can be accessed by the client using a GET request like this (Javascript):
if (true)
{
  window.open('/download?mode=paper&fid=' + fid, '_blank');
  return;
}

And here is the (simplified) handler:
function downloadPaper($fid)
{
    // Adds a record to the database, but it seems to be called multiple times
    Daban\PaperTools::addPaperDownloadRecord($fid);

    header('Content-Description: File Transfer');
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$fakeFileName");
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header("Content-Length: " . filesize($file));

    $fh = fopen($file, "rb");
    while (!feof($fh))
    {
        echo fgets($fh);
        flush();
    }
    fclose($fh);
}

The problem is that according to the database, there are multiple download records for each download. In other words, the handler is called multiple times for a single request (or at least that is what I believe).
P.S. addPaperDownloadRecord() is jsut some piece of SQL code and it is not the culprit. I also checked the client side, it sends only once.

A: I managed to find the reason. If anyone has a similar problem, this may help. Since I had a download manager in my system, it sent multiple requests to divide the file in order to expedite the download process.


Q: User Generated Hyperlinks to Files Hosted on a Network Share My ultimate goal is to allow users to select a file from a dialog as if they are uploading a file.  Instead of file being saved to the server, a hyperlink will be generated from the file's path.  This hyperlink will then be used on our intranet page in order to open the file located on our network share.  Is there any practical way to accomplish this?
I have tried both an HTML file type insert and .Net's FileUpload Control but neither will work since for security reasons the full path of the file is never accessible.
The intranet site is built in VB.Net.

A: You would not be able to do this through a regular web page, since a web site gaining access to a file's path would be a gross security violation.  One thing you could do is have a control on your page where the server creates a file tree from browsing the network share.  Then the user would select the file path from this server-generated tree.

A: suppose your network share drive is the S: drive
if you use plain old file:// style URI's the links will auto open to your files on the share drive.
i.e. file://s:\techfiles\myfile.txt
in order to put the file on the share drive, you must be running that webapp on the share drive server(or have access to it), so just save that file off to the share server, then generate the path. The fact that the webapp server temporarily holds on to the file before storing it shouldn't bother you too much...


Q: php group array together based on key value being the same I have the following array
Array
(
[0] => Array
    (
        [id_product_option] => 1
        [id_option] => 1
        [id_product] => 3
        [option_value] => White
        [option_name] => color

    )

[1] => Array
    (
        [id_product_option] => 2
        [id_option] => 2
        [id_product] => 3
        [option_value] => 9oz
        [option_name] => size

    )

[2] => Array
    (
        [id_product_option] => 3
        [id_option] => 1
        [id_product] => 3
        [option_value] => Blue
        [option_name] => color

    )

)

What i need to do is loop through it and find the ones where the id_option values match and group them into a new array that should look like
Array
(
[0] => Array
    [0] => Array
        (
            [id_product_option] => 1
            [id_option] => 1
            [id_product] => 3
            [option_value] => White
            [additional_cost] => 0
            [is_active] => 1
            [created_on] => 2014-11-15 01:29:35
            [option_name] => color
            [option_text] => Color
        )

    [1] => Array
        (
            [id_product_option] => 3
            [id_option] => 1
            [id_product] => 3
            [option_value] => Blue
            [additional_cost] => 0
            [is_active] => 1
            [created_on] => 2014-11-15 01:29:35
            [option_name] => color
            [option_text] => Color
        )

[1] => Array
    (
        [id_product_option] => 2
        [id_option] => 2
        [id_product] => 3
        [option_value] => 9oz
        [additional_cost] => 0
        [is_active] => 1
        [created_on] => 2014-11-15 01:29:35
        [option_name] => size
        [option_text] => Size
    )

)

where the options with id_option 1 are grouped together
I tried the following but no luck
    $groupOptions = array();
    $prev = "";
    foreach($productOptions as $key=>$options) {
        $id_option = $options['id_option'];

        if($id_option != $prev) {
            $groupOptions[] = $productOptions[$key];
        }

        $prev = $id_option;
    }

A: You should use that id_option as the key in your new array, otherwise you're stuck having to hunt through the new array to find where the matching items are, which you're ALREADY doing in the first loop
$newarray = array();
foreach($oldarray as $item) {
   $newarray[$item['id_option']][] = $item;
}

A: I have tested with you example and seems to work fine :
$notFactored; # you should provide here your input array
$factored = array();
foreach($notFactored as $nf) {
    $found = FALSE;
    foreach($factored as &$f) { # passed by address !
        if(!empty($f[0]) && $nf['id_option'] == $f[0]['id_option']) {
            $f[] = $nf;
            $found = TRUE;
            break;
        }
    }
    if(!$found) {
        $factored[count($factored)][] = $nf;
    }
}
print 'my factored array : ' . print_r($factored);

Hope that Helps :)


Q: Размер выпадающего окна в хроме У меня написано расширение для хрома. На страничке есть несколько табиков. Один таб заполнен информацией и отображается нормально. Когда же происходит переключение на следующий, окно сжимается до минимума. При этом размеры всех элементов выставлены в максимум. Если открыть страницу как обычно, через браузер, все ок. Как правильно выставить размер страницы в расширение хрома?
A: Размер окошка расширения определяется внутренней разметкой. Если разметка пустая, то окошко сожмется до минимума - это правильное поведение. Чтобы этого избежать, надо определить размеры. Это можно сделать по разному, самый простой способ:
<body width="100" height="100" />


Q: How to group countries with similar age distributions? How can I group the world's 200-odd countries into (say) ten groups, with each group's countries having 'similar' age distributions?
I want to compare COVID-19 fatality rates across countries. But the proportion of aged is a confounding variable. I don't have the age-breakup of COVID fatalities for every country. Instead, I have population counts for each age group (e.g., "Country X has 10.3 million in the 10 to 20 age group", and so on).
So basically I want to stratify countries and compare within the resulting groups. Intuitively, 'older' countries like the US and Greece would be in different groups from 'younger' ones like India or Mexico. How would I go about this using R or another language?
A commenter asked why I didn't standardize fatality rates against some reference age distribution. That's because I suspect information on differences inherent to these countries may be lost in such standardization process.
Specifically, I'm comparing Covid-19 mortality with flu vaccination rates of the aged and there's a correlation (1) -- but I have to account for differences in national age distributions. I don't have age information on for Covid deaths in each country.  So stratification is the only other approach I can think of.
Source data: https://sourceforge.net/p/costat/code/ci/master/tree/

A: Why not standardizing the data?
You write

That's because I suspect information on differences inherent to these countries *may be lost in such standardization process.

and you write

but I have to account for differences in national age distributions.

I find this contradictory because age standardization is a way to account for differences in national age distributions.
But, you also write

I don't have age information on for Covid deaths in each country.

That is a valid reason why you can not use age standardization. You simply lack the information to do it.
Use a hypothetical age distribution
You could apply a hypothetical age distribution of deaths for the countries where you do not have this information.
You can do this by computing for all countries where you have the age information the relative risk of fatality as a function of age and based on that compute the hypothetical age distribution of the fatalities (hypothetical: if the distribution of fatalities would be according to the estimated/observed risk ratio in each age category)
Below is an example from the code below. The comparison is made with the death rates in the Netherlands. The x-axis gives the expected death rate in a country if it would experience the same age-dependent death rates as observed in the Netherlands. For instance you see Japan (JPN) with an old population having a high expected death rate and China (CHN) with a young population having a low expected death rate. On the y-axis you see the actual observed death rates. For this data and this set of countries, there is no clear correlation or dependency between age and death rate (this means that while age plays a role, it are other factors that are much more important in determining the death rate in a country).

Scale factor dependent on age distribution
Effectively this standardization based on a hypothetical age distribution provides a scale factor by which you multiply the fatality rate. You mention that information might get lost in this way. What you could do instead is perform a regression not on the transformed variable but by using the scale factor as an additional parameter in the model. You can do this either by making the classification into ten groups, but you could also use this scale factor without discretizing and as a non-categorical variable.
Simpler way
The above might be too complex and depending on the public that you are using your analysis for it might be difficult to explain your data and get you into (possibly unneccesary) details. An alternative is that you just use the % of the population that is 65 or older (or use some other age cutoff).
In the image below you see how the complex factor computed with the code below, is not much different from the percentage of the population older than 65.

Example code and graph

Eventually, the difference due to the standardization is not so big (the difference with your image is due to the data in this graph being from December instead of August). This is because many other factors play a more important role than age.
In addition, the effect of the parameters that you are investigating, influence vaccination, is not so clear. Even if the effect would be clear then there are too many other factors involved and you can not really say that influenza vaccination has a causal effect (I guess that this might be what you attempt to show).
library(countrycode)
library(readxl)

### data files
data  <- read_excel("Downloads/data.xlsx", sheet = "main")

### XLSX from UN https://population.un.org/wpp/Download/Standard/Population/
data2 <- read_excel("Downloads/WPP2019_POP_F07_1_POPULATION_BY_AGE_BOTH_SEXES.xlsx", skip = 16)

### CSV from RIVM https://www.rivm.nl/coronavirus-covid-19/grafieken
#data3 <- read.csv("~/Downloads/leeftijd-en-geslacht-overledenen.csv", sep=";")
#agecases <- rowSums(data3[,2:3]) ### adding male + female columns
agecases <- c(0,   0,   0,    2,    0,    3,    6,
              13,  11,  42,   76,   133,  241,
              474, 942, 1538, 2063, 2283, 1414, 534)

### John Hopkins data
data4 <- read.csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv")

### selection of countries which have flu vaccination data
sel <- which(!is.na(data$flu))
sel <- sel[-6] ### Remove Liechtenstein for lack of age distribution data
datasel <- data[sel,]

### get a reference key to connect rows with same countries from the two data sets
years <- data2$`Reference date (as of 1 July)`
countries <- countrycode(data2$`Country code`, origin = 'iso3n', destination = 'iso3c' )
refkey <- sapply(datasel$ccode, FUN = function(x) {
                    which((years == 2020) * (countries == x) == 1)[1]
                })
refkey <- as.numeric(refkey)

### get covid cases from JH data
cc <- 'USA'
name <- countrycode(cc, origin = 'iso3c', destination = 'country.name')

ncases <- function(cc) {
  subsel <- c(1)

  ### special cases where JH data has multiple regions
  if (cc == 'NLD') {subsel <- c(5)} ### only use Netherlands, no colonees
  if (cc == 'DNK') {subsel <- c(3)} ### only use Danmark, no Greenland + Faroe
  if (cc == 'GBR') {subsel <- c(11)} ### only use UK, no colonies
  if (cc == 'FRA') {subsel <- c(11)} ### only use France, no colonies
  if (cc == 'AUS') {subsel <- c(1:8)} ### sum all provinces
  if (cc == 'CAN') {subsel <- c(1:16)} ### sum all provinces
  if (cc == 'CHN') {subsel <- c(1:33)} ### sum all provinces

  name <- countrycode(cc, origin = 'iso3c', destination = 'country.name')

  ### special cases where JH data uses other country name
  if (cc == 'USA') {name <- 'US'}
  if (cc == 'KOR') {name <- 'Korea, South'}

  rows <- which(data4$Country.Region == name)[subsel]
  nc <- max(colSums(data4[rows,-c(1:4)])) ### get the last non-empty column (which is the maximum)

  return(nc)
}
ncases <- Vectorize(ncases)

# compute age dependent risk (incidence) based on Netherlands
# this will be roughly an exponential function of age
nrow  = refkey[27]
data_row <- data2[nrow,]
agepop <- as.numeric(data_row[9:28])*1000
agepop[20] <- agepop[20] + as.numeric(data_row[29])*1000  ## combine 95-99 and 100+ to create 95+
agerisk <- agecases/(agepop/10^6)  ### cases per million

###
### function to compute risk based on age distribution
### this will give the risk if the death rates
### would be according to the data of the Dutch RIVM
###
age_risk <- function (nrow) {
  data_row <- data2[nrow,]
  agepop <- as.numeric(data_row[9:28])*1000
  agepop[20] <- agepop[20] + as.numeric(data_row[29])*1000  ## combine 95-99 and 100+ to create 95+
  avgrisk <- sum(agerisk*agepop)/sum(agepop)
  return(avgrisk)
}
age_risk <- Vectorize(age_risk)
risk <- age_risk(refkey)

### plotting

deaths <- ncases(datasel$ccode) ### deaths per country
pop <- datasel$pop

### color + size of bubbles
region <-  countrycode(datasel$ccode, origin = 'iso3c', destination = 'continent' )
color <- as.numeric(as.factor(region))+1
size <- 1+sqrt(datasel$pop)/10^4

### scatterplot
plot(datasel$flu, (deaths/(pop/10^6))/risk, log = "y",
     pc = 21,
     col = 1, bg = color, cex = size, xlim = c(0,100),
     ylab = "standardized incidence \n (1 = equal to Dutch RIVM figures)",
     xlab = "influenza vacination rates"
     )

lines(c(-10,110),c(1,1), lty = 2, col = 8)

### add labels
text(datasel$flu, (deaths/(pop/10^6))/risk, datasel$ccode, cex = 0.7, pos = 4)


Q: Change Icon on Bootstrap 4.6 accordion I want to have a 'plus' icon when the accordion is collapsed, and a 'minus' icon when the accordion is 'expanded'.
I have checked other answers on the internet, but what am I asking is can't I do something simple like this? (For learning purposes)
Say I place both the plus and minus icons on the accordion
<i class="fa-plus"> <i class="fa-minus">
As I see, when the accordion is collapsed, it has a collapsed class, so I'd like to hide and show both the icons as the collapsed class gets toggled on click. Why doesn't it work as the DOM gets updated when the accordion is clicked?

if(document.getElementById('candidateName').classList.contains('collapsed')) {
  document.querySelector('.fa-minus').style.display = 'none';
  document.querySelector('.fa-plus').style.display = 'block';
  }
 else {
  document.querySelector('.fa-plus').style.display = 'none';
  document.querySelector('.fa-minus').style.display = 'block';
 }

Please note that this is just for learning purposes. I want to understand this, please don't get offended. Thankyou

A: Glad you are learning. Apologies if my response comes across in a different plane than your current level.
When you run JS, you're executing the code in the current state of the content. It appears that you are hoping for the icon to change from a + to a - and vice verse when the accordion is expanded/collapsed.
What you need to do, is watch the page for changes to the accordion - these are called event listeners. Bootstrap has some really convenient ones that you can use for this. Since the Accordion uses collapse events API. From there, you can watch the page for changes, and execute the change you want whenever that change happens.
const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.bs.collapse', event => {
  // do something...
})


Q: How to push data from AWS IoT MQTT broker to a random file in S3 bucket I have created a rule to forward all messages published to any topic e.g. foo/bar of my AWS IoT core managed MQTT broker to a nested folder in S3 bucket. For that, I am using key section. I can send data to nested folder like a/b/c. The problem is - it takes c as destination file and this file gets updated with new data as it arrives. Is there any configuration that I can do to put data in bucket in a new file (with any random name) as it arrives (similar to how it happens when we forward data from firehose to S3)

A: You can change your key to use the newuuid() function. e.g.
a/b/${newuuid()}

This will write the data to a file in the a/b folder with a filename that is a generated UUID.
The key in AWS IoT S3 Actions allow you to use the IoT SQL Reference Functions to form the folder and filename.
The documentation for the key states:

The path to the file where the data is written. For example, if the value of this argument is "${topic()}/${timestamp()}", the topic the message was sent to is "this/is/my/topic,", and the current timestamp is 1460685389, the data is written to a file called "1460685389" in the "this/is/my/topic" folder on Amazon S3.

If you don't want to use a timestamp then you could form the name of the file using other functions such as a random float (rand()), calculate a hash (md5()), a UUID (newuuid()) or the trace id of the message (traceid()).


Q: Wordpress + Divi: Custom Section Toggle I have a child theme editing the main-structure-elements.php file from the Divi parent theme. I have tried to override this file by moving it into the child theme and making the changes there, as well as modifying the functions.php file to require that file, still no luck.
I just need to add a toggle to the Divi sections that adds a css filter. This is the code I have written in the main-structure-elements.php file which works great in the main divi file but is unrecognized if added just in the child theme file.
public function get_fields() {
    $fields = array(

        'fullpage_height'              => array(
            'label'            => esc_html__( 'Enable Fullpage', 'et_builder' ),
            'type'             => 'yes_no_button',
            'option_category'  => 'configuration',
            'options'          => array(
                'off' => et_builder_i18n( 'No' ),
                'on'  => et_builder_i18n( 'Yes' ),
            ),
            'default'          => 'off',
            'description'      => esc_html__( 'Here you can select whether or not your page should have Full Height enabled. This must be enabled on all sections to function', 'et_builder' ),
            'tab_slug'         => 'advanced',
            'toggle_slug'      => 'layout',
            'default_on_front' => 'off',
        ),

this code then is triggering this code later in that same file.
if ( 'on' === $fullpage_height ) {
        $this->add_classname( 'fullpage-vertical' );
    }

I have been working on this for days, any insight would be a life saver

A: Did you try run this code as snippet using plugin "Code Snippets"? Maybe at this way the code will work fine.


Q: Java: show compiler phases like `scalac -Xprint:parser` javac -Xprint only shows the class's API.
i can write a scala program, compile it with scalac -Xprint:<phase>, and print out the tree with whatever processing has done at any phase.
i want something that can emit the representation at each of the fundamental stages of java compilation:
$ javac -Xshow-phases
             phase name  description
             ----------  -----------
                 parser  parse source into ASTs, perform simple desugaring
                  namer  resolve names, attach symbols to named trees
         packageobjects  load package objects
                  typer  the meat and potatoes: type the trees
         superaccessors  add super accessors in traits and nested classes
              refchecks  reference/override checking, translate nested objects
                erasure  erase types
                flatten  eliminate inner classes
                    jvm  generate JVM bytecode

does such an option or tool exist? how could we do this in java?


Q: How do I group objects by similiar items that they contain? I have 10,000 baskets.
In each basket, I have 10 food objects, no repetitions.
I need to group baskets in groups where all baskets in the group have >=6 of the same objects within them, with no repetitions in any group. Basically, if a group has basket1, basket2, basket33, basket 123, then no other groups will have them.
When I try to do it with combinations, I end up with many redundant groups.
from typing import Generic, TypeVar, List
import random
from uuid import uuid4
import attr

T = TypeVar("T")

food = ['apple', 'banana','grapes','orange','potato','kiwi','pomegranate','blueberry','strawberry','cantalope','honeydew','papaya','mango','raspberry',
        'celery','carrot','potato','raddish','lettuce','tomato','garlic','onion','cabbage','corn','shallot','peas','squash','broccoli','spinach']
        #'pasta','sugar','flour','honey','salt','pepper','corn starch','baking soda','cinnamon','paprika','butter','cream','chocolate']

@attr.dataclass
class Basket(Generic[T]):
    items: List[T]
    volume: int
    id: str = attr.ib(factory=lambda: str(uuid4()))

#Generate baskets
basket_names = [f"basket{i}" for i in range(1, 10001)]
baskets: List[Basket[str]] = [
    Basket(items=random.sample(food, 10), volume=random.randint(0, 1000), id=name)
    for name in basket_names
]

A: Here is a solution using scikit-learn.

*

*sklearn.preprocessing.MultiLabelBinarizer to transform each basket into a 0-1 vector with one coordinate per food type;

*sklearn.cluster.AgglomerativeClustering to make clusters, with baskets in the same cluster if they differ by at most 8 food types (8 = 2 * 4 = 2 * (10 - 6), so if two baskets have exactly 6 food types in common, then their vectors will differ by 8 coordinates)

*AgglomerativeClustering().fit_predict() returns a list of numbers: number x at index i in the list means that the ith basket is in the xth cluster.

*itertools.groupby with zip can be used to get the clusters as a list of lists of baskets.

import random
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import MultiLabelBinarizer
from itertools import groupby
from operator import itemgetter

n_baskets = 10000
n_foodperbasket = 10
n_samefoodpercluster = 6
max_volume = 1000

food = sorted(['apple', 'banana','grapes','orange','potato','kiwi','pomegranate','blueberry',
 'strawberry','cantalope','honeydew','papaya','mango','raspberry', 'celery','carrot',
 'raddish','lettuce','tomato','garlic','onion','cabbage','corn','shallot',
 'peas','squash','broccoli','spinach']) # removed your duplicate 'potato'

baskets = [(random.sample(food, n_foodperbasket), random.randint(0,max_volume), i) for i in range(n_baskets)]

vectorbaskets = MultiLabelBinarizer(classes=food).fit_transform([b[0] for b in baskets])

clustering = AgglomerativeClustering(n_clusters=None, distance_threshold=2*(n_foodperbasket - n_samefoodpercluster))
clusters = clustering.fit_predict(vectorbaskets)

groups = [list(g) for k,g in groupby(sorted(zip(clusters, baskets)), key=itemgetter(0))]

print(groups)