text:
Q: Can a domain event be emitted without being part of an aggregate state change (DDD) I would like to know how can a domain event be implemented (in DDD) if it is not a natural result of an aggregate's state change.
I will borrow the example of this post.
So lets say that we need an event like: temperatureWasMeasured which could be a product of some modelling we have done (e.g. in an event storming session).
This event feels like a product of some read action and not an actual state change of some aggregate.
So the question is:
Where and how this event could make sense to be emmited?.
We could create an entity or an aggregate, which could have a state to count the number of reads in order to be emmited as a state change. But is this really necessary?
In the resources out there, the definition of the "domain event" does not seem to mention state change, but just as something which has happened in the domain.
So an action of a measurement (in a non quantum mechanical environment ), is considered to be a domain event, like the temperatureWasMeasured event?
It would be great if someone could clarify these questions, since it seems there is no clear answer out there.

A: Interesting question... I'm trying to get to grips with DDD as well.
Wouldn't you use a Boolean value object within an aggregate to define if its true to false in this case? If temperature was measured or not?
I've always thought you would need to associate any event to an aggregate....

A: Nice question, my understanding is that domain events should occur when domain state changes and not in a simple query.
In the above example if we want to measure temperature we just query using a repository directly from application layer that has nothing to do with domain, so no domain events should occur.
If someone else is interested in the temperature changes like the example they should probably listen to temperature changed domain event and get their initially state from a query.
If there is a need to know the measurements for this domain a TemperatureMeasure aggregate might be missing from the design that will persist all the measurements and also emit domain events.


text:
Q: Frobenius pullback of $\mathcal O_X$ and Frobenius twist Let $k$ be a perfect field of characteristic $p > 0$ and let $X \to S = \textrm{Spec } k$ be a scheme. Let $F : X \to X$ be its absolute Frobenius and let $X' := X \times_{F_S} S$ be the Frobenius twist of $X$.

Question: are the sheaves $F^* \mathcal O_X$ and $\mathcal O_{X'}$ the same (as sheaves of $k$-algebras)?

Note that $X$ and $X'$ have the same underlying topologial space, hence we can compare those sheaves. It seems to me that both sheaves are just $\mathcal O_X$ with a "funny" $k$-algebra structure:
$$(\lambda, x) \mapsto \lambda^{1/p} \cdot x$$
-hence the question.
For an arbitrary scheme $S$ (not necessarily perfect) of characteristic $p$ this isn't true in general, right?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tetris trouble bug-fixing I have just started learning pygame and wanted to begin with Tetris. I chose TechwithTim's tutorial to start with
Link to github
My 2 problem that I encounter are with
def clear_rows(grid, locked):
    # need to see if row is clear the shift every other row above down one

    inc = 0
    for i in range(len(grid)-1,-1,-1):
        row = grid[i]
        if (0, 0, 0) not in row:
            inc += 1
            # add positions to remove from locked
            ind = i
            for j in range(len(row)):
                try:
                    del locked[(j, i)]
                except:
                    continue
    if inc > 0:
        for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
            x, y = key
            if y < ind:
                newKey = (x, y + inc)
                locked[newKey] = locked.pop(key)

   return inc

If you fill 3 lines but there is one in the middle that is not complete in between those two, then the grid doesn't go down correctly,

Secondly:
def check_lost(positions):
    for pos in positions:
        x, y = pos
        if y < 1:
            return True
    return False

If The player rotate the shape above the grid the game automatic count that as a lost

Anyone have any idea on how to fix these bug? I have looked for solutions in the comments on the youtube tutorial and similar code on github but they never fix any of these


text:
Q: how to make cdn server ubuntu system I am searching for a software that can be use for setup CDN Server on ubuntu system i also have tried Squid Cache but unable to setup it please anybody suggess me software that can be used for make CDN server on my ubuntu system

A: Squid Cache is a caching system it is not proper CDN system try to use OpenCdn it should be helpfull for make cdn server you can get detail information and documentation on labtel.ing.uniroma1.it

A: Try to use Ubuntu OpenStack cloud you can download it from here Ubuntu OpenStack


text:
Q: Confidence when "sorting" multiple samples by mean? In a one-way ANOVA, we test if the mean is different amongst multiple groups.  The results of this might not be super useful when testing a large number of groups, because we only get a confidence related to "someone being out of place" rather than a confidence for "which is biggest", etc.  OTOH, it seems that I can sort my sample means from smallest to largest, and that this provides me with some evidence of which population has the smallest mean, which has the largest mean, which population is in the middle, etc.  However, ANOVA doesn't allow me to quantify evidence for my sorting procedure.
One option here is to compute an X% confidence interval for each mean, use a multiple-comparisons correction (how many comparisons are there?), and make statements about my sorting based on this.  e.g. if the largest sample mean has a confidence interval that doesn't overlap any other CIs, then I have good evidence that this is, in fact, the population with the largest mean.  This seems like it will be extremely conservative.
How can I find the e.g. largest, smallest, median population mean in a group of $M$ populations?

A: This is related to what the Newman-Keuls method does: "Prior to any mean comparison, all sample means are rank-ordered in ascending or descending order." It starts by comparing the lowest and highest means based on the Studentized range.
If they differ significantly, then it proceeds with sets of further comparisons between successively more closely spaced mean values--lowest versus next-to-highest, highest versus next-to-lowest, etc. If two mean values at the extremes of a range aren't found to differ significantly this way, then "all the null hypotheses within that range would be retained and no further comparisons within smaller ranges are necessary."
So this way you would get the set of other means that can't be distinguished significantly from the highest or the lowest or the median of your ranking of means. It doesn't provide confidence intervals or correction for multiple comparisons other than the use of the Studentized range.


text:
Q: What is the best way to convert text from different direction? I'm creating an interface that has a list of employees with the names of each one. But in this list I'm going to have random names from all countries. And in the interface there will be two text directions LTR (Left To Right) and RTL (Right To Left).
However, I don't know the names that go into this list of employees as I'm going to take it from the database and insert it into my document and my solution was to insert the names inside each <bdi> element:

<bdi>Bernado Silva</bdi>

<bdi>Lucas Oliveira</bdi>

<bdi>إبرو</bdi>

Thus, if the name is in a right-to-left direction, the browser will treat the text in isolation from the surrounding text. But I wonder, is this right? I care about accessibility and semantics and if the name is LTR, wouldn't it be incorrect to say it's RTL?


text:
Q: Communication between PHP (Zend) and the database I'm trying to understand how actually the communication between Zend framework and the database works (but it's not so easy as it seems ;) ).
My main focus is on  Zend_Http_Client_Adapter_Socket class, especially read() function. In some magical way it receives the response from the database and sets the status of the answer. However I cannot spot where is the actual data processing done. What if I want to control the code returned by the database? F.e. I want database to return 204 in some special cases depending on data. Where can it be done?
I see that sockets enable communication by waiting for each other requests/responses. But Where is it exactly done on the part of the database?

A: I think you should concentrate more on the Zend_Dd_Adapter as RockyFord mentioned in the comment section.
When i am working with the ZF my model comes in 2 parts. An object where the data from the database is holded in and a mapper that has the methods save, edit, delete, find and many more.
So the Mapper is initialising a new Zend_Db_Table_Abstract. Example:
class Application_Model_DbTable_Cable extends Zend_Db_Table_Abstract
{
    protected $_name = "cable";
    protected $_primary = "ID";
}

The instance of Zend_Db_Table_Abstract should you store in your mapper and than you can call for example:
$this->dbTable->find($id);

For more information have a look at the Reference Guide of the ZF: Zend_Db
Or ask it here :)

A:
Where can it be done? I see that sockets enable communication by
  waiting for each other requests/responses. But Where is it exactly
  done on the part of the database?

Your questions really don't apply to Zend_Http_Client_Adapter_Socket as it relates to a database.
Zend_Http_Client_Adapter_Socket deals with an http connection request/response cycle.
All of the database adapters in Zend Framework are primarily wrappers (emulate and/or extend the function) for the PHP extensions. (PHP extensions are registered in the php.ini file and have the format of extension=extension_name)
Most of us are currently using the PDO extension for our favorite variety of database.
So to really answer your questions you'll need to dig into the creation of a database adapter for PHP. You might start with http://www.php.net/manual/en/internals2.pdo.php if you are really curious.
However you can code a controller to return a response through  Zend_Http_Client_Adapter_Socket based on the results of a database query.


text:
Q: Use Haml files in Redmine plugin I am creating a Redmine plugin and would like to use Haml for the view templates.  There is an existing plugin which has Haml views (ekanban) and it does not contain any special code to get Haml working other then having you add require 'haml' to your main application's Gemfile.
So here is what happens -- the templating system loads the .html.haml file correctly but renders the HAML markup (like it was rendering ERB).
I've tried to insert the require 'haml' at various intervals to no avail.  I've even tried manually trying to activate Haml.init_rails(...) as suggested in this SO question.  I've tried inserting that in a few places, tried it in a Rails.configuration.to_prepare block in the plugins' init.rb file.  I've tried telling the Gemfile to not require 'haml' and attempting to do it during plugin load to no avail.  What gives?

A: The view template had Textile in it and I did not notice because the markup for <h2> is similar (h2. vs. %h2).  Including gem 'haml_rails' in the plugin's Gemfile is sufficient with no extra code.

A: Read carefully Installation instruction for this gem :)

Add "gem 'haml'" to your #{RAILS_ROOT}/Gemfile

I can't agree with this strategy: plugin can't change Redmine core! Any Redmine plugin can have own gems (defined in own Gemfile) - so I think you can create Gemfile in your plugin, run bundle install from the Redmine root and I believe you will manage to use Haml


text:
Q: How to link IRC and Google Talk? I am looking for a way to link IRC to Google Talk.
At the moment we use Partychatapp for google talk and we'd like to find a way to migrate to using IRC.
The vision is to have everyone in an IRC room and we'd be able to have a google talk bot people could use to talk to the room.
Does anything like this exist?

