text:
Q: Detecting USB Device Insertion on Windows 10 using python I can't get the following code for Detecting USB Device Insertion to work on my Windows 10 (64 bit) computer with Python 3.7.
import win32serviceutil
import win32service
import win32event
import servicemanager

import win32gui
import win32gui_struct
struct = win32gui_struct.struct
pywintypes = win32gui_struct.pywintypes
import win32con

GUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
DBT_DEVICEARRIVAL = 0x8000
DBT_DEVICEREMOVECOMPLETE = 0x8004

import ctypes

#
# Cut-down clone of UnpackDEV_BROADCAST from win32gui_struct, to be
# used for monkey-patching said module with correct handling
# of the "name" param of DBT_DEVTYPE_DEVICEINTERFACE
#
def _UnpackDEV_BROADCAST (lparam):
  if lparam == 0: return None
  hdr_format = "iii"
  hdr_size = struct.calcsize (hdr_format)
  hdr_buf = win32gui.PyGetMemory (lparam, hdr_size)
  size, devtype, reserved = struct.unpack ("iii", hdr_buf)
  # Due to x64 alignment issues, we need to use the full format string over
  # the entire buffer.  ie, on x64:
  # calcsize('iiiP') != calcsize('iii')+calcsize('P')
  buf = win32gui.PyGetMemory (lparam, size)

  extra = {}
  if devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
    fmt = hdr_format + "16s"
    _, _, _, guid_bytes = struct.unpack (fmt, buf[:struct.calcsize(fmt)])
    extra['classguid'] = pywintypes.IID (guid_bytes, True)
    extra['name'] = ctypes.wstring_at (lparam + struct.calcsize(fmt))
  else:
    raise NotImplementedError("unknown device type %d" % (devtype,))
  return win32gui_struct.DEV_BROADCAST_INFO(devtype, **extra)
win32gui_struct.UnpackDEV_BROADCAST = _UnpackDEV_BROADCAST

