text:
Q: Updating from a Debian RC to a stable version when released? If I install the Debian Jessie RC today do I need to do anything special besides 'apt-get update' to get the Jessie Stable version when released?

A: The only thing you'll need to do, besides "apt-get update", is "apt-get upgrade" :)
Moreover, you can even migrate from Debian 7 to Debian 8 using those two commands.

A: Update from stable to stable  (for example, from 6 squeeze to 7 wheezy)
apt-get update
apt-get upgrade
apt-get dist-upgrade
reboot

For update from RC to Stable would be enough, to use the commands which SOFA wrote


text:
Q: iOS: PageViewController with Buttons I am new to iOS app development and I am attempting to create use a pageviewcontroller to have a left and right scroll-able menu with clickable buttons. I have a top and bottom section
which I do not want to scroll. The scrollable menu is in the middle. I followed this tutorial and was able to get the desired effect but I am unable to do anything with the buttons inside each of the view controllers. I am guessing that this is possibly due this chunk of code from the linked tutorial:
private(set) lazy var orderedViewControllers: [UIViewController] = {
 return [self.newColoredViewController("Green"),
    self.newColoredViewController("Red"),
    self.newColoredViewController("Blue")] }()

private func newColoredViewController(color: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil) .
        instantiateViewControllerWithIdentifier("\(color)ViewController")
}
Is it creating a viewcontroller class on the fly which I am unable to access? How do I go about controlling the buttons on each viewcontroller.
Here is a basic drawing of the app.
App Sample
There is a top and bottom section, with the horizontal scrollable menu in the middle. I am developing an Android and iPhone version. I currently have the Android version finished and need the iPhone to look as close to the Android as possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set default text color when extending Text component Unity's Text component has 323232FF set as color by default. When i extend Text component, that color is not longer set (it's white).

¿How can i set the default text color when extending the component?
using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("UI/CodeText", 10)]
public class CodeText : Text
{
    void Awake() {
        Game.Instance.trackMe();
    }
}

Unity's Text component source code:
https://bitbucket.org/Unity-Technologies/ui/src/0155c39e05ca5d7dcc97d9974256ef83bc122586/UnityEngine.UI/UI/Core/Text.cs?at=5.2&fileviewer=file-view-default
I'm not overwriting the "GetGenerationSettings" which looks to be setting the color :S

A: Two things to consider here:

*

*When you remove and re-add Text component from one GameObject, its initial color becomes white. That white color is the default value in Graphic which Text inherits from.

*This is because invoking hierarchy UI/Text context menu does more than simply adding a Text component, it applies a default theme.
Unless you can spot exactly what's done by that hierarchy menu in the sources, you can do the following to set default properties:
using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("UI/MyText", 10)]
public class MyText : Text
{
    protected override void Awake()
    {
        color = GUI.skin.textField.normal.textColor; // or whatever
    }
}

A: It seems to me, without diving into the code of Text, that your class isn't calling Text's constructor. Even though you don't define a constructor, your class by default looks like this.
public class CodeText : Text
{
    public CodeText() {
    }

    void Awake() {
        Game.Instance.trackMe();
    }
}

What you may need to do is have the constructor call Text's constructor.
public class CodeText : Text
{
    public CodeText() : base() {
    }

    void Awake() {
        Game.Instance.trackMe();
    }
}


text:
Q: Wireguard "wg0: Packet has unallowed src IP" Using the https://github.com/angristan/wireguard-install project I configured a server. Which produced the following server config file at /etc/wireguard/wg0.conf:
[Interface]
Address = 10.66.66.1/24,fd42:42:42::1/64
ListenPort = 51202
PrivateKey = ***************
PostUp = iptables -A FORWARD -i ens3 -o wg0 -j ACCEPT; iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE; ip6tables -A FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -A POSTROUTING -o ens3 -j MASQUERADE
PostDown = iptables -D FORWARD -i ens3 -o wg0 -j ACCEPT; iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ens3 -j MASQUERADE; ip6tables -D FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -D POSTROUTING -o ens3 -j MASQUERADE

### Client chris
[Peer]
PublicKey = ***************
PresharedKey = ****************
AllowedIPs = 10.66.66.2/32,fd42:42:42::2/128,209.250.230.114/32

And the following client file:
[Interface]
PrivateKey = ******************
Address = 10.66.66.2/32,fd42:42:42::2/128
DNS = 94.140.14.14,94.140.15.15

[Peer]
PublicKey = 8ZF6U0mHKvMtVw2A4jha4mZR+a0GP5W85unV05zJIyw=
PresharedKey = **************************
Endpoint = 192.248.162.216:51202
AllowedIPs = 0.0.0.0/0,::/0