A: You want bitlbee.  It looks like an IRC server to IRC clients and gateways to other IM protocols.

A: I wrote an application that does exactly this: https://github.com/PaulFreund/I2X
Multiple Users use it on a daily base and there are Ideas to expand it further.
At the moment it logs on to a XMPP account and to an IRC channel, and translates between the two. It works as-is without problems but could be better, if there were more users I probably had more interrest in developing it further.

A: I played with bitlbee a few years ago.  Unless it's changed, it's not actually an IRC server, it just pretends to be one.  It provides an irc-flavored proxy to the jabber server, so you can use your favorite IRC client to connect to a jabber server via bitlbee.


text:
Q: MySQL (MariaDB) Not Starting I am running Arch Linux 4.8.4-1 on a 64bit installation. I installed MariaDB via pacman. When I try to start it with systemctl start mysqld, it gives me
Job for mariadb.service failed because the control process exited with error code.
See "systemctl status mariadb.service" and "journalctl -xe" for details.

The output of systemctl status mariadb.service is
● mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Wed 2016-11-02 16:55:12 IST; 3min 6s ago
  Process: 5123 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUSTER $_WSREP_START_POSITION (code=exited, status=1/FAILURE)
  Process: 5070 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`/usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set
  Process: 5067 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 5123 (code=exited, status=1/FAILURE)
   Status: "MariaDB server is down"

Nov 02 16:55:11 pranav-laptop systemd[1]: Starting MariaDB database server...
Nov 02 16:55:12 pranav-laptop mysqld[5123]: 2016-11-02 16:55:12 140082509282496 [Note] /usr/sbin/mysqld (mysqld 10.1.18-MariaDB) starting as process 5
Nov 02 16:55:12 pranav-laptop mysqld[5123]: 2016-11-02 16:55:12 140082509282496 [Warning] Can't create test file /var/lib/mysql/pranav-laptop.lower-te
Nov 02 16:55:12 pranav-laptop mysqld[5123]: [90B blob data]
Nov 02 16:55:12 pranav-laptop systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE
Nov 02 16:55:12 pranav-laptop systemd[1]: Failed to start MariaDB database server.
Nov 02 16:55:12 pranav-laptop systemd[1]: mariadb.service: Unit entered failed state.
Nov 02 16:55:12 pranav-laptop systemd[1]: mariadb.service: Failed with result 'exit-code'.

If I need to post anything else, let me know...
UPDATE: After trying Jérémy Munoz's comment, mysql still doesn't start, but I get a different systemctl status mariadb.service
● mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Wed 2016-11-02 21:03:24 IST; 4min 7s ago
  Process: 14350 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUSTER $_WSREP_START_POSITION (code=exited, status=1/FAILURE)
  Process: 14296 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`/usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl se
  Process: 14294 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 14350 (code=exited, status=1/FAILURE)

Nov 02 21:03:24 pranav-laptop mysqld[14350]: 2016-11-02 21:03:24 140412958252224 [ERROR] Could not open mysql.plugin table. Some plugins may be not lo
Nov 02 21:03:24 pranav-laptop mysqld[14350]: 2016-11-02 21:03:24 140412958235392 [Warning] Failed to load slave replication state from table mysql.gti
Nov 02 21:03:24 pranav-laptop mysqld[14350]: 2016-11-02 21:03:24 140412362684160 [Note] InnoDB: Dumping buffer pool(s) not yet started
Nov 02 21:03:24 pranav-laptop mysqld[14350]: 2016-11-02 21:03:24 140412958252224 [ERROR] Can't open and lock privilege tables: Table 'mysql.servers' d
Nov 02 21:03:24 pranav-laptop mysqld[14350]: 2016-11-02 21:03:24 140412958252224 [Note] Server socket created on IP: '::'.
Nov 02 21:03:24 pranav-laptop mysqld[14350]: 2016-11-02 21:03:24 140412958252224 [ERROR] Fatal error: Can't open and lock privilege tables: Table 'mys
Nov 02 21:03:24 pranav-laptop systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE
Nov 02 21:03:24 pranav-laptop systemd[1]: Failed to start MariaDB database server.
Nov 02 21:03:24 pranav-laptop systemd[1]: mariadb.service: Unit entered failed state.
Nov 02 21:03:24 pranav-laptop systemd[1]: mariadb.service: Failed with result 'exit-code'.

UPDATE: After running mysql_install_db, I get this error:
FATAL ERROR: Could not find ./bin/my_print_defaults

If you compiled from source, you need to either run 'make install' to
copy the software into the correct location ready for operation.
If you don't want to do a full install, you can use the --srcddir
option to only install the mysql database and privilege tables

If you are using a binary release, you must either be at the top
level of the extracted archive, or pass the --basedir option
pointing to that location.

The latest information about mysql_install_db is available at
https://mariadb.com/kb/en/installing-system-tables-mysql_install_db

/etc/mysql/my.cnf

A: cd /var/lib/mysql
ls
rm -r *
mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
systemctl start mysqld
systemctl start mysql.service
systemctl start mariadb
mysql

Then it works just fine

A: You need to run mysql_install_db to initialize MySQL data directory.

A: Faced same problem. This got resolved after following below steps:

*

*Uninstalled the mariadb maridb-server packages

*Removed the directory /var/lib/mysql.

*Reinstalled the Mariadb, Mariadb-server packages.

*systemct start mariadb; systemctl enable mariadb

(problem solved).

A: If you haven't any real data in your database then clear all in /var/lib/mysql.
After that try again to run command mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql to initialize database directory.

A: I had same problem on Ubuntu 18.04m packages registered seem unable to start or else...
I resolved by adding correct package list and signature from the this site.
sudo apt-get install software-properties-common
sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8
sudo add-apt-repository 'deb [arch=amd64,arm64,ppc64el] http://mariadb.mirrors.ovh.net/MariaDB/repo/10.3/ubuntu bionic main'
sudo apt update
sudo apt install mariadb-server

et voila..

A: If I can help people who didn't solve their problem with the solutions above :
I also had this problem and it came from a bad configuration in a config file in this repertory :
/etc/apache2/sites-available/
So check the config files to see if there isn't a script error.


text:
Q: KVM machine does not start ssh, network is started, used to work have been searching an pulling my hear out for the last 6 hours. I have a virtual machine that has been running fine for the last six months. I was happy ssh'ing into it and it was running a database and some small apps. Tonight ssh stopped working, so I decided to reboot the machine. I now have the following situation:

*

*virsh list --all states machine as running

*I can ping the machine and get a reply

*When I ssh to the machine I see "ssh: connect to host [myserver] port 22: Connection refused"

*nmap does not show port 22 as open

I have tried to:
- reboot the machine once more (no luck)
- mount the filesystem and check /etc/ssh/sshd.conf (has not changed since working situation)
- install virsh console, however this does not seem to work
When I mount the fs directly using losetup the strange thing is that file dates seem to be frozen in /var/log/ around the time of the crash. If I look in /var/run/ I can see an sshd.pid, but the time is 6 hours ago (and numerous reboots).
My virsh xml looks like this:
<domain type='kvm' id='21'>
  <name>myserver</name>
  <uuid>09678c8d-a99b-1d18-a7af-88d027cc8f93</uuid>
  <memory>1048576</memory>
  <currentMemory>1048576</currentMemory>
  <vcpu>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-1.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <devices>
    <emulator>/usr/bin/kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='raw'/>
      <source file='/dev/disk01/myserver'/>
      <target dev='hda' bus='ide'/>
      <alias name='ide0-0-0'/>
      <address type='drive' controller='0' bus='0' unit='0'/>
    </disk>
    <controller type='ide' index='0'>
      <alias name='ide0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <interface type='bridge'>
      <mac address='52:54:00:e3:13:86'/>
      <source bridge='br0'/>
      <target dev='vnet0'/>
      <model type='virtio'/>
      <alias name='net0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <source path='/dev/pts/1'/>
      <target port='0'/>
      <alias name='serial0'/>
    </serial>
    <console type='pty' tty='/dev/pts/1'>
      <source path='/dev/pts/1'/>
      <target type='serial' port='0'/>
      <alias name='serial0'/>
    </console>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='5900' autoport='yes' listen='127.0.0.1'>
      <listen type='address' address='127.0.0.1'/>
    </graphics>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
      <alias name='video0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <alias name='balloon0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </memballoon>
  </devices>
  <seclabel type='dynamic' model='apparmor' relabel='yes'>
    <label>libvirt-09678c8d-a99b-1d18-a7af-88d027cc8f93</label>
    <imagelabel>libvirt-09678c8d-a99b-1d18-a7af-88d027cc8f93</imagelabel>
  </seclabel>
</domain>

I'm sort of lost as to where I can look to get the machine up and running again.
On the same instance of kvm I have another server running which is working fine. Both are Ubuntu 12.04.
All help is welcome....

A: I thought I'd answer myself in the hope that Google indexes this and someone may find it usefull one day. Of course no guarantees and I am not responsible for any consequence. It's going to be a long answer.
Situation:
I have a Ubuntu 12.04 LTS server (M for master) running two virtual servers (V1 and V2), both Ubuntu 12.04 LTS as well. On the host machine I have three IP adresses, so each machine can be accessed under it's own public IP. The servers are installed on LVM basis.
Yesterday one of the virtual servers stopped accepting SSH connects. Also I could not connect to the database running on it anymore. When I investigated I found:

*

*machine was pingable

*ssh would result in connection refused

*nmap -sS from another server showed open ports, but not 22

*virsh list --all showed the machine as running

*I had no console (serial) installed (lazy, yeah yeah I know)

*The other virtual server and the master server were running normally

My first instinct was to powercycle the machine, perhaps some process got stuck (have some own software running on the server), so I did:

*

*virsh destroy virtual2

*virsh start virtual2

This resulted in the exact same status:

*

*virsh reports virtual2 as running

*virtual2 is pingable

*ssh still connection refused

Oke, so something else is the matter. At this time I started worrying a bit that my server may have been compromised, however I could not access it at all. I was slightly less worried when nmap -sS -v -v did not show any strange open ports, but one never knows.
Now my battle plan changed to two main goals:

*

*It seems the server is booting but for some or other reason ssh and other processes are not started

*I need console access to see what is going on

In order to get console access I found I need to make two changes:

*

*install a serial console on the virtual machine

*make a change to the XML of the virtual machine on the master

The problem however was that most of these sites assume a running and accesable server, something I did not have. So I first needed to find a way to gain access to the LVM. Again there are a lot of tutorials, however all of them seemed to work right up to where I wanted to mount the filesystem. It would continously fail with a "mount: you must specify the filesystem type". Even specifying the the filesystem with -t did not resolve this matter.
I finally stumbled onto this site: http://blog.leenix.co.uk/2010/07/howto-mount-kvmxen-virtual-disk-image.html. Perhaps my issue with kpartx was that my LVM contains three partitions (boot, / and var).
Steps I took to mount my logical volumes:

*

*list the LVM's with : lvs
 LV        VG     Attr   LSize   Origin Snap%  Move Log Copy%  Convert
 OS        disk01 -wi-ao  18.62g
 virtual1  disk01 -wi-ao  20.00g
 virtual2  disk01 -wi-ao  30.00g
 swap      disk01 -wi-ao 952.00m

*list the partitions in the LVM :  fdisk -l /dev/disk01/virtual2
Disk /dev/disk01/virtual2: 32.2 GB, 32212254720 bytes
4 heads, 32 sectors/track, 491520 cylinders, total 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00064ee2

Device Boot                         Start         End      Blocks   Id  System
/dev/disk01/virtual21               63    15623046     7811492   83  Linux
/dev/disk01/virtual22         15624192    19529727     1952768   82  Linux swap / Solaris
/dev/disk01/virtusl23         19529728    58591231    19530752   83  Linux

*This gave me the start sectors to be able to mount the partions.

*Created a mount directory : mkdir /mnt/tempfs

*Now I could mount the two partitions by using:
losetup -o32256 /dev/loop0 /dev/disk01/virtual2
or
losetup -o9999220736 /dev/loop0 /dev/disk01/virtual2

If your start blocks are different you can calculate the offste (-o option) by multiplying the start position (63 for the first partition and 19529728 for the third) with the sector size reported in the fdisk -l output.

*

*Now I could mount the partition : mount /dev/loop0 /mnt/tempfs/

*I now had access to my files. I later found there is also a tool called guestfish. You can use this to gain access to the files by issuing :  guestfish -d virtual2 -i. If you want readonly access add --ro at the end).

*To return the partion to a state were I felt comfortable starting the virtual machine I issued:
umount /mnt/tempfs
losetup -d /dev/loop0

So first I wanted to see if my server was actually compromised, so I mounted both partitions (one a the time) and:

*

*find /mnt/tempfs -ctime 0 -type f (see which files had changed in the last 24 hours)

*looked at log files and .bash_history files

Fortunately this did not show strange things, so I started to think something was going wrong during boot. The strange thing was that none of the log files actually were updated at boot, so I could not get any information from that. I needed console access.
Again there are lots of tutorials on gaining console access, all seem to be relatively simple like this post:
http://ubuntuforums.org/showthread.php?t=1159220
In the 7th post nullzone describes a fairly simple way to set this up. So I went to work:

*

*stopped the virtual machine

*mounted the drive

*created a file in etc/init/ttyS0.conf with the parameters suggested

*changed my xml as suggested

*reloaded libvert-bin

*started my virtual machine

*started console

This would continously get stuck after 'Escape character is ^]'. I got no output and no response to any key. I then tried various combinations of serial speeds, different /dev/pts/ devices, nothing worked.
Then finally it dawned on me I had another server that was still running and had ssh access. I made the same change to the XML for that machine and added the /etc/init/ttyS0.conf. On this machine I could simply reload the ttyS0 by issuing 'sudo ttyS0 start'.
Back to virsh, reloaded libvert-bin, destroyed server, started server, console virtual1 and exactly the same. Stuck after the escape character. Fortunately I could check the log files on this machine and noticed an error in /var/log/auth.log : "Nov 22 03:46:11 virtual1 getty[1272]: /dev/–L: No such file or directory". It seemed that getty was not accepting the commandline parameters, so I played around with them and finally found that my /etc/init/ttyS0.conf needed to look like this:
# ttyS0 - getty
#
# This service maintains a getty on ttyS0 from the point the system is
# started until it is shut down again.

start on stopped rc RUNLEVEL=[2345]
stop on runlevel [!2345]

respawn
exec /sbin/getty -L ttyS0 9600 vt102

So the serial device and speed need to be switched in place. When I now reloaded everything I got console access to the virtual1 server, but still not to the virtual2 server.
By this time I was nearly pulling my hair out and it was 4 o'clock in the morning. It dawned on me that maybe the machine was not getting into a stated were it would acutally load the /etc/init/ttyS0.conf file. Some further research showed that one could also change the /boot/grub/menu.lst file and add console output to grub:
title           Ubuntu 12.04 LTS, kernel 3.2.0-24-virtual
uuid            ba4c41ed-30b6-4a80-808d-64fe26ad7e17
kernel          /boot/vmlinuz-3.2.0-24-virtual root=UUID=ba4c41ed-30b6-4a80-808d-64fe26ad7e17 ro console=ttyS0,9600 earlyprint=serial,ttyS0,9600
initrd          /boot/initrd.img-3.2.0-24-virtual

After reloading and rebooting everything I finally had console output and of the boot process as well. It turned out that an NFS mount could not be made. Fortunately Ubuntu is so smart that it then halts the boot and starts waiting for input from the user. Hence the machine is pingable (network has started), but it never completes the boot process, so SSH is not started and so on.
Quite a long answer, but I hope that maybe someone someday can solve these issues quicker than me and simply have a nice night of sleep.


text:
Q: CakePHP 2 path to webroot dir How to create $this->Html->link(); to download file from Plugin webroot directory?
It's possible?

A: Why do you have to put the file in Plugin folder to be downloaded. This is not a good practice. Keep the file in webroot/file/name_of_folder
to get the path to webroot/ simply:
debug(WEBROOT);

A: Prefix with the plugin name
As mentioned in the docs, you can download plugin assets if the request url is prefixed with the plugin name (lower cased and underscored):

Simply prepend /plugin_name/ to the beginning of a request for an asset within that plugin, and it will work as if the asset were in your application's webroot.

Note however that if the file is intended to be public it's a better idea for the asset to actually be in the webroot:

But keep in mind that handling static assets, such as images, Javascript and CSS files of plugins, through the Dispatcher is incredibly inefficient. It is strongly recommended to symlink them for production. For example like this:
ln -s app/Plugin/YourPlugin/webroot app/webroot/your_plugin

This would make it possible to access all files in a plugin's webroot directly without any rewrite or php logic being involved.


text:
Q: Apache and Passenger performance on AWS I am seeing a strange issue on AWS and I was hoping to see if anyone had any insight into what it might be?
Setup:
t2.medium instance utilising 3 EBS GP2 volumes in a raid0 group
elasticache (memcached)
Local mysql configured to run from the raid group
Ubuntu 14.04
Apache 2.4.7
Passenger 5.1.7
Logs are sent to papertrail and not written to local disc
The test:
The test is run from jmeter on a t2.micro instance in AWS which visits the home page, logs in, views a profile page, then logs back out. There are DB queries made at the Login and Profile View, but mysql doesn't appear to be the bottle neck.
Test configuration 1:
mpm_event.conf
<IfModule mpm_event_module>
StartServers        10
MinSpareThreads     75
MaxSpareThreads     250
ThreadLimit     128
ThreadsPerChild     32
MaxRequestWorkers   1984
ServerLimit     800
MaxConnectionsPerChild  0
</IfModule>

And the passenger.conf looks like this:
<IfModule mod_passenger.c>
PassengerRoot /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
PassengerDefaultRuby /usr/bin/passenger_free_ruby
PassengerMaxPoolSize 30
PassengerPoolIdleTime 150
PassengerPreStart *** points to host in /etc/hosts ***
PassengerMaxRequestQueueSize 500
</IfModule>

So the above config results in no errors (in part by the increase in the RequestQueueSize) but responses are taking north of 90seconds(!) towards the end of the test.
Now, here's where things get weird, if I change the configuration of passenger to:
<IfModule mod_passenger.c>
PassengerRoot /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
PassengerDefaultRuby /usr/bin/passenger_free_ruby
PassengerMaxPoolSize 2
PassengerPoolIdleTime 150
PassengerPreStart *** points to host in /etc/hosts ***
PassengerMaxRequestQueueSize 500
</IfModule>

The response times are faster, bringing them down to 60seconds, which is still slow but much better.
What I see when monitoring (using htop, iotop, iftop, mytop, free -m and passenger-status) is the queue in passenger-status grows steadily from the start of the test, if there was a 100 queue limit as standard, it'd start serving 503 errors, but when the queue is increased the requests queue for large amounts of time.
Passenger-enterprise isn't really an option for me to use.
I'm doing something wrong here with the passenger config or with mpm right? This server should be able to handle 600+ connections and respond in 1.3s max (I've run the same tests on a server in Brightbox, and the performance is ridiculously good comparing)
I'm open to any and all suggestions.
Note:
I've ran through the calculations for memory usage for passenger, which should stand at 35, I used 30 to not completely max out RAM due to not running swap, because it's even worse when it hits it.

A: Passenger author here. This sounds like you are running into some bottleneck inside, or behind, the application. If your application cannot process requests fast enough, then it's normal that the Passenger request queue keeps growing until its limit. It is then also normal that the more you increase the queue, the slower your responses are towards the end of the queue.
That more processes makes things slower sounds like your processes are contending for a shared resource that only supports very low concurrency. That might be the database, but you already ruled that out. It might be a web service that you call. It might be a file lock. Without knowledge about your application, I cannot tell what the problem exactly is, but at the very least it does not seem like Passenger is the problem.