class DeviceEventService (win32serviceutil.ServiceFramework):

  _svc_name_ = "DevEventHandler"
  _svc_display_name_ = "Device Event Handler"
  _svc_description_ = "Handle device notification events"

  def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__ (self, args)
    self.hWaitStop = win32event.CreateEvent (None, 0, 0, None)
    #
    # Specify that we're interested in device interface
    # events for USB devices
    #
    filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE (
      GUID_DEVINTERFACE_USB_DEVICE
    )
    self.hDevNotify = win32gui.RegisterDeviceNotification (
      self.ssh, # copy of the service status handle
      filter,
      win32con.DEVICE_NOTIFY_SERVICE_HANDLE
    )

  #
  # Add to the list of controls already handled by the underlying
  # ServiceFramework class. We're only interested in device events
  #
  def GetAcceptedControls(self):
    rc = win32serviceutil.ServiceFramework.GetAcceptedControls (self)
    rc |= win32service.SERVICE_CONTROL_DEVICEEVENT
    return rc

  #
  # Handle non-standard service events (including our device broadcasts)
  # by logging to the Application event log
  #
  def SvcOtherEx(self, control, event_type, data):
    if control == win32service.SERVICE_CONTROL_DEVICEEVENT:
      info = win32gui_struct.UnpackDEV_BROADCAST(data)
      #
      # This is the key bit here where you'll presumably
      # do something other than log the event. Perhaps pulse
      # a named event or write to a secure pipe etc. etc.
      #
      if event_type == DBT_DEVICEARRIVAL:
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          0xF000,
          ("Device %s arrived" % info.name, '')
        )
      elif event_type == DBT_DEVICEREMOVECOMPLETE:
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          0xF000,
          ("Device %s removed" % info.name, '')
        )

  #
  # Standard stuff for stopping and running service; nothing
  # specific to device notifications
  #
  def SvcStop(self):
    self.ReportServiceStatus (win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent (self.hWaitStop)

  def SvcDoRun(self):
    win32event.WaitForSingleObject (self.hWaitStop, win32event.INFINITE)
    servicemanager.LogMsg (
      servicemanager.EVENTLOG_INFORMATION_TYPE,
      servicemanager.PYS_SERVICE_STOPPED,
      (self._svc_name_, '')
    )

if __name__=='__main__':
  win32serviceutil.HandleCommandLine (DeviceEventService)

*

*I start the script with the following command: python main.py start

*Then the following error messages appear in the command prompt:
Starting service DevEventHandler
Error starting service: Access denied

*I then ran the script with administrator privileges: runas /user:administrator "python main.py start"

*Another error messages appear in the command prompt:
Starting service DevEventHandler
Error starting service: The specified service does not exist as an installed service.
How can the 'The specified service does not exist as an installed service' error be fixed?

A: I tested with Python 3.8.2 x64.

*

*Install pywin32 (pip install pywin32)

*Install the current/last version (1.5) of the WMI module from https://github.com/tjguk/wmi (pip install -e git+https://github.com/tjguk/wmi.git#egg=wmi)

*run a script (test.py in my case), like:

import wmi

raw_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_USBHub\'"
c = wmi.WMI ()
watcher = c.watch_for(raw_wql=raw_wql)
while 1:
  usb = watcher ()
  print(usb)

*plug in a USB device. Output looks like:

(wmi-py) C:\Users\USER\Source\wmi-py>py test.py

instance of Win32_USBHub
{
        Caption = "USB Composite Device";
        ConfigManagerErrorCode = 0;
        ConfigManagerUserConfig = FALSE;
        CreationClassName = "Win32_USBHub";
        Description = "USB Composite Device";
...

Many thanks to the WMI module author, and the Windows nerds' discussion here Detecting USB drive insertion and removal using windows service and c#

A: I tried to run the script with debug argument and a message saying that service is not installed appeared.
Try first to type

python main.py install

then

python main.py start


text:
Q: How do I find one element after using Findelements in Selenium? I'm trying to create this global method that click on this link called "Categories". The ID (t_166) is dynamic, Xpath (//*[@id="t_166"]) and "copy selector" (#t_166) use the id number also so they won't work.
So, I'm left with the html:

I figured class would be a good candidate. So... to start:
var categorymenu = driver.instance.findelement(by.classname("fontMediumBigColorGrey navigatorLinkClicked z-label")

And then I want it to find the category one and click on it, something like:
categorymenu.getattribute(category).click();
Two problems.
Problem 1: The link's class changes depending if you've visited it previously, or the "linkclicked" part in it. It becomes "fontMediumBigColorGrey z-label" if you haven't been on it. Question: it won't be able to find categories if the class is different. How would I handle this?
Problem 2: There are many other links (like users) that use the same classes, so shouldn't I be using findelements and then isolate it by an attribute (category is this case) But findelements doesn't seem to be able to use getattribute (because there are many of them) so how do I cover that part?
Thanks!

A: You can use search by XPath to find your element:
var categorymenu = driver.instance.findelement(by.xpath("//span[text()='Categories']")

In code above you search for span element with "Categories" as its text value
Also you can try to ignore dynamically changing part of id attribute in following way:
var categorymenu = driver.instance.findelement(by.xpath("//div[starts-with(@id, 't_')][substring-after(@id, '-')='cave']/span")

Above code should search for span that is child of div with id="t_XXXX-cave" where XXXX is ignored part
Note You should also be aware that you will not be able to complete categorymenu.getattribute(category).click(); as categorymenu.getattribute(category) (actually categorymenu.GetAttribute(category)) returns just a string value

A: In case you want to see if the span has the fontMediumBigColorGrey class:
var categorymenu = driver.instance.findelement(by.xpath("//span[contains(@class, 'fontMediumBigColorGrey')]")

In case you want to see if the text is equal to "Categories":
var categorymenu = driver.instance.findelement(by.xpath("//span[text()='Categories']")

A trick that I sometimes use, and could be useful for you too - if you're using Chrome, open the console and edit the HTML in such a way that you delete the "id" tag. Then, right click and choose 'Copy > Copy XPath'. This will copy the XPath but neglect the ID (because you can't use it since it's dynamic).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Style:Display and Visibility errors?

        1
        1
        1
        1
        1

        2
        2
        2
        2
        2

        3
        3
        3
        3
        3

        4
        4
        4
        4
        4

        5
        5
        5
        5
        5

        6

        7

see the code I am using visibility and display for hidden or showing rows but both have errors
Visibility hide the row but do not removed space, like "display:none",
I can use "display" but it is not working properly with safari and Firefox.
Please give me solution for it.
My requirement is:-
Hide the row and also removed its space on all browsers.

A: Change display: block; to display: table-row; for a start, then use display: none; instead of visibility: hidden;.
display:block; applies to div elements and similar, not table rows.

A: display: none works fine to remove a table row in all browsers.
However what you have is display: block, which makes no sense. A 'block' element is like a
; you can't sensibly put one directly inside a
.
A table row that is not removed by display: none should have the display value table-row. However in IE only, before version 8, it is display: block instead. That means if you are switching between shown and removed with JavaScript, you would have to sniff the browser to choose whether to set display: table-row or display: block when re-showing the row.
In that case it is much easier to do it indirectly instead, by adding and removing row.className= 'hidden' and using a stylesheet rule to .hidden { display: none; }. This way requires no browser workarounds.

A: don't use
style="display:block"

Also there are some basic missing in you code
such that dont use

it should be

Use colspan="" in your
Number of td in each row should be matched to work properly. if they don't match you have to adjust it properly using colspan=""
Following is work for me

        1
        1
        1
        1
        1

        2
        2
        2
        2
        2

        3
        3
        3
        3
        3

        4
        4
        4
        4
        4

        5
        5
        5
        5
        5

        6

        7

A: It is a bit vague what you are after but display:none hides the rows and does not save space on all IE, FF and (as far as I know but I dont develop specifically for Safari) Safari.


text:
Q: Mysql Select Specific Column with N Column Let's say i have 'db_institute' and 'tb_data' which have 39 Column
While This Answers Selecting from the last 10 column, i want to add extra column in the query
the result would be like this when i prepared statement it
SELECT Name,lastcolumn1,...,lastcolumn10 from tb_data

And here's my failed attempt
    SELECT Name,
      CONCAT('SELECT ',
             GROUP_CONCAT(COLUMN_NAME),
             ' FROM 'tb_data')
    FROM
      (SELECT
        COLUMN_NAME,
        ORDINAL_POSITION
      FROM
        INFORMATION_SCHEMA.COLUMNS
      WHERE
        TABLE_SCHEMA='db_institute'
        AND
        TABLE_NAME='tb_data'
      ORDER BY
        ORDINAL_POSITION DESC LIMIT 10) AS ord_desc
    ORDER BY
      ord_desc.ORDINAL_POSITION
  into @sql

Which result error
Unknown column 'Name' in 'field list'

A: your reference is already correct. try this
SELECT
  CONCAT('SELECT Franchisee, ', GROUP_CONCAT(COLUMN_NAME), ' FROM product_staging') # change product_staging to your table name and Franchisee to Name
FROM
  (SELECT
    COLUMN_NAME,
    ORDINAL_POSITION
  FROM
    INFORMATION_SCHEMA.COLUMNS
  WHERE
    TABLE_SCHEMA='myob' # change it to your schema name
    AND
    TABLE_NAME='product_staging' # change it to your table name
  ORDER BY
    ORDINAL_POSITION DESC LIMIT 10) AS ord_desc
ORDER BY
  ord_desc.ORDINAL_POSITION
INTO @qry;
PREPARE stmt1 FROM @qry;
EXECUTE stmt1;


text:
Q: Helm3 with EKS cluster During Installation of Helm3 stable, i found Helm3 stable does not implement tiller deployment for fetching cluster details, it works as a Client utility only, my question is it, if it is not implementing tiller concept for fetching details, how does it connect with EKS.
I have already installed kubectl and it is running fine, is it something like this, helm client is dependent on kubectl service?
I performed following steps:
1.helm version
version.BuildInfo{Version:"v3.1.0", GitCommit:"b29d20baf09943e134c2fa5e1e1cab3bf93315fa", GitTreeState:"clean", GoVersion:"go1.13.7"}
2.kubectl create serviceaccount tiller --namespace kube-system
serviceaccount/tiller created
3.notepad rbac-config.yaml
4.kubectl apply -f rbac-config.yaml
clusterrolebinding.rbac.authorization.k8s.io/tiller-role-binding created
5.helm init --service-account tiller
Error: unknown flag: --service-account
I know steps 2,3,4 are not required in Helm3, but curious to know how helm3 interacts as a client service with EKS cluster.

A: Just like kubectl, helm also uses kubeconfig to communicate with the cluster.
So, both kubectl and helm depend on the cluster's config file rather depending on each other.


text:
Q: Method for exchange MTU for BTLE in iOS is there any method like gatt_exchange_mtu (BlueZ stack) for iOS? Or any other method how to change ATT_MTU in iOS?

A: The MTU seems to be hard wired within the operating system.
I made some tests with iOS 7 and I get a MTU of 132 bytes.
Until iOS 7.0, one could not even query the MTU. In iOS 7.0, it is in the maximumUpdateValueLength property of CBCentral.
Attempting to update characteristic values with my application running on iOS 6.1, I noticed that a 30 byte update on the peripheral would be read as the first 20 bytes by the central. This triggered me to:
1. look deeper into the documentation,
2. Update all my devices to iOS 7.04
3. Run some tests and query the value of CBCentral.maximumUpdateValueLength
My results, based on a iPhone 4S, a iPodTouch and a iPad mini:
132 bytes seems to be constantly reported.
I no longer observe the "clipping" of my 30 bytes update down to 20 bytes.
I think this due to some middle-layer of code dealing with the Bluetooth stack, not accessible to the developer, controlled by Apple.
iOS CoreBluetooth API is a high level API and it does not allow the application writer to "mess" with the lower level bluetooth


text:
Q: Override US_export_policy and local_policy jar for a application Is it possible to override US_export_policy and  local_policy jar through JVM or application arguments?

A: There is no way to do this. If you could do it programmatically, the entire idea behind export restriction of large-keysize encryption collapses.


text:
Q: What is dual vector and covector? I tried to learn dual vectors online but failed to exactly understand it, I know that it could be understood using change of basis. Below is a example for change of basis, kindly help me with this.
Let V be a space over $\Bbb{R}^3$ and the basis be
$\begin{Bmatrix}
  \begin{bmatrix}1\\1\\0\\ \end{bmatrix},&
  \begin{bmatrix}0\\2\\0\\ \end{bmatrix},&
  \begin{bmatrix}1\\0\\1\\ \end{bmatrix}
\end{Bmatrix}$ and U be another space over $\Bbb{R}^3$ with basis
$\begin{Bmatrix}
  \begin{bmatrix}5\\0\\3\\ \end{bmatrix},&
  \begin{bmatrix}2\\3\\4\\ \end{bmatrix},&
  \begin{bmatrix}1\\6\\2\\ \end{bmatrix}
\end{Bmatrix}$, $\begin{bmatrix}3\\5\\7\\ \end{bmatrix}$ is a vector in U and we want this vector's coefficient in V. The approach would be:
$$c_1\left[\begin{matrix}1\\1\\0\\ \end{matrix}\right]+
c_2\left[\begin{matrix}0\\2\\0\\ \end{matrix}\right]+
c_3\left[\begin{matrix}1\\0\\1\\ \end{matrix}\right]
=
3\left[\begin{matrix}5\\0\\3\\ \end{matrix}\right]+
5\left[\begin{matrix}2\\3\\4\\ \end{matrix}\right]+
7\left[\begin{matrix}1\\6\\2\\ \end{matrix}\right]
$$
Where $\mathbf{c}$ are coefficients of $V$'s basis.
$$\left[\begin{matrix}1 & 0 &1 \\ 1&2&0 \\0& 0 & 1\\ \end{matrix}\right]
\left[ \begin{matrix}c_1\\c_2\\c_3\\ \end{matrix}\right]=
\left[\begin{matrix}5 &2&1\\ 0&3&6 \\3& 4 & 2\\ \end{matrix}\right]
\left[ \begin{matrix}3\\5\\7\\ \end{matrix}\right]
$$
$$
\left[ \begin{matrix}c_1\\c_2\\c_3\\ \end{matrix}\right]=
\left[\begin{matrix}1 & 0 &1 \\ 1&2&0 \\0& 0 & 1\\ \end{matrix}\right]^{-1}\left[\begin{matrix}5 &2&1\\ 0&3&6 \\3& 4 & 2\\ \end{matrix}\right]
\left[ \begin{matrix}3\\5\\7\\ \end{matrix}\right]= \left[ \begin{matrix}-11\\34\\43\\ \end{matrix}\right]
$$
Now I want to know from  above example:

*

*What is/are dual vector?

*What is/are covector?

*What is dual space?

Let me know if I have understood it completely wrong. Thanks

A: Given a vector space $V$ over field $K,$ the dual space of $V,$ denoted $V^\ast,$ is the set of all linear maps $\varphi:V\to K.$ For example, consider $V=\mathbb{R}\times\mathbb{R}$ with addition $+:V\times V\to V$ defined as:
$$\begin{bmatrix}a \\ b\end{bmatrix}+\begin{bmatrix}c \\ d\end{bmatrix}=\begin{bmatrix}a+c \\ b+d\end{bmatrix}$$ and vector multiplication $\cdot:K\times V\to V$ defined as
$$k\cdot\begin{bmatrix}a \\ b\end{bmatrix}=\begin{bmatrix}k\cdot a \\ k\cdot b\end{bmatrix}$$
The $+$ and $\cdot$ inside represent field addition and multiplication, but I'll just use the same symbol because I'm lazy. Define a linear mapping $\varphi:V\to K$ as $\varphi\!\left(\begin{bmatrix}a\\b\end{bmatrix}\right)=a+b.$ One can show that this function adds linearly:
$$\varphi\!\left(\begin{bmatrix}a\\b\end{bmatrix}\right)+\varphi\!\left(\begin{bmatrix}c\\d\end{bmatrix}\right)=a+b+c+d=a+c+b+d=\varphi\!\left(\begin{bmatrix}a+c\\b+d\end{bmatrix}\right)$$
and that it scales linearly:
$$k\cdot\varphi\!\left(\begin{bmatrix}a\\b\end{bmatrix}\right)=k\cdot\left(a+b\right)=k\cdot a+k\cdot b=\varphi\!\left(\begin{bmatrix}k\cdot a\\k\cdot b\end{bmatrix}\right).$$ Since it's linear, it's said to be a co-vector. Thus, one can show that this is equivalent to the "row vector" $\begin{bmatrix}1 & 1\end{bmatrix}$ using matrix multiplication.$\begin{bmatrix}1 & 1\end{bmatrix}\begin{bmatrix}a\\b\end{bmatrix}=a+b.$ When this collection of maps comes equipped with addition and multiplication that behaves linearly, the set itself also becomes a vector space over $K$ called the vector dual space that contains dual vectors.


text:
Q: Drawer Layout initially showed on the View Usually the Drawer Layout is hidden on the view until the onTouch or onSwipe in is triggered. I'd like to make the drawer layout initially displayed. I also checked out the SlidingLayer Library but
It is more complicated that the new drawer layout that Android has released. In the image below, the blue lines represents the initial drawer that needs interaction which also triggers the opening and closing of the drawer.
My last resort on this it to have a button, on the view that will handle the interaction, but as much as possible I want to have a normal view on drawer layout.
I have seen this on the documentation, not sure what it does:
setDrawerShadow(Drawable shadowDrawable, int gravity)
Set a simple drawable used for the left or right shadow.


text:
Q: Help on Generating function - Analysis of Median of three - Quick Select I am trying to find out the average case analysis of median of 3 - quick select. The recurrence relation is
\begin{equation}
C_{n,j} = 1 + \sum_{k=1}^{j-1}\pi_{n,k}C_{n-k,j-k} + \sum_{k=j+1}^{n} \pi_{n,k}C_{k-1,j}
\end{equation}
where
$$\pi_{n,k} = \frac{(n-k)(k-1)}{{{n}\choose{3}}}.$$
First we consider
$$C_j(x) = \sum_{n} C_{n,j}x^n.$$
Multiplying by ${{n}\choose{3}}\;  x^{n-3}$ and summing over $n$ on both sides
$$\sum_{n\geq 3}{{n}\choose{3}} x^{n-3}\; C_{n,j}
=\sum_{n\geq 3}{{n}\choose{3}}(1+\sum_{k=1}^{j-1}\pi_{n,k}C_{n-k,j-k} + \sum_{k=j+1}^{n} \pi_{n,k}C_{k-1,j} )\; x^{n-3} $$
We expand out the binary coefficients, since ${n\choose 3}=n(n-1)(n-2)/6$, so we get
$$\begin{aligned}\frac{1}{6} &\; \sum_{n\geq 3}n(n-1)(n-2) \;x^{n-3}\; C_{n,j}\\
&=\sum_{n\geq 3} \frac{n(n-1)(n-2)}{6} x^{n-3} +\sum_{n\geq 3} \sum_{k=1}^{j-1}(k-1)(n-k)C_{n-k,j-k}x^{n-3} \\
&\qquad+\sum_{n\geq 3} \sum_{k=j+1}^{n} (k-1)(n-k)C_{k-1,j}\; x^{n-3}\end{aligned} $$
But look, the left hand side is precisely
$$\frac{1}{6} \sum_{n\geq 3}n(n-1)(n-2) \;x^{n-3}\; C_{n,j}=\frac{C^{'''}_{j}(x)}{6}$$
so we have
$$ \begin{aligned}
1/6 C_j^{'''}(x)
&= \sum_{n\geq 3} n(n-1)(n-2)/6\; x^{n-3} +\sum_{n\geq 3} \sum_{k=1}^{j-1}(k-1)(n-k)C_{n-k,j-k}x^{n-3} \\
&\qquad+\sum_{n\geq 3} \sum_{k=j+1}^{n} (k-1)(n-k)C_{k-1,j}\; x^{n-3} \\
&= 1/6\; \sum_{n\geq 3} n(n-1)(n-2)\; x^{n-3} \rightarrow (1)\\
&\qquad  +\sum_{n\geq 3} \sum_{k=1}^{j-1}(k-1)(n-k)C_{n-k,j-k}x^{n-3} \rightarrow (2)\\
&\qquad +\sum_{n\geq 3} \sum_{k=j+1}^{n} (k-1)(n-k)C_{k-1,j}\; x^{n-3} \rightarrow (3) \end{aligned}$$
Lets solve each parts named $(1), (2)$ and $(3)$ separately.
$$\tag{1}
 \sum_{n\geq 3} n(n-1)(n-2)\; x^{n-3} = \frac{d^4}{dx^4}\sum_{n\geq 0} x^{n} = \frac{d^4}{dx^4} (\frac{1}{(1-x)}) = \frac{6}{(1-x)^4}  $$
The second term (2)
$$\tag{2}
\sum_{n\geq 3} \sum_{k=1}^{j-1}(k-1)(n-k)C_{n-k,j-k}x^{n-3} = $$
Since, $C_j(x) = \sum C_{n,j}x^n$  we have
      $C_{j-k}(x) = \sum C_{n,j-k}x^n$
      or  $C_{j-k}(x) = \sum C_{n-k,j-k}x^{n-k}$
      This term,$ \sum_{n\geq 3}(n-k)C_{n-k,j-k}x^{n-3} $ can be rewritten as $\sum_{n\geq 3}(n-k)C_{n-k,j-k}x^{n-k}\;x^{k-3} = x\; C_{j-k}^{'}\;x^{k-3} =C_{j-k}^{'}\;x^{k-2}$
       $\sum_{n\geq 3} \sum_{k=1}^{j-1}(k-1)(n-k)C_{n-k,j-k}x^{n-3} = \sum_{k=1}^{j-1} (k-1)x^{k-2}C_{j-k}^{'}\;$
The third term (3) is
$$\begin{aligned}
\sum_{n\geq 3} &\sum_{k=j+1}^{n}& (k-1)(n-k)C_{k-1,j}\; x^{n-3} \\
&= \sum_{n\geq 3} \sum_{k=1}^{n} (k-1)(n-k)C_{k-1,j}\; x^{n-3} \;\rightarrow (3.1)\\
&\qquad - \sum_{n\geq 3} \sum_{k=1}^{j} (k-1)(n-k)C_{k-1,j}\; x^{n-3}\; \rightarrow (3.2)\end{aligned}$$
We have
$$\tag{3.1} \sum_{n\geq 3} \sum_{k=1}^{n} (k-1)(n-k)C_{k-1,j}\; x^{n-3} = \sum_{n\geq 2} \sum_{k=1}^{n} (k-1)(n+1-k)C_{k-1,j}\; x^{n-2}$$
      Here, $a = k-1, b = n+1 -k ;\;a+b = n $
      $=1/x^2\;\sum_{n\geq 0} \sum_{a+b=n} (a)(b)C_{b,j}\; x^{n}  = 1/x^2 \;[\sum_{a\geq 0} a\;x^a] \;[\sum_{b\geq 0} bC_{b,j}\;x^b ]$
      $= 1/x^2 \; x \frac{d}{dx} \frac{1}{(1-x)} \; x \; \frac{d}{dx}\sum_{b=1}^{\infty} C_{b,j} \;x^b $
      Since, $C_{b,j} x^b = C_j$
      hence, $ = \frac{C^{'}}{(1-x)^2} $
{3.2}:
      How can we solve this?
      $\sum_{n\geq 3} \sum_{k=1}^{j} (k-1)(n-k)C_{k-1,j}\; x^{n-3} = $


text:
Q: Python: Change class variable with method from another file I want to change class dictionary in main file with a method from another file. When I call the method it acts like it did it's job, yet when dictionary is called from the main file again, it looses the appended entry.
Main file, testmain.py:
import testside

class MainClass(object):
    objects = {'three': 'four'}

if __name__ == '__main__':

    testside.SideClass.add_to('one', 'two') # prints {'three': 'four', 'one': 'two'}
    print(MainClass.objects)                # prints {'three': 'four'}

Side file, testside.py:
import testmain

class SideClass(object):

    @staticmethod
    def add_to(name, thing):
        testmain.MainClass.objects[name] = thing
        print(testmain.MainClass.objects)

What can I do to change class value from outside the file? Note, that I don't want to create an instance of MainClass().

A: SideClass is importing its own copy of the MainClass class.  You need to pass in the copy you want to change (even though it isn't an instance!) because MainClass has already been read in its own file.
This works:
Main file, testmain.py:
import testside

class MainClass(object):
    objects = {'three': 'four'}

if __name__ == '__main__':
    testside.SideClass.add_to(MainClass, 'one', 'two') # prints {'three': 'four', 'one': 'two'}
    print(MainClass.objects)                # prints {'three': 'four', 'one': 'two'}

Side file, testside.py:
class SideClass(object):

    @staticmethod
    def add_to(cls, name, thing):
        cls.objects[name] = thing
        print(cls.objects)

As a bonus, you no longer need to import MainClass in SideClass, and can dynamically use SideClass for any class you want.
I feel compelled to ask though, why do you want to do this?  The question reeks of X-Y problem.


text:
Q: How to display hardcode image on flutter which is not available in json link I am new to flutter and I'm currently developing a flutter application that fetches data from https://private-anon-b242a842d4-carsapi1.apiary-mock.com/manufacturers. I am displaying the image and name from the above JSON file. some of the image URL s don't have images. How can I display an image from my assets folder except for the unavailable images in the JSON file?
Home Page - where i display list of images and names
  Future<List<Car>> fetchCar() async {
    carList = [];
    final response = await http.get(
      Uri.parse('https://private-anon-b242a842d4-carsapi1.apiary-mock.com/manufacturers')
    );
    if (response.statusCode == 200) {
      List<dynamic> values = [];
      values = json.decode(response.body);

      if (values.length > 0) {
        for (int i = 0; i < values.length; i++) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            carList.add(Car.fromJson(map));
          }
        }
        setState(() {
          carList;
        });
      }
      return carList;
    }else {
      throw Exception('Failed to load cars');
    }
  }

     @override
      void initState() {
        fetchCar();
        Timer.periodic(Duration(seconds: 10), (timer) => fetchCar());
        super.initState();
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: ListView.builder(
              scrollDirection: Axis.vertical,
              itemCount: carList.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: (){
                    Navigator.of(context).push(MaterialPageRoute(builder: (_)=>DetailsPAge(
                      name: carList[index].name,
                      img_url: carList[index].img_url,
                      avg_price: carList[index].avg_price,
                      num_models:carList[index].num_models,
                      max_car_id: carList[index].max_car_id,
                      avg_horsepower: carList[index].avg_horsepower,
                )),);
              },
              child: CarCard(
                name: carList[index].name,
                img_url: carList[index].img_url
              ),
            );
          },
        ));
      }
    }

    class Car {
      Car({
        required this.name,
        required this.id,
        required this.img_url,
        required this.max_car_id,
        required this.num_models,
        required this.avg_price,
        required this.avg_horsepower
      });

      String name;
      int id;
      String img_url;
      int max_car_id;
      int num_models;
      double avg_horsepower;
      double avg_price;

      factory Car.fromJson(Map<String, dynamic> json) {
        return Car(
            name: json['name'],
            id: json['id'],
            img_url: json['img_url'],
            max_car_id: json['max_car_id'],
            num_models:json['num_models'],
            avg_price: json['avg_price'],
            avg_horsepower: json['avg_horsepower']
        );
      }
    }

    List<Car> carList = [];

CarCard widget - where I customize image and text
    class CarCard extends StatelessWidget {
      CarCard({
        required this.name,
        required this.img_url,
      });

      String name;
      String img_url;

      @override
      Widget build(BuildContext context) {
        return Padding(
          padding: const EdgeInsets.only(top: 15, left: 10, right: 10),
          child:  Container(
            height: 100,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey,
                  offset: Offset(4, 4),
                  blurRadius: 10,
                  spreadRadius: 1,
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(-4, -4),
                  blurRadius: 10,
                  spreadRadius: 1,
                ),
              ],
            ),
            child: Row(
              children: [
                Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey,
                          offset: Offset(4, 4),
                          blurRadius: 10,
                          spreadRadius: 1,
                        ),
                        BoxShadow(
                          color: Colors.white,
                          offset: Offset(-4, -4),
                          blurRadius: 10,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                    height: 60,
                    width: 60,
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Image.network(img_url),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        FittedBox(
                          fit: BoxFit.scaleDown,
                          child: Text(
                            name,
                            style: TextStyle(
                              color: Colors.grey[900],
                              fontSize: 25,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }

A: As far as I understood your question you want to display an image from your assets if there are no image in the json.
If that is what you want to do then you can use ?? operator, to check if there is an image in that json, like:
Navigator.of(context).push(MaterialPageRoute(builder: (_)=>DetailsPAge(
  name: carList[index].name,
  img_url: carList[index].img_url ?? Image.assets("<Your asset image path>"),
  avg_price: carList[index].avg_price,
  num_models:carList[index].num_models,
  max_car_id: carList[index].max_car_id,
  avg_horsepower: carList[index].avg_horsepower,
)),);

You can add this everywhere you want an image.
Also don't put all of your code no one is actually going to read and understand all of that; only add the code that is causing the error.

A: If the image is not in json link, then you can check it first and then show from local assets, lets try
child: Padding(
  padding: const EdgeInsets.all(10.0),
  child: img_url!=null && img_url.isNotEmpty
    ? Image.network(img_url)
    : Icon(Icons.add),
),

instead of icon you can try with
Align(
  alignment: Alignment.center,
  child: Image.asset('images/ic_alert_triangle.png'),
),


text:
Q: PostgreSQL 9.3 - Performance Issue: Counting table entries slower with jdbc postgres driver I'm using PostgreSQL 9.3 and want to ask if it is possible to improve the performance of my queries based on the following database schema:
CREATE TABLE "entities" (
  "id" BIGSERIAL,
  "type" INT NOT NULL,
  "name" VARCHAR(255) NOT NULL,
  "sentence_id" BIGINT NOT NULL, -- REFERENCES sentences(sentence_id)
  "date" DATE NOT NULL
);

CREATE TABLE "relationships" (
  "id" BIGSERIAL,
  "type" INT NOT NULL,
  "entity1" BIGINT NOT NULL, -- REFERENCES entities(id)
  "entity2" BIGINT NOT NULL, -- REFERENCES entities(id)
  "sentence_id" BIGINT NOT NULL, -- REFERENCES sentences(sentence_id)
  "date" DATE NOT NULL
);

The primary key for entities is (id, name, sentence_id) and I do have index on the fields "id" and "date". The primary key for relationships is (id, entity1, entity2, sentence_id) and I also have index on "id" and "date".
I will briefly explain the domain below. Maybe some of you do know another better approach.
There are sentences containing Persons on a certain date:
sent_id, date, sentence
1, 27.09.1990, "Franz Beckenbauer bedankt sich bei Angela Merkel"
2, 27.09.1990, "Angela Merkel feiert ihren Abschluss in Physik"

From this sources I extract the following table entries for the table "entities":
entitie_id, name, sent_id, date
1, Angela Merkel, 1, 27-09-1990
1, Angela Merkel, 2, 27-09-1990
2, Franz Beckenbauer, 1, 27-09-1990

I use this query to get the frequency of entities within a given time period:
SELECT COUNT(*) FROM entities AS e
WHERE e.id = {id} AND (e.date BETWEEN {from} AND {to})

and this one for the frequency of the relationship between them (how often they occurred together):
SELECT COUNT(*) FROM relationships AS r
WHERE r.id = {id} AND (r.date BETWEEN {from} AND {to})

Following a working example with explain analyze:
EXPLAIN ANALYZE SELECT COUNT(*) from entities as e
WHERE e.id = 474118 AND
(e.date BETWEEN '2010-01-01' AND '2010-12-01');

Aggregate  (cost=741.92..741.93 rows=1 width=0) (actual time=0.077..0.077   rows=1 loops=1)
  ->  Bitmap Heap Scan on entity e  (cost=6.66..741.46 rows=183 width=0) (actual   time=0.067..0.072 rows=4 loops=1)
     Recheck Cond: (id = 474118)
     Filter: (("date" >= '2010-01-01'::date) AND ("date" <= '2010-  12-01'::date))
     ->  Bitmap Index Scan on e_pkey_index  (cost=0.00..6.61 rows=190 width=0) (actual time=0.053..0.053 rows=4 loops=1)
           Index Cond: (id = 474118)
 Total runtime: 0.119 ms
(7 rows)

Is there a possibility to speed up this query or can I change the structure according to my domain to improve performance? I'm using this sort of query in my application very extensively to sort entities and relationships based on their individual frequency. In total I have run times of about more or less 6 seconds. If I can decrease a single query time this may also improve.
EDIT:
Explain Analyze after combined index (id, date) with another id:
Aggregate  (cost=707.84..707.85 rows=1 width=0) (actual time=0.108..0.108 rows=1 loops=1)
   ->  Bitmap Heap Scan on entities e  (cost=6.74..707.39 rows=181 width=0)    (actual time=0.081..0.104 rows=4 loops=1)
     Recheck Cond: ((id = 957604) AND (date >= '2010-01-01'::date) AND (date   <= '2010-12-01'::date))
     ->  Bitmap Index Scan on e_id_date_index  (cost=0.00..6.70 rows=181   width=0) (actual time=0.073..0.073 rows=4 loops=1)
           Index Cond: ((id = 957604) AND (date >= '2010-01-01'::date) AND (date <= '2010-12-01'::date))
 Total runtime: 0.168 ms
(6 rows)

EDIT 2
Found the culprit. It seems that some of the queries (here the entity query) takes more than a second. This would explain why my application function, which calls relation and entity query n times, takes more than 6 seconds. Found this with the "auto_explain" module of PostgreSQL. It logs all queries from my application which takes more than a seconds automatically and performs explain analyze on them.
2014-08-04 00:02:25 CEST LOG:  execute <unnamed>: SELECT COUNT(*)            FROM entities AS e           WHERE e.id = $1           AND           (e.date   BETWEEN $2 AN$
2014-08-04 00:02:25 CEST DETAIL:  parameters: $1 = '879', $2 = '2010-02-09', $3 = '2010-11-24'
2014-08-04 00:02:26 CEST LOG:  duration: 1266.621 ms
2014-08-04 00:02:26 CEST LOG:  duration: 1266.547 ms  plan:
        Query Text: SELECT COUNT(*)            FROM entities AS e           WHERE e.id = $1           AND           (e.date BETWEEN $2 AND $3)
        Aggregate  (cost=85495.58..85495.59 rows=1 width=0) (actual rows=1 loops=1)
           ->  Bitmap Heap Scan on entities e  (cost=4704.17..84977.27   rows=207326 width=0) (actual rows=219714 loops=1)
            Recheck Cond: (id = 879::bigint)
                Rows Removed by Index Recheck: 6437814
            Filter: ((date >= '2010-02-09'::date) AND (date <= '2010-11-  24'::date))
                 Rows Removed by Filter: 44104
                 ->  Bitmap Index Scan on e_pkey_index  (cost=0.00..4652.34   rows=251720 width=0) (actual rows=263818 loops=1)
                      Index Cond: (id = 879::bigint)

Sorry that it is another id but it's hard to get the same twice. It seems that the problem are id's that have many entries in the entities table. After recreating the index it looks like:
2014-08-04 22:38:23 CEST LOG:  duration: 697.026 ms
2014-08-04 22:38:23 CEST LOG:  duration: 697.002 ms  plan:
    Query Text: SELECT COUNT(*)            FROM entities AS e           WHERE     e.id = $1           AND           (e.date BETWEEN $2 AND $3)
        Aggregate  (cost=83520.53..83520.54 rows=1 width=0) (actual rows=1   loops=1)
           ->  Bitmap Heap Scan on entities e  (cost=1775.72..83319.78   rows=80297 width=0) (actual rows=81936 loops=1)
                Recheck Cond: (id = 514::bigint)
                 Rows Removed by Index Recheck: 3651177
                 Filter: ((date >= '2010-02-02'::date) AND (date <= '2010-11-  25'::date))
                Rows Removed by Filter: 11888
                 ->  Bitmap Index Scan on e_pkey_index  (cost=0.00..1755.64  rows=94828 width=0) (actual rows=93824 loops=1)
                  Index Cond: (id = 514::bigint)

A: There are too many different topics in one question, and even after many updates not all is clear. I'll just pick the elephant in th room and ignore the rest:
Query 1
->  Index Scan using r_pkey_index on relationships r (cost=0.43..57.53 rows=13 width=0)
                                                     (actual rows=1 loops=1)
         Index Cond: (id = 947367::bigint)
         Filter: ((date >= '2010-02-09'::date) AND (date <= '2010-11-24'::date))
Query 2
Filter: ((date >= '2010-02-09'::date) AND (date <= '2010-11-24'::date))
   Rows Removed by Filter: 44104
      ->  Bitmap Index Scan on e_pkey_index (cost=0.00..4652.34 rows=251720 width=0)
                                            (actual rows=263818 loops=1)
          Index Cond: (id = 879::bigint)
Obviously, a single row matches your criteria in the first query, while there are more than 200.000 in the second. Obviously, the first can be much faster.
Leaving aside that we are comparing two queries on two different tables.


text:
Q: Pass 2D array to function by reference So in my main function I'm creating a 2D array:
int dataDim = 100;
float inData[2][dataDim];

I want to pass it to a function where I will be able to fill it up with data. How to pass it in a manner that I will be able to fill it up directly? Maybe
function(float** array)

and then accessing array[0][0] probably doesn't work? Strange how I can't find any quick example about this.

A: in C, multidimensional arrays' sizes must be known to pass as such, although some sizes may be omitted, if you like.
Exact
void function(float array[][100]);
void function(float (*array)[100]);

Syntactically Valid
Although the compiler may legally ignore the size 2.
void function(float array[2][100]);


text:
Q: Why graphene's substrate is important I just have some feelings that somehow it is important what specific subtrate is used to grow graphene monolayer on. Some substrates are better, another ones are not so good. But I cannot completely understand in what sense they are good or bad. If someone could enlighten this moment for me I would be really greateful.
It is not about graphene at all. For exmaple, one prefers sapphire substrate for another 2D material, namely tungsten disulphide (WS2). So what is so special about substrates for 2D materials?
Thanks in advance!


text:
Q: How to strip HTML tags using a black list in PHP? PHP strip_tags use a whitelist for skip some tags that you don't want were get rid. Anybody knows some implementation but using a blacklist instead of a whitelist?

A: A simple compound regex search would work (if this is still about your previous issue):
$html =
preg_replace("#</?(font|strike|marquee|blink|del)[^>]*>#i", "", $html);

A: Try this function posted by LWC on php.net - http://www.php.net/manual/en/function.strip-tags.php#96483
<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = 'red text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?>


text:
Q: If the blocks can only be traversed backwards, how do we know which one is the newest? Our blockchain consists of a range of blocks that are chained together with a linked list, going only backward, where each block header has a prevHash (bitcoin) or parentHash (ethereum).
Here's my question: If I can't go forward, how do I know I'm on the latest block?
Do I ask other peers in the network what block they are on?
And, theoretically, if I'm the only one on the network, what happens then?

A:
If I can't go forward, how do I know I'm on the latest block?

Each miner, after they created a block, broadcasts the new block (including its number) to the network.
So each node (both miners and non-miners) gets the latest block from this broadcasted message.
Plus, you can also ask other peers directly about their current block to validate if you're on the current block as well.
Note: Sometimes multiple miners create and broadcast a valid block with the same number. Only one of them is accepted by the network (usually the one with the lowest timestamp) and the others are discarded as "uncle blocks".

And, theoretically, if I'm the only one on the network, what happens then?

Then you're the only miner as well, so you also have the last block number from the block that you mined.


text:
Q: How i print each second element in a list full of lines? Python I have a list of numbers like this(saved in .txt file):
list_of_numbers = [
   ('5', 2.5, 5200),
   ('6', 3.2, 5236),
   ('8', 5.4, 5287),
   ('6', 8.7, 2563)
]

And i imported this list (list is .txt file) like this:
list_of_numbers = open("list_of_numbers.txt").read().strip().split()

but now i want that python print me each second element in each line.. I tried this:
p = x[1] for x in list_of_numbers
print(p)

but it's not correct..
And i want that python printed me like this:
p = 2.5, 3.2, 5.4

Please help me..

A: You missed the brackets. Try this:
p = [x[1] for x in list_of_numbers]

To print the values, you could use
print(', '.join([str(x) for x in p]))

You also need to change the way you load the data from the file
Full Code:
def parse(raw):
    data = []
    for line in raw.split("\n"):
        line = line.strip()
        # --> "('5', 2.5, 5200)"
        if line.startswith("(") and line.endswith(")"):
            d = line[line.index("(")+1 : line.index(")", -1)]
            # --> "'5', 2.5, 5200"
            d = d.split(",")
            data.append([])
            for i in d:
                i = i.strip()
                try:
                    i = float(i)
                except:
                    pass
                data[-1].append(i)
    return data

raw = open("list_of_numbers.txt").read()

list_of_numbers = parse(raw)

p = [x[1] for x in list_of_numbers]
# --> [2.5, 3.2, 5.4, 8.7]
print(', '.join([str(x) for x in p]))
# ---> 2.5, 3.2, 5.4, 8.7

I suggest using pickle. Storing and loading your data is easy as:
import pickle
data = ...
# store
file = open('data.txt', 'w')
pickle.dump(data, file)
file.close()
# load
file = open('data.txt', 'r')
data = pickle.load(file)
file.close()

A: Another option is to use numpy.ndarray.
import numpy as np
list_of_numbers = [
    ('5', 2.5, 5200),
    ('6', 3.2, 5236),
    ('8', 5.4, 5287),
    ]
list_of_numbers = np.array(list_of_numbers)
p = list_of_numbers[:,1]
print(p)
# outputs: ['2.5' '3.2' '5.4']

In addition, since you're reading data from a text file, your first list should contain only str. (I really don't understand how you get mixed strings and numbers using the method you describe in your question.) To fix that, you can either:

*

*use numpy.loadtxt,

*convert to float when switching to a ndarray: `np.array(list_of_numbers, dtype=float).

Finally, I strongly suggest that you learn about slices in Python.


text:
Q: Internet Explorer 11: Print functionality creates blank pages
*

*Data within Page renders from the start leaving extra blank pages at the end.

*When data more than a page creates blank page in first page and extra blank pages at the end.
exportElement.setAttribute('id', 'demo-table');
tableElement.appendChild(exportElement);
exportElement.innerHTML = tableElement.outerHTML;
window.print();


text:
Q: Creating Join to Display Values of One column from T1 which are not in T2 with some where comparisons I am trying to create join in MYSQL Stored Procedure, one table is EMployeeMaster and Other Table is WeekRest.
My join should result values of EMPID from EmpMaster for ONLY THOSE EMPIDs which EMPIDs do not exist in second Table WeekRest with some conditions. I am not able to get expected results.
Attaching Table Structures with just necessary columns and sample values for Table and the Join I have created.

*

*Create Statement for First Table hrmempmaster
    CREATE TABLE `hrmempmaster` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `EMPID` varchar(45) NOT NULL,
  `Department` varchar(45) DEFAULT NULL,
  `Designation` varchar(45) DEFAULT NULL,
  `ShiftName` varchar(45) DEFAULT NULL,
  `ShiftID` varchar(45) DEFAULT NULL,
  `ReportingTo` varchar(45) DEFAULT NULL,
  `UnitCode` varchar(45) DEFAULT NULL,
  `UnitName` varchar(45) DEFAULT NULL,
  `DivisionName` varchar(45) DEFAULT NULL,
  `DivisionCode` varchar(45) DEFAULT NULL,
  `Name` varchar(50) DEFAULT NULL,
  `Gender` varchar(50) DEFAULT NULL,
  `DOB` varchar(50) DEFAULT NULL,
  `DOJ` varchar(50) DEFAULT NULL,
  `FatherName` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `EMPID_UNIQUE` (`EMPID`),
  UNIQUE KEY `ID_UNIQUE` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=428 DEFAULT CHARSET=utf8;

*Create Statement For Second Table WeekRest
CREATE TABLE `hrmweekrest` (
  `ID` int(11) DEFAULT '1',
  `EmpID` varchar(45) NOT NULL,
  `EmpName` varchar(45) DEFAULT NULL,
  `FatherName` varchar(45) DEFAULT NULL,
  `Department` varchar(45) DEFAULT NULL,
  `Designation` varchar(45) DEFAULT NULL,
  `WeekRestOn` varchar(45) DEFAULT NULL,
  `Month` varchar(45) NOT NULL,
  `Year` varchar(45) NOT NULL,
  `Status` varchar(45) DEFAULT NULL,
  `MonthYear` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`EmpID`,`Month`,`Year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

*My Procedure which is not giving expected Values
CREATE DEFINER=`root`@`localhost` PROCEDURE `HRFetchWeekRest`(IN Department VARCHAR(25), IN MonthYear varchar (15))
begin

select hrmempmaster.empid, hrmempmaster.Name,hrmempmaster.FatherName, hrmempmaster.Department,hrmempmaster.Designation, HRMWEEKREST.WeekRestOn FROM HRMEMPMASTER

LEFT JOIN HRMWEEKREST ON HRMEMPMASTER.EMPID = HRMWEEKREST.EMPID

where hrmempmaster.empid not in (select empid from HRMWEEKREST where HRMWEEKREST.MonthYear = MonthYear  ) and  hrmempmaster.department = Department;

end

*Example
IF  EmployeeMaster table has 1 Employee with EMPID ID1, ID2, ID3...., and I pass Department as Dept1 for all employees and WeekRest table contains following Values in Columns
    # ID, EmpID, EmpName, FatherName, Department, Designation, WeekRestOn, Month, Year, Status, MonthYear
    1, ID1, Name1, Fname1, Dept1, Designation1, Sunday, January, 2017, Active, January2017

Then when
i)  Department is Passed as "Dept1" and MonthYear as "February2017"
The select statement should return ALL EMPIDs as None of then have Value in Weekrest table. Treat February as any other month in year except January
ii)  Department is Passed as "Dept1" and MonthYear as "January2017"
The select statement should return ALL EMPIDs except ID1 as except ID1 none of the IDs have Value in Weekrest table.
Will try to provide any further information at earliest

A: Try this
 CREATE DEFINER=`root`@`localhost` PROCEDURE `HRFetchWeekRest`(IN Department VARCHAR(25), IN MonthYear varchar (15))
    begin

    select hrmempmaster.empid, hrmempmaster.Name,hrmempmaster.FatherName, hrmempmaster.Department,hrmempmaster.Designation, HRMWEEKREST.WeekRestOn FROM HRMEMPMASTER

    LEFT JOIN HRMWEEKREST ON HRMEMPMASTER.EMPID = HRMWEEKREST.EMPID AND HRMWEEKREST.MonthYear = MonthYear

    where HRMWEEKREST.empid  IS NULL and  hrmempmaster.department = Department;

    end


text:
Q: How to Speed Up Load Time of RSS Feed? I'm using feedroll.com for my site to receive 4 different feeds.  After testing the page speed, it's obvious the RSS is slowing down the site by far and taking the longest to load.  Any general tips on how to somehow minimize the page load time for RSS feeds?  Thanks.

*

*side note: I'm using the feeds because I have one site where parts of it are JSP and other parts PHP (Wordpress).

A: One simple approach (if the content of the feeds do not change very much over time): Use a cron job to download the feeds periodically to your web server. Take the downloaded feeds from your web server's file system when you serve documents to the client.
For example: If you use the Feedcombiner you can periodically download the feed to your server and make a link to this downloaded RSS Feed on your server's file system.


text:
Q: Interpretation of the Weyl tensor My question arises from the interpretation of Ricci curvature. If I am not mistaken :

*

*The Ricci scalar measures the change of volume of small geodesic balls, compared to a euclidean space, it is a generalization of the notion of Gauss curvature.

*The Ricci tensor measures the change of volume of small spherical geodesic cones. So it accounts for a "directional" or "partial" change of volume of small geodesic balls in a way.
As a consequence, if the Ricci tensor is not zero, a null Ricci scalar means that geodesic balls do not change volume, but are still deformed.
Like a ball becomes an ellipsoid of same volume, say.
Now if we take a Ricci-flat space with the Schwarzschild metric for example, the space outside the Schwarzschild radius is empty of matter-energy and Ricci-flat. So no change in volume nor form.
But, there is still a curvature because the Riemann tensor is not zero, and the spherical mass has to curve space anyway.
Since the only non-vanishing part left of the Riemann tensor must be the Weyl tensor, most books and articles I've read attribute the space curvature to the tidal forces of gravitational waves.
BUT, tidal forces would deform the geodesic balls, wouldn't they ? So there couldn't be any !
Evidently, I am missing something in the interpretation of the Weyl tensor. Is it geodesic deviation ? Can there be gravitational waves without tidal forces ?
[EDIT : My mistake was to think the deformation of geodesic balls was measured only by the Ricci tensor, when in fact both it and the Weyl tensor account for deformation, though for different reasons.]

A: Actually there are some equations and results that make the Weyl tensor more intuitively clear, and that also makes the intuitive description that it denotes the deformation of a sphere, whereas the trace of the Riemann tensor is more closely related to its volume growth.
That deformation of the shapes, is due to the tidal forces, and more technically to the shear in the spacetime. The Weyl tensor describes it.
First is the fact that it is also called the conformal tensor, or the conformal Weyl tensor. That is, for two metrics that are conformally related, i.e., $g' = fg$, with $f$ a conformal transformation function of the spacetime coordinates, then, $C' = C$, with $g$ the metric and $C$ the Weyl tensor.
That means that a conformal (or simplistically) 'volume' change leaves the Weyl tensor invariant. The transformations or variations which affect the Weyl tensor are more the deformations than the 'volume' changes. This is explained a little better in Wikipedia at https://en.m.wikipedia.org/wiki/Weyl_tensor.
But one can do better, and understand what it denotes in spacetime.

In essence, the Weyl tensor describes the shear of null geodesics.
  Thus, how geodesic balls deform. From a nice description in
  https://www.physicsforums.com/threads/geometrical-meaning-of-weyl-tensor.708383/
  and with mostly a copy/paste below while leaving out unnecessary
  parts,
'Let $k^a$ represent the tangent vector field to a congruence of null
  geodesics. We want to find a way to describe the behavior of a
  neighboring collection of null geodesics in the congruence relative to
  each other and for this we need a spatial deviation vector connecting
  a given null geodesic in the congruence to infinitesimally nearby ones
  in the congruence.' The equation turns out to be (also from the same
  reference)
$$k^{c}\nabla_{c}\sigma_{ab} = -\theta {\sigma}_{ab}+
> C_{cbad}k^{c}k^{d} $$
where $\sigma_{ab}$ is the shear, and describes the deformation of a
  ball into an ellipse for instance, and $\theta$ is the expansion
  factor of the volume. C is the Weyl tensor. Those are in the subspace
  orthogonal to $k_a$. If $\theta$ = 0, then the C term in the equation
  above is the rate of change of the shear along the null geodesic. This
  is described for instance in Wald.

It has some very useful properties to describe and analyze how a shape in spacetime changes along null geodesics, I.e., along gravitational waves.
It is useful in analyzing gravitational waves. One is the  classification of Petrov types, with a general Weyl tensor asymptotically (as we go towrds infinity, ie, further from the course) able to be described as a sum of successively faster decaying Weyl Tensors, as higher inverse powers of u, with u a parameter along the null geodesics towards infinity. This is called the Peeling Theorem, and allows for the classification of Ricci flat spacetimes, and analysis of gravitational waves in vacuum. See a simple description at https://en.m.wikipedia.org/wiki/Peeling_theorem
Another useful tool derived from the Weyl tensor, the Newman-Penrose formulation, uses the Weyl scalars, 5 complex scalars which are formed from the 10 independent components of the Weyl tensor. One of those complex scalars is the outgoing gravitational wave, another is incoming, one is a static term (like the static Schwarzschild field), and two define gauges, at large distances (i.e., as u gets large). See https://en.m.wikipedia.org/wiki/Weyl_scalar


text:
Q: Service worker & client communication. Fetch Event finished I am trying to communicate a Service worker with a client in a bidirectional way. My aim is to delegate the processing of the request to the client and come back to the service worker with a proper response. The sequence of steps are the following:
Service Worker:

*

*The Service worker gets a request

*It checks if it must be ignored or properly managed

*A message with the request and a correlation ID is created

*The message is sent to the client via the Incoming message

*The pair {id: event} is registered in Messages store

Client:

*

*A request message comes via the Incoming Channel

*The message is destructured to get the correlation ID & the request

*A proper response is created for the request

*The response & correlation ID is sent back to worker via the Outgoing Channel

Service Worker:

*

*A response message comes via the Outgoing Channel

*The message is destructured to get the correlation ID & the response

*The pending message for this ID is retrieved from the Messages store

*A new Response object is created for the response

*The response object is returned via respondWith
This is my Service Worker:
const INSTALL   = 'install'
const ACTIVE    = 'activate'
const FETCH     = 'fetch'
const MESSAGE   = 'message'
const INSTALLED = 'Worker Installed'
const ACTIVATED = 'Worker Activated'
const FETCHING  = 'Worker fetching'
const ICHANNEL  = 'whale-ichannel'
const OCHANNEL  = 'whale-ochannel'
const HEADERS   = { 'Content-Type' : 'text/javascript' }
const PREFIX    = '/whale/'

let toJson   = JSON.stringify
let toJs     = JSON.parse
let Messages = new Map ()
let idx      = 0
let iChannel = new BroadcastChannel (ICHANNEL) // Incoming Channel
let oChannel = new BroadcastChannel (OCHANNEL) // Outgoing Channel

self.addEventListener (INSTALL, function (event) {

  console.log (INSTALLED)
  self.skipWaiting ()

})

self.addEventListener (ACTIVE, function (event) {

  console.log (ACTIVATED)
  event.waitUntil (clients.claim ())
  oChannel.addEventListener (MESSAGE, function ({ data }) {

    let id       = data.id
    let response = data.response
    let message  = Messages.get (id)

    Messages.delete (id)
    message.send (response)

  })
})

self.addEventListener (FETCH, async function (event) {

  if (isRequest (event)) await doRequest (event)

})

function isRequest (event) {
  let { request } = event
  let { url     } = request
  let uri  = new URL (url)
  let path = uri.pathname
  let ok   = path.startsWith (PREFIX)
  return ok
}

function getRequest (event) {
  let { request  } = event
  let { url      } = request
  let { referrer } = request
  let   headers    = toJs (toJson (request)) || {}

  return {
    url,
    referrer,
    headers
  }
}

function getResponse (data) {
  let headers  = HEADERS
  let text     = data
  let response = new Response (text, { headers })
  return response
}

function doRequest (event) {
  let request    = getRequest (event)
  let {id, wait} = getMessage (event)
  iChannel.postMessage ({ id, request })
  return wait
}

function getMessage (event) {
  let signal
  let wait = new Promise (function (ok) { signal = ok })
  let id   = idx++
  Messages.set (id, {
    send : function (data) {
      let response = getResponse (data)
      event.respondWith (response) // [1]
      signal (data)
    }
  })
  return { id, wait }
}

This is my Client:
const ICHANNEL = 'whale-ichannel' // Incoming Channel
const OCHANNEL = 'whale-ochannel' // Outgoing Channel

// Register worker ...

let iChannel = new BroadcastChannel (ICHANNEL)
let oChannel = new BroadcastChannel (OCHANNEL)
iChannel.addEventListener (MESSAGE, async function ({ data }) {
  let { id      } = data
  let { request } = data
  let response    = MyFancyResponse (...)
  oChannel.postMessage ({
    id,
    response
  })
})

When I run this code the following message error is emitted. See [1] in the Service Worker code. Please notice the entire communication flow is correctly executed.
Uncaught DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event handler is already finished.

If I do not misunderstand, that means when the worker is abandoned to find the client-side the fetch event is finished. So my approach is not valid. My question is: how can be done this kind of two-way communication where the request-response process is split via message events?

A: I think, the problem is, that the onFetch event needs immediate response with
event.respondWith()
If the onFetch doesn't get an event.respondWith, it generates one, and You cannot pass Your response later, and You'll get this error: The event handler is already finished.
So, instead of
self.addEventListener (FETCH, async function (event) {
  if (isRequest (event)) await doRequest (event)
})

I'd try
self.addEventListener (FETCH, function (event) {
    event.respondWith( ( async function() {
        if (isRequest (event)) return await doRequest (event); // note the RETURN
    }) () ); // note the (), what will call the inline async function to get a promise
})

and change the inner event.respondWith(xxx) to return xxx;

Please tell, if this solves the problem.


text:
Q: Creating a safe environment on (backup) server I want to use my server as backup server and let other users let their data backup to it aswell. I was thinking of using rsync instead of FTP (due to the obvious reasons), however how would I prevent user A to be browsing user B's files? If using rsync over SSH (preferable method due to encryption) then the user has to be CHrooted probably.
So, how can I set up a safe environment so users cannot browse eachother's files?

A: Even without chroot there's this little thing called file permissions.
Just make sure user home directories (/home/user or wherever they are located) have 0700, or u+rwx,go-rwx permissions, so they can't enter each other's directories at all.


text:
Q: ng-options filter based on text input value I have a select drop down in Angular based HTML like below. The requirement is to filter the drop down values based on the text the user enter in a text input box. The drop down value in this select is op
How do I add the filter.
<select class="form-control" size="12" data-ng-model="selItem.SelectedItems"
ng-options="option as displaycodeandlabel(option,selItem.isCodeonLabel)disable when option.disabled==true for option in ::a.sData"></select>

A: Not sure about your data structure, but generally you can just use the native filter.
Here's a working demo:

(function() {
  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.a = {};
    $scope.a.sData = [
       {
          "vm":"0000",
          "dm":"U.S. city average",
          "disabled":false
       },
       {
          "vm":"0100",
          "dm":"Northeast urban",
          "disabled":false
       },
       {
          "vm":"0200",
          "dm":"Midwest urban",
          "disabled":false
       }
    ];

    $scope.displayCodeandLabel = function(item, displayCode) {
      return displayCode ? item.vm + " " + item.dm : item.dm;
    }
  }
})();
<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">

    Search
    <input type="text" id="search" class="form-control" placeholder="Search" ng-model="search">

    <select class="form-control" size="12" data-ng-model="selItem.SelectedItems" ng-options="option as displayCodeandLabel(option, selItem.isCodeonLabel)
disable when option.disabled == true for option in a.sData | filter: search"></select>


text:
Q: What are the names of the Current Lords of Terra? In the most current timeline of the W40k universe it is M42.
Of the 12 Lords that are supposed to rule the Empire of Man I know only the name of one, Decius XXIII is Ecclesiarch of the Adeptus Ministorum as of 945.M41.
What are the names of the rest of the Lords?
Most current names are preferable (if nothing else can be found) as we know that with juvenant treatmants etc. these guys can prolong their lives considerably.
Ecclesiarch: Decius XXIII
EDIT
The second name that is now known is Roboute Guilliman who again holds his own original title as Lord Commander.
Lord Commander: Roboute Guilliman

A: Looking at the topic, I found this:

Determining who will hold the position of High Lord has resulted in millennia of political intrigue between the various bureaucracies seeking to increase their power. However, some organisations are so powerful, so fundamentally important to the Imperium, that their position on the Council is considered sacrosanct. For this reason the following nine offices are almost always represented as High Lords:

*

*The Master of the Administratum

*The Inquisitorial Representative

*The Ecclesiarch of the Adeptus Ministorum

*The Fabricator-General of the Adeptus Mechanicus

*The Grand Provost Marshal of the Adeptus Arbites

*The Paternoval Envoy of the Navigators

*The Master of the Astronomican

*The Grand Master of the Officio Assassinorum

*The Master of the Adeptus Astra Telepathica
The remaining three positions are most likely to be filled from among the
  following powerful leaders:

*

*Lord Commander of Segmentum Solar

*Lord Commander Militant of the Imperial Guard

*Cardinal(s) of the Holy Synod of Terra

*The Abbess of the Adepta Sororitas

*Captain-General of the Adeptus Custodes

*The Chancellor of the Estate Imperium

*The Speaker for the Chartist Captains

*Lord High Admiral of the Imperial Navy

Sadly apart from the ones that you have already named, only two other names are known:

*

*The Last Fabricator-General: Gastaph Hediatrix

*The Last Captain-General of the Adeptus Custode: Beyreuth
But these names are indicative because it is not known whether they are still active or not. (M36)
On the rest of the name, I have not been able to find anything in reliable sources.
SOURCE:

*

*Battlefleet Gothic 41st Millennium, pg. 86 //

*Codex: Assassins (2nd Edition), pg. 24 //

*Codex: Chaos Space Marines (3rd Edition, 2nd Codex), pg. 7 //

*Codex: Gray Knights (5th Edition) //

*Codex: Imperialis (2nd Edition) by Rick Priestley, pp. 13-14 //

*Codex: Orks (4th Edition), p. 92 //

*Codex: Sisters of Battle (2nd Edition), pp. 5, 13, 16 //

*Codex: Space Marines (6th Edition) (Digital Edition), pp. 36, 85, 100, //

*Codex: Ultramarines (2nd Edition), pg. Referring to Fig. //

*Codex: Witchhunters (3rd Edition), pg. Four. Five //

*Dark Heresy: Blood of Martyrs (RPG), p. 9, 12, 14, 17, 22 //

*Dark Heresy: Daemon Hunter (RPG), pg. 7 //

*Deathwatch: Core Rulebook (RPG), pp. 12, 285, 297, 323, 331-332 //

*Deathwatch: Rites of Battle (RPG), pp. 13-16, 38, 54, 65, 98, 247 //

*Deathwatch: The Achilus Assault (RPG), pp. 12, 14-15, 22, 102, 110, 119 //

*Horus Heresy: Visions of War //

*Warhammer 40,000: Rulebook (Digital Edition) (7th Edition), pp. 270, 275-278, 284, 286, 314, 323, 331, 335, 374, 381-382, 385, 387, 540-542 //

*Warhammer 40,000: Rulebook (6th Edition), pg. 403 //

*Warhammer 40,000: Rulebook (5th Edition), pg. 124 //

*Warhammer 40,000: Rulebook (4th Edition), pp. 9-10, 92 //

*White Dwarf 293 (UK), "Index Malleus: The Blood Pact", p. 57 //

*White Dwarf 140 (UK), "Space Fleet: Additional Background, Rules, Data Cards & Counters", p. fifty //

*False Gods (Novel) by Graham McNeill //

*Legion of the Damned (Novel) by Rob Sanders, pg. eleven //

*Wolfblade (Novel) by William King, pp. 32, 37, 70, 104 //

PS: Here I would miss the information of the last books but as they are about the heresy of Horus I don't know if they would contribute with anything ...


text:
Q: Create category on runtime/dynamically in Objective C I have a class BaseObject in my project, now I want to create category at runtime and add methods to them also at runtime.
Actually it's a framework project and I need to access one of the Class of Main project from Library project without any duplication. My main project has that BaseObject class and I need to execute some code of that class in my framework project.
I though category might be solution.
Please let me know how can I do that. I will try to give more information if required.
Thanks in advance.


text:
Q: Hive avro table schema not updated after setting properties of table from avro.schema.literal to avro.schema.url First i have cretaed a avro hive table as below.
CREATE EXTERNAL TABLE user
STORED AS AVRO
LOCATION '/work/user'
TBLPROPERTIES  ('avro.schema.literal'='{"type":"record","name":"user", "fields": [{ "name":"user_id", "type":["null","int"], "default":null, "columnName":"user_id", "sqlType":"4" }, { "name":"username", "type":["null","string"], "default":null, "columnName":"username", "sqlType":"-1" }], "tableName":"user"}')

I was able to see the data.
I have changed some schema, but this time, did by using below code.
ALTER TABLE user SET TBLPROPERTIES ('avro.schema.url'='/work/avro/user_schema.avsc')

New schema in url is as below.
{"type":"record","name":"user", "fields": [{ "name":"user_id", "type":["null","int"], "default":null, "columnName":"user_id", "sqlType":"4" }, { "name":"username", "type":["null","string"], "default":null, "columnName":"username", "sqlType":"-1" }, { "name":"city", "type":"string", "default":"Pune", "columnName":"city" }], "tableName":"user"}

Schema is not updated. Table shows only 2 fields i.e user_id and username.
The same thing works when schema is provided in literal as below.
ALTER TABLE user SET TBLPROPERTIES ('avro.schema.literal'='{"type":"record","name":"user", "fields": [{ "name":"user_id", "type":["null","int"], "default":null, "columnName":"user_id", "sqlType":"4" }, { "name":"username", "type":["null","string"], "default":null, "columnName":"username", "sqlType":"-1" }, { "name":"city", "type":"string", "default":"Pune", "columnName":"city" }], "tableName":"user"}');

But not by specifying url as specified above.
But this is not working. Table schema not getting updated.

A: The avro schema file needs to be in hdfs and reference could be like below.
TBLPROPERTIES ('avro.schema.url'='hdfs:///user/cloudera/categories.avsc')


text:
Q: What path should I install files to? I've searched everywhere and can't seem to find an answer... I've just switched from windows and am trying to get the hang of ubuntu 13.04. I just installed JDK7u40 with netbeans 7.3.1 but it defaulted to the home folder... I don't think this was right since all my other apps that were installed through software centre went somewhere else and it doesn't show up when I search using the superkey.
So where should/can I set the install path next time to better my allocation? For example, when I manually install eclipse android sdk, can I set the install path to "/usr/share"?
Help is most appreciated!

A: When I install software, I tend to do 1 of 2 things:

*

*If the software is via a deb file, I just let it install where it defaults to.

*If it's not, I tend to install stuff to the /opt/ dir (requires sudo-er privileges) and then add an appname.application file to /usr/share/applications so it shows up in dash.


text:
Q: Entity Framework - Rollback for Mix of Stored Procedures and Entities I need to call a few stored procedures (data inserts) plus update an entity value to the database.
I want these operations to be atomic, so if an error occurs, they all rollback.
In my code, if I force an exception to observe the behavior of the rollback, my entity changes are rolling back, but my stored procedure changes do not get rolled back.
Looking at the implementation for unit of work, it's just looking at _context.ChangeTracker.Entries() - I assume completely ignoring any stored procedure changes?
When I change the unit of work implementation to use
new System.Transactions.TransactionScope()

the rollback works as expected.
Should I be using new System.Transactions.TransactionScope()? Are there any gotchas?
Code
...
using (var scope = _unitOfWork.Begin())
{
    try
    {
        var outcome = _context.Database.ExecuteSqlCommand("SOME EXEC COMMAND", parameters);

        throw new Exception("Something happened");

        scope.Commit(); // Never gets called because of Exception
    }
    catch (Exception e)
    {
        scope.Rollback();
    }
}

Unit of work:
public class UnitOfWork : IUnitOfWork, ITransaction
{
    private readonly DbContext _context;
    private bool _committed;

    public UnitOfWork(DbContext context)
    {
        _context = context;
    }

    public ITransaction Begin()
    {
        _committed = false;
        return this;
    }

    public void Commit()
    {
        _context.SaveChanges();
        _committed = true;
    }

    public void Rollback()
    {
        foreach (var entry in _context.ChangeTracker.Entries())
        {
            switch (entry.State)
            {
                case EntityState.Modified:
                    entry.State = EntityState.Unchanged;
                    break;
                case EntityState.Added:
                    entry.State = EntityState.Detached;
                    break;
                case EntityState.Deleted:
                    entry.Reload();
                    break;
                case EntityState.Detached:
                    break;
                case EntityState.Unchanged:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    public void Dispose(bool disposing)
    {
        if (!disposing)
            return;

        if (!_committed)
        {
            Rollback();
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

A: Well yes - the Change Tracker of course can only track whatever you've changing / modifying / adding through means of the DbContext class.
Running a stored procedure is outside the scope of the EF Change Tracker - so if you base your "rollback" on simply things in the Change Tracker, you won't be able to properly handle anything your stored procedure have done.
Using TransactionScope is fundamentally different - this is an "umbrella" over all the database operations - including any stored procedures being executed - since it's basically on the database's level. So rolling back based on the transaction scope will roll back all database operations - whether handled via the EF DbContext, or via other means.


text:
Q: JSP Template in other file - Spring Boot I'm making a web application in spring boot. I have a lot of views created in JSP, but every view has the same footer and the same menu. Of course I can just copy all menu and footer code and paste it to 30 JSP but I would like to do somethink like this: I have file in which I have something like that menu="HTML CODE WITH MENU", and then in JSP in body section I just put {menu}, and all HTML code is put inside JSP. When I want to change my menu I will just change its code in "menu" variable/string or whatever it will be, and menu in all JSP will change. I tried a few solutions for example with include but it doesn't work. I search scritly the solution I have mentioned. Has anybody got any ideas how I can do this ?

A: Since you are using JSP you can use the standard JSTL <c:import> tag as explained here. The other options would be to use <%@ include @> or <jsp:include>, either of them will work for local files:
<jsp:include page="footer.jsp" />
<%@ include file="footer.jsp" %>
<c:import url="footer.jsp" />


text:
Q: django orm, backward relations, I have models as,
class Invoice():

class Entry():
   invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT, related_name='entries')
   amount = CurrencyField()

I have to calculate total amount for a invoice by backward relation

A: A CurrencyField [GitHub] stores a currency, like 'USD', not an amount of a given currency, so not 5 USD. You need a MoneyField to do this.
The modeling thus should look like:
from django.db import models
from djmoney.models.fields import MoneyField

class Invoice(models.Model):
    pass

class Entry(models.Model):
    invoice = models.ForeignKey(
        Invoice, on_delete=models.PROTECT, related_name='entries'
    )
    amount = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
You can sum up the currency of an invoice with:
from django.db.models import Sum

my_invoice.entries.aggregate(total=Sum('amount'))['total']
this will only work if the amounts all have the same currency.


text:
Q: Find the biggest interval that has all its members in list in O(n) I was asked this in an interview. Given a list of integers, How can we find the biggest interval that has all its members in the given list?
E.g. given list 1,3,5,7,4,6,10 then answer would be [3, 7]. Because it has all the elements between 3 and 7.
I tried to answer but I wasn't convincing. The approach I took was to first sort the list and then check it for the biggest interval. But I was asked to do so in O(n).

A: If sorting is not desirable, you can use a combination of hash map and Disjoint-set data structure.
For each element in the list create a node and insert it into hash map with key = element's value. Then query the hash map for value+1 and value-1. If anything is found, combine current node with set(s) where adjacent nodes belong. When finished with the list, the largest set corresponds to the biggest interval.
Time complexity is O(N * α(N)) where α(N) is inverse Ackermann function.
Edit: Actually Disjoint-set is too powerful for this simple task. Solution by Grigor Gevorgyan does not use it. So it is simpler and more efficient.

A: You can trade off space to get this in linear time.

*

*Scan the list for the smallest and largest values, S and L.

*Use an array of booleans or a bitvector, A, large enough to hold (L - S + 1) entries.

*Go through the list again, setting the appropriate element of A to true when you see it.

*Now, A is sorted. Go through A and find the largest consecutive set of true values.

The first steps are linear in your list. The last is linear in the size of A, which could be large relative to your list if you have just a few values which are far apart. But, since you're dealing with ints, A is bounded.

A: I know a solution based on hashing and dynamic programming. Let f(x) be the hash function. The trick is the hash-table value. Consider the longest interval contained in the list, which either starts or ends with x. Then h[f(x)] = y, where y is the other end of that interval. Note that length of that interval will be abs( x - y ) + 1.  The algorithm description will make clear why to store that value.
Move over the list. Let i be current index, x := list[ i ] - current number. Now

1. if h[f(x)] is not empty, then we've met number x before. Nothing to do, continue.

2. Check h[f(x-1)] and h[f(x+1)].
2.1. If they're both not empty, that means we've already met x-1 and x+1, and we know some intervals [a..x-1] and [x+1..b] which we've already met in the list. We know it because a=h[f(x-1)] and b=h[f(x+1)] by definition of h. Now when we got x, it means that we now have met the whole interval [a,b], so we update values as follows: h[f(a)] := b and h[f(b)] := a.
Also set h[f(x)] to some value (let's say x, not to impact the answer), just so that next time we meet x in the list, we ignore it. x has already done his job.
2.2. If only one of them is set, let's say h[f(x-1)] = a, that means we've already met some interval [a..x-1], and now it's extended with x. Update will be h[f(a)] := x and h[f(x)] := a.
2.3. If none of them is set, that means we've met neither x-1, nor x+1, and the biggest interval containing x we've already met is the single [x] itself. So set h[f(x)] := x.
Finally, to get the answer, pass over the whole list and take maximum abs( x - h[f(x)] ) + 1 for all x.

A: 1 idea: well, I think you have to kinda sort the list anyway, but you can't go with merge or quick sort. But if you have memory, you could use idea from counting sort for integers.
So you can create array of 0 and 1, from 0 to max int value, then fill it with ones if you have value and then find maximum continous array
2 idea: create dictionary of values, find min and max - all O(N) operations:
dict = {1: 1, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 10: 10}
min = 1
max = 10

then, go like i in range(min, max) and and find longest continuous subset
>>> d = [1, 3, 5, 7, 4, 6, 10]
>>> s = set(d)
>>> mind = min(d)
>>> maxd = max(d)
>>> a, b, j = 0, 0, 0

>>> for i in range(mind, maxd):
        if i not in s:
            if (b - a) < (i - j - 1):
                a, b = j, i - 1
            j = i + 1

>>> a, b
(3, 7)

but this could be slow for sparse lists like [1, 9000, 100000]
EDIT: based on super great answer of Grigor Gevorgyan, here's the code for O(N) dictionary solution  in Python (I just love it's simplicity!!!)
l = [1, 3, 5, 7, 4, 6, 10]
d = {x:None for x in l}
print d
for (k, v) in d.iteritems():
    if v is not None: continue
    a, b = d.get(k - 1), d.get(k + 1)
    if a is not None and b is not None: d[k], d[a], d[b] = k, b, a
    elif a is not None: d[a], d[k] = k, a
    elif b is not None: d[b], d[k] = k, b
    else: d[k] = k
    print d

m = max(d, key=lambda x: d[x] - x)
print m, d[m]

output:
{1: None, 3: None, 4: None, 5: None, 6: None, 7: None, 10: None}
{1: 1, 3: None, 4: None, 5: None, 6: None, 7: None, 10: None}
{1: 1, 3: 3, 4: None, 5: None, 6: None, 7: None, 10: None}
{1: 1, 3: 4, 4: 3, 5: None, 6: None, 7: None, 10: None}
{1: 1, 3: 5, 4: 3, 5: 3, 6: None, 7: None, 10: None}
{1: 1, 3: 6, 4: 3, 5: 3, 6: 3, 7: None, 10: None}
{1: 1, 3: 7, 4: 3, 5: 3, 6: 3, 7: 3, 10: None}
{1: 1, 3: 7, 4: 3, 5: 3, 6: 3, 7: 3, 10: 10}
3 7

A: I crafted a very straightforward solution using a HashSet.  Since contains and remove are O(1) operations, you can simply create a new interval from a random set item and 'expand' the interval it until you discover its full size, removing items from the set as you go along.  The removal is key, because this is what prevents you from 'repeating' any intervals.
It might help to think about it this way - the list has K intervals, whose sizes add up to N.  Your task, then, is to discover what these intervals are, without repeating any intervals or items.  This is why the HashSet is perfect for the job - you can efficiently remove items from the set as you expand your intervals.  Then all you need to do is keep track of the largest interval as you go along.

*

*Put the list into a HashSet

*While the set is non-empty:

*

*remove an item at random from the set

*Define a new interval from that item

*Expand the interval as follows:

*

*Define i = interval.start-1

*While the set contains i, remove i from the set and decrement both i and interval.start

*Repeat step 2 in the other direction (expand up from interval.end)

*If the expanded interval is larger than the previously largest interval, record the new interval as the largest interval

*Return the largest interval

Here is the solution in Java:
public class BiggestInterval {

    static class Interval {
        int start;
        int end;

        public Interval(int base) {
            this(base,base);
        }

        public Interval(int start, int end) {
            this.start = start;
            this.end = end;
        }

        public int size() {
            return 1 + end - start;
        }

        @Override
        public String toString() {
            return "[" + start + "," + end + "]";
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(biggestInterval(Arrays.asList(1,3,5,7,4,6,10)));
    }

    public static Interval biggestInterval(List<Integer> list) {
        HashSet<Integer> set = new HashSet<Integer>(list);
        Interval largest = null;

        while(set.size() > 0) {
            Integer item = set.iterator().next();
            set.remove(item);

            Interval interval = new Interval(item);
            while(set.remove(interval.start-1)) {
                interval.start--;
            }
            while(set.remove(interval.end+1)) {
                interval.end++;
            }

            if (largest == null || interval.size() > largest.size()) {
                largest = interval;
            }
        }

        return largest;
    }
}

A: That would be linear considering dictionaries built with average O(1) hash tables.
L = [1,3,5,7,4,6,10]

a_to_b = {}
b_to_a = {}

for i in L:
    if i+1 in a_to_b and i-1 in b_to_a:
        new_a = b_to_a[i-1]
        new_b = a_to_b[i+1]
        a_to_b[new_a] = new_b
        b_to_a[new_b] = new_a
        continue
    if i+1 in a_to_b:
        a_to_b[i] = a_to_b[i+1]
        b_to_a[a_to_b[i]] = i
    if i-1 in b_to_a:
        b_to_a[i] = b_to_a[i-1]
        a_to_b[b_to_a[i]] = i
    if not (i+1 in a_to_b or i-1 in b_to_a):
        a_to_b[i] = i
        b_to_a[i] = i

max_a_b = max_a = max_b = 0
for a,b in a_to_b.iteritems():
    if b-a > max_a_b:
        max_a = a
        max_b = b
        max_a_b = b-a

print max_a, max_b

A: Here's a solution similar to Grigor's.  Two main differences are that this solution stores the length of the sequential set instead of other indexes and that this eliminates the need for the last hash-set iteration.

*

*Iterate over the array

*

*Build a hashmap by looking for and updating adjacent set endpoints:
Key - The array values
Value - When the key is an endpoint of a sequential set, store the length of that set.  Otherwise, keep it truthy so you only consider things once.

*If the current set size is longest, update the longest set size and longest set start.
Here's a JavaScript implementation for clarity, as well as a fiddle to see it in action:
var array = [1,3,5,7,4,6,10];

//Make a hash of the numbers - O(n) assuming O(1) insertion
var longestSetStart;
var longestSetSize = 0;

var objArray = {};
for(var i = 0; i < array.length; i++){
    var num = array[i];

    if(!objArray[num]){//Only consider numbers once
        objArray[num] = 1;//Initialize to 1 item in the set by default

        //Get the updated start and end of the current set
        var currentSetStart = num;//Starting index of the current set
        var currentSetEnd = num;//Ending index of the current set

        //Get the updated start of the set
        var leftSetSize = objArray[num - 1];
        if(leftSetSize){
            currentSetStart = num - leftSetSize;
        }

        //Get the updated end of the set
        var rightSetSize = objArray[num + 1];
        if(rightSetSize){
            currentSetEnd = num + rightSetSize;
        }

        //Update the endpoints
        var currentSetSize = currentSetEnd - currentSetStart + 1;
        objArray[currentSetStart] = currentSetSize;
        objArray[currentSetEnd] = currentSetSize;

        //Update if longest set
        if(currentSetSize > longestSetSize){
            longestSetSize = currentSetSize;
            longestSetStart = currentSetStart;
        }
    }
}

var longestSetEnd = longestSetStart + longestSetSize - 1;

A: The trick is to think of the items as a set instead of a list. This allows you to identify items that are at the start or end of contiguous ranges, because a set lets you check if item-1 or item+1 is present. With that, you can solve the problem in linear time and space.
Pseudo-Code:

*

*Enumerate the items in the set, looking for ones that are at the start of a range (x starts a range when x-1 is not in the set).

*For each value that is the start of a range, scan upwards until you find the corresponding end of range value (x ends a range when x+1 is not in the set). This gives you all the relevant contiguous ranges.

*Return the contiguous range whose end was furthest from its start.

C# Code:
static Tuple<int, int> FindLargestContiguousRange(this IEnumerable<int> items) {
    var itemSet = new HashSet<int>(items);

    // find contiguous ranges by identifying their starts and scanning for ends
    var ranges = from item in itemSet

                 // is the item at the start of a contiguous range?
                 where !itemSet.Contains(item-1)

                 // find the end by scanning upward as long as we stay in the set
                 let end = Enumerable.Range(item, itemSet.Count)
                           .TakeWhile(itemSet.Contains)
                           .Last()

                 // represent the contiguous range as a tuple
                 select Tuple.Create(item, end);

     // return the widest contiguous range that was found
     return ranges.MaxBy(e => e.Item2 - e.Item1);
}

note: MaxBy is from MoreLinq
Testing
Small sanity check:
new[] {3,6,4,1,8,5}.FindLargestContiguousRange().Dump();
// prints (3, 6)

Big contiguous list:
var zeroToTenMillion = Enumerable.Range(0, (int)Math.Pow(10, 7)+1);
zeroToTenMillion.FindLargestContiguousRange().Dump();
// prints (0, 10000000) after ~1 seconds

Big fragmented list:
var tenMillionEvens = Enumerable.Range(0, (int)Math.Pow(10, 7)).Select(e => e*2);
var evensWithAFewOdds = tenMillionEvens.Concat(new[] {501, 503, 505});
evensWithAFewOdds.FindLargestContiguousRange().Dump();
// prints (500, 506) after ~3 seconds

Complexity
This algorithm requires O(N) time and and O(N) space, where N is the number of items in the list, assuming the set operations are constant time.
Note that if the set was given as an input, instead of being built by the algorithm, we would only need O(1) space.
(Some comments say this is quadratic time. I think they assumed all items, instead of just items at the starts of ranges, triggered scans. That would indeed be quadratic, if the algorithm worked that way.)

A: I think I would have sorted them into lists of consecutive integers (assuming each number can appear only once)
take first number
if the number 1 lower than or 1 higher than a number in an existing list?
yes: pre/post pend existing list
no : create a new list starting with the current number
if there are more numbers, return to top
display the longest list

A: Disclaimer: Since the solution is based on hashtables, the running times are expected, not worst case.
This O(n) solution depends on the integers being unique. If they are not unique, make a hashset with O(1) insertion and membership lookup, and just skip the numbers already encountered, as you go through the list.

*

*Make a O(1) lookup/insert hashmap where the values are the beginnings of ranges, and the keys are the numbers that fit at the end of those ranges. For a value v and a key k, this means that the range starting from v and ending with k-1 inclusive is located at key k.

*Go through the list of numbers. For each number n check if the map has a value v at key n. This corresponds to there being a range starting from v that would allow n at the end. If there is, move v to key n+1 and delete the entry at key n. If there isn't any range, insert n at key n+1.

*Since the numbers are unique, none of the ranges overlap in the end, but there may be some contiguous ones. Run through the key/value pairs of the map. For each key k and value v, if the map has a value v1 at key k1 = v, then it means that there is a range from v1 to k-1. Insert v1 at k, and delete the entry k1/v1.

*Go through the k/v entries of the map to find the largest range [v,k-1] of size k-v, using a running maximum.
For your example:
setup:
l = [1,3,5,7,4,6,10]
m = {}

iteration:
process 1  : m = {2->1}
process 3  : m = {2->1, 4->3}
process 5  : m = {2->1, 4->3, 6->5}
process 7  : m = {2->1, 4->3, 6->5, 8->7}
process 4  : m = {2->1, 5->3, 6->5, 8->7}
process 6  : m = {2->1, 5->3, 7->5, 8->7}
process 10 : m = {2->1, 5->3, 7->5, 8->7, 11->10}

concatenation of contiguous ranges:
initial:              m = {2->1, 5->3, 7->5, 8->7, 11->10}
first concatenation:  m = {2->1,       7->3, 8->7, 11->10}, k=7, v=5, k1=5, v1=3
second concatenation: m = {2->1,             8->3, 11->10}, k=8, v=7, k1=7, v1=3

result:
largest range : [3,7] of size 5


text:
Q: Update a count variable in model object What I want to do is simple I want to update the count variable of the object every time my view function is called.
My models is like this:
class Url(models.Model):
      #some vars here
      count=0

      def __unicode__(self):
            return self.urlx
      def incr(self):
            self.count+=1

and my view code is like this
@transaction.autocommit
def redirect(request,key):
    if(key):
        key='/'+key
        try:
            ob=Url.objects.get(urlx=key)
            ob.incr()  #not working
            ob.save()  #not working
            return HttpResponseRedirect(ob.url)
            val=ob.count
        except Url.DoesNotExist:
            key="Sorry! couldn't find that url"

    return render_to_response('redir.html',{},context_instance=RequestContext(request))

I am sure I am overlooking something here, or is this not the correct way to do this?

A: Since you've missed out the "other vars here", it's not clear if you realize that Django model fields need to be, well, fields - that is, models.CharField, models.IntegerField, etc. Putting count=0 just makes a class variable that won't be persisted in the database. You probably just want count = models.IntegerField(default=0).


text:
Q: Django: Sort Items in Dropdown (via field_order?) I am using a dropdown on a template. I do want an alphabetical order in that dropdown and don't know how to get this.
template.html:
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <fieldset>
        {{ form|crispy }}
    </fieldset>
    <div>
        <button type="submit">OK</button>
    </div>
</form>

The context comes from views.py:
def my_view(request):

    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():

            …

    return render(request, 'xxx/template.html', {'form': form})

The form is defined in forms.py:
from django import forms

from .models import Project

class MyForm(forms.Form):
    project = forms.ModelChoiceField(queryset=Project.objects)
    field_order = ['name', ]

models.py:
class Project(models.Model):
    name = models.CharField()
    …

The documentation talks about field_order. The line field_order = ['name', ] in form.py has no effect.
What's wrong?

A: You can order them by changing your query to
queryset=Project.objects.order_by("name")
or if you need reverse order ...order_by("-name").

A: As documentation states this is ordering of form fields
for example of:
class MyForm(forms.Form):
    project = forms.somefield
    name = forms.somefield
    field_order = ['name', ]

would show name prior to project in form

What you want is change sort order of ModelChoiceField that means you should change your queryset argument
forms.ModelChoiceField(Project.objects.order_by('name'))


text:
Q: Function activates whenever images load This is related to my previous question where the HTML is located: Grouping siblings into a div
I found it hard to explain what I was attempting to accomplish so I drew up a quick wireframe representation:

I found a different solution from grouping the content and getting the visual that is desired. The image is being held in an anchor tag so I used jQuery to find the tallest img on the page and apply that height to the containing a tag. So instead of vertical-align bottom with a fixed height set to the content I have vertical-aligned the content to the top with a Maximum Height set to the Anchor Tag and vertical-aligned the image in that tag to the bottom.

var maxHeight = 0;

$('.Product img').each(function() {
    maxHeight = Math.max(maxHeight, $(this).height()); })

$('.ProductThumbnail').css({"height":maxHeight});

The code works perfectly. However, some of the categories have several pages and when you select the "Next Page" link the eCommerce solution uses jQuery to load in the page dynamically and the code breaks.
So, my question is "How can I have the function listed above onLoad whenever images are loaded onto the page?"
[note 1:] I have already attempted to use imagesloaded by desandro and it did not work as I had hoped it would.
[note 2:] I would also like the maxHeight to be matched for each row rather than the entire page, as the TD's are kept within TR's.
[note 3:] I can not alter the html at all. I am only allowed to make addendums to the head, a custom Header, and a custom footer. The content is uneditable.

A: in your case you should , or have to use this function
$('img').ready(function(){
    console.log('image is loaded');

})

it will see if the element is loaded and then preform the function ...
here is an example
jsfiddel

A: You could attach a delegate to each tr (which is triggered whenever a child img fires the ready event) that recalculates that row's height:
$("table#tableId tr").on("ready", "img", function(){
       var maxHeight = 0;

       $(this).find('.Product img').each(function() {
           maxHeight = Math.max(maxHeight, $(this).height()); })

       $(this).find('.ProductThumbnail').css({"height":maxHeight});
    })
});

ETA:
This code uses the live() method to delegate the event. With this method you can bind events to elements that do not exist yet. Note that live() is deprecated, and on() should be used, but to delegate with on() you need a parent element that is not replaced.
$("table#tableId img").live("ready",  function(){
       var maxHeight = 0;
       var $row = $(this).parents("tr");
       $row.find('img').each(function() {
           maxHeight = Math.max(maxHeight, $(this).height()); })

       $row.find('.ProductThumbnail').css({"height":maxHeight});
    })
});


text:
Q: Rails / ActiveRecord: how to get all articles whose tags are included in current article tags? This one is a head scratcher!
I'm trying to get all articles whose categories are included in current article's categories.
What I have so far, which is wrong of course:
@rq = Article.includes(:tags).where(tags: { name: @article.tags.first.name })

There is a join table setup between Article and Tag (has_and_belongs_to Tag and has_and_belongs_to Article). Essentially I can access all tags of current article with @article.tags and all articles of current tag with @tag.articles.

A: Should be something easy like:
@rq = Article.joins(:tags).where(tags: {id: @article.tag_ids})

If I understood your requirement correctly.


text:
Q: Como transformar um texto selecionado para caixa baixa no VSCode? Gostaria de transformar um trecho de código em caixa baixa no VSCode. Obter um efeito similar ao do CTRLSHIFTY do Eclipse?
Algo que seja semelhante ao gif abaixo:

A: Cara o VS Code tem uma forma de pesquisar e substituir strings usando regex aqui tem um artigo que pode te ajudar nisso https://dev.to/rfornal/vs-code-search-and-replace-regex-mn2

Mas como não manjo de Regex aqui tem um exemplo manual. Mas só consegui fazer com uma string por vez... Vale lembrar que vc pode tb definir se quer usar o case sencitive na substituição

Criando um Atalho
Vc  pode  criar um atalho de teclado para transforma o que estiver selecionado para Upper, ou Lower Case conforme imagem abaixo. Basta vc entrar nos Settings e procurar por Keyboard Shortcut

A: *

*Selecione o texto a ser transformado. Use Ctrl + L para selecionar
toda a linha;

*Abra Mostrar todos os comandos. Linux e Windows: Ctrl + Shift + P,
Mac: ⇧⌘P;

*Digite o comando, por exemplo: lowercase, uppercase, titlecase;

*Aguarde o preenchimento automático;

*Pressione Enter.