This is the file I have in the client. Running wg-quick up server on the client results in:
root@vultr:~# wg-quick up server
[#] ip link add server type wireguard
[#] wg setconf server /dev/fd/63
[#] ip -4 address add 10.66.66.2/32 dev server
[#] ip -6 address add fd42:42:42::2/128 dev server
[#] ip link set mtu 1420 up dev server
[#] resolvconf -a tun.server -m 0 -x
[#] wg set server fwmark 51820
[#] ip -6 route add ::/0 dev server table 51820
[#] ip -6 rule add not fwmark 51820 table 51820
[#] ip -6 rule add table main suppress_prefixlength 0
[#] ip6tables-restore -n
[#] ip -4 route add 0.0.0.0/0 dev server table 51820
[#] ip -4 rule add not fwmark 51820 table 51820

After which I loose network connectivity with the client (I mean my prior SSH connection).
On the server I see the following debug logs:
Feb 14 18:14:21 car kernel: wireguard: wg0: Packet has unallowed src IP (209.250.230.114) from peer 1 (209.250.230.114:56584)
Feb 14 18:14:22 car kernel: wireguard: wg0: Sending keepalive packet to peer 1 (209.250.230.114:56584)
Feb 14 18:14:23 car kernel: wireguard: wg0: Packet has unallowed src IP (209.250.230.114) from peer 1 (209.250.230.114:56584)
Feb 14 18:14:26 car kernel: wireguard: wg0: Packet has unallowed src IP (209.250.230.114) from peer 1 (209.250.230.114:56584)
Feb 14 18:14:33 car kernel: wireguard: wg0: Sending keepalive packet to peer 1 (209.250.230.114:56584)

Surely AllowedIPs = 0.0.0.0/0,::/0 allows any ip? Why am I getting the error about the IP not being allowed?

I tried adding the client ip (209.250.230.114) to the AllowedIps under [Peer] in the server config at /etc/wireguard/wg0.conf + restarting the wireguard systemd service - slight change in behavior now - seems to keep recreating the keypair + sending the handshake:
Feb 14 18:27:15 car kernel: wireguard: wg0: Sending handshake response to peer 2 (209.250.230.114:46777)
Feb 14 18:27:15 car kernel: wireguard: wg0: Keypair 40 destroyed for peer 2
Feb 14 18:27:15 car kernel: wireguard: wg0: Keypair 41 created for peer 2
Feb 14 18:27:20 car kernel: wireguard: wg0: Receiving handshake initiation from peer 2 (209.250.230.114:46777)
Feb 14 18:27:20 car kernel: wireguard: wg0: Sending handshake response to peer 2 (209.250.230.114:46777)
Feb 14 18:27:20 car kernel: wireguard: wg0: Keypair 41 destroyed for peer 2
Feb 14 18:27:20 car kernel: wireguard: wg0: Keypair 42 created for peer 2
Feb 14 18:27:25 car kernel: wireguard: wg0: Receiving handshake initiation from peer 2 (209.250.230.114:46777)
Feb 14 18:27:25 car kernel: wireguard: wg0: Sending handshake response to peer 2 (209.250.230.114:46777)
Feb 14 18:27:25 car kernel: wireguard: wg0: Keypair 42 destroyed for peer 2
Feb 14 18:27:25 car kernel: wireguard: wg0: Keypair 43 created for peer 2

Here is some packet logs output from tshark -i any on the client after running wg-quick up.... Please note the IPs are now different from earlier in my question (tried to set this up from scratch again - hence new ips).
80 30.827763166 87.246.7.226 <E2><86><92> 192.248.154.136 TCP 76 [TCP Retransmission] 57034 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=342868104 TSecr=0 WS=128
   81 30.827859690 192.248.154.136 <E2><86><92> 87.246.7.226 TCP 56 25 <E2><86><92> 57034 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   82 33.439281276 192.248.154.136 <E2><86><92> 192.248.152.91 UDP 192 59054 <E2><86><92> 58338 Len=148
   83 36.811164287 192.248.154.136 <E2><86><92> 108.61.73.244 NTP 92 NTP Version 4, client
   84 38.146118476 87.246.7.243 <E2><86><92> 192.248.154.136 TCP 76 6076 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=211747651 TSecr=0 WS=1024
   85 38.146182173 192.248.154.136 <E2><86><92> 87.246.7.243 TCP 56 25 <E2><86><92> 6076 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   86 38.559280480 192.248.154.136 <E2><86><92> 192.248.152.91 UDP 192 59054 <E2><86><92> 58338 Len=148
   87 38.852121979 87.246.7.226 <E2><86><92> 192.248.154.136 TCP 76 [TCP Retransmission] 57034 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=342876128 TSecr=0 WS=128
   88 38.852220458 192.248.154.136 <E2><86><92> 87.246.7.226 TCP 56 25 <E2><86><92> 57034 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   89 39.146306580 87.246.7.243 <E2><86><92> 192.248.154.136 TCP 76 [TCP Retransmission] 6076 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=211748652 TSecr=0 WS=1024
   90 39.146388276 192.248.154.136 <E2><86><92> 87.246.7.243 TCP 56 25 <E2><86><92> 6076 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   91 41.150763667 87.246.7.243 <E2><86><92> 192.248.154.136 TCP 76 [TCP Retransmission] 6076 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=211750656 TSecr=0 WS=1024
   92 41.150880444 192.248.154.136 <E2><86><92> 87.246.7.243 TCP 56 25 <E2><86><92> 6076 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   93 41.630158997 212.70.149.54 <E2><86><92> 192.248.154.136 TCP 76 46658 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=42893859 TSecr=0 WS=1024
   94 41.630236617 192.248.154.136 <E2><86><92> 212.70.149.54 TCP 56 25 <E2><86><92> 46658 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   95 41.811177910 192.248.154.136 <E2><86><92> 108.61.73.243 NTP 92 NTP Version 4, client
   96 42.630885040 212.70.149.54 <E2><86><92> 192.248.154.136 TCP 76 [TCP Retransmission] 46658 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=42894860 TSecr=0 WS=1024
   97 42.630953128 192.248.154.136 <E2><86><92> 212.70.149.54 TCP 56 25 <E2><86><92> 46658 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
   98 43.353963530 fe:00:03:35:d7:65 <E2><86><92>              ARP 44 Who has 192.248.154.136? Tell 104.238.168.72
   99 43.354021247 56:00:03:35:d7:65 <E2><86><92>              ARP 44 192.248.154.136 is at 56:00:03:35:d7:65
  100 43.679313102 192.248.154.136 <E2><86><92> 192.248.152.91 UDP 192 59054 <E2><86><92> 58338 Len=148
  101 44.634917692 212.70.149.54 <E2><86><92> 192.248.154.136 TCP 76 [TCP Retransmission] 46658 <E2><86><92> 25 [SYN] Seq=0 Win=29200 Len


text:
Q: How to install new hardware drivers so when it is plugged in for the first time, windows will know to find the drivers automatically I want to be able to deploy a project to some of my users the requires a USB-serial adapter. The hard way is to give them the drivers and tell them to plug in the adapter and when prompted, they will have to locate the files manually. I don't want to do that.
Most install shields know how to do that automatically - you install the software, plug in the new hardware and windows will automatically install the correct drivers. This is the solution I want, only without an install shield. What are my options?

A: Checkout:
FAQ: Information about Driver Install Frameworks Tools
InstallShield has support creating installers that leverage DIFx ( Driver Installation Framework ).  If you don't want to buy/use InstallShield, you can also take a look at Windows Installer XML (WiX). It also has extensions that support DIFx.
Drivers Installation With WiX


text:
Q: How to check a dict key? I`m doing an unit test for the first time and I need to check if a success key is the same as the other one, how can I check a success key without checking the whole dictionary?
I just need to check the success key not all the other ones
I need to do it with assert using the unit test module
dict 1 = {'success': RC.input_validation,
          'return_msg': return_msg,
          'debug_data': debug_data}

dict 2 = {'success':  RC.success,
          'return_msg': return_msg,
          'debug_data': debug_data}

class MyTestCase(unittest.TestCase):
    def test_something(self):
        call_result = {}
        debug_data = []

        test = SetShape()
        call_result = SetShape.setShape(test, shapechoosing=1)
        debug_data.append(call_result)
        print("10")

if __name__ == '__main__':
    unittest.main()

A: Access the values of the 'success' key in each dictionary and check if they're equal
if dict1['success'] == dict2['success']:
    print("they're the same")

A: Is this what you're looking for?
if dict_1.get('success') == dict_2.get('success'):
   # your body of code

Hope it helps!!

A: This should work for you.
dict_1 = {'success': "RC.input_validation",
          'return_msg': "return_msg",
          'debug_data': "debug_data"}

dict_2 = {'success':  "RC.success",
          'return_msg': "return_msg",
          'debug_data': "debug_data"}

dict_1.get('success')==dict_2.get('success')


text:
Q: How to interpolate in n dimensions with different length axes So I was looking at how to use scipy's interpn function, and the example they have on the documentation isn't quite working with what I need it to do.
My implementation is a bit different. I have a precomputed value array with shape [200,40,40,40] that I get from a different script.
So when I do something like:
t = np.linspace(0,1, 200)
x = np.linspace(0,1, 40)
y = np.linspace(0,1, 40)
z = np.linspace(0,1, 40)
points = (t,x,y,z)
interpn(points,values,point)

I get an error: "ValueError: There are 40 points and 200 values in dimension 0"
It seems as though the dimensions of my points tuple and value array are not lining up, but I thought since my "t" axis is first in the tuple, it should be match. Any advice?

A: So this works for me:
import numpy as np
from scipy.interpolate import interpn

def f(x,y,z,t):
    '''Simple 3D + time dimensional function.'''
    return (np.sin(x)+y+np.sqrt(z))*t

t = np.linspace(0,1,200)
x = np.linspace(0,1,40)
y = np.linspace(0,1,40)
z = np.linspace(0,1,40)
points = (x,y,z,t)
values = f(*np.meshgrid(*points))

# example point in domain
point = [0,0.5,0.75,1/3.]

print(interpn(points, values, point))
array([0.44846267])

You defined x,y,z as np.linspace(0,40,1), this means you have a single point on the interval [0,40]. The same for t. That's probably your error. Example taken from the official scipy documentation.


text:
Q: Inner join with 3 tables in Visual Studio I am trying to do an inner join with 3 tables in Visual Studio but I am getting an error. When I do the inner join with only 2 tables it works.
Here is my code for 3 tables:
"select b.bidID, b.userID, u.userFirstName, u.userLastName, c.clientName, b.productName, b.openingDate, b.status
from Bid b
inner join Client c on b.clientID = c.clientID
inner join User u on b.userID = u.userID
where b.clientID = '" + cId + "' ";

with 2 tables:
"select b.bidID, b.userID, c.clientName, b.productName, b.openingDate, b.status
from Bid b
inner join Client c on b.clientID = c.clientID
where b.clientID = '" + cId + "' ";

A: user is reserved keyword in MSSQL.
Use it with square brackets like this [user]
select b.bidID ,b.userID , u.userFirstName, u.userLastName ,c.clientName , b.productName , b.openingDate,b.status
from Bid b
inner join Client c on b.clientID=c.clientID
inner join [User] u on b.userID=u.userID
where b.clientID='" + cId + "' "

A: It is difficult to tell since you didn't include the error you are getting but my guess would be that you are getting an error because User is a keyword in SQL Server.  Try to change User to [User] and see if your error goes away.

A: Try out the following SQL query
select b.bidID ,b.userID , u.userFirstName, u.userLastName, c.clientName , b.productName , b.openingDate,b.status
from ([Bid] b inner join [Client] c on b.clientID=c.clientID )
inner join [User] u on (b.userID=u.userID) where b.clientID='" + cId + "' ;


text:
Q: Google analytics event tracking not showing accurate data? I have a "Download" button on my webpage(page1). Onclick of this button, a downloadFile.php page(page2) opens and a zip file automatically downloads.
I want to track the onclick event in page1. So I have set up the Google analytics event tracking on click. The code is below:

 Download

I also store the user(USER_AGENT) info on page load. So I get the number of downloads.
The google analytics event data shows up but, the onclick event number and the download number do not match. That is, if on click event is 85, the download count that I have recorded is 700. That big difference. I feel that the analytics click event tracking is not accurate. Is this possible? Or have I made a mistake in setting up the tracking code?


text:
Q: Are Linux commands included with or part of the shell? I am trying to figure out the different components of Linux and how they work together, and I have a terminology related question. The terminal runs the shell, which is usually Bash. One can also run Linux commands (e.g. ls, mkdir and cp) in terminal. But then I learned that not all Linux commands are part of bash (or shell). Does that mean that the terminal does not run shell only?

A: The short answer is YES.  Commands are both internal and external to the shell.
The shell is merely a user interface, and (ignoring various standards), it it is up to the shell if it wants to implement commands internally or externally.  For example, the busybox shell tries to implement nearly all basic commands internally, so it is the only required executable on an embedded system.
If you read the man page for bash, you will find a section called SHELL BUILT IN COMMANDS that lists internal commands.  Some commands would not work if implemented externally, such as cd, export, source.
External commands are searched for in directories listed in $PATH.  Some commands are available both internally and externally, and the two are not necessarily identical.
One example of that is the pwd command.  The built in version gives you bash's idea of the current directory.  The external one can be run as /bin/pwd and will give a different answer if you cd through a symlink to a directory.
Technically speaking, the external commands not built into the shell are not run by terminal, but by the shell itself.  Having said that, you can tell the terminal specifically to start with a command that isn't the shell, or is a different shell.

A: It probably depends on the terminal, but those I've used have been able to run any command (but many commands terminate so quickly that it's pointless to start a terminal to run them, whether they produce output does not matter). I remember using terminals to run screen (and then let screen start the appropriate number of shells).
As described in the other answer you've gotten, shells have a number of built in commands (some shells have more than other, so check the manual for the one you use), to have access to those, and as shells generally stay running (until you exit them), you should just let the terminal start as shell unless you know what you're doing. (In a few cases you can save a process, but unless you have very peculiar needs it won't hurt to have one more process running).

A: The terminal doesn't run anything: it's just the user interface. Or, for the processes the operating system runs, it's a particular sort of a "file", something that can be read from and written to using the read() and write() system calls. (Plus some special ones for terminals in specific.)
When you login via (say) SSH, the SSH server launches a shell and gives it  file descriptors connected to (the device node representing) the terminal.
If you login via a GUI and start a terminal emulator, pretty much the same happens, just replace the SSH server with the terminal emulator.
Which ever way you go, the shell can now print the prompt to and read commands from the terminal, and launch external programs (e.g. ls or git or whatever), which can also access the terminal. Or it can run builtin commands (read, echo) similarly.
(Note that you can run non-interactive shell sessions too. Running a shell script is pretty much the same, the input to the shell just then comes from a file and not a terminal. What ever the shell launches, then also gets input from the file. The point is that the programs mostly don't need to care if they're connected to a terminal or something else.)
On a usual general-purpose system, most of the commands you'd run are not built in to the shell, but external programs. On some embedded systems with Busybox, the common stuff may well be implemented within Busybox itself. But even then, you probably have some external application that actually does whatever it is the system is supposed to do, even if that's just a Python or Lua interpreter.
See also: What is the exact difference between a 'terminal', a 'shell', a 'tty' and a 'console'?


text:
Q: "RuntimeError: could not retrieve last insert ID" on my mysql i'm trying to install the Prelude package and the Prewikka package from this sources. i'm following all instructions from this ManualUser.
i already builds all sources without errors on my Ubuntu but when i try connecting to localhost:8000, i get the errors from server side :
$ prewikka-httpd
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/bin/prewikka-httpd", line 62, in application
    return wsgi.application(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/web/wsgi.py", line 161, in application
    core.process(WSGIRequest(environ, start_response))
  File "/usr/local/lib/python2.7/dist-packages/prewikka/main.py", line 280, in process
    response = err.respond()
  File "/usr/local/lib/python2.7/dist-packages/prewikka/error.py", line 106, in respond
    return self._html_respond()
  File "/usr/local/lib/python2.7/dist-packages/prewikka/error.py", line 90, in _html_respond
    from prewikka import baseview
  File "/usr/local/lib/python2.7/dist-packages/prewikka/baseview.py", line 27, in <module>
    from prewikka import error, history, hookmanager, resource, response, template, utils, view
  File "/usr/local/lib/python2.7/dist-packages/prewikka/history.py", line 102, in <module>
    crontab.schedule("search_history", N_("Search history deletion"), "0 * * * *", _regfunc=history._history_cron, enabled=True)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/crontab.py", line 240, in schedule
    self._init_system_job(ext_type, name, schedule, enabled, _regfunc)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/database.py", line 91, in inner
    ret = func(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/crontab.py", line 152, in _init_system_job
    res = env.db.query("SELECT 1 FROM Prewikka_Crontab WHERE ext_type=%s AND userid IS NULL", ext_type)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/database.py", line 547, in query
    return preludedb.SQL.query(self, sql)
RuntimeError: Table 'prewikka.Prewikka_Crontab' doesn't exist

so i try make a tables database manually like :
mysql> desc Prewikka_Crontab;
+----------+-----------+------+-----+---------+-------+
| Field    | Type      | Null | Key | Default | Extra |
+----------+-----------+------+-----+---------+-------+
| id       | int(11)   | YES  | UNI | NULL    |       |
| name     | char(255) | NO   | PRI | NONE    |       |
| userid   | int(11)   | YES  | UNI | NULL    |       |
| schedule | char(255) | NO   | UNI | NONE    |       |
| ext_type | char(255) | NO   | UNI | NONE    |       |
| ext_id   | int(11)   | YES  | UNI | NULL    |       |
| base     | char(255) | NO   | UNI | NONE    |       |
| runcnt   | char(255) | NO   | UNI | NONE    |       |
| enabled  | char(255) | NO   | UNI | NONE    |       |
| error    | char(255) | NO   | UNI | NONE    |       |
+----------+-----------+------+-----+---------+-------+
10 rows in set (0.09 sec)

mysql>

and then i try connection to localhost:8000 again, i get the errors :
$ prewikka-httpd
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/bin/prewikka-httpd", line 62, in application
    return wsgi.application(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/web/wsgi.py", line 161, in application
    core.process(WSGIRequest(environ, start_response))
  File "/usr/local/lib/python2.7/dist-packages/prewikka/main.py", line 280, in process
    response = err.respond()
  File "/usr/local/lib/python2.7/dist-packages/prewikka/error.py", line 106, in respond
    return self._html_respond()
  File "/usr/local/lib/python2.7/dist-packages/prewikka/error.py", line 90, in _html_respond
    from prewikka import baseview
  File "/usr/local/lib/python2.7/dist-packages/prewikka/baseview.py", line 27, in <module>
    from prewikka import error, history, hookmanager, resource, response, template, utils, view
  File "/usr/local/lib/python2.7/dist-packages/prewikka/history.py", line 102, in <module>
    crontab.schedule("search_history", N_("Search history deletion"), "0 * * * *", _regfunc=history._history_cron, enabled=True)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/crontab.py", line 240, in schedule
    self._init_system_job(ext_type, name, schedule, enabled, _regfunc)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/database.py", line 91, in inner
    ret = func(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/crontab.py", line 154, in _init_system_job
    self.add(name, schedule, ext_type=ext_type, enabled=enabled)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/crontab.py", line 219, in add
    return self.update(None, name=name, schedule=schedule, user=user, ext_type=ext_type, ext_id=ext_id, enabled=enabled)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/crontab.py", line 209, in update
    return env.db.getLastInsertIdent()
RuntimeError: could not retrieve last insert ID

i'm still not understanding the errors RuntimeError: could not retrieve last insert ID on my database.
Edit #1
i tried @Vineesh advice, my table database to be :
mysql> DESC Prewikka_Crontab;
+----------+-----------+------+-----+---------+----------------+
| Field    | Type      | Null | Key | Default | Extra          |
+----------+-----------+------+-----+---------+----------------+
| id       | int(11)   | NO   | PRI | NULL    | auto_increment |
| name     | char(255) | NO   | UNI | NONE    |                |
| userid   | int(11)   | YES  | UNI | NULL    |                |
| schedule | char(255) | NO   | UNI | NONE    |                |
| ext_type | char(255) | NO   | UNI | NONE    |                |
| ext_id   | int(11)   | YES  | UNI | NULL    |                |
| base     | char(255) | NO   | UNI | NONE    |                |
| runcnt   | char(255) | NO   | UNI | NONE    |                |
| enabled  | char(255) | NO   | UNI | NONE    |                |
| error    | char(255) | NO   | UNI | NONE    |                |
+----------+-----------+------+-----+---------+----------------+
10 rows in set (0.03 sec)

and when i connect my server, i get the errors :
$ prewikka-httpd
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/bin/prewikka-httpd", line 62, in application
    return wsgi.application(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/web/wsgi.py", line 161, in application
    core.process(WSGIRequest(environ, start_response))
  File "/usr/local/lib/python2.7/dist-packages/prewikka/main.py", line 280, in process
    response = err.respond()
  File "/usr/local/lib/python2.7/dist-packages/prewikka/error.py", line 106, in respond
    return self._html_respond()
  File "/usr/local/lib/python2.7/dist-packages/prewikka/error.py", line 91, in _html_respond
    return baseview.BaseView().respond(self._setup_template(self.template, False), self.code)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/view.py", line 481, in __init__
    registrar.DelayedRegistrar.__init__(self)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/registrar.py", line 46, in __init__
    i(ref)
  File "/usr/local/lib/python2.7/dist-packages/prewikka/view.py", line 583, in _add_route
    self._views_rules[rule] = v
TypeError: unhashable type: 'Rule'

what should i do? Hope anyone can helps me!
Thanks in advance.

A: id field in your table "Prewikka_Crontab" should be an auto increment column.

A:
the output errors appears cause it really bad table on my index tables. i need to delete it and recreate it again.

the format table available on the python script at here
The table Required :
mysql> DESC Prewikka_Crontab;
+----------+---------------------+------+-----+---------+----------------+
| Field    | Type                | Null | Key | Default | Extra          |
+----------+---------------------+------+-----+---------+----------------+
| id       | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name     | varchar(255)        | NO   |     | NULL    |                |
| userid   | varchar(32)         | YES  |     | NULL    |                |
| schedule | varchar(32)         | YES  |     | NULL    |                |
| ext_type | varchar(255)        | YES  |     | NULL    |                |
| ext_id   | int(11)             | YES  |     | NULL    |                |
| base     | datetime            | NO   |     | NULL    |                |
| enabled  | tinyint(4)          | YES  |     | 1       |                |
| runcnt   | int(11)             | YES  |     | 0       |                |
| error    | text                | YES  |     | NULL    |                |
+----------+---------------------+------+-----+---------+----------------+
10 rows in set (0.01 sec)

Hope this helps.


text:
Q: Using .append to iterate upon an expanding list of numbers in Python Both these methods return a None type; their purpose is to append a new number equal to 1 higher than the final integer in the list. The dual print statements are just to test the viability of the code in a loop. What am I doing wrong so as to not get the desired result?
Method 1:
number_list = [1,2,3,4,5,6,7,8]
number_list = number_list.append(number_list[-1]+1)
print(number_list)
print(number_list)

Method 2:
number_list = [1,2,3,4,5,6,7,8]
number_list = number_list.append(number_list[0]+number_list[-1])
print(number_list)
print(number_list)

A: .append returns none which is what you are setting number_list to. Instead, use the method without setting it to number_list and it will work fine.
>>> number_list = [1,2,3,4,5,6,7,8]
>>> number_list
[1, 2, 3, 4, 5, 6, 7, 8]
>>> number_list.append(number_list[-1]+1)
>>> number_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. 1 This is a design principle for all mutable data structures in Python. [source]

A: you dont need to numberlist = numberlist.append(...)
just
numberlist.append(..)


text:
Q: Why am I getting the following output in this simple code? #include<stdio.h>
int main()
    {
        int i,l,*A;char C;
        A=(int*)malloc(5*4);
        for(i=0;i<5;i++)
            scanf("%d",A+i);
        scanf("%c",&C);
        scanf("%d",&l);
        printf("%d%c\n",l,C);

return 0;
}

Input: 5 4 3 3 9
       r 1
I expect the output to be 1r.  But I am getting the output as 21473443
84...i.e. garbage.

A: In your example, %c reads the space before the r, and the subsequent scanf("%d") fails to read an integer (since it's presented with r 1).
To verify this, examine the return value of scanf(): it is the number of items successfully matched and stored, so the final scanf() will return zero.
P.S. In the malloc() (or anywhere else for that matter) you should not assume that sizeof(int) == 4.

A: For %c conversion specifier, scanf does not omit whitespaces as it does for %d for example. You have to tell scanf to skip whitespaces and then read first non-whitespace character. Here's your fixed code.
#include<stdio.h>
#include <stdlib.h>
int main()
    {
        int i,l,*A;char C;
        A=malloc(5*sizeof(int));
        for(i=0;i<5;i++)
            scanf("%d",A+i);
        scanf(" %c",&C);
        //     ^ here
        scanf("%d",&l);
        printf("%d%c\n",l,C);
        free(A);  // remember to free what you've malloc'd

return 0;
}

Since you are asking how to verify return value from scanf, see prototype of scanf:

int scanf(const char *format, ...);

As you can see, it returns int. Man page says even more about return value:

RETURN VALUE These functions return the number of input items
  successfully matched and assigned, which  can be fewer than provided
  for, or even zero in the event of an early matching failure.

This part I will leave for you to do it. I hope that it is now clear how to check scanf's return value.

A: (1)Give space before %c in scanf (i.e) scanf(" %c",&C);
(2)Scanf function  return the number of input items successfully matched and assigned.
To check scanf return value,
void main
  {
    int a,b,c,d;
    a=scanf("%d%d%d",&b,&c,&d);
    printf("a=%d\n",a);//a=3
    a=scanf("%d",&b);
    printf("a=%d",a);//a=1
  }


text:
Q: Laravel replace variable on Model I would like to be able to override a variable on the model, so that a normal field is instead replaced by a relationship's field, i.e.
Where product.image might normally be a field, I want to run a function which will go through all of the resulting products from a query and replace the image field with something like the following --
(Product.php) Model
...

public function variantImages(){
    return $this->image = $this->variants()->first()->pluck('image_url');
}

...

So the default product image field is replaced by the "first product variant's image". I don't want to do this in a collection once I have already got the data, the problem here is being able to do this at a Model level.
Is there a way to do this within a scope?

A: You can create an accessor instead of a normal function:
// Singular because it only gets one
public function getVariantImageAttribute(){
    return $this->image = $this->variants()->first()->pluck('image_url');
}

This will make it available under $product->variant_image
Then you can ensure it is always appended to your model (if you want) by adding it to the appends e.g.:
$appends = [ 'variant_image' ];

Since this is not the best idea since it will force load the relationship every time you get a product (even if you didn't request it) you can conditionally control when to append it via e.g.:
return response()->json($product->append('variant_image'));

Note that the append method also works for collecitions of eloquent models.


text:
Q: how to get textContent of textarea after change? I have a textarea tag. I want to be able to get its textContent after textContent changed?
<textarea id="xxx"> sameple text </textarea> // before
<textarea id="xxx"> sameple text and new text </textarea> // after

I want listen even when the textarea's content has changed.

A: you can put your script as
$(document).ready(function(){
  $("#xxx").change(function(){
     alert($("#xxx").val());
  });
});

if you put $("#xxx").html() it will give you before text but if you keep $("#xxx").val() it will give you changed value.

A: You will need to use onkeyup and onchange for this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.
$(document).ready(function(){
       $(document).on('change','#xxx',function(){
             var newtext = $(this).text();
       });
});

A:
Use input event.

The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed.

$('#xxx').on('input', function() {
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea id="xxx">sameple text</textarea>


text:
Q: iMac wont startup and won't boot from CD My 24" 3.06Ghz iMac will no longer fully boot. It constantly gives me the grey "Your machine needs to be restarted" half way through booting. At first I was able to boot into SuperUser mode and run an fsck which passed normally, but eventually after the constant rebooting fsk now reports:
Invalid node structure
The volume Macintosh HD could not be verified completely

I have also tried booting to my Snow Leopard install DVD but that just brings up the grey "Your machine needs to be restarted" screen.
I assume now that my HD is toast (When using another Mac, I am unable to mount it in Target disk mode), but the inability to boot to the CD tells me there is something deeper at fault here. Is there any way that I can further diagnose the problem?

A: From what you describe, your internal hard drive failed, which will require a replacement;  since you have an iMac, I suggest that unless you're very comfortable using a variety of tools and have time, let Apple do it for you. In any case, what you can try to do is, connect an external USB/FW drive and try to install into that drive.
The fact that your drive doesn't want to boot from the DVD is intriguing if anything, but the DVD may be crashing when reading the "broken" drive. It's rare, but it could happen. Do you have any other Mac to "clone" into an external drive and try to boot from there?
Since it's an iMac, your best bet is to remove the internal drive and proceed from there. The problem is that removing the drive is a painful operation.
Best idea: go to an Apple store or certified shop. They have the tools and the spare parts to better diagnose the problem.


text:
Q: Loop requests in react with axios I have a socket defined in the backend that accepts continuous requests for the server. Now, I want to send requests continuously to the backend API, until a stop button is pressed. So, I can use a loop (BAD PRACTICE). The problem is that it never checks the updated state. So, How can I implement this with the best possible coding practice?

*

*I'm using two different pages in Next.JS for client and server. The server has a simple button to start and stop the server, and when the button is set to start, it should continuously accept requests and update the response state, and when the button is set to stop, it should stop requesting any more.

const [close, closeButton] = useBoolean() // State for close button
let req;
proto ? req = 'UDP' : req = 'TCP' // There is a checkbox to select the connection mode. proto is a state.
console.log(`Close button: ${close}`) // This state updates correctly.

const onSubmit = async () => {
   while(!close)
        console.log(`Close button: ${close}`) // This state does not update while staying in the loop.
        const res = await serverRequest(req)
        console.log(res.messageFromClient)
    }
}

So, how should I get this to run indefinitely until the close button is pressed. Should I use redux for the global state or is there a better way other than the while loop?
Client code for reference:
 const onSubmit = async values => {
        const clientData = await clientRequest({proto, JSON.stringify(values.message)})
        console.log(clientData)
        console.log(values.message)
    }

This code sends client data every time the message is sent from the client. So, in order to run the client, the server should continuously listen to requests. Whenever the client sends a request, the server should get a response and start the server once again, until the mode of connections is changed or the close button is pressed in the server-side code.

A: If you absolutely must use this code, and want it to access updated state then you could cache a copy of state in a React ref and refer to that instead.
const [close, closeButton] = useBoolean() // State for close button
const closeRef = React.useRef();

React.useEffect(() => {
  closeRef.current = close; // <-- cache close value when it updates
}, [close]);

const onSubmit = async () => {
  while(!closeRef.current) // <-- cached close state value
    console.log(`Close button: ${closeRef.current}`)
    const res = await serverRequest(req)
    console.log(res.messageFromClient)
  }
}


text:
Q: Which find() function is called when " using namespace std" added to code with while using STL set containers? I've read that STL Set container has a specialized find() function which was more efficient than std::find(). My question is that which find() function would be called if I'd use using namespace std?

A: std::find is a free function, std::set::find is a member function of set, the way to call them is different.
Refer to:  http://www.cplusplus.com/reference/set/set/find/
https://www.cplusplus.com/reference/algorithm/find/
I will fill in the details once I reach home, but it should be obvious.


text:
Q: scipy.integrate.solve_ivp unclear how to solve implicit ODE of form 0=F(t, y(t), y'(t)) Currently, I do use assimulos solver suite to solve an implicit differential equation of the form 0 = F(t, y(t), y'(t)). I would like to use a solver which comes with a native scipy installation and had a look at the documentation for scipy.integrate.solve_ivp. The documentation says that the solver solves a a system of the form:

Solve an initial value problem for a system of ODEs.
  This function numerically integrates a system of ordinary differential equations given an initial value dy / dt = f(t, y) y(t0) = y0

I do miss the ability to solve a system of the form dy / dt = f(t, y, y'). Is this possible with scipy.integrate.solve_ivp ?

A: Such an equation is called a differential algebraic equation (DAE). As far as I know, SciPy doesn't have a built-in DAE solver.
This answer to this similar question provides an example of using fsolve to solve the algebraic part of the problem in combination with odeint. This might be applicable to your problem.
You might also be interested in the ODES package, which provides additional solvers as an extension for SciPy, including a DAE solver.


text:
Q: Method of characteristics for Burgers' equation with rectangular data
Using the method of characteristics, find a solution to Burgers' equation
  \begin{cases}
u_t+\left(\frac{u^2}{2} \right)_x =0 & \text{in }\mathbb{R}\times(0,\infty) \\
\qquad \qquad \, \, u=g & \text{on } \mathbb{R} \times\{t=0\}
\end{cases}
  with the initial conditions
  $$g(x)=\begin{cases}
0 & \text{if }x < 0 \\
1 & \text{if }0 \le x \le 1 \\
0 & \text{if }x > 1
\end{cases}$$

First, I realized that the equation $u_t+\left(\frac{u^2}{2} \right)_x =0$ is equivalent to this form: $$u_t+uu_x =0$$
Then should I generally follow the method of solution as outlined in the answer of this page?
Note that this is not a duplicate question of that page. Rather I want to know if that page can be used for my problem, even though my ICs are different.
By the way, the solution printed in my book (PDE Evans, 2nd edition, page 142) is

$$u(x,t) =
\begin{cases} 0 & \text{if } x < 0 \\
\frac xt & \text{if } 0 < x < t
\\ 1 & \text{if } t < x < 1 + \frac t2
\\ 0 & \text{if } x > 1 + \frac t2 \tag{$0 \le t \le 2$}
\end{cases}$$

A: The variable $u$ is constant along the characteristic curves, which satisfy
\begin{aligned}
x'(t) & = u(x(t),t) \, ,
\\
& = u(x(0),0) \, .
\end{aligned}
Thus, the latter are straight lines in the $x$-$t$ plane, determined by the initial data. Here, the initial data is piecewise constant, i.e. we solve Riemann problems. As displayed in the figure below,

*

*characteristics separate in the vicinity of $x=0$, and a rarefaction wave occurs;

*characteristics cross in the vicinity of $x=1$, and a shock-wave occurs.

The rarefaction wave is a continuous self-similar solution, deduced from the self-similarity Ansatz $u (x,t)=v (\xi)$ with $\xi = x/t$. Indeed,
$$
\partial_t
 u(x,t) + u(x,t)\, \partial_x u(x,t) = \left(v(\xi) - \xi\right) \frac{v'(\xi)}{t} \, ,
$$
and thus, $v(\xi) = \xi$ or $u(x,t) = x/t$.
The shock speed $s$ is given by the Rankine-Hugoniot jump condition:
$$
s = (1+0)/2\, .
$$
As long as the rarefaction and the shock don't interact, the solution is
therefore
$$
u(x,t) =
\left\lbrace
\begin{aligned}
& 0 &&\text{if }\; x\leq 0 \, , \\
& x/t &&\text{if }\; 0\leq x\leq t \, , \\
& 1 &&\text{if }\; t \leq x < 1+ t/2 \, ,\\
& 0 &&\text{if }\; 1+t/2 < x \, ,
\end{aligned}
\right.
$$
valid for times $t<t^*$ such that $t^* = 1 + t^*/2 = 2$. At the time $t^*$, both waves interact. The new shock speed is determined from the Rankine-Hugoniot condition
$$
x'(t) = (x(t)/t+0)/2 \, ,
$$
with initial shock speed $x'(t^*) = s$.
Hence, the solution for $t\geq t^*$ is
$$
u(x,t) =
\left\lbrace
\begin{aligned}
& 0 &&\text{if }\; x\leq 0 \, , \\
& x/t &&\text{if }\; 0\leq x< \sqrt{2t} \, , \\
& 0 &&\text{if }\; \sqrt{2t} < x \, .
\end{aligned}\right.
$$

A: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dt}{ds}=1$ , letting $t(0)=0$ , we have $t=s$
$\dfrac{du}{ds}=0$ , letting $u(0)=u_0$ , we have $u=u_0$
$\dfrac{dx}{ds}=u=u_0$ , letting $x(0)=f(u_0)$ , we have $x=u_0s+f(u_0)=ut+f(u)$ , i.e. $u=F(x-ut)$
$u(x,0)=\begin{cases}0&\text{if}~x<0\\1&\text{if}~0\le x\le1\\0&\text{if}~x>1\end{cases}$ :
$\therefore u=\begin{cases}0&\text{if}~x-ut<0\\1&\text{if}~0\le x-ut\le1\\0&\text{if}~x-ut>1\end{cases}=\begin{cases}0&\text{if}~x<0\\1&\text{if}~0\le x-t\le1\\0&\text{if}~x>1\end{cases}$
Hence $u(x,t)=\begin{cases}0&\text{if}~x<0\\1&\text{if}~0\le x-t\le1\\0&\text{if}~x>1\\c&\text{otherwise}\end{cases}$


text:
Q: Bootstrapping to Overcome Power Concern with ANOVA? all,
I just conducted the power analysis for a lab study I am hoping to run soon. The main idea is comparing the difference in means across three conditions with a balanced one-way ANOVA (see image below).
Basically, I am amazed at how underpowered I am with moderate effect sizes. Unless I set large effect sizes (f=0.4), I am severely underpowered.
To help overcome these power issues, I'm wondering if bootstrapping may be an appropriate method of resampling? While I recognize the lab study participants are not nationally representative of the broader public, I'm more interested in the psychological phenomenon that occurs.
What do you all think--would bootstrapping be one method of
overcoming this potential issue with power? Open to any and all suggestions!
**


text:
Q: Changing the contents of a file with sed in Solaris 10 I have a bash script that I want to change all occurrences of  jdk1.5.0_14 with jdk1.6.0_20 in a file
I have the following piece of code :
#!/bin/bash
myvar="jdk1.6.0_20"
sed "s/jdk1.*/$myvar/g" answer_file.1 > answer_file.2

However I have the following information in answer_file.1 (pasting the relevant part):
JDKSelection.directory.JDK_LIST=/usr/jdk/jdk1.5.0_14 (v. 1.5.0_14 by Sun Microsystems Inc.)
JDKSelection.directory.HIDDEN_JDK=/usr/jdk/jdk1.5.0_14

The code above changes the occurence of jdk1.5.0_14 to jdk1.6.0_20 but also removes the information contained in paranthesis in the first line.
So after the change, I need the answer_file.2 file look like this:
 JDKSelection.directory.JDK_LIST=/usr/jdk/jdk1.6.0_20 (v. 1.6.0_20 by Sun Microsystems Inc.)
 JDKSelection.directory.HIDDEN_JDK=/usr/jdk/jdk1.6.0_20

How can I achieve this?
Thanks for your answers....

A: If it is just the matter of changing of JDK version, you can try the following commands
#!/bin/bash
myvar="1.6.0_20"
sed "s/1\.5\.0_14/$myvar/g" answer_file.1 > answer_file.2

A: Your pattern searches for "jdk1.*" and thus replaces jdk1 and all that follows up to the end of the line.
You might want to match on version numbers only, like 1\.5\.0_[0-9][0-9], and replace only the numbers.
Make sure to quote the pattern accordingly, so that the backslashes do not get lost.

A: May be this will help in handling the version as well
myvar="1.6.0_20"

sed "s/\(\(jdk\)\{0,1\}\)[1-9]\.[0-9]\.0_[0-9][0-9]/\1$myvar/g" answer_file.1 > answer_file.2

EDITED: Added myvar def

A: You can anchor the version number using the trailing space:
sed "s/jdk1[^ ]* /$myvar /g" answer_file.1 > answer_file.2


text:
Q: Performance hit when editing a quesiton We have a question on Code Review, that when editing causes the browser to become unresponsive. And for me, it causes Firefox to say the script is unresponsive and asks if I wish to kill it:

Warning: Unresponsive script
A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.
Script: https://cdn.sstatic.net/Js/wmd.en.js?v=00b75d767930:1

The source of the problem, diagnosed by another user, is due to using regex:

Steps to reproduce:

*

*Go this question.

*Click edit.

A: Sorry about that.
I had about 30k chars on one line and probably caused catastrophic backtracking as seen in this answer. The accepted answer explains the cause of the intense crashing:

That (the long string) led to the parsing of the code block taking unusually long.

To prevent anymore crashing, I replaced most of the values with one ... so the string is extremely short and non-crashable. Do not worry, I will put this experience in mind when dealing with super long strings. Now the Python list looks like this:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, ... 9669, 9670, 9671, 9672, 9673, 9674, 9675, 9676, 9677, 9678, 9679, 9680]


text:
Q: I was just attacked by an onslaught of downvotes! What do I do? Checking my recent activity, I noticed that [nearly] all of my posts were downvoted within a short span of a few minutes. It seems as though I've been the victim of a systematic downvoting spree.
What can I do if I suspect that someone has downvoted all my posts in retaliation or revenge? Is there something in place that will stop this kind of voting abuse? Do I have any possible avenues of recourse?

A:

A: It just looks like you have gotten on the wrong side of somebody, and they have went on a downvoting rage against you.
SO runs scripts and checks for this kind of behaviour every 24 hours, so it should be fixed up soon.

A: Looks like you made enemies with some other user who is now downvoting your stuff. Contact the team (Contact us link at the bottom) so that they can reverse it any educate that user about the penalty-box.
Edit: Or not, wasn't aware of the automated checks. Leaving this here just as a sign of what not to do.

A: As already stated, there are automated processes to watch for this. Checking in a few places (your "recent" tab on SO, Jon's SO tracker, etc), it looks like this may have already been undone by the system.
If you think there is still a problem, flag for a ♦ moderator (or add a comment here), or e-mail the team (page footer). BTW; it makes it easier to investigate if you associate your SO/MSO accounts, plus you get free rep ;-p

A: Serial-downvoting is a consequence of any anonymous community -- and there are systems in place to combat it. It is frowned upon, and I'm sure that if the user did it repeatedly they'd be asked (politely) to stop.
If you feel you've been the target of serial downvoting, flag one of your posts for moderator attention, and ask for a rep-recalc.
Also, there's an automated system that performs a vote 'undo' when a certain pattern of downvoting is seen, this could also be triggered.

A: Just suffered a similar "storm of downvotes" myself, in the space of one-two minutes about an hour ago -- "just" nine of them, in my case, not twenty like Philippe had, but similarly "random fury" (the downvoter hit several of my questions and a random-ish sample of my answers).  I will patiently wait for the cleansing script to run, and hope the script in question doesn't have a threshold of ten to identify "sabotage downvotes"!-).

A: Happening to me (second time) now... this time it seams like a reply to a comment I did (just pointed a little error in the answer code). First time was because of a downvote I did (60% - 80% fixed).
But who cares, I lost 10+ received 100... and someone else got his revenge for my - just wanted to help - comment.
EDIT 2010-01-01:
seams like someone really got hurt :-(
5 additional down-votes this night/yesterday...
kind of childish.


text:
Q: Showing an error This MinMaxScaler instance is not fitted yet. Call 'fit' with appropriate arguments before using this method I am trying to get back the original values after predicting Cost.
I used MinMax feature scaling to scale the target feature. I got a scaled output. I am trying to convert them into original values but it shows me an error.
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
food[["COST"]] = scaler.fit_transform(food[["COST"]])

scaler.inverse_transform(y)
pd.DataFrame(y,columns=["COST"])
y.to_excel("yg.xlsx",index=False)

I am trying to convert the predicted cost value to the original values and save a excel sheet with the original cost values. Please help!

A: Here is what you should do:
Assume X is your original data, X_scaled is your scaled data, and you would like to get X_hat, which should be identical to X.
In other words:
X_scaled = scaler.fit_transform(X)

To get X_hat, first you have to create an external MinMaxScaler object:
obj = scaler.fit(X)

Then you use:
X_hat = obj.inverse_transform(X_scaled)


text:
Q: Pymunk: prevent dynamic objects to move into static objects I have a dynamic object to which I set different velocity values. However when this dynamic body hits a static body, it overlaps partly with the static shape until this collision is resolved and it moves back.
Is there a way in pymunk to make the dynamic body stop exactly at the borders of the static body, even when velocity is applied in this direction? If there are collision conflicts I would rather have them solved in another way than to make the two shapes overlap.
Applying forces and impulses are not really an option since I want to have a constant velocity.
(The below code needs to be executed twice to work.)
import pymunk
import pyglet
from PIL import Image
from PIL import ImageDraw

# setup of pyglet

window = pyglet.window.Window()
main_batch = pyglet.graphics.Batch()
keys = pyglet.window.key.KeyStateHandler()
window.push_handlers(keys)

# setup of pymunk

space = pymunk.Space()

"""MOVABLE CIRCLE"""

# creating pyglet sprite

circle_img = Image.new('RGBA', (50,50))
draw = ImageDraw.Draw(circle_img)
draw.ellipse((1, 1, 50-1, 50-1), fill=(255,0,0))
circle_img.save('circle.png')
pyglet_circle_img = pyglet.resource.image('circle.png')
pyglet_circle_img.anchor_x = pyglet_circle_img.width/2
pyglet_circle_img.anchor_y = pyglet_circle_img.height/2
circle_sprite = pyglet.sprite.Sprite(pyglet_circle_img, window.width/2, window.height/2, batch=main_batch)

# creating pymunk body and shape

mass = 2
radius = 25
moment = pymunk.moment_for_circle(mass, 0, radius)
circle_body = pymunk.Body(mass, moment)
circle_body.position = circle_sprite.position
circle_shape = pymunk.Circle(circle_body, 25)
circle_shape.elasticity = 0.0
space.add(circle_body, circle_shape)

"""STATIC SQUARE"""

# creating pyglet sprite

square_img = Image.new('RGBA', (70,70))
draw = ImageDraw.Draw(square_img)
draw.rectangle([(0, 0), (70-1, 70-1)], fill=(0,255,0))
square_img.save('square.png')
pyglet_square_img = pyglet.resource.image('square.png')
pyglet_square_img.anchor_x = pyglet_square_img.width/2
pyglet_square_img.anchor_y = pyglet_square_img.height/2
square_sprite = pyglet.sprite.Sprite(pyglet_square_img, 3*window.width/4, window.height/2, batch=main_batch)

# creating pymunk body and shape

square_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
square_body.position = square_sprite.position
square_shape = pymunk.Poly(square_body, [(-35,-35),(-35,35),(35,35),(35,-35)])
square_shape.elasticity = 0.0
space.add(square_body, square_shape)

def update(dt):
    space.step(dt)
    circle_sprite.position = circle_body.position
    print(circle_body.position)
    key_pressed = False
    if keys[pyglet.window.key.LEFT]:
        circle_body.velocity = (-100,0)
        key_pressed = True
    elif keys[pyglet.window.key.RIGHT]:
        circle_body.velocity = (100, 0)
        key_pressed = True
    if keys[pyglet.window.key.UP]:
        circle_body.velocity = (0, 100)
        key_pressed = True
    elif keys[pyglet.window.key.DOWN]:
        circle_body.velocity = (0, -100)
        key_pressed = True
    if not key_pressed:
        circle_body.velocity = (0,0)

@window.event
def on_draw():
    window.clear()
    main_batch.draw()

pyglet.clock.schedule_interval(update, 1/60.)

pyglet.app.run()

A: In general the answer it that you should expect strange effects when you set the position or velocity manually of a body, since that it tricking the physics engine (just like you would get strange effects in real life if
something teleported around)
Its also the case that a small overlap is to be expected when objects collide, that is how the collision is solved. There are two properties on the space that you can use to control this a bit, collision_slop and collision_bias.
However, you can experiment with some manual fixes which might help. One way would be to move the objects away once a collision happen. You can do this with a collision callback.
Here is a quick example you can put just before the update function in your example to prevent the overlap:
circle_shape.collision_type = 1
h = space.add_wildcard_collision_handler(circle_shape.collision_type)
def f(arbiter, space, data):
    ps = arbiter.contact_point_set
    arbiter.shapes[0].body.position += ps.normal * ps.points[0].distance
h.post_solve = f

(in your real code you need to add some fail safes and also account for more than one point in case you have more complex shapes)


text:
Q: Getting horizontal scroll in mobile when close the menu I am using anime.js and displaying the menu on mobile. I am getting a horizontal scroll on mobile.
I added display:none so that my menu will hide and when user click on the menu then I am adding the display block using the script but the issue is, after closing the menu I am still getting the scroll
Script adding the class
 $('html').addClass('noscroll');

and added below css
 html.noscroll {
    overflow: hidden;
}

So that scroll will hide. Then also I am getting an issue if I close the menu.
Would you help me out with this issue?
I am using the below code.

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});
.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}

Open

close

Home

About

contact

A: You're thinking right direction - overflow would solve the problem. But in your code, I can't see where you're adding overflow.
One of the solutions would be to add a static overflow for X-axis to whole body:
body {
    overflow-x: hidden;
}

Another solution, as you said, add it when necessary using JS.
function menuClose() {
  $('.menu-background').hide(300);
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}

A: You can set display none on function menuClose using delay 1300 and queue.
$('.menu-background').delay(1300).queue(function(next) {
      $(this).css('display', 'none');
      next();
  });

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
  $('.menu-background').delay(1300).queue(function(next) {
      $(this).css('display', 'none');
      next();
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});
.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}

Open

close

Home

About

contact


text:
Q: How to call a field method using reflection I have a lot of struct like this, with diff fields but have common field: fn func()
type a struct{
    // ....
    fn func()
}

what I want is call diff structs' instance's fn function, how to implement it;no use receiver func to implement, and the fn not exported
func call(i interface{}){
    // TODO
    // how to use reflect to call fn func
}

A: If you are not using a dynamic assignment to function then you can go about using interfaces; you can also create logic that interface method calls the struct field method; I would recommend using methods and interfaces
package main

import (
    "fmt"
)

type A struct {
}

type myInterface interface {
    fn()
}

func (a *A) fn(){
    fmt.Println("Hello, playground")
}

func main() {
    var i myInterface
    i = &A{}
    call(i)
}

func call(input myInterface) {
    input.fn()
}

But If you want to call field method using reflection you can go doing something like this; But the field Fn needs to be exported
package main

import (
    "fmt"
    "reflect"
)

type A struct {
    Fn func()
}

func main() {
    a := A{func() { fmt.Println("Hello!!!") }}
    call(a)
}

func call(i interface{}) {
    valOf := reflect.ValueOf(i)
    valOf.FieldByName("Fn").Call([]reflect.Value{})
}


text:
Q: BIG QUERY: SELECT list expression references examiner.first_name which is neither grouped nor aggregated at [2:8] Can anyone provide advice on below:
select
concat(examiner.first_name," ", examiner.last_name) as full_name,
count(*) AS Rebuttals_Concluded,
coalesce(r.FNL_APRVD_DT, r.FNL_DECLND_DT) AS fnl_rebuttal_date

from `ltl-prd-datahub.DATAHUB_ALL_VIEWS.CLM_REBUTTAL_RDS_VW`r

join `ltl-prd-datahub.DATAHUB_ALL_VIEWS.CLM_CLAIM_RDS_VW`c
  on c.clm_id = r.clm_id

join `ltl-prd-datahub.DATAHUB_ALL_VIEWS.EMPLOYEE_CURRENT_VW` examiner
  on c.EXAMINED_BY_EMPL_ID = examiner.EMPLOYEE_NUMBER

where r.intrnl_stat_cd IN ('APPROVED','DECLINED')

A: The error message is clear enough. Just add the relevant columns to the group by clause:
select
    concat(examiner.first_name," ", examiner.last_name) as full_name,
    count(*) AS Rebuttals_Concluded,
    coalesce(r.FNL_APRVD_DT, r.FNL_DECLND_DT) AS fnl_rebuttal_date
from `ltl-prd-datahub.DATAHUB_ALL_VIEWS.CLM_REBUTTAL_RDS_VW`r
join `ltl-prd-datahub.DATAHUB_ALL_VIEWS.CLM_CLAIM_RDS_VW`c
    on c.clm_id = r.clm_id
join `ltl-prd-datahub.DATAHUB_ALL_VIEWS.EMPLOYEE_CURRENT_VW` examiner
    on c.EXAMINED_BY_EMPL_ID = examiner.EMPLOYEE_NUMBER
where r.intrnl_stat_cd IN ('APPROVED','DECLINED')
group by examiner.first_name, examiner.last_name, coalesce(r.FNL_APRVD_DT, r.FNL_DECLND_DT)

A: You can use column aliases in BigQuery, so I would recommend:
select concat(examiner.first_name, ' ', examiner.last_name) as full_name,
       count(*) AS Rebuttals_Concluded,
       coalesce(r.FNL_APRVD_DT, r.FNL_DECLND_DT) AS fnl_rebuttal_date
from `ltl-prd-datahub.DATAHUB_ALL_VIEWS.CLM_REBUTTAL_RDS_VW`r
join
     `ltl-prd-datahub.DATAHUB_ALL_VIEWS.CLM_CLAIM_RDS_VW`c
      on c.clm_id = r.clm_id join
      `ltl-prd-datahub.DATAHUB_ALL_VIEWS.EMPLOYEE_CURRENT_VW` examiner
      on c.EXAMINED_BY_EMPL_ID = examiner.EMPLOYEE_NUMBER
where r.intrnl_stat_cd IN ('APPROVED', 'DECLINED')
group by full_name, fnl_rebuttal_date;


text:
Q: Trying to use attr_accessor value in model in Rails 5 I have a model where I create an attr_accessor:
attr_accessor :schedule_date

In my form I have a field:
<%= f.text_field :schedule_date, label: 'Date', required: true %>

And now after submitting the form I want to use this field in my model to make some calculation.
The problem is that schedule_date is undefined in my model. Just to test it I am trying to raise an error with the value of the field:
My model looks like this:
class Ride < ApplicationRecord
  attr_accessor :schedule_date, :schedule_time
  raise schedule_date
end

But when submitting the form I get:

NoMethodError (undefined method `schedule_date'

Why can't I use my attr_accessor value inside my model?

A: You can only call it via the object itself or @schedule_date
obj.schedule_date

because
attr_accessor :schedule_date is simply a shortcut for the following:
def schedule_date=(var)
  @schedule_date = var
end

def schedule_date
  @schedule_date
end

Update
 ride = Ride.new()
 ride.schedule_date


text:
Q: Convergence of the characteristic function Check that $$A_n \rightarrow A \iff 1_{A_n} \rightarrow 1_A$$ pointwise.
Is my proof correct?

Proof so far:
$A_n \rightarrow A \iff \limsup_{n \rightarrow \infty} A_n=\liminf_{n \rightarrow \infty}A_n=A$.
$\iff \limsup_{n \rightarrow \infty} 1_{A_n}=1_{\limsup_{n \rightarrow \infty} A_n}=1_A= 1_{\liminf_{n \rightarrow \infty} A_n}=\liminf
_{n \rightarrow \infty} 1_{A_n} \iff \lim_{n \rightarrow \infty}1_{A_n}=1_A \iff 1_{A_n} \rightarrow 1_A$ .

A: I'm not sure the problem makes sensea. It seems like you are asked to prove:

Given a probability space $(\Omega, \mathscr F, \mathbb P)$, let $A_1, A_2, ...$ be events.

*

*If $\limsup A_n = \liminf A_n := A$ and $\limsup 1_{A_n} = \liminf 1_{A_n}$, then $\lim 1_{A_n} = 1_A$

*If $\lim 1_{A_n} = 1_A$, then $\limsup A_n = \liminf A_n := A$

If we change all your $\iff$ to $\rightarrow$, you've proven #1, but...
What does #2 even mean? By definition $\limsup A_n = \liminf A_n := A$.
I think #2 should be restated:

If $1_{A_n} \to 1_{\limsup A_n}$ and $1_{A_n} \to 1_{\liminf A_n}$,
  then $\limsup A_n = \liminf A_n$

which I'm not even sure is true:
We have $\lim 1_{A_n} = 1_{\limsup A_n} = 1_{\liminf A_n}$
$\to 1_{\limsup A_n} = 1_{\liminf A_n}$
$\to \limsup A_n = \liminf A_n?$
I think we merely have $\limsup A_n = \liminf A_n$ a.s.


text:
Q: WSO2 installing developer studio problems in helios I'm trying to install WSO2 developer studios and carbon in my eclipse Helios for developing API2 software, the first issue is the page of wso2 site for download Eclipse Helios with Carbon studio is down, the download links doesn't work. So I have to manually install carbon studio.
I manage to do it so, now I'm having problems trying to install the developer studio, this is the error stack.
Your original request has been modified.
  "Smooks Tools" will be ignored because it is already installed.
Cannot complete the install because of a conflicting dependency.
  Software being installed: Application Factory Tools 2.1.0 (org.wso2.developerstudio.eclipse.appfactory.feature.feature.group 2.1.0)
  Software currently installed: Eclipse IDE for Java EE Developers 1.3.2.20110218-0812 (epp.package.jee 1.3.2.20110218-0812)
  Only one of the following can be installed at once:
    Core Runtime 3.6.0.v20100505 (org.eclipse.core.runtime 3.6.0.v20100505)
    Core Runtime 3.11.1.v20150903-1804 (org.eclipse.core.runtime 3.11.1.v20150903-1804)
  Cannot satisfy dependency:
    From: Eclipse IDE for Java EE Developers 1.3.2.20110218-0812 (epp.package.jee 1.3.2.20110218-0812)
    To: org.eclipse.epp.package.jee.feature.feature.group [1.3.2.20110218-0812]
  Cannot satisfy dependency:
    From: Java EE IDE Feature 1.3.2.20110218-0812 (org.eclipse.epp.package.jee.feature.feature.group 1.3.2.20110218-0812)
    To: org.eclipse.platform.feature.group [3.6.2.r362_v20110210-9gF78Gs1FrIGnHDHWkEcopoN8AmxeZflGDGKQi]
  Cannot satisfy dependency:
    From: Maven Integration for Eclipse 1.6.2.20150902-0002 (org.eclipse.m2e.core 1.6.2.20150902-0002)
    To: bundle org.eclipse.core.runtime 3.7.0
  Cannot satisfy dependency:
    From: Eclipse Platform 3.6.2.r362_v20110210-9gF78Gs1FrIGnHDHWkEcopoN8AmxeZflGDGKQi (org.eclipse.platform.feature.group 3.6.2.r362_v20110210-9gF78Gs1FrIGnHDHWkEcopoN8AmxeZflGDGKQi)
    To: org.eclipse.rcp.feature.group [3.6.2.r362_v20101104-9SAxFMKFkSAqi8axkv1ZjegmiBLY]
  Cannot satisfy dependency:
    From: Eclipse RCP 3.6.2.r362_v20101104-9SAxFMKFkSAqi8axkv1ZjegmiBLY (org.eclipse.rcp.feature.group 3.6.2.r362_v20101104-9SAxFMKFkSAqi8axkv1ZjegmiBLY)
    To: org.eclipse.core.runtime [3.6.0.v20100505]
  Cannot satisfy dependency:
    From: AppFactory Tools UI 2.1.0 (org.wso2.developerstudio.appfactory.ui 2.1.0)
    To: bundle org.eclipse.m2e.core 0.0.0
  Cannot satisfy dependency:
    From: Application Factory Tools 2.1.0 (org.wso2.developerstudio.eclipse.appfactory.feature.feature.group 2.1.0)
    To: org.wso2.developerstudio.appfactory.ui [2.1.0]

A: From Dev Studio download page you can download latest Eclipse JavaEE luna + Developer Studio v 3.8.0 zip.
Furthermore, for certain WSO2 products (eg. ESB, APIM), there is a separate tooling distribution which is customized dev studio. You can download them from tooling link in each product download page.


text:
Q: Question about the Intel's IA-32 software developer manual I'm studying the Intel's IA-32 software developer manual. In particular, I'm reading the following manual: http://www.intel.com/Assets/PDF/manual/253666.pdf. Let's take for example the ADD instruction. On page 79 it is written that you can add an r8 (8-bit register) to an r/m8 (8-bit register or memory location). A few rows below, it is also written that you can add an r/m8 to an r8. The question is: if I add two 8-bit registers, which instruction I am using? Thanks.

A: The add instruction has multiple versions... same mnemonic can be encoded to different opcodes, depending on what operands you use.
(and to answer your specific question: the "add r8,r8" instruction probably has 2 different possible encodings, that do the same thing)

A: The ADD instruction has 9 different encoding types and two opcodes are reserved for:
Opcode: 00/r = ADD r/m8, r8
Opcode: 02/r = ADD r8, r/m8

In case "ADD r8, r8" both have some effect.


text:
Q: Stack overflow when opening forms I am very new to C# so I am sorry if I use wrong terms. Here is my problem. I have 2 forms. and I want If I click the button in Form1, it shows up the Form2 by overlapping the Form1. And now, if I click the button in form2, I want the form1  overlap the form2. But I always get error "stackOverFlowException". Why did i get the error? How to resolve it? I am sorry if my question is not clear. I hope these picture can explain better about my question.
Here is the code  for form1.
 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Form2 frm2 = new Form2();
    private void Form1_Load(object sender, EventArgs e)
    {
        frm2.Show();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
       frm2.Left += 10;
        if (frm2.Left >= 750)
        {
            timer1.Stop();
            this.TopMost = false;
            frm2.TopMost = true;
            timer2.Start();
        }
    }
    private void timer2_Tick(object sender, EventArgs e)
    {

        frm2.Left -= 10;
        if (frm2.Left <= 535)
        {
            timer2.Stop();
        }
    }
}

}
and here is the code for form2
 public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    Form1 frm1 = new Form1();
    private void Form2_Load(object sender, EventArgs e)
    {
        frm1.Show();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        frm1.Left += 10;
        if (frm1.Left >= 750)
        {
            timer1.Stop();
            this.TopMost = false;
            frm1.TopMost = true;
            timer2.Start();
        }
    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        frm1.Left -= 10;
        if (frm1.Left <= 535)
        {
            timer2.Stop();
        }

A: You are creating and endless chain of opened forms.
When you first create a Form1 object with new Form1(), the initialization code inside this form
Form2 frm2 = new Form2();

... is called. This in turn triggers the initialization code of Form2, which is
Form1 frm1 = new Form1();

This creates a new instance of this form (now you have two Form1 instances) and calls Form2 frm2 = new Form2(); again in this new instance (now you have two Form2 instances). This goes on until thousands of form objects have been created and the stack overflows.

What can you do about it?
In Form2 add a parameter to the constructor that allows you to pass a reference to the first form
private readonly Form1 _frm1;

public Form2 (Form1 frm1)
{
    InitializeComponent();
    _frm1 = frm1;
}

In Form1 do this
private Form2 _frm2;

private void Form1_Load(object sender, EventArgs e)
(
    _frm2 = new Form2(this);
)

I.e. Form2 never creates a Form1. Instead, it gets a reference to the already opened form.

How do you bring a form to front?
The TopMost property controls the behavior of a form when it is opened. Instead, use
_frm1.BringToFront();

to change the z-order afterwards.


text:
Q: How i can make My Server BASEURL dynamic as a frontend developer? As a Front-end developer Does making my server URL dynamics before the route name is good?
like https://example.com/api/routeame if I make the "https://example.com/api/ "as a dynamic to come from outside is that good ?!
if it's good how I will implement this faraway firebase dynamic link cause it's made for not that purpose

A: I will come to the answer, but before that, one a quick look at the URL, it seems like you are planning to use /api/routename as a view URL.
This convention is not good. I would rather do the below-
My Routes will be a URL without /api and the API's this Route component will call will have the /api attached to it.
Route Name -> https://example.com/routename (without the /api. This is what the browser address bar will show)
API calls -> https://example.com/api/endpoint (internal API call from the routename component. This is what you will see in the network tab when this component makes the call to the backend API).
And finally, to answer your question, you should only make the host dynamic when you develop the web application.
Because, any other changes needed in the URL (be it changing /api to /xyz in the calls, removing /api from the URL in the network calls, etc) you can always do it from your network layer by adding a reverse proxy or with some redirect configurations using nginx or something similar.
So, make only the domain dynamic. For the rest, we should use the network layer tools which is recommended solution.


text:
Q: App crashes if string value contains character '&' I am working with JSON array received from a PHP file on a web server.
This is the code I am using for this:
NSMutableString *ms = [[NSMutableString alloc] initWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/comprobartipo.php?id="];
    NSString *tipo=[[view annotation] title];
     NSString* urlTextEscaped = [tipo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ms appendString:urlTextEscaped];
    NSLog(@"TIPO ES AQUI %@", urlTextEscaped);

    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];

    [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data1, NSError *connectionError) {
        if (data1) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];
            NSLog(@"PROCEDENCIA DESDE INTERNET %@", [array objectAtIndex:0]);
            NSLog(@"ESTO ES DATA en If %@",data1);
        }else{
            NSLog(@"ESTO ES DATA en ELSE %@",data1);
            // Tell user there's no internet or data failedN
            NSLog(@"NO HAY CONEXION");
        }
    }];

The code is working fine, but the app crashes if the string value for NSString *tipo contains a character like &.
Error:

'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 0
  beyond bounds for empty array'

Any help to avoid this issue is welcome.

A: Your crash will be here,
NSArray *array = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];

NSLog(@"PROCEDENCIA DESDE INTERNET %@", [array objectAtIndex:0]); // Crash will be here

You should check your array whether it has objects or not.
Let's try as below
if (array.count)
    NSLog(@"PROCEDENCIA DESDE INTERNET %@", [array objectAtIndex:0]);

Thanks!


text:
Q: How to compress the following in scala? my code :
val result= rdd.filter(x=> x.get[DateTime]("mytime") > offsetvalue._1 &&
             row.get[DateTime]("mytime") <= offsetvalue._2)

I would like to compress the code like:
val result = rdd.filter(x => myFunction())
where myFunction() {x=> x.get[DateTime]("mytime") > offsetvalue._1 &&
             row.get[DateTime]("mytime") <= offsetvalue._2 }

when  myFunction is call it is showing exeception:
org.apache.spark.SparkException: Task not serializable
at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:166) ~[spark-core_2.10-1.2.2.2.jar:1.2.2.2]
at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:158) ~[spark-core_2.10-1.2.2.2.jar:1.2.2.2]
at org.apache.spark.SparkContext.clean(SparkContext.scala:1476) ~[spark-core_2.10-1.2.2.2.jar:1.2.2.2]
at org.apache.spark.rdd.RDD.filter(RDD.scala:300) ~[spark-core_2.10-1.2.2.2.jar:1.2.2.2]
at com.aruba.sparkjobs.apprf.LeaderBoardJob.runJob(LeaderBoardJob.scala:203) ~[ee507b50-011f-42de-8bd5-536ca113d640-2015-09-25T11:11:23.637+05:30.jar:1.0.0-b.3]

How to serialize the above function

A: Something like
def resultFilter(offsetValue: (A, A)) = (x: B) => {
  val date = x.get[DateTime]("mytime")
  date > offsetValue._1 && date <= offsetValue._2
}

rdd.filter(resultFilter(offsetValue))

where you have to fill in A and B because there's not enough information in your question to infer them.

A: It's not a direct answer to your question, but you could make your expression more readable this way:
val (min, max) = offsetValue
val result = rdd.map(_.get[DateTime]("mytime"))
  .filter(t => t > min && t <= max)

and here's a direct answer to your question:
def myFun(x: YourType): Boolean = {
  val (min, max) = (dateTime1, dateTime2) // the values from offsetValue, assuming they are constant
  val t = x.get[DateTime]("mytime")
  t > min && t <= max
}

and then you call it as
val res = rdd.filter(myFun)


text:
Q: Match (lookup) under Matrix in R I have a matrix,
set.seed(100)
x <- matrix(sample(11, 110, replace = T), nrow = 11)

and another matrix,
y <- cbind(1:11, sample(110, 11))

I want to match each element of x with the first column of y. If matches should return the second column of y else 0. The final out put should have same dimension as x.
I tried to do this with for-loop with 3 nested loops, but is there any efficient way for this?
The Expected output is
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   26   85    4   40   96    9    4   21   26    21
 [2,]    9   26   21   75    4   88  103   85   21    26
 [3,]   96  103  103   85   21    9    9   88   85   103
 [4,]   93   21   88   88   85   96   75    4    9    93
 [5,]    4   75   21   96    9    9  103   96   26    26
 [6,]    4    9   85   40   26    4   26   40  103    96
 [7,]   21   26   96   88   26   75   96   40   85    75
 [8,]  103   26   26   26    9   40   40   93  103    40
 [9,]   96   75    4   85    9   75   75   96    4    75
[10,]   88    4   40   21   26  103   96   21   88    93
[11,]   96   75   26   85   96   26   85    9   93     4

A: Here's one possibility:
x[!x%in%y[,1]] <- 0 # set all elements to zero which are not in first column of y
sapply(1:nrow(y),function(i) x[x==y[i,1]] <<- y[i,2]) #replace all matches with second column of y
#> x
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]   26   85    4   40   96   21    4   21   26    21
# [2,]   21   26   21   75    4   88  103   85   21    26
# [3,]   96  103  103   85   21   21   21   88   85   103
# [4,]   93   21   88   88   85   96   75    4   21    93
# [5,]    4   75   21   96   21   21  103   96   26    26
# [6,]    4   21   85   40   26    4   26   40  103    96
# [7,]   21   26   96   88   26   75   96   40   85    75
# [8,]  103   26   26   26   21   40   40   93  103    40
# [9,]   96   75    4   85   21   75   75   96    4    75
#[10,]   88    4   40   21   26  103   96   21   88    93
#[11,]   96   75   26   85   96   26   85   21   93     4

A: A proposition using replace:
x2 <- matrix(0, nrow(x), ncol(x))
ind <- unlist(sapply(1:11, function(el) which(x == el) ))
val <- unlist(sapply(1:11, function(el) rep(y[el,2], sum(x == el)) ))
replace(x2, ind, val)


text:
Q: How would I implement a particle filter for vision tracking? So I just did sebsastian thrun's course on AI. In there, he mentions how to build a particle filter for tracking a moving xy robot based on heading theta and forward movement.
The code is here:
https://gist.github.com/soulslicer/b4765ee8e01958374d3b
In his implementation, he does the following:
1. Get Range from Sensor of all bearings after moving R=1, Theta=0.5
2. Move all the particles by R=1, Theta=0.5
3. Compute the weights of all particles ranges against the measured range from sensor
4. Resample and draw new particles

This works for a motion model great. How on earth would this work for computer vision tracking? For example, I want to track a yellow circular blob.
How would I "move" the particles? What might my cost functions be? Especially the moving part, I'm not sure how I'd do that step for computer vision tracking

Here is how I think it might work, but I'm probably wrong:
1. Get features from image, and compute the optical flow velocities of each feature
2. Place alot of particles in the scene with varying x,y,xvel,yvel
3. For the computation of weights, we can compare the each particle's velocity and position against all features
    If we can threshold out the object based on color/shape, can match image features to shapes and put that in the cost function
4. Resample and draw new particles

A: To use particle filtering, you need:

*

*a transition model (e.g., a motion model used for moving the robot) and

*an observation model (i.e., a model used to compute weights given sensor readings).

it is also helpful to clearly define spaces for

*

*observations (e.g., a range for sensor readings)

*tracking states (e.g., a range for robot positions)

Now, based on the description in your question, I'm assuming the goal is tracking positions of the yellow blob based on computed optimal flow features. Then I would model

*

*transition as a function that samples a new position given previous position by sampling noise only, e.g., imagine using only + random.gauss(0.0, self.turn_noise) or + random.gauss(0.0, self.forward_noise) part in def move(self, turn, forward):

*observation as a function that returns high-scores for likely observation and state input pairs

The problem I see is defining the observation model, a likelihood function between blob positions and optimal flow outputs, is not trivial/intuitive, e.g., is the yellow blob likely be in the center of high optical flow outputs area? if so how can I express such relationship as a likelihood function? For this reason, I would look into using different observations, e.g., using outputs from noisy yellow blob detector.
My answer is based on pg 16. of the particle-filters.ppt file available at http://www.probabilistic-robotics.org/


text:
Q: Grab image from screen to numpy array and display it as black and white image I am trying to read image data from a certain part of the screen, so I can post-process it in a form of a numpy array.  This is what I tried so far:
import numpy as np
from PIL import ImageGrab, Image

img = ImageGrab.grab(bbox=(798, 166, 300, 400))  # (bbox=x,y,width,height)
img_np = np.array(img)

But when I try to print img_np, it returns:
<PIL.Image.Image image mode=RGB size=0x234 at 0x109F8F0>

It doesn't seem like it's an numpy array.  I also want to display the black and white image from the numpy array to verify what I am doing is right (and also display processed numpy arrays in the future).  Is there anything I am doing wrong?

A: I think that your
(bbox=798, 166, 300, 400))

the x=798 is over your screen
so you must make your (x,y) in your screen.
look this picture:
enter image description here
the result is None ,because it cant capture your screen
and when I modify the x=100,it works
enter image description here
the code:
import numpy as np
from PIL import ImageGrab,Image
img=ImageGrab.grab(bbox=(798,166,300,400))  #798
# img=Image.open("Modric.jpg")
print(type(img))
img_np=np.array(img)
print(type(img_np))
print(img_np.shape)

result:
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
()      *******None

after x=100:
import numpy as np
from PIL import ImageGrab,Image
img=ImageGrab.grab(bbox=(100,166,300,400))  #798
# img=Image.open("Modric.jpg")
print(type(img))
img_np=np.array(img)
print(type(img_np))
print(img_np.shape) code here

result:
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
(234, 200, 3)

the right x coord and in screen, it can works

I am sorry for the first question,the right is here
import tkinter
win=tkinter.Tk()
width=win.winfo_screenwidth()   #get your screen's width
height=win.winfo_screenheight() #get your screen's height
print(width,height)
img=ImageGrab.grab(bbox=(300,400,width,height)).convert("L")  #798
img_np=np.array(img)
print(img_np.shape)

result:
1536 864
(464, 1236)

when you use the bbox=(x,y,width,height)   ,the pixel counting method is width-x and height-y . so you must make your width>x and height>y and it works

as for convert to gray image,you can use opencv
import cv2
gray=cv2.cvtColor(img_np,cv2.COLOR_RGB2GRAY)[enter link description here][3]

link
    or
the PIL convert("L")  function
img=ImageGrab.grab(bbox=(300,400,width,height)).convert("L")  #798

 or

the formula:
def rgb2gray(rgb):
"""
gray=0.299*R+0.587*G+0.144*B
"""
return np.uint8(np.dot(rgb[...,:3], [0.299, 0.587, 0.114]))

A: as @Ma Jun pointed out the
(bbox=x,y,width,height) is not really like start from (x,y) and get a width to height window.
Rather the opening window is x,y width-x, height-y
I added this post because it took me a long time to figure this out :)
keywords: Python ImageGrab bbox


text:
Q: Ruby: bsearch returning nil I have an sorted array of number, and wanted to check if number is in the array or not. I think I should use bsearch here but it return nil even if the number is present in the array, and only give positive result for the middle element.
Here is what I test.
>> [1,2,3,4,5].bsearch { |value| value <=> 1}
>> nil
>> [1,2,3,4,5].bsearch { |value| value <=> 3}
>> 3

I am using Ruby version 2.3.8

A: You are using Array#bsearch in Find-any mode.
As the documentation says, your block needs to satisfy the following requirements:

*

*All positive-evaluating elements precede all zero-evaluating elements.

*All positive-evaluating elements precede all negative-evaluating elements.

*All zero-evaluating elements precede all negative-evaluating elements.

Your block violates those requirements.
Let's run through an example. In the first iteration, Array#bsearch will pick the middle element, which is 3 and pass it to your block. Your block returns 1, which means that the element you are searching for is greater than 3 and thus must be to the right of the current element. So, Array#bsearch throws away the left half of the array, and we are left with [4, 5]. Now again, Array#bsearch picks the "middle" element, which is 4 and passes it to your block. Your block returns 1, which is a positive number and thus means that the element you are looking for is greater than 4 and thus must be in the right half of the array. So again, Array#bsearch throws away the left half and we are left with [5]. Same thing, Array#bsearch passes 5 to the block, your block returns 1 which is a positive number and thus means we need to look to the right, except we are already at the end of the array, and thus we can conclude that the element you are looking for is not in the array.
So, basically, you are just telling Array#bsearch to look in the wrong place.
Let's look again at the documentation:

These make sense as blocks in find-any mode:
a = [0, 4, 7, 10, 12]
a.map {|element| 7 <=> element } # => [1, 1, 0, -1, -1]
a.map {|element| -1 <=> element } # => [-1, -1, -1, -1, -1]
a.map {|element| 5 <=> element } # => [1, 1, -1, -1, -1]
a.map {|element| 15 <=> element } # => [1, 1, 1, 1, 1]

This would not make sense:
a = [0, 4, 7, 10, 12]
a.map {|element| element <=> 7 } # => [-1, -1, 0, 1, 1]

So, essentially you wrote your block exactly like the block that the documentation explicitly says is wrong, and exactly the opposite way of what the documentation tells you to.
If you flip the two operands in the block, so that your block looks like the example in the documentation says it should look, it will work:
[1, 2, 3, 4, 5].bsearch { |value| 0 <=> value } #=> nil
[1, 2, 3, 4, 5].bsearch { |value| 1 <=> value } #=> 1
[1, 2, 3, 4, 5].bsearch { |value| 2 <=> value } #=> 2
[1, 2, 3, 4, 5].bsearch { |value| 3 <=> value } #=> 3
[1, 2, 3, 4, 5].bsearch { |value| 4 <=> value } #=> 4
[1, 2, 3, 4, 5].bsearch { |value| 5 <=> value } #=> 5
[1, 2, 3, 4, 5].bsearch { |value| 6 <=> value } #=> nil


text:
Q: My Darkcode is showing error "the value of the local variable 'choice' isn't used" I just started learning dart for flutter and wrote this code for a simple calculator but there is an error associated with a variable "choice".It is declared inside the while loop but when I use it for condition checking, it's showing "The value of the local variable 'choice' isn't used". Please help me.
import 'dart:io';

void main() {
  do {
    print(
        "Choose operation:\n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\nChoice:");
    int ch = int.parse(stdin.readLineSync());

    print("Enter two numbers");

    int num1 = int.parse(stdin.readLineSync());
    int num2 = int.parse(stdin.readLineSync());

    switch (ch) {
      case 1:
        print("Addition of $num1 and $num2 is ");
        print(add(num1, num2));
        break;
      case 2:
        print("Subtraction of $num1 and $num2 is ");
        print(sub(num1, num2));
        break;
      case 3:
        print("Division of $num1 and $num2 is ");
        print(div(num1, num2));
        break;
      case 4:
        print("Multiplication of $num1 and $num2 is ");
        print(mul(num1, num2));
        break;
      default:
        print("Invalid choice...");
    }

    String choice = stdin.readLineSync();
  } while (choice == "Yes" || choice == "yes");
}

int add(int x, int y) => (x + y);
int sub(int x, int y) => (x - y);
double div(int x, int y) => (x / y);
int mul(int x, int y) => (x * y);

Shown errors:
The value of the local variable 'choice' isn't used - line 30
Undefined name 'choice' - line 30
Undefined name 'choice' - line 30

A: As you declared choice inside the do-while, its scope is only inside the block of the do-while, so is not visible in the condition. Try declaring choice before the do keyword:
void main() {
    String choice;
    do {
        print("Choose operation:\n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\nChoice:");
        int ch= int.parse(stdin.readLineSync());
        print("Enter two numbers");
        int num1=int.parse(stdin.readLineSync());
        int num2=int.parse(stdin.readLineSync());
        switch(ch)
        {
            case 1:
               print("Addition of $num1 and $num2 is ");
               print(add(num1,num2));
               break;
            case 2:
               print("Subtraction of $num1 and $num2 is ");
               print(sub(num1,num2));
               break;
            case 3:
               print("Division of $num1 and $num2 is ");
               print(div(num1,num2));
               break;
            case 4:
               print("Multiplication of $num1 and $num2 is ");
               print(mul(num1,num2));
               break;
            default:
                print("Invalid choice...");
        }
        choice = stdin.readLineSync();
    } while (choice=="Yes" || choice=="yes");
}


text:
Q: Envío automático de sms (Python, Windows) Estoy en unas prácticas en empresa y me han propuesto un proyecto.
Trata de hacer un script en Python para Windows que mande sms de manera automática a los clientes para recordarles una cita anual (coger de la base de datos la fecha de la última visita y cuando haya pasado 1 año, mandar sms).
He visto que hay varios servicios de sms, pero me gustaría saber si podéis recomendarme alguno por aquí que tenga buena documentación de su API, o un poco de guía sobre cómo proceder, ya que nunca he hecho nada parecido y el "jefe" tiene aún menos idea que yo.
Gracias.

A: Si lo que quieres es utilizar una Api puedes utilizar la de https://www.twilio.com/ esta bien documentada .
Este seria un ejemplo:
from twilio.rest import Client
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' #tu sid de tu cuenta
auth_token = 'your_auth_token' # tu token
client = Client(account_sid, auth_token)
message = client.messages.create(body='HolaMundo!',from_='+15017122661',to='+15558675310')
print(message.sid)


text:
Q: Images appearing in search results (when they shouldn't) Have two SP2013 on-prem site collections -- one where we explore and build tests and the other is for everyone in our company to use. In our "public" facing site search results we are trying to only show pages and documents that our users would be interested in. So we've gone through the list/library settings and marked them as No for "Allow items in this document library to appear in search results?"
For example the Style, Images, and Site Assets library. Those are not results our users will find valuable.
In our development site, this works great, but in our public site I'm still seeing some graphics from the images library. So for example we have a graphic for our department's logo. Someone might search on the name of our department and get a return of the logo. Not useful. The link returned is also strange.
<site>/PublishingImages/Forms/DispForm.aspx?ID=##

Not sure why it is to the display form.
I've checked that the library is not to be included and I've do a reindex (from the UI) for both the library and for the site, but that didn't fix it.
I added a new image to the library and strangely it doesn't appear in search results.
I've checked my result sources, search result webpart query builder, and search and offline availability settings and they are the same between the development and public sites. Not really sure where to go next.
Edit
Additional information. I just noticed that even the name of a folder in the image library is being included in the search results. So I think it must be indexing the list view pages? Why would it do that in one site but not in another?
And more importantly how do I tell it not to include urls like:
PublishingImages/Forms/Thumbnails.aspx
PublishingImages/Forms/Thumbnails.aspx?RootFolder=%2Fteams%2Ftop%2FPublishingImages%2Ffolder-namey&FolderCTID=0x012000A35920B88D683C4C8C4115EC9092245A&View=%7B3C17B5FA-1C6D-4A8C-A3FB-101B5E32A42E%7D

A: The best way to manage search exposure is to set permissions. Search is security trimmed. Although there may be "leaks" due to visibility via web parts.
As to why the images are being included... while the library is set to no crawl, and search is respecting that, search does crawl every page and every link in the site, just like how Google or Bing would crawl a web site. So, somewhere search has found a page with a web part that displays the content of that library. (which would explain why the display form is in the URL)


text:
Q: Can I declare local temporary table in Oracle 12c I'm trying to declare local temporary table using the example from Oracle / PLSQL: LOCAL TEMPORARY TABLES. But when I try to insert it into sqlplus' CLI and hit Enter, it does not execute anything and I don't know what to do next to complete the command except pressing Ctrl+C interrupting command inputing:
SQL> DECLARE LOCAL TEMPORARY TABLE suppliers_temp
( supplier_id number(10) NOT NULL,
  supplier_name varchar2(50) NOT NULL,
  contact_name varchar2(50)
);  2    3    4    5
  6
  7  ;
  8  ^C

To execute this query I've logged in as SYSTEM user.
Why this example does not work for me?

A: local temporary tables aren't a thing in the Oracle RDBMS. Instead, you can have a Global Temporary Table (GTT) (which creates a permanent table, but the data is held at session level) or, introduced in 18c, you can have a Private Temporary Table (PTT) (the table definition and data are held at session level).
Both are similar to the standard create table statement, so to create a GTT that drops the rows when you commit, you would do something like:
create global temporary table table_name (col1 number, col2 varchar2(20))
   on commit delete rows;