text:
Q: why does GCC give me this `-Wdiscarded-qualifiers` warning? In the C SDL project I am working on, I typedefed char * to str for readability.
Now when I do:
const str title = SDL_GetWindowTitle(win);

where SDL_GetWindowTitle returns a const char *, I get:
warning: return discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

The warning is removeed when I change the type to char *:
const char *title = SDL_GetWindowTitle(win);

A typedef is merely an alias to a type, right? So declaring a variable as str or char * should be equivalent, why do I get that warning? Or is there something I missed...?
I am using GCC on the CLI, so it's not an IDE's fault.
Thx in advance!

A: typedefs are not macro substitution, so in your case
const str
const char *

are different types.  The former is actually equivalent to:
char *const

This is a const value of char * type, so it points to a mutable string.  In your example, you cannot modify title, but you could modify *title through that pointer (if it actually points to non-const memory, which depends on what SDL_GetWindowTitle does).
You would have to add a separate typedef for const char * to fix this.


text:
Q: Hiding some columns if table is too big I am a beginner in react and web apps in general let me know if anything is unclear.
I have the following table :

        Name
        Address
        Phone Number
        Age
        Sex
        Blood Type

        John Doe
        Some place somewhere
        093-1252-4879
        51
        Male
        AB

Let's say I want to hide Address and blood type if table is too big to fit in a div.
The way I am thinking of doing this is to check the size of the div and the table in componentDidMount
if the size of the table is bigger than the div then I will set the style of those two columns to display:none.
I did something similar for submenu transitions where I would change my component set on the componentDidMount to get the height then put the visibility to hidden by changing the state. I didn't notice any slowness neither can I see that the submenu was actually visible(on chrome)
I saw some people are doing things like for the nth column to not be displayed if the screen is too small using purely css which is nice. But in my case I am not sure if I could do something similar as I would like the user of my component to specify which columns to hide.
My question is if it is the usual way for webapp developers to display the component check the result on componentDidMount and then change how things look or is there a different pattern?

A: The one pattern I have seen is, removing items on demand in such cases, i.e. user has choice of which columns to see and which  one to hide. Refer this dynamic-columns example from an open source.
http://uikernel.io/examples/dynamic-columns/


text:
Q: Is it possible to convert Avro messages using schema registry to scala case classes? When producing or consuming messages in kafka along with Avro schema's being stored in schema registry, is it possible to have the messages automatically convert to scala case classes?
val props = new Properties()
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, classOf[KafkaAvroSerializer].getName)
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, classOf[KafkaAvroSerializer].getName)
props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081")
...

val producer = new KafkaProducer[String, User](props)
val user = User(123, "my-name")
producer.send(new ProducerRecord[String, User]("my-topic", user.id, user)

Currently when I do this I get an error:

java.lang.IllegalArgumentException: Unsupported Avro type. Supported
types are null, Boolean, Integer, Long, Float, Double, String, byte[]
and IndexedRecord

My User object is just a case class like:
case class User(id: Int, name: String)

I believe I need to use some sort of Avro to java class generator so it will serialize/deserialize correctly right?
Is there a way for me to skip that step and have this somehow automatically map to a scala case class using Avro4s or something?
What are my options?
I want to only store my schemas in schema-registry ideally also.

A: By default, case classes are not Avro subclasses.
You can use projects like avro4s to generate and map Avro schemas to classes, but to my knowledge there's no way to skip that.
If you want to skip class generation, use GenericRecord


text:
Q: Calculating Total Sales from Multiple MySQL Tables I'm trying to figure out how to determine the total sales for an employee using MySQL. The DB has 4 tables in it that will help determine the total sales.  I was able to create a Query that selects all the necessary tables to calculate the Sales Total.
Query:
SELECT employees.eno, employees.ename, orders.ono, orders.eno,
    parts.pno, parts.price,odetails.ono, odetails.pno, odetails.qty
FROM test.employees, test.parts, test.orders, test.odetails
WHERE employees.eno = orders.eno AND parts.pno = odetails.pno

This comes up with a Table that displays the Employee's name, Item, price it's sold at.  I'm not sure where to go from here.  And any help would be much appreciated!  I'm not sure if a stored procedure would help, then I could call it in a Java program to print out the results.  Just really confused here.  Any help would be appreciated.  Thank you!

A: Try:
SELECT employees.eno, employees.ename, SUM(parts.price * odetails.qty) as TotalSales
FROM test.employees
INNER JOIN test.orders
ON empoyee.eno = orders.eno
INNER JOIN test.odetails
ON orders.ono = odetails.ono
INNER JOIN test.parts
ON odetails.pno = parts.pno
GROUP BY employees.eno, employees.ename

A: The following should work.
SELECT employees.ename, COUNT(employees.ename), (COUNT(employees.ename) * parts.price) FROM test.employees INNER JOIN (orders, parts) ON (employees.eno = orders.eno AND parts.pno = odetails.pno)

A: You should use JOINs to join all your tables together into the appropriate results. Here's an example from what I can tell from your query/database structure that will return each order, joining the order details, part information and employee info:
SELECT
*
FROM test.orders O
LEFT JOIN test.odetails OD ON OD.pno = O.ono
LEFT JOIN test.employees E ON E.eno = O.eno
LEFT JOIN test.parts P ON P.pno = OD.pno

From here, if you want to get a total per employee, you could do something like this:
SELECT
E.eno,
SUM(OD.qty * P.price) AS employee_total
...
GROUP BY E.eno

...which should return the employee number and total of all prices associated which each order, multiplied by the quantity for each order, and grouped by the employee number.
You could then add:
ORDER BY employee_total ASC -- or DESC...

To order from lowest to highest or vice versa.


text:
Q: Font Embedding Causes Scrambled Characters When Making PDF from Word or Excel I have a peculiar issue where if I File + Print and Choose PDF as the Printer, I get scrambled up text, the PDF doesn't embed nor do I get errors it couldn't embed fonts.  If I choose File + Make PDF, it generally doesn't fail, though it does at times.

If I were to do a test in InDesign, it has no issues upon Exporting the PDF, nor when I go to Find Font, do I see any restrictions on the font listed.
Has this issue been seen before and if so how do I fix it?
Thank you.


text:
Q: Reference for calculating $R^2$ on a subset of the samples I've been looking for a method to calculate $R^2$ on a subset of the samples (a subset of the instances, not a subset of features), and found this answer from Dave. It suggests using the mean of the original samples ($\bar{y}$), rather than the mean of the subset, when calculating the TSS - .i.e.:
$R^2=\dfrac{\sum_j (y_j - \bar{y})^2 - \sum_j (y_j - \hat{y})^2}{\sum_j (y_j - \bar{y})^2}$.
Using this method has resolved the problem I'm having when using the subset mean to calculate $R^2$, where I get a low or negative value if my subset has very low variance (e.g. if the subset is instances with target values in a small range), and I'd like to use Dave's method in a paper I'm writing.
I've searched for academic references for this method of calculating $R^2$ but I have not found one so far.
Does anyone know of a suitable reference to use for this?

A: As my question is so far unanswered and I haven't been able to find a reference, I'm posting how I resolved this as an answer.
In my paper I justified this approach with the statement "When $R^2$ is calculated for a subset of samples, $\bar{y}$ is the mean of the measured LFMC for the full sample set, not the mean of the subset. By using this value for the mean, all $R^2$ calculations are compared to the same baseline, thus allowing comparisons between $R^2$ for different subsets of samples."


text:
Q: Wanted to test my app on device through app store without review I have a small problem but couldn't find solution for that. I have founded Questions like this but the answers are not upto my requirement or may be i am not able to understand them correctly.
Problem :-
I have my app on app store(Reading PDF and downloading them). It is working fine for downloading small pdf's and showing them, but when it comes to download large pdf's my app crashes or abort. One more strange thing my app works fine on simulator with huge pdf's also but not on devices.
Now, i have made some changes in my code and i wanted to test it on device.I can not deploy it directly on device as i am not having iphone right now. so i want it to upload on appstore for testing purpose without giving it for Apple review.
i want to know the whole procedure how to do it.Starting from whether i have to create a new account for that to how to test it on device.Url's will also be helpful.
And ya my device is not having any memory issues. Thanks.
Any help will be appreciated.

A: You wouldn't sell an experimental piece of equipment in any store, so you also do not upload things for debugging to the app store.
If you want to test it on someone's device why don't you just create a provisioning profile and send him the app? Then he can install it through itunes.
Also you should write the data you received ( while downloading ) to the disk every now and then, otherwise you are going to keep having this issue of running out of memory.
Something like:
// received data
NSFileHandle *yourFileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[yourFileHandle writeData:dataChunk];
// get rid of data chunk

A: I'm afraid you can't distribute your app via the app store without going through the app store review process. You might want to read up about ad hoc distribution of your apps. I've used TestFlight successfully in the past for ad-hoc distribution.

A: You can not upload to the app store without review process. period.
Large PDF's work in the simulator because the simulator runs on your computer which has lots more RAM than the iPhone.
You will need any iPhone or iPod Touch to test it. you could even use a friends.

A: You can't upload to the App Store for testing purposes. You must either get hold of an iPhone to test or employ the services of a testing company who will have a whole suite of devices to test on.


text:
Q: Linux Mint 17.2 "Rafaela" Kernel 3.1, Need help installing AMD Radeon R290 driver I really need help getting AMD driver installed i dont know why it fails.
I'm comming as far as unpacking the package then when running the sh it says my card is not compatible while it is listed as compatible in driver notes.
When i run it in a terminal i get a litlle bit further in the install and it then tells me to build a package but of course Mint is not listed ;(
So any ideas would be appriciated ;)

A: First, make sure Mint is up to date.
sudo apt-get update
sudo apt-get dist-upgrade -y

You will then need to update/download your Linux headers, per this article.
sudo apt-get install linux-headers-$(uname -r)

Once things are updated, keep the terminal open and cd into the appropriate directory. My ATI drivers were in the downloads folder. Once you've found and extracted the drivers, use bash to run them. It should look something like what I've typed below.
sudo bash ati-fglrx-versionnamehere.sh

You will enter the prompt and be asked which type of package you want to install, since the default packages are distribution-specific. You also have the option to build your own. Since you're using Linux Mint, it's likely that the package for Ubuntu 14/15 will work for you. However, you can also choose the generic installer and let the program do the work for you. I have found that it's not entirely critical to get this part right.
Note: At least in my experience, I received several errors -- especially without the appropriate headers. You can probably ignore these. The drivers will most likely still work.
Once the install is done, reboot and run the following command when you're back to your desktop:
sudo amdcccle

Hope it helps!


text:
Q: Query located in cellAtIndexPath I have a query located in my cellAtIndexPath. This query takes objects from an array at the index for the cell row, as is common. I was wondering if every time I load my tableView will there just be one query, or will it count as a query for every indexPath.row. The reason why this is important is because it could be the difference between one request and hundreds of request overtime I load the tableView. Is the query called for every row or just once?

A: The query will be called one time for each indexPath.row as cellAtIndexPath is the method called for each cell. You can try to cache it somehow to avoid loading data each time you load the table.
But the better approach would be using some framework (Parse provides it for its database) which can help you load the data in background.


text:
Q: Check if a Facebook user likes a page using fql I want to check whether the loggedIn user has liked a specified page or not. Below is my code.
$fql_pageid = "SELECT url,site,id FROM object_url WHERE url
                     IN('http://developers.facebook.com/')";
$api_pageid = $facebook->api(array(
                    'method' => 'fql.query',
                    'query' => $fql_pageid
));
$pageid = $api_pageid[0]["id"]; //get id of the specified page
$fql_like = 'SELECT object_id FROM like WHERE user_id=me()';
$api_like = $facebook->api(array(
                    'method' => 'fql.query',
                    'query' => $fql_like
));

When I do var_dump($api_like), there are only 6 records appearing. But I checked my Facebook account, there are 22 likes.
Anyone knows what's wrong the above code? Or is there any other way to check whether a user has liked a specified page?

A: If instead you want to see if the current user likes a website:
SELECT user_id FROM url_like WHERE url='http://someurl.com' AND user_id=me()

This is useful for page tab apps where normal like buttons will only like the page the tab resides in.

A: Let's say that you want to check if the current user (uid=me()) is Fan of the "Big Bang Theory" page with *page_id=22934684677* (http://graph.facebook.com/TheBigBangTheory) you should run this query:
SELECT page_id FROM page_fan WHERE uid=me() AND page_id=22934684677


text:
Q: Invert the output of the boolean visibility converter? In WPF, I have an element whose visibility should be bound to a checkbox. I can use BindingPath=IsChecked and Converter={StaticResource convVisibility} to make it visible. However, I want to make it hidden and there is no BindingPath=IsUnchecked. Can I invert the value of the boolean to visibility converter? Thanks for help.
This is in the window xaml:
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="convVisibility"/>
</Window.Resources>

A: This is my solution of this problem:
public class BoolVisibilityCollapsedConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool param = true;

            if (parameter != null)
                param = System.Convert.ToBoolean(parameter);

            bool state = (bool)value;

            Visibility visibility = Visibility.Visible;

            if (state != param)
                visibility = Visibility.Collapsed;

            return visibility;
        }

If you use this converter, you will switch visibilty like True = Visible / False = Collapsed. If you want the different behavior (True = Collapsed / False = Visible) just use CommandParameter="False"


text:
Q: loading various images for boolean buttons? I am creating buttons at runtime, I wanted to add an image for each value true and false,
so if I have onOff button, true would be green pic, false red. and want this to work for other properties too.
My questions are
1. How to load the pictures to best suit this purpose?
2. How to create the buttons the right way?
3. I was using the same function for Enum buttons,if it looks strange.
4. I am sure am doing many things wrong, advice please.
foreach(p in properties){
if(p is bool){createBoolButton(p);}
//so on

string path;
string path2;
private Control createBoolButton(IProperty p) {
  countControls2 = 1;
  locationY = 10;
  int gbHeight = 2;
  radioButtonY = 10;
  IType pType = p.Type;
  var myP = new MyProperty(p, this);
  if (myP.Value != null) {
  }
  Panel gb = new Panel();
  gb.Location = new Point(locationY, nextLocationX);
  nextLocationX += rbWidth + 10;
  gb.Name = "groupBox" + p.Id;
  gb.Text = p.Id;
  gb.Tag = p;
  bool[] x = { true, false };
  foreach (var t in x) {
    RadioButton rb = new RadioButton();
    rb.Appearance = Appearance.Button;
    rb.Width = rbWidth;
    rb.Height = rbHeight;
    rb.Name = t.ToString();
    rb.Text = t.ToString();
    rb.Tag = t;
    countControls++;
    rb.Location = new Point(radioButtonY, radioButtonX);
    if (myP.Value != null && myP.Value.ToString().SafeEquals(rb.Text)) {
      rb.Checked = true;
    }
    radioButtonY += rbHeight;
    gb.Controls.Add(rb);
    rb.CheckedChanged += rb_CheckedChanged;
  }
  gb.Width = rbHeight * gbHeight + 20;
  gb.Height = rbWidth + 10;
  Controls.Add(gb);
  countControls2++;
  return gb;
}
  private void getimagesPath(EnumValue[] TypesArray) {

  foreach (var enumType in TypesArray) {
    string path = @"C:\Folder\" + enumType.Name + ".png";
    string path2 = @"C:\Folder\" + enumType.Name + "_checked.png";
    FileInfo fi = new FileInfo(path);
    FileInfo fi2 = new FileInfo(path2);
    if (!imagePaths.ContainsKey(enumType.Name) && !imagePaths.ContainsKey(enumType.Name + "_checked")) {
      if (fi.Exists && fi2.Exists) {
        imagePaths.Add(enumType.Name, path);
        imagePaths.Add(enumType.Name + "_checked", path2);
      }
    }
    else {
      if (!imagePaths.ContainsKey(enumType.Name)) {
        imagePaths.Add(enumType.Name, DEFAULT_IMAGE_PATH);
      }
    }
  }
}

A: *

*I think In this case you don't need pictures. Just change the backColor of the buttons.

*Sample code for creating buttons:
Dim pnl as new Panel

Dim btn as new Button
btn.Name = "btn1"
btn.Location = new Point(..., ...)

pnl.Controls.Add(btn)

Sorry, but I dont know C#.

A: You should save your checked image and unchecked image as Resources in your project. Just look in the Solution Explorer, you will see there is a Resources node under Properties node under your project node. Double click on that node and you should know how to add an image to that Resources. Once you add images to it, you can access those images easily as I show in the code below. I suppose your checked image is added to Resources with name CheckedImage and your unchecked image is added to Resources with name UncheckedImage:
//Here is your RadioButton CheckedChanged event handler to change to image accordingly.
private void rb_CheckedChanged(object sender, EventArgs e){
   RadioButton button = sender as RadioButton;
   button.Image = button.Checked ? Properties.Resources.CheckedImage : Properties.Resources.UncheckedImage;
}

Your code is too much redundant and not efficient.


text:
Q: How to run a script from another path, and know the script's path? I need to run a script that access a file in the same path it is located.
For example: I have the script in /home/me/folder/script.sh, and this script will access the file /home/me/folder/myfile. As the file is in the same path of the script, I just use the name myfile, not the full path.
But if I run it from /tmp/, like:
/tmp$ /home/me/folder/script.sh

it gives me:
myfile: No such file or directory

So, how can I say in the script that the file is in the same path as the script itself?

A: You can't know in all circumstances, but often (not always) when you run a script by path instead of letting the shell search $PATH, the path to the script will be in $0.  You can then use dirname "$0" or ${0%/*} to get the path.

A: How about $(dirname "$0")/myfile?

A: I would normally do something like this at the head of my script:
SCRIPTDIR=$(dirname "$0")

Or, to get the full pathname to the script's directory (instead of a relative pathname):
SCRIPTDIR=$(cd $(dirname "$0") && pwd)

Then just reference ${SCRIPTDIR} where needed.


text:
Q: The current off-topic close reasons are bad The Problem
After speaking to many users who have been moderating this site clean many, many times, and after some thought, I came to the conclusion that the current custom off-topic reasons do not represent the real reasons questions need to be closed. One by one:

Questions about general computing hardware and software are off-topic for Stack Overflow unless they directly involve tools used primarily for programming. You may be able to get help on Super User.

If it's on-topic on Super User, it should be migrated there. If it's crap enough to not be accepted there, it shouldn't be closed with this close reason. This reason is moot.

Questions on professional server, networking, or related infrastructure administration are off-topic for Stack Overflow unless they directly involve programming or programming tools. You may be able to get help on Server Fault.

Exactly the same as above. Replace Super User for ServerFault.

This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.

This reason is exactly the same as "Unclear what you're asking". UWYA should be upgraded with instructions on what to do.

This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting.

This is the only reason that currently has some merit.

Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

This reason is very similar to "primarily opinion based". There are some differences, but it's basically the same.

The Solution?
These "Go and ask on [some-other-site.se]" have to die. They either belong there, in which case you migrate, or they don't. In which case, close it as something else that's appropriate.
The general close reasons (unclear and opinion based) can and should be rephrased so that they include practical instructions as to what to do "Add more examples, describe the problem rather than the possible solution")
Finding duplicates and creating canonicals should be made easier, but that's a feature-request all to it's own.
Ideas?
I don't know the entire solution to the problem. But the problem is there. Right now, I see a huge amount of questions getting closed as a reason that's about right, that's understandable to the regulars but is incredibly confusing to the user whose question just got closed!
Don't forget who those reasons and those elaborate texts are for, we know the rules, they don't. The point is not to close and forget, but to help educate users so that they'll know our rules and standards, and be able to contribute and get help.

A:
If it's on-topic on Super User, it should be migrated there. If it's crap enough to not be accepted there, it shouldn't be closed with this close reason. This reason is moot.

What if you're absolutely certain it doesn't belong here for the reasons stated, but are not 100% sure it would be a good fit on the target site? Then a "have a look over there" might be a better option than an outright "let's move that sucker". The same goes for your second option.

This reason is exactly the same as "Unclear what you're asking". UWYA should be upgraded with instructions on what to do.

Nope. Unclear what you're asking is "say what?". This is "I know what you're saying, but we need a bit more info than this".

This reason is very similar to "primarily opinion based". There are some differences, but it's basically the same.

There will always be some overlap between reasons, but it's not bad to have an explicit "don't ask for libraries or tools or ..." reason.
There are plenty of tweaks to make to close reasons, but I don't agree with your view.


text:
Q: Tree of inheritance of Git branches Is there any way to replicate an inheritance tree of Git branches in shell?
For example, I have local branches b1, b2, ... , bN as listed by git branch.
Example:
     ++ b7 <--+ b4
     |
b8 <--+ b5   +-+ b2
     |       |
     ++ b1 <---+ b3
             |
             +-+ b6

So, in the above case I would like to have a variables representing branch names (or their hashes, doesn't matter).
I know about binary search tree data structures in shell (at least one approach which is working nicely). The problem is how to get a proper left or right choice when submitting the branch into the BST-like structure?
I suppose I need to do something with git branch --contains and git merge-base, though I can't clearly see a picture of algorithm right now. The git branch --contains works quite slowly, perhaps because of nature of the tree, it would be also good to hear alternatives.
libgit2 + python approach seems not the best choice to me because I need to rebase those branches and it looks like libgit2 is quite low level for that.

A: Does this command's output look like what you want:
git log --oneline --graph --decorate --simplify-by-decoration --all


text:
Q: Can TRegistry write REG_NONE values? I'm trying to work with the OpenWithProgids key of an extension using TRegistry.  I don't see that TRegistry can write these values (which require a type of REG_NONE.)  I know that I could just use the API RegSetValueEx function to set these, but I'm wondering if I'm missing something in TRegistry that can do it.

A: It is true that TRegistry has no direct support for REG_NONE values. However, with the protected hack, you can trick it into creating zero-length binary REG_NONE values:
type
  TRegistryHack = class(TRegistry);
....
TRegistryHack(Registry).PutData(ValueName, nil, 0, rdUnknown);

You need to use the protected hack to gain access to PutData which is a protected member. A cleaner approach would be to use a class helper or true class derived from TRegistry, but you get the idea.


text:
Q: Can I use a 4 Band composite band tif file to make blend out borders around an image? In ArcGIS 10.6 I have a 3 Band tif image which has large areas which I do not want to display. I have created polygons of these areas and converted them to a raster tif in order to create a 4th band to use as an alpha channel to make areas transparent. I used the Composite band tool to create the 4 band raster but when I activate the alpha channel using this band the whole image becomes transparent and not just the defined areas.
The 4th Band consists of just 2 values 0 and 1. Is ArcGIS assuming that the extent of the 4th band is the transparent area and not just the pixels with a value of 1? How to I set the raster to only make pixel value 1 the transparent pixel.
I am aware than I can set a nodata color in ArcGIS but I need to try to do this using an alpha channel for a client.

A: If you want your 1 values visible and your 0 values transparent, convert your 1 values to 255.
If you want your 1 values transparent and your 0 values visible, convert your 1 values to 0 and your 0 values to 255.
Alpha channels are 0-255 where:

*

*0 = fully transparent

*255 = no transparency

*1 - 254 are decreasing transparency/increasing opacity.

When you set your band with 0 and 1 as the alpha channel, 1 was treated as being almost completely transparent.


text:
Q: What does square subset and square union symbol mean? I am reading a program analysis book and the author jump right into using some notations without explaining the meaning of them and now I have trouble understand the whole thing. The notations in question are: $\sqsubset$, $\sqsubseteq$, $\sqsupset$, $\sqsupseteq$, $\sqcap$, $\sqcup$, and $\models$. I just wonder if someone could give me some pointers to the definition of these symbols or and references will be greatly appreciated.

A: The last symbol you included, the double right-facing turnstile $\vDash$, has various uses in some literature in Modal Logic.
On its own (or, perhaps more formally, as a unary symbol), for a proposition $\varphi$, $\vDash \varphi$ signifies that $\varphi$ is valid. Embellishments on the turnstile yield different meanings, e.g. $\vDash^M_w \varphi$ means proposition $\varphi$ is true at world $w$ in model $M$, $\vDash^M \varphi$ means $\vDash^M_w \varphi$ for all $w\in M$, etc.
The symbol can also take two arguments, e.g. for a class of models, frame, or class of frames $X$, $X\vDash \varphi$ means $\varphi$ is valid with respect to $X$.
I believe this symbol has uses in Model Theory and other branches of Logic, but I'm not as aware of those.

A: It might be symbols used in domain theory, which in short is about how out-data depends on in-data. For example, a program is always monotonic in the respect that less in-data can not give more out-data.

A: Having a similar question while reading a static analysis book, I was looking for answers.  Speaking with my advisor on the subject, I believe I have an answer that at least satisfied me.
In the context of program analysis and static analysis, the square versions of the various relations denote that the relationship between the elements (operands) may no longer be sets, but simply partial orderings.  For example, consider the relation $\forall a \in \mathbb{A}$, $\alpha(\gamma(a)) \sqsubseteq a$ , where $\alpha$ is the abstraction function, $\gamma$ is concretization function, and $\mathbb{A}$ is the abstract domain.  The value on the left hand side and the right hand side are not necessarily sets, they may simply be ordered elements (according to some lattice) depending on the abstract domain.


text:
Q: Summing a list of floats:TypeError: 'int' object is not callable so the problem is that I keep getting this error message:
TypeError: 'int' object is not callable
range_list = range(1, 97)

for p in range_list:

    p_numerator = 4*((-1)**(p+1))
    p_denominator = 2*p - 1

    function_ofK = float(p_numerator)/float(p_denominator)

    total = sum(function_ofK)
    print(total)

Here is the problem I need to solve:
Problem:

A: Always remember that sum() function takes a list of values (iterable). In your case, you are just passing a float. A little help on its usage can be gotten from Python interactive terminal as follows.
Rishikeshs-MacBook-Air:Try hygull$ python3
Python 3.6.7 (v3.6.7:6ec5cf24b7, Oct 20 2018, 03:02:14)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> help(sum)

Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

Now, you can try like this.
Using sum()
range_list = range(1, 97)
values = []

for p in range_list:
    p_numerator = 4*((-1)**(p+1))
    p_denominator = 2*p - 1

    function_ofK = float(p_numerator)/float(p_denominator)

    values.append(function_ofK)

total = sum(values)
print(total) # 3.131176269454982

Without using sum()
range_list = range(1, 97)
total = 0

for p in range_list:
    p_numerator = 4*((-1)**(p+1))
    p_denominator = 2*p - 1

    function_ofK = float(p_numerator)/float(p_denominator)

    total += function_ofK

print(total) # 3.131176269454982

You should try
def get_sum(start, end):
    range_list = range(start, end + 1)
    total = 0

    for p in range_list:
        p_numerator = 4*((-1)**(p+1))
        p_denominator = 2*p - 1

        function_ofK = float(p_numerator) / float(p_denominator)

        total += function_ofK

    return total

Now you just call that function and get your work done.
total = get_sum(1, 96)
print(total) # 3.131176269454982

total = get_sum(1, 100)
print(total) # 3.1315929035585537

A: function_ofK is a float. sum function needs a list (more specifically an iterable)
This is what you might need to do.
range_list = range(1, 97)
function_ofK = []

for p in range_list:
    p_numerator = 4*((-1)**(p+1))
    p_denominator = 2*p - 1

    function_ofK.append(p_numerator/p_denominator)

# the total is out of for loop
total = sum(function_ofK)
print(total) # 3.131176269454982


text:
Q: Pyqt: QTextCursor.WordUnderCursor not working as expected I am using QTextCursor.WordUnderCursor but it isn't working how I want it to, for example if I had:

(text)

it will only give ( OR text OR ) not (text) which is what I want. It also doesn't work with commas, $, #, etc.
Is there any way I can get it to work with those characters?

A: QTextCursor.WordUnderCursor considers a "word" to be an unbroken set of characters of the same class. I did some searching, and couldn't find how to change this behaviour.
However, it should be easy enough to get the word under the cursor, then progressively widening the selection using QTextCursor.setPostition(), checking if the new character is "acceptable" and then doing that for both sides (left and right).


text:
Q: bootstrap navbar in single page app I have a problem with Bootstrap's navbar: https://jsfiddle.net/2wwgt3to/1/
I'm making single page application and it turns out that bootstraps dropdown navigation menu for mobile is not really working well with it i.e. its not collapsing after clicking, I managed to solve this with adding data-toggle="collapse" data-target="#navbar" attributes but then the whole menu is collapsing even when it is not in dropdown form.

A: Remove data-toggle="collapse" data-target="#navbar" from

Edited code:

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      Project name

Home

About

Contact

          Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default

Static top

Fixed top (current)


text:
Q: How to fetch more than 25 post messages I'm trying to get all post messages using restfb, my code is as follows
public Connection<Post> publicSearchMessages(Date fromDate, Date toDate) {
    Connection<Post> messages = publicFbClient.fetchConnection("search",
            Post.class,
            Parameter.with("q", "Watermelon"),
            Parameter.with("since", fromDate),
            Parameter.with("until", toDate),
            Parameter.with("type", "post"));

    return messages;
}

This only gives latest 25 post messages.

Parameter.with("limit",100 )

If i set limit parameter, it gives 100 messages but i don't want to limit to fetching post messages. So,
Is there anyway I can get a full list of post messages matching the search criteria without setting limit parameter?

A: Maybe you can try using a loop. FB can't get more than 1000 each time, so you can use the loop to get the whole feeds. Use the offset like this:
Parameter.with("limit", 1000));
Parameter.with("offset", offset));

Offset will be a variable and its value will be 1000,2000,3000...

A: There is no way to fetch unlimited results from FB. The default limit is set to 25. As you know, you can change this using the limit parameter. I have not found an upper border for limit searching the web. Maybe, you can set it to a very high amount.

A: As I tested recently, You don't have to specify anything. Connection class implements Iterable in this way:

*

*fetch 25 results

*hasNext check if there is next item to process

*if not, it will fetch next page of 25 results

So basically all you need to do is this:
Connection<Post> messages = publicFbClient.fetchConnection("search",
        Post.class,
        Parameter.with("q", "Watermelon"),
        Parameter.with("since", fromDate),
        Parameter.with("until", toDate),
        Parameter.with("type", "post"));

for (List<Post> feedConnectionPage : messages) {
        for (Post post : myFeedConnectionPage) {
                 // do stuff with post
        }
}

If you want to have some kind of method that returns results I would be very careful, because you can be returning thousands of results and crawling through them may take some time (from seconds to minutes or even hours) and result object array is going to be really big. Better idea is to use some asynchronous call and check out results of method periodically.
Though it seems that parameter "since" is ignored. Posts are fetched from newest to oldest and I think that it somehow leave out this parameter when doing paging.
Hope I made it more clear for you :)

A: We have an Iterator object in Post. So we can do it like this:
Connection<Post> messages = publicFbClient.fetchConnection(...) ;
someMethodUsingPage(messages);
    while (messages.hasNext()) {
        messages = facebookClient.fetchConnectionPage(messages.getNextPageUrl(), Post.class);
        someMethodUsingPage(messages);
    }

Then in each messages we'll have next 25 messages.


text:
Q: Sleep mode in Win7 doesn't work any more (shuts down PC somehow, and taking very long to load system again), battery defect? UPDATE:
So, i figured out that i behaves like i remove battery when sleeping. Like it has no power connection, how could that be?
OLD POST:
I'm not sure what is wrong, but after putting in "sleep-mode", my pc normally starts within seconds, not showing bootscreen and not asking for OS.
But somehow every time is start "sleep-mode" my pc starts booting again. The only thing i know is that after selecting OS (which i m usually not asked when slept) Windows takes so long to start. After logged in it takes some while to react again. It's like it is loosing power connection or something like that...
I hope you understood what i mean. It takes much longer than it normally does, and even hibernate is faster.
Could it be there is something wrong with battery or what else could be the reason?

A: So, my computer is is finally back from waranty services and they replaced some internal parts (which i amg oing to find out what) and now it works.  So it was caused by some hadware defect. Thanks again for you help and answers.


text:
Q: Hide DataGridView Column I show Grid View in my web site but i want to hide "PID" column, i try
dataGridView1.Columns[0].Visible = false; but its not working , this is my Database Connection code :
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SocialConnection"].ConnectionString);

        SqlCommand cmd = new SqlCommand("select PID , description As Post,U_Name As Name from Post ", conn);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        conn.Close();
    }

MarkUp :
 <asp:GridView ID="GridView2" runat="server" BackColor="White"
        BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
        Width="1000px" PageIndex="2"  AllowPaging="True" >
         <Columns>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Buttonid" runat="server"  CommandName='<%# Bind("PID") %>' Text="Rate" OnClick="Button_rate_click"></asp:Button>
            </ItemTemplate>
            </asp:TemplateField>

            <asp:ButtonField ButtonType="Link" CommandName="Reply" HeaderText="Reply" Text="Reply"  />
         </Columns>
    </asp:GridView>

A: You can try hiding the column from the onRowCreated event since it is an auto-generated column.
Add the onRowCreated event to your GridView markup:
 <asp:GridView OnRowCreated="gridView_OnRowCreated" ID="GridView2"
 runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
 Width="1000px" PageIndex="2"  AllowPaging="True" >

Then add the method in code-behind:
protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
{
    //You want to remove third column (column with index 2)
    if(e.Row.Cells.Count > 2)
       e.Row.Cells[2].Visible = false; // hides the first column
}

Hope this helps.


text:
Q: Q Learning Applied To a Two Player Game I am trying to implement a Q Learning agent to learn an optimal policy for playing against a random agent in a game of Tic Tac Toe.
I have created a plan that I believe will work. There is just one part that I cannot get my head around. And this comes from the fact that there are two players within the environment.
Now, a Q Learning agent should act upon the current state, s, the action taken given some policy, a, the successive state given the action, s', and any reward received from that successive state, r.
Lets put this into a tuple (s, a, r, s')
Now usually an agent will act upon every state it finds itself encountered in given an action, and use the Q Learning equation to update the value of the previous state.
However, as Tic Tac Toe has two players, we can partition the set of states into two. One set of states can be those where it is the learning agents turn to act. The other set of states can be where it is the opponents turn to act.
So, do we need to partition the states into two? Or does the learning agent need to update every single state that is accessed within the game?
I feel as though it should probably be the latter, as this might affect updating Q Values for when the opponent wins the game.
Any help with this would be great, as there does not seem to be anything online that helps with my predicament.

A: In general, directly applying Q-learning to a two-player game (or other kind of multi-agent environment) isn't likely to lead to very good results if you assume that the opponent can also learn. However, you specifically mentioned

for playing against a random agent

and that means it actually can work, because this means the opponent isn't learning / changing its behaviour, so you can reliably treat the opponent as ''a part of the environment''.
Doing exactly that will also likely be the best approach you can take. Treating the opponent (and his actions) as a part of the environment means that you should basically just completely ignore all of the states in which the opponent is to move. Whenever your agent takes an action, you should also immediately generate an action for the opponent, and only then take the resulting state as the next state.
So, in the tuple (s, a, r, s'), we have:

*

*s = state in which your agent is to move

*a = action executed by your agent

*r = one-step reward

*s' = next state in which your agent is to move again
The state in which the opponent is to move, and the action they took, do not appear at all. They should simply be treated as unobservable, nondeterministic parts of the environment. From the point of view of your algorithm, there are no other states in between s and s', in which there is an opponent that can take actions. From the point of view of your algorithm, the environment is simply nondeterministic, which means that taking action a in state s will sometimes randomly lead to s', but maybe also sometimes randomly to a different state s''.

Note that this will only work precisely because you wrote that the opponent is a random agent (or, more importantly, a non-learning agent with a fixed policy). As soon as the opponent also gains the ability to learn, this will break down completely, and you'd have to move on to proper multi-agent versions of Reinforcement Learning algorithms.

A: Q-Learning is an algorithm from the MDP (Markov Decision Process) field, i.e the MDP and Learning in practically facing a world that being act upon. and each action change the state of the agent (with some probability)
the algorithm build on the basis that for any action, the world give a feedback (reaction).
Q-Learning works best when for any action there is a somewhat immediate and measurable reaction
in addition this method looks at the world from one agent perspective
My Suggestion is to implement the agent as part of the world. like a be bot which plays with various strategies e.g random, best action, fixed layout or even a implement it's logic as q-learning
for looking n steps forward and running all the states (so later you can pick the best one) you can use monte-carlo tree search if the space size is too large (like did with GO)
the Tic-Tac-Toe game is already solved, the player can achieve win or draw if follows the optimal strategy, and 2 optimal players will achieve draw, the full game tree is fairly easy to build


text:
Q: box shadow not rendering over content so this is driving me crazy.  I have two divs, floated left, the bottom one has a drop shadow box shadow, in this JS fiddle  http://jsfiddle.net/q79Lg/ the shadow renders correctly, it covers the content, but when I copy literally the exact same thing to a page http://www.klossal.com/portfolio/index_backup2.html the shadow doesn't cover the content in the div above.  Why is this happening??
Ultimately I'd like to use it here http://www.klossal.com/portfolio/index_backup5.html but it's just the same issue as listed in the first two sources, but I've taken all the other garbage out.
Thanks so much for helping me.

A: Try
<div align="center" style="background: #ffffff; position: absolute; bottom: 0px; left: 0px; z-index: 5; border:1px solid red; -webkit-box-shadow: 0px -7px 20px 0px rgba(0, 0, 0, 1); -moz-box-shadow: 0px -7px 20px 0px rgba(0, 0, 0, 1); box-shadow: 0px -7px 20px 0px rgba(0, 0, 0, 1); width:100%;height:200px;">

for the botttom div, see if that works :)


text:
Q: How do you put two TextViews next to each other in a LinearLayout? I am a beginner in Android Studios, and my TextViews will not be placed next to each other, instead one is on top of the other. I am really confused about what I did wrong.
<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:text="@string/already_registered"/>

        <TextView
            android:id="@+id/textview_login"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:paddingLeft="10dp"
            android:textStyle="bold"
            android:textColor="#ECAB71"
            android:textSize="16sp"
            android:text="@string/login"/>

</LinearLayout>

A: LinearLayout tag closed too early. Use > instead of /> in your LinearLayout element.
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" android:orientation="horizontal">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:text="Already registered"/>

    <TextView
            android:id="@+id/textview_login"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:paddingLeft="10dp"
            android:textStyle="bold"
            android:textColor="#ECAB71"
            android:textSize="16sp"
            android:text="login"/>

</LinearLayout>

A: You must clear the backslash in line 5
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:text="@string/already_registered"/>

    <TextView
        android:id="@+id/textview_login"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:paddingLeft="10dp"
        android:textStyle="bold"
        android:textColor="#ECAB71"
        android:textSize="16sp"
        android:text="@string/login"/>

</LinearLayout>


text:
Q: Laravel - Call to a member function categorie() on bool I'm trying to attach my categories to my products.
When i'm trying to db:seed i get :
Error on ProductSeeder : Call to a member function categories() on bool
Here is my code :
2020_04_09_073846_create_products_table
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('categoryId')->unsigned();
            $table->string('name');
            $table->string('slug');
            $table->string('category');
            $table->string('description');
            $table->string('releaseDate');
            $table->float('price');

            $table->timestamps();
        });
    }

2020_05_02_201337_create_categories_table
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });
    }

2020_05_03_105839_create_category_product_table
    public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {

            $table->increments('id');
            $table->integer('product_id')->unsigned()->nullable();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

            $table->integer('category_id')->unsigned()->nullable();
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

            $table->timestamps();
        });
    }

Category.php
class Category extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\Product');
    }
}

Product.php
class Product extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
    public function presentPrice()
    {
        return money_format('$%i', $this->price / 100);
    }
}

DatabaseSeeder
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(CategorieSeeder::class);
        $this->call(ProductSeeder::class);
    }

CategorieSeeder
use Carbon\Carbon;
use App\Category;
use Illuminate\Database\Seeder;

class CategorieSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $now = Carbon::now()->toDateTimeString();

        DB::table('categories')->insert(
            array(
                array(
                    'name' => 'Xbox',
                    'slug' => 'xbox',
                ),
                array(
                    'name' => 'Playstation',
                    'slug' => 'playstation',
                ),

ProductSeeder
use Illuminate\Database\Seeder;
use App\Product;

class ProductSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        for ($i=0; $i < 30; $i++) {
            DB::table('products')->insert([
                'name' => 'Halo 5',
                'slug' => 'halo-5',
                'categoryId' => '1',
                'category' => 'Xbox One',
                'description' => "Halo 5: Guardians sur Xbox One est un FPS mettant en scène les
                 aventures du Master Chief et d'un nouveau personnage, le Spartan Jameson Locke. ",
                'releaseDate' => '27 octobre 2015',
                'price' => '54.99',

            ])->categories()->attach(1);
        }
    }
}

Thanks for the help.

A: Instead of using Db::table, use models, here the Product model you already created.
Product::create([
            'name' => 'Halo 5',
            'slug' => 'halo-5',
            'categoryId' => '1',
            'category' => 'Xbox One',
            'description' => "Halo 5: Guardians sur Xbox One est un FPS mettant en scène les
             aventures du Master Chief et d'un nouveau personnage, le Spartan Jameson Locke. ",
            'releaseDate' => '27 octobre 2015',
            'price' => '54.99',
        ])->categories()->attach(1);

When using models you will have to set fillables, this is a guard to avoid settting properties unexpected.
class Product extends Model {
    protected $fillable = [
        'name',
        'slug',
        'categoryId',
        'category',
        'description',
        'releaseDate',
        'price',
    ];
}


text:
Q: Check for particular Child ViewModel in WPF panel I am very new to WPF, and am currently working on a project to test my knowledge.
I have a panel on which I would like to change different views on, but the view should be changed only if it is not the current child element of the panel.. So I wrote code that looks like this
 public void OnAddNewQuestionBank(object paramter)
 {
        var childIsCurrent = _mainWindow.ContentBox.Children.OfType<AddQuestionsPane>().Equals(typeof(AddQuestionsPane));

        if(!childIsCurrent)
        {
            //Display the panel
            _mainWindow.ContentBox.Children.Add(new AddQuestionsPane());
        }
 }

But I realised that the childIsCurrent always returns false... How do I solve this problem

A: OfType<T>() returns an IEnumerable<T> object. It does not equal a Type, which is why that always returns false. Instead, you could try and see if there are any items in the IEnumerable<T>. For example:
var childIsCurrent = _mainWindow.ContentBox.Children.OfType<AddQuestionsPane>().Any();


text:
Q: What is the wrong in the following c code ? MISRA quality warning message I am getting MISRA QAC warning for the following code sample snippet. That is 'Value of control expression is not derived from an explicit logical operation.'
It is clear that without assigning the return value to a variable evaluation has been done. What is the exact reason for this quality warning?
file.c
if(fun1())
{
//statement1
}
else
{
//statement2
}

bool fun1()
{
  return (bool) (Global_variable1 && Global_Variable2)
}

A: Your code has the following MISRA-C:2012 violations:

*

*
Rule 8.2 Functions shall be in prototype format with named parameters.

*
Rule 8.4 A compatible declaration shall be visible when an object or function with external linkage is defined".

*
Rule 17.3 A function shall not be declared implicitly

I'd expect a compliant tool to give at least one of the above errors. In addition, a compliant C99 or later compiler will not compile code with implicit functions/implicit int.
None of these problems are the slightest related to booleans. Notably, MISRA-C has no rule "value of control expression is not derived from an explicit logical operation". The relevant MISRA-C rule is

Rule 14.4 The controlling expression of an if statement /--/ shall have essentially Boolean type.

In MISRA-C:2004 this rule is called 13.2 and was just advisory back then. It was pretty much an identical rule.
What's different in MISRA-C:2012 is that they explicitly mention that the tool must have some means of configuring which type it should treat as "essentially Boolean" (called "effectively Boolean" in 2004), in case you aren't using the C99 bool type.
If your tool does not know which type to regard as essentially Boolean, it will treat your C90 home-made bool as an int. And then it will think that the if statement is using an int, which would have been a violation of the rule.
In addition, C90 functions that have no prior function declaration visible implicitly assume that the function returns int. But because of the 3 mentioned rules above, the MISRA-C checker should never let such code through.
Solution to fix the specific error:

*

*Ask your tool vendor how to configure the tool so that it knows which type that's to be regarded as "essentially Boolean".

*Alternatively, patch the code to if(fun()==true), but you really shouldn't need to do that just for MISRA compliance.

Solution to get MISRA-C:2004/MISRA-C:2012 compliant code:
bool fun1 (void); /* you must declare the function before using it and it must use void */

...

if(fun1())
{
  /*statement1*/   /* Note that you can't use // comments in C90 or MISRA-C:2004 */
}
else
{
  /*statement2*/
}

...

bool fun1 (void) /* must use void */
{
  /* return is not a controlling expression, no need for compound statements.
     No need to cast, the result of && is essentially boolean.
     MISRA-C:2004 has no requirement to cast to underlying type if using booleans.
  */
  return Global_variable1 && Global_Variable2;
}

Please note that using global variables is likely to get you into trouble with other MISRA-C rules, and with co-workers who have to maintain your code.

A: The call fun1() is not an explicit logical expression. The explicit form would be fun1() == true or fun1() != 0. Yes, that seems unnecessary, but it's what the warning is complaining about.


text:
Q: Undefined variable ins_id in jquery in the below code I am getting ins_id undefined when making AJAX call.
<script type="text/javascript">
$(document).ready(function() {

        var state_id;
        var city_id;
        var ins_id;

        $('#state_id').change(function(){
            var state_id = $(this).val();
            console.log(state_id);
            if(state_id){
                $.ajax({
                   type:"GET",
                   url:"http://domain/?state_id="+state_id,
                   success:function(res){
                    if(res){
                        console.log(res);
                        $("#city_id").empty();
                        $("#city_id").append('<option>Select</option>');
                        $.each(res,function(key,value){
                            $("#city_id").append('<option value="'+value.city_id+'">'+value.city_name+'</option>');
                        });
                    }else{
                       $("#city_id").empty();
                    }
                   }
                });
            }else{
                $("#city_id").empty();
            }
       });

        $('#city_id').change(function(){
            var city_id     = $(this).val();
            var ins_id  = $("ins_id").val(); // I AM GETTING undefined ins_id
            var t = "city_id="+city_id+"&ins_id="+ins_id;
            console.log(t);

            if(city_id){
                $.ajax({
                   type:"GET",
                   url:"http://domain/?city_id="+city_id+"&ins_id="+ins_id,
                   success:function(res){
                    if(res){
                        console.log(res);
                        $("#is_office").append('<option>Select</option>');
                        $("#app_office").append('<option>Select</option>');
                        $.each(res,function(key,value){
                            $("#is_office").append('<option value="'+value.office_id+'">'+value.office_name+'</option>');
                            $("#app_office").append('<option value="'+value.office_id+'">'+value.office_name+'</option>');
                        });
                    }else{
                       $("#is_office").empty();
                       $("#app_office").empty();
                    }
                   }
                });
            }else{
                $("#is_office").empty();
                $("#app_office").empty();
            }
       });
    });
</script>

I have spend more than two hours just to figure out what is wrong with this code, tried different browsers, but no avail. Kindly help.

A: Just check this line again
var ins_id  = $("ins_id").val();

If ins_id ia an element id then you need to write
var ins_id  = $("#ins_id").val();

If it is a class name then you need to specify
var ins_id  = $(".ins_id").val();

According to the name ins_id i think that it is self explanatory for the element id. Always use the proper jquery selector when getting and setting the values.

A: var ins_id  = $("ins_id").val();

Above line should be replaced by
var ins_id  = $("#ins_id").val();


text:
Q: Never use Turbolinks to load a specific route I know that I can use the data-no-turbolink attribute to ensure that a link (or many links) don't use turbolinks, but is there any way to ensure that a specific page will never be loaded via turbolinks?
I have a particular page that is broken when loaded via turbolinks, and instead of employing some hacks to fix this, I'd rather that this page just always load in the usual fashion.
I know I can add data-no-turbolink to all links going to this page, but then I'd have to remember to do this to every subsequent link to this page, which is pretty hacky.
Is there a better way?

A: To modify all new and existing URLs to remove turbolinks to a specific URL, read below:
Since you're wanting to always use "data-no-turbolinks" when linking to a specific page via link_to, you can modify the method to check the URL of its destination and set the data-no-turbolinks attribute.
Modify the link_to helper (be sure to replace ROUTE_url and ROUTE_path with the correct variables from your routes:
# application_helper.rb
def link_to(name, path, options = {})
  no_turbolink_routes = [ROUTE_url, ROUTE_path]  # Add URLs/PATHs here

  if no_turbolink_routes.include? path
    options['data-no-turbolinks'] = 'true'
  end

  super(name, path, options)
end

A: You can add the following code to your application's helper file. It will check the controller and action being called on the page, then return an HTML attribute if it matches.
# application_helper.rb
def no_turbolinks
  "data-no-turbolinks='true'".html_safe if controller_name == "your_controller" && action_name == "your_action"
end

Then, in your application's HTML:
<body <%= no_turbolinks %>>

Ideally, this would only load on the specific page that you want it to; disabling turbolinks for that one page.