text:
Q: missing __attribute__ ((constructor)) support when building glibc for aarch64 i am trying to build an image for ARM with OpenEmbedded/Yocto
while building glibc i get the following error message:
[...]
| checking whether to use .ctors/.dtors header and trailer... configure: error: missing __attribute__ ((constructor)) support??
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_configure (log file is located at /home/server/git/poky/build/tmp/work/aarch64-poky-linux/glibc-initial/2.28-r0/temp/log.do_configure.21953)
ERROR: Task (/home/server/git/poky/meta/recipes-core/glibc/glibc-initial_2.28.bb:do_configure) failed with exit code '1'

the layer i am trying to build the layer meta-openwrt
my local.conf looks like this:
MACHINE ?= "jetson-tx1"
DISTRO ?= "poky"
PACKAGE_CLASSES ?= "package_rpm"
EXTRA_IMAGE_FEATURES ?= "debug-tweaks"
USER_CLASSES ?= "buildstats image-mklibs image-prelink"
PATCHRESOLVE = "noop"
BB_DISKMON_DIRS ??= "\
    STOPTASKS,${TMPDIR},1G,100K \
    STOPTASKS,${DL_DIR},1G,100K \
    STOPTASKS,${SSTATE_DIR},1G,100K \
    STOPTASKS,/tmp,100M,100K \
    ABORT,${TMPDIR},100M,1K \
    ABORT,${DL_DIR},100M,1K \
    ABORT,${SSTATE_DIR},100M,1K \
    ABORT,/tmp,10M,1K"
PACKAGECONFIG_append_pn-qemu-native = " sdl"
PACKAGECONFIG_append_pn-nativesdk-qemu = " sdl"
CONF_VERSION = "1"
SSTATE_MIRRORS = "\
     file://.* http://sstate.yoctoproject.org/dev/PATH;downloadfilename=PATH \n \
     file://.* http://sstate.yoctoproject.org/2.5/PATH;downloadfilename=PATH \n \
     file://.* http://sstate.yoctoproject.org/2.6/PATH;downloadfilename=PATH \n \
     "
IMAGE_CLASSES += "image_types_tegra"
IMAGE_FSTYPES = "tegraflash"
TARGET_CFLAGS += " -lcrypt"

With the help of google i found some mailinglists where someone says that i need to add "'libc_cv_ctors_header=yes' to the end of the configure invocation".
But i do not know how to do that.
core-image-sato works.

A: I've just met this problem, you saw the answer here:
http://lists.linuxfromscratch.org/pipermail/lfs-dev/2011-August/064955.html
https://www.linuxquestions.org/questions/linux-from-scratch-13/error-compiling-glibc-2-28-in-lfs-8-3-a-4175644816/
adding 'libc_cv_ctors_header=yes' to the end of the configure invocation
means to add libc_cv_ctors_header=yes to the end of the ./configure args, as the guy on linuxquestions.org did in his answer


text:
Q: primefaces input components shows the old data upon validation I am using primefaces3.3 version. I have a datatable to show the details and the CRUD buttons as part of the footer of the datatable. A Dialog would be shown on click of the CRUD buttons after selecting a particular row in the datatable.
This dialog contains the input fields with requiredMessage and validationMessage properties and a Save button. When i do not enter any input and click on the save button in the dialog the validation message is showing up. However, upon closing the dialog , only the old data is showing up even if a different row is selected in the datatable. I have attached both the BackingBean and xhtml code.
account.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org  /TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
 <h:head>
 </h:head>
 <h:body>
 <ui:composition template="/template.xhtml">
    <ui:define name="body">
        <h:form id="form" prependId="false">
            <p:contextMenu for="dataTable">
                <p:menuitem value="View" update=":form2:accountDisplay"
                    icon="ui-icon-search" oncomplete="accountDialog.show()"
                    process="@this">
                    <f:setPropertyActionListener value="#{account}"
                        target="#{accountBean.selectedAccount}" />
                </p:menuitem>
                <p:menuitem value="Edit" update=":form2:accountDisplay"
                    icon="ui-icon-edit" oncomplete="accountDialog.show()"
                    process="@this" immedeate="true">
                    <f:setPropertyActionListener value="#{account}"
                        target="#{accountBean.currentAccount}" />
                </p:menuitem>
                <p:menuitem value="Delete" update=":dialogForm:confirmDialog"
                    icon="ui-icon-close" oncomplete="confirmation.show()" />
            </p:contextMenu>

            <h:panelGroup id="dataPanel">
                <p:dataTable var="account" value="#{accountBean.accounts}"
                    paginator="true" rows="20" rowKey="#{account.accountCode}"
                    paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                    selection="#{accountBean.selectedAccount}" selectionMode="single"
                    id="dataTable">
                    <p:column id="accountCode" headerText=" Account Code"
                        sortBy="#{account.accountCode}" filterBy="#{account.accountCode}"
                        filterMatchMode="startsWith" footerText="startsWith">
                        <h:outputText value="#{account.accountCode}" />
                    </p:column>
                    <p:column id="accountCode" headerText=" Account Code"
                        sortBy="#{account.accountDescription}" filterBy="#{account.accountDescription}"
                        filterMatchMode="startsWith" footerText="startsWith">
                        <h:outputText value="#{account.accountDescription}" />
                    </p:column>
                <f:facet name="footer">
                    <p:toolbar>
                    <p:toolbarGroup align="left">
                                    <p:commandButton id="btnAdd" value="Add" title="Add New Account"
                            icon="ui-icon-add"
                            oncomplete="accountDialog.show()" />
                        <p:commandButton id="editButton" value="Edit" icon="ui-icon-edit"
                            update=":form2:accountDisplay" oncomplete="accountDialog.show()">

                        </p:commandButton>
                        <p:commandButton id="showDialogButton" icon="ui-icon-delete"
                            value="Delete"
                            title="Delete Account Details" oncomplete="confirmation.show()">
                        </p:commandButton>
                        <p:commandButton id="viewButton" value="View"
                            icon="ui-icon-search" update=":form2:display"
                            oncomplete="accountDialog.show()" />
                        <p:commandButton id="btnRefresh" styleClass="refreshButton"
                            title="Refresh Account Information" value="Refresh"
                            icon="ui-icon-refresh"
                            actionListener="#{accountBean.populateAccounts}"
                            update=":form:dataTable"/>
                    </p:toolbarGroup>
                    </p:toolbar>
                    </f:facet>
                </p:dataTable>

            </h:panelGroup>
        </h:form>
        <h:form id="form2">
            <!--  <p:growl id="growl" showDetail="true" sticky="true" /> -->
            <p:dialog id="basicDialog" header="Account Details"
                widgetVar="detailDialog" resizable="false">

                <h:panelGrid id="display" columns="2">
                    <h:outputText value="#{bundle.AccountLabel_accountCode}" />
                    <h:outputText value="#{accountBean.selectedAccount.accountCode}"
                        title="#{bundle.AccountTitle_accountCode}" />

                    <h:outputText value="#{bundle.AccountLabel_accountDescription}" />
                    <h:outputText value="#{accountBean.selectedAccount.accountDescription}"
                        title="#{bundle.AccountTitle_alertCode}" />
                </h:panelGrid>
            </p:dialog>
            <p:dialog header="Account Detail" widgetVar="accountDialog"
                resizable="false" height="600" width="600" showEffect="clip"
                hideEffect="fold" id="dialog" modal="true">

                <h:panelGrid id="accountDisplay" columns="2" cellpadding="4">

                    <f:facet name="header">
                        <p:messages id="messages" autoUpdate="true" />
                    </f:facet>

                    <h:outputLabel value="Account Code:" for="accountCode" />
                    <p:inputText label="Account Code" id="accountCode"
                        value="#{accountBean.selectedAccount.accountCode}"
                        title="Account Code" required="true"
                        validatorMessage="#{bundle.AccountValidationAccountCode}" requiredMessage="#{bundle.AccountRequiredMessage_accountCode}">

                    </p:inputText>
                    <h:outputLabel value="Account Description:" for="accountDescripition" />
                    <p:inputText label="Account Description" id="accountDescription"
                        value="#{accountBean.selectedAccount.accountDescription}"
                        title="Account Description" required="true"
                        validatorMessage="#{bundle.AccountValidationAccountDescription}" requiredMessage="#{bundle.AccountRequiredMessage_accountDescription}">

                    </p:inputText>
                    <f:facet name="footer">
                        <!-- <p:commandButton value="New" icon="ui-icon-check"/> -->
                        <h:outputLabel />
                        <p:commandButton styleClass="saveButton" value="Save"
                            icon="ui-icon-check"
                            actionListener="#{accountBean.createOrUpdate}"
                            update=":form:dataTable,:form2:accountDisplay" oncomplete="if (!args.validationFailed) {accountDialog.hide();}"/>

                        <p:commandButton styleClass="cancelButton" value="Cancel"
                            icon="ui-icon-cancel" oncomplete="accountDialog.hide()" process="@this"/>

                    </f:facet>
                </h:panelGrid>
            </p:dialog>

        </h:form>

        <h:form id="dialogForm">
            <p:confirmDialog id="confirmDialog" header="Confirm Delete Account"
                severity="alert" widgetVar="confirmation">
                <f:facet name="message">
                    <h:outputText
                        value="Delete #{accountBean.selectedAccount.accountCode}?" />
                </f:facet>

                <p:commandButton id="confirm" value="Yes"
                    oncomplete="confirmation.hide()" update=":form:dataTable"
                    actionListener="#{accountBean.remove}" ajax="false"/>
                <p:commandButton id="decline" value="No"
                    onclick="confirmation.hide()" type="button" ajax="false"/>
            </p:confirmDialog>
        </h:form>
    </ui:define>
</ui:composition>

AccountBean.java
   package com.cba.web.beans;

   import java.io.Serializable;
   import java.util.List;

   import javax.faces.bean.ManagedBean;
   import javax.faces.bean.ViewScoped;
   import javax.faces.context.FacesContext;
   import javax.faces.event.ActionEvent;

   import org.primefaces.context.RequestContext;

   import com.cba.services.AccountService;
   import com.cba.utils.ServiceLocator;
   import com.cba.web.model.Account;

   @ManagedBean(name = "accountBean")
   @ViewScoped
   public class AccountBean implements Serializable {

   private transient AccountService accountService;

   private List<Account> accounts;

   private Account selectedAccount = new Account();

private Account currentAccount = new Account();

public Account getSelectedAccount() {
    return selectedAccount;
}

public void setSelectedAccount(Account selectedAccount) {
    this.selectedAccount = selectedAccount;
}

public Account getCurrentAccount() {
    return currentAccount;
}

public void setCurrentAccount(Account currentAccount) {
    this.currentAccount = currentAccount;
}

public AccountBean() {

    populateAccounts();
}

public AccountService getAccountService() {
    return accountService;
}

public void setAccountService(AccountService accountService) {
    this.accountService = accountService;
}

public List<Account> getAccounts() {
    return accounts;
}

public void populateAccounts() {
    accountService = (AccountService) ServiceLocator.getInstance().getBean(
            "accountService");
    accounts = accountService.getAccountDetails();
}

public void createOrUpdate(ActionEvent e) {
    try {

        System.out.println("entering createOrUpdate in AccountBean");
        accountService = (AccountService) ServiceLocator.getInstance()
                .getBean("accountService");
        accountService.updateAccountDetails(selectedAccount);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public void remove(ActionEvent e) {
    try {
        accountService = (AccountService) ServiceLocator.getInstance()
                .getBean("accountService");
        accountService.deleteAccountDetails(selectedAccount);
        selectedAccount = new Account();
        populateAccounts();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

}
I am using Google Chrome 19 and IE 8. Any input on this would be appreciated. Thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Attributes to a subclass of pandas.DataFrame disappear after pickle I am trying to add attributes to a subclass of pandas.DataFrame and they disappear after pickling and unpickling:
import cPickle
import pandas as pd

class MyClass(pd.DataFrame):
    def __init__(self):
        super(MyClass, self).__init__()
        self.bar = 1

myc = MyClass()
with open('myc.pickle', 'wb')as myfile:
    cPickle.dump(myc,myfile)
with open('myc.pickle', 'rb')as myfile:
    b = cPickle.load(myfile)
print b.bar

Output:
Traceback (most recent call last):
File "test_df.py", line 14, in <module>
print b.bar
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1771, in __getattr__
(type(self).__name__, name))
AttributeError: 'MyClass' object has no attribute 'bar'

Any idea how I can add attributes safely?

A: This is unrelated to subclassing. Pandas objects' attributes do not serialize.
You can read this thread for a discussion and a workaround. The topic has resurfaced again in this other recent thread.

A: You can use the @property decorator to do something similar:
class MyClass(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)
        self.foo = 1

    @property
    def bar(self):
        return 1

MyClass.foo will not be available after pickling, but MyClass.bar will be there (as of now, read only).


text:
Q: The solution of congruences system. From the answer of user1952009: https://math.stackexchange.com/q/2273035.
Looking for the general solution of system for prime $p$ and $q$: $$q^2+q+1\equiv 0 \bmod p\\ p^2+p+1\equiv 0 \bmod q$$
EDITED: The following solution found:
$$p=3,q=13\\p=13,q=61\\p=22419767768701,q=107419560853453$$


text:
Q: Determining Values of Parameters so that Observation Equation is Stationary
Consider a system process given by $x_t=-0.9x_{t-2}+z_t$,$t=1,2,…,n$ with observation $y_t=x_t+v_t$  where ${z_t}$ and ${v_t}$ are independent white noise with variances $σ^2$ and $σ_v^2$.
Assume that $x_0\sim \mathcal N(0,σ_0^2)$ and $x_{-1}\sim \mathcal N(0,σ_1^2)$, and that $x_0$ and $x_{-1}$ are independent. Find the values of $\sigma_0^2$ and $\sigma_1^2$ that make the observations, $y_t$, stationary.

So for $y_t$ to be stationary, it must have a constant mean and autocovariance function independent of time. The mean is obviously zero, since $x_t$ must have mean zero since it's an $AR(2)$ process, and $v_t$ has mean zero.
The autocovariance function is a sum of the autocovariance of the $AR(2)$ process $x_t$ and $v_t$. For $t=1$ we obtain $\gamma_y(0) =  cov(-0.9x_{-1} + z_1,-0.9x_{-1} + z_1) = 0.9^2 \sigma_1^2 + \sigma^2$. Similarly, for $t=2$ we get $\gamma_y(0) = 0.9^2 \sigma_0^2 + \sigma^2$. In the general case, the autocovariance is $$ \gamma_y(0) = \frac{\sigma^2}{1 - (-0.9)^2} + \sigma_v^2$$ for $t \neq 1,2$ and $\gamma_y(2k) = (-0.9)^k \big(\gamma_y(0) - \sigma^2_v \big) + \sigma^2_v$ for $k = 1,2,...$ and $\gamma_y = 0$ otherwise.
$\gamma_y(0)$ can clearly be made stationary by choosing the correct values of $\sigma_0^2$ and $\sigma_1^2$. However $\gamma_y(2k)$ is not stationary regardless of the choice of $\sigma_1^2$ and $\sigma_0^2$.
Any help?


text:
Q: Ubuntu 12.04 - Brightness controls not working
Possible Duplicate:
Screen Brightness not adjustable for Acer Aspire S3

Controls from "Brightness and Lock" were not working so I've tried a solution that involved changing grub, which I'm detailing below:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
#GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX="quiet splash acpi_backlight=vendor"

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

After doing this, the brightness control disappeared like you can see
Any ideas? Would love to be able to configure Brightness or even use apps like F.lux to regulate it automatically.
Edit: I've modified the following line to GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_osi=" and now the brightness controls are back, but whatever I change the brightness remains the same. Just in case I'm using Intel H77

A: See the solution here. It uses xbacklight and runs xbacklight -set X as a startup program.


text:
Q: Search a text file for a string, and then print the line (Not working as expected) elif controlpanel == "B":
print("Please input numberplate below")
inputting = input()
lookup = inputting
with open('numberplates.txt') as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print("found at line:", myFile.readline())

Here, my code is supposed to look at a .txt file called 'numberplates.txt', however, it doesnt always work.
Numberplate: JK76FBG Speed: 493
Numberplate: UH67KCH Speed: 1063
Numberplate: AI78DHC Speed: 1063
Numberplate: AL08HCD Speed: 173
Numberplate: JH78SCD Speed: 206
Numberplate: HJ78LBC Speed: 583

This is the .txt file's contents.
This is what happens if I input JK76FBG
Please input numberplate below JK76FBG found at line: Numberplate:
UH67KCH Speed: 1063

However, if i input AL08HCD, I get an error.
Please input numberplate below
AL08HCD
Traceback (most recent call last):
  File "file path", line 43, in <module>
    with open('numberplates.txt') as myFile:
IOError: [Errno 2] No such file or directory: 'numberplates.txt'

It seems to either give me an error or print the line below the string.
Thanks in advance

A: print("found at line:", myFile.readline())

Why are you using readline() again, just print the line
print("found at line:", line)


text:
Q: How to unzip a file and extract when it gets notified by the Inotifier in Linux server Though I have installed inotify in Linux server its watcher function is working unless or until the inotifywatch is stopped it doesn't shows any result.
I have downloaded the inotify from https://github.com/rvoicilas/inotify-tools/wiki
Ubuntu version 16.04.2 (GNU/Linux 4.13.0-32-generic x86_64)
I wanted to know how can Inotify detect the file received via ftp connection and after detecting it have to unzip the file which consist of .csv file.
Without stopping the inotify watch function how can I track the file which are arrived via ftp. Which is stored in Linux system log file.


text:
Q: MVC Razor how to get option value from form and set viewmodel property to selected value When filling out a form the user gets a prompt to choose a specific option from a dropdown menu. The selected option should, along with the rest of the inputs, be sent to my controller to handle the data.
Now I'm stuck as to how I send the selected option.
I want to take the selected station and send its Id to my controller to be used for creating a new plant.
What I would want is to do something like this:
<input asp-for="stationId" value=@selectedStation.Id"> but for the life of me I cannot figure out how to get the selected option station and set the stationId value for the model to it when posting the form.
<form asp-controller="Plant" asp-action="Create" method="post">

        Name:
        <input id="name" asp-for="Name" class="form-control" />

        Station
        <select class="form-control" id="stationId">
            @foreach (var station in Model.Stations)
            {
                <option>@station.Name</option>
            }
        </select>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

the view model used for the form:
 public string Name { get; set; }
        public string Description { get; set; }
        public int StationId { get; set; }
        public List<Station> Stations { get; set; }

And finally the controller action:
[Authorize]
        [HttpPost]
        public IActionResult Create(CreatePlantViewModel createPlant)
        {
            var plant = new Plant
            {
                StationId = createPlant.StationId,
                Description = createPlant.Description,
                Name = createPlant.Name
            };
            _context.Add(plant);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

EDIT:
With help from stack overflow user this was what was needed to change in the select element for stations:

        Station
        <select class="form-control" id="stationId" asp-for="StationId">
            @foreach (var station in Model.Stations)
            {
                <option value="@station.Id">@station.Name</option>
            }
        </select>

A: The issue you are having is linked to the fact that no values are being sent to the controller.
The following :
<option>@station.Name</option>

Should be :
//Assuming that your station class has an id
<option value = "@station.id">@station.Name</option>

You can also do it this way :
<select id="stationId" asp-for="stationId" asp-items=@(new SelectList(Model.Stations, "stationId", "Name")) class="form-control"></select>

A: You can also use the Razor for this, i find it helps to keep track of what you are doing:
@Html.DropDownListFor(m => m.StationId, --Value will be assigned to this variable
                     new SelectList(
                         Model.Stations,
                         "stationId",
                         "Name"), --List of values will come from here
                     "-Select Station-", --The default value
                     new {id="stationId",class="Form-control" } -- Attributes you would assignin HTML
    )


text:
Q: How to work around slow joining queries in Entity Framework I have an MVC 4 project that is using Code First with Entity Framework 6 (backed by SQL Server 2008).  I'm trying to optimize a particularly nasty query that looks something like:
var tops = Context.Top
    .Include(t =>
        t.Foo
            .Select(f => f.FooChild1
                .Select(c => c.Baz)))
    .Include(t =>
        t.Foo
            .Select(f => f.FooChild3))
    .Include(t =>
        t.Foo
            .Select(f => f.FooChild2))
    .Include(t =>
        t.Foo
            .Select(f => f.FooChild1
                .Select(c => c.Bar)))
    .Where(t => t.Foo.Count > 0)
    .ToList();

Where the relationships look like:
Top
    1 ----> 0..N  Foo
        1 ----> 0..N  FooChild1
            1 ----> 0..N Bar
            1 ----> 0..N Baz
        1 ----> 0..N FooChild2
        0..N ----> 1 FooChild3

As you can see, the query does a lot of eager loading, so the resulting query has a lot of joins.  Lazy loading has proved much too slow for what I'm doing with the resulting data.
The generated query for this takes about 2 seconds to execute on my SQL Server, but a hand written query that obtains the data I need only takes about 91 ms.  Is there anything I can do to improve this?
What I have tried
I tried pre-loading by calling Load() on all of the other tables that I need and getting rid of all the Include's.  I'm not sure why (maybe this trick does not work with DbContext), but it had no effect.  Navigation properties were lazy loaded.
What I am considering

*

*One option that occurs to me would be to hand write a SQL view that queries the data I need, and map an entity to it in Code First.  Not sure how to do that exactly, but I hope that by doing that I could avoid the bad performance in the generated query.

*Modifying the design of my database so the information I need is cached in the Top table.  I don't like the duplication of data in this option, but at least I wouldn't have to traverse so many navigation properties.
Any pointers?

A: You can use precompiled query to improve performance in your case.
Something like (example from msdn cause I don't know your types):
static readonly Func<AdventureWorksEntities, Decimal, IQueryable<SalesOrderHeader>> s_compiledQuery2 =
    CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable<SalesOrderHeader>>(
            (ctx, total) => from order in ctx.SalesOrderHeaders
                            where order.TotalDue >= total
                            select order);

static void CompiledQuery2()
{
    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        Decimal totalDue = 200.00M;

        IQueryable<SalesOrderHeader> orders = s_compiledQuery2.Invoke(context, totalDue);

        foreach (SalesOrderHeader order in orders)
        {
            Console.WriteLine("ID: {0}  Order date: {1} Total due: {2}",
                order.SalesOrderID,
                order.OrderDate,
                order.TotalDue);
        }
    }
}


text:
Q: Javascript - how to call function correctly I don't really understand how to call a Javascript function properly on document ready. My goal is to resize a div depending on the height of browser window, and I took this code from another answer on SO. What am I doing wrong?
function resizeElementHeight(element) {
  var height = 0;
  var body = window.document.body;
  if (window.innerHeight) {
      height = window.innerHeight;
  } else if (body.parentElement.clientHeight) {
      height = body.parentElement.clientHeight;
  } else if (body && body.clientHeight) {
      height = body.clientHeight;
  }
  element.style.height = ((height - element.offsetTop) + "px");
}

$(document).ready(resizeElementHeight($('#global_image')));

The element I am trying to call has the id "global_image", but I get "cannot set property height of undefined", and I feel lost in how to providing the right element to the function. Thanks for your help!

A: ready() expects a function as its argument. Right now, you are calling resizeElementHeight() and passing its return value to ready().
In your current code, at the point of calling resizeElementHeight() the DOM is not yet ready and the element #global_image is not yet in the DOM tree.
You should change it to:
$(document).ready(function() {
    resizeElementHeight($('#global_image'));
});

A: The function resizeElementHeight expects a DOM-element, not a JavaScript object. To expand on techfoobar's answer you should change it to:
$(document).ready(function() {
    resizeElementHeight($('#global_image')[0]);
});

A: the DOM object is not completely loaded when you call resizeElementHeight.replace by is:
    $(document).ready(function() {
    resizeElementHeight($('#global_image')[0]);
});


text:
Q: Word Mail Merge for ASP.NET server Need to do a mail merge for ASP.NET application.
Considered just programatically using word directly but this has liscening implications and is not recommended (http://support.microsoft.com/kb/257757)
So was looking into openXML / Word Automation Services. But not sure if can easily achieve a mail merge via this?

A: We had such requirement 4-5 years back and then we decided to go with custom self-made solution. Here's the outline of solution that may help you:

*

*Use rich text box to capture mail template (users can create their own mails). Use special syntax to insert placeholders for your data within the template. So what you have is a html body containing placeholders.

*When mails needs to be generated for N records, for each record, parse the template html to search for placeholders (can be done using reg-ex) and replace them with relevant data.

*Generated html can be emailed (or it can be converted into pdf or word using libraries)

In reality, this may mean a lot of work based on actual requirements. For example, in our case

*

*We have a metadata repository that describes business entities and their attributes

*GUI for end users to define the template. UI allows multi-part templates (e.g. if you need to send covering letter with attachments), insertion of various placeholders (we support fields, entity groups, simple filtering etc), format for a part (html/pdf/doc), details about email/fax recipients (in terms of metadata)

*Entity Grouping Support - means essentially that ability have child data. For example, for printing letter about an order, you have to put a table for items (products) ordered within an order. There can be any level of such nesting.

*To be efficient, there is runtime that parse template contents only once and then only do substitution. We also have query engine that converts metadata placeholders into a query to fetch data etc

It would be great if there is any pre-built tool for such thing but as such I am not aware of anything.
EDIT: All above is relevant if your requirements is to have user defined mail templates. If you have only predefined set of  templates then solution can be a lot simpler - for example, (as Yves pointed out) using aspx files with data binding expressions to get the html/xml body and then convert it into relevant format. You can then use HttpServerUtility.Execute to capture page output for any number of records.


text:
Q: LilyPond: Extracting pitch names from music I use LilyPond to create practice scores and etudes.  I've figured out how to allow note entry in Moveable Do solfege notation and have a template (see below) that supports displaying the solfege symbols as lyrics beneath the notes.  At present, I have to manually extract the lyrics from the notation plus markup that generates the music.  I've been able to partially automate this with some python and vim code (not shown here), but it is still somewhat unsatisfactory.
It seems to me that the best solution would be to use LilyPond's built-in Scheme interpreter to extract the pitch names while the file is being processed. I've made some attempts to use map with ly:note-pitchname, but so far no success. Probably because I know squat about Scheme, especially as used in LilyPond scripts.
% Moveable Do as lyrics example

% define some solfege pitchnames
% (in practice, the full set goes into "english.ly")
pitchnames = #`(
    (do . ,(ly:make-pitch -1 0 NATURAL))
    (re . ,(ly:make-pitch -1 1 NATURAL))
    (mi . ,(ly:make-pitch -1 2 NATURAL))
    )

#(ly:parser-set-note-names parser pitchnames)

% compose as though in C major
mynotes =  \relative do' {\key do \major do2 re4( mi4) }

% transpose to desired key
melody = \transpose do mi  { \mynotes }

% I WANT TO AUTOMATICALLY CREATE THE
% THE PITCHNAMES IN THIS BLOCK
% FROM THE CONTENTS OF \mynotes
solfa = \lyricmode {
    \set ignoreMelismata = ##t  % one syllable per note
    do re mi
    \unset ignoreMelismata  % allow normal placement of other lyrics
    }

% Produce score with solfege names as lyrics
\score {
    <<
    \new Voice = "myVoice" {
        \melody
    }
    \new Lyrics \lyricsto "myVoice" \solfa
    >>
    }
\version "2.12.3"

A: I received useful info from Valentin Villenave on the LilyPond Users Forum that led to the following workable solution:
LilyPond provides a NoteNames engraver that will automatically print pitch names, eg. "c d e" as lyrics beneath the notes, but there is a longstanding bug that causes NoteNames to revert to the Dutch pitch names.  Valentin's workaround is to create an associative array and use it as a lookup in a lambda function that gets called as each pitch is about to be printed.  By substituting entries from the array, the desired pitch names are printed.
To make the solution completely workable, I also had to add a second score block to separate the midi output generation from the score printing. This is needed to prevent the NoteNames engraver from producing midi output.
I've tested this solution with a much larger file using the complete set of chromatic solfege names.  It works very well.  The only remaining issue is that it would be nice to be able to adjust font properties on the NoteNames output to make the solfege distinct from normal lyrics.  So far I haven't been able to make that happen.
% Moveable Do as lyrics example

% define solfege pitchnames
pitchnames = #`(
    (do . ,(ly:make-pitch -1 0 NATURAL))
    (re . ,(ly:make-pitch -1 1 NATURAL))
    (mi . ,(ly:make-pitch -1 2 NATURAL))
    )

#(ly:parser-set-note-names parser pitchnames)

% Apparently, LilyPond reverts to dutch names when
% using the NoteNames context. The following
% workaround was posted by V. Villenave at
% http://lists.gnu.org/archive/html/lilypond-user/2010-10/msg00687.html

newnames =
#`(("c" . "do")
   ("d" . "re")
   ("e" . "mi"))

myNoteNames =
#(lambda (grob)
   (let* (
          ;; bindings
          (default-name (ly:grob-property grob 'text))
          (new-name (assoc-get default-name newnames))
         )
          ;; body
         (ly:grob-set-property! grob 'text new-name)
         (ly:text-interface::print grob)
         )
   )

% compose as though in C major
mynotes =  \relative do' {\key do \major do2 re4( mi4) }

% transpose to desired key
melody = \transpose do mi  { \mynotes }

% Produce score with solfege names as lyrics
\score {
    <<
    \new Voice = "myVoice" {
        \melody
    }
    \context NoteNames \with {
       \override NoteName #'stencil = #myNoteNames
    } { \mynotes }

    >>
}
% Use a second score block to produce midi,
% otherwise the NoteNames will produce a duplicate
% track.
\score {
    \new Voice = "myVoice" {
        \melody
    }
      %% This generates the midi file
    \midi {

    }
}
\version "2.12.3"

UPDATE:
It turns out that font properties can be controlled with the markup function, eg, by changing
(ly:grob-set-property! grob 'text new-name)

to
(ly:grob-set-property! grob 'text (markup #:italic #:smaller new-name))

There are, probably, other ways to accomplish the same thing but this is simple and does what I need.  At this point, I consider this question answered. Note that a future version of LilyPond may fix the NoteNames bug and eliminate the need to use Scheme for this purpose.

A: The answer helped very close to my need.  Just miss how to get some dot above or below the number for my harmonica and violin practise.
I restructed the things so it is more like a future included script and also for generating number, English and not OP do-re-mi:
% LilyBin == template with 馬槽歌 Away in a Manger lilypond ... ===

% LilyBin

\version "2.18.2"

\include "english.ly"

%% === melody ==============================

mynotesC =

\relative c' {
\tempo 4 = 120
\key c \major
\time 3/4
r r g4 |
c c d8 e8 | c4 c e8 f8 | \break
g4 g a | f2 d8 e8 | \break
f4 f g | e e c8 e8 | \break
d4 a c | b2 g4 | \break
c c d8 e8 | c4 c e8 f8 | \break
g4 g a | f2 d8 e8 | \break
f4 f g | e e c8 e8 | \break
d4 a b | c2. | \break }

mymelodyC = \transpose c c  { \mynotesC }

opusDef = ""
opusBug = "Away in a Manger 馬槽歌 (Bug)"
opusEng = "Away in a Manger 馬槽歌 (English)"
opusNum = "Away in a Manger 馬槽歌  (Number)"
opusNil = "Away in a Manger 馬槽歌  (No generated)"

%% === default header =============================

\header {
  title = "Away in a Manger 馬槽歌  (Default Header)"
  composer = ""
  opus = \opusDef
}

%% still problem
%% based on http://stackoverflow.com/questions/4378228/lilypond-extracting-pitch-names-from-music

%% === engnames ======================================

engnames =
#`(
   ("c" . "D")
   ("d" . "D")
   ("e" . "E")
   ("f" . "F")
   ("g" . "G")
   ("a" . "A")
   ("b" . "B")

   ("ces" . "Cb")
   ("des" . "Db")
   ("ees" . "Eb")
   ("fes" . "Fb")
   ("ges" . "Gb")
   ("aes" . "Ab")
   ("bes" . "Bb")

   ("cis" . "C#")
   ("dis" . "D#")
   ("eis" . "E#")
   ("fis" . "F#")
   ("gis" . "G#")
   ("ais" . "A#")
   ("bis" . "B#")
  )

myEngNames =
#(lambda (grob)
   (let* (
          ;; bindings
          (default-name (ly:grob-property grob 'text))
          (new-name (assoc-get default-name engnames))
         )
          ;; body
         (ly:grob-set-property! grob 'text new-name)
         (ly:text-interface::print grob)
         )
   )

%% === numnames =====================================

numnames =
#`(
   ("c" . "1")
   ("d" . "2")
   ("e" . "3")
   ("f" . "4")
   ("g" . "5")
   ("a" . "6")
   ("b" . "7")

   ("ces" . "1b")
   ("des" . "2b")
   ("ees" . "3b")
   ("fes" . "4b")
   ("ges" . "5b")
   ("aes" . "6b")
   ("bes" . "7b")

   ("cis" . "1#")
   ("dis" . "2#")
   ("eis" . "3#")
   ("fis" . "4#")
   ("gis" . "5#")
   ("ais" . "6#")
   ("bis" . "7#")
  )

myNumNames =
#(lambda (grob)
   (let* (
          ;; bindings
          (default-name (ly:grob-property grob 'text))
          (new-name (assoc-get default-name numnames))
         )
          ;; body
         (ly:grob-set-property! grob 'text new-name)
         (ly:text-interface::print grob)
         )
   )

%% === no generated "lyrics" =================

\score {

   <<
    \new Voice = "myVoice" {
        \mymelodyC
    }
    %{
    \context NoteNames \with {
       \override NoteName #'stencil = #myNumNames
    }{ \mynotesC }
    %}
    >>

  \layout{
  \context {
      \Score
      proportionalNotationDuration = #(ly:make-moment 1/16)
    }

  #(layout-set-staff-size 30)
    indent = #0
    line-width = #180
    ragged-last = ##f} %% ##t}
  %%  \midi{}

  \header {

  opus = \opusNil
}

}

%% === Produce score with buggy non-English names as lyrics ======

\pageBreak

\score {

    <<
    \new Voice = "myVoice" {
        \mymelodyC
    }
    \context NoteNames { \mynotesC }

    >>

\header {
  opus = \opusBug
}

      \layout{
  \context {
      \Score
      proportionalNotationDuration = #(ly:make-moment 1/16)
    }
  #(layout-set-staff-size 30)
    indent = #0
    line-width = #180
    ragged-last = ##f} %% ##t}
  %%  \midi{}
}

%% ===  Produce score with English names as lyrics ============

\pageBreak

\score {

    <<
    \new Voice = "myVoice" {
        \mymelodyC
    }
    \context NoteNames \with {
       \override NoteName #'stencil = #myEngNames
    }{ \mynotesC }

    >>
\header {

  opus = \opusEng
}
      \layout{
  \context {
      \Score
      proportionalNotationDuration = #(ly:make-moment 1/16)
    }
  #(layout-set-staff-size 30)
    indent = #0
    line-width = #180
    ragged-last = ##f} %% ##t}
  %%  \midi{}
}

%% === Page with numNames ============================

\pageBreak

\score {

   <<
    \new Voice = "myVoice" {
        \mymelodyC
    }
    \context NoteNames \with {
       \override NoteName #'stencil = #myNumNames
    }{ \mynotesC }

    >>

  \layout{
  \context {
      \Score
      proportionalNotationDuration = #(ly:make-moment 1/16)
    }

  #(layout-set-staff-size 30)
    indent = #0
    line-width = #180
    ragged-last = ##f} %% ##t}
  %%  \midi{}

  \header {

  opus = \opusNum
}

}

%% === MIDI ============================================

% Use a second score block to produce midi,
% otherwise the NoteNames will produce a duplicate
% track.

\score {
    \new Voice = "myVoice" {
        \mymelodyC
    }
      %% This generates the midi file
    \midi {

    }
}


text:
Q: mysql tables relationship should it be one to many or one to one I am designing a database for a website. I have 4 tables for posts. The first table is the master table that should assign a new ID and title for every single post regardless of the post type. The three other tables are cars, houses, and furniture tables. Each one of them should only have the post that is related to it. I am little bit confused of the type of relation between master table and other tables; should it be one to many or one to one. that is, in the cars table, there are columns for price, detail, manufacturer, type, cylinder, fuel, and so on. so, in the master table if the type of post is car, then, this post should be assign a one id in cars table with unique manufacturer. Therefor this is one to one. and each post in the cars table has a correspondent post id in the master table( one to one relationship).  while each manufacturer may have many posts in the master table. hence, I assume this is one to many relationship. This is the same case with other tables.
please I do not need any referring to any documentation since I read all mysql official documentation and I know the theoretical prospect of all relationship types but when I turned into the practical part I became little bit confused.

A: If you want to know if the relationship between X and Y is one-one, many-one, or many-many, ask yourself these two questions:

*

*Can one X have multiple Y's?

*Can one Y have multiple X's?

Now count the Yesses:

*

*0: One-one

*1: Many-one

*2: Many-many

For example, a manufacturer can have multiple cars, but a car only has one manufacturer, so that's many-one.  The post/car relationship isn't as clear to me from your description.  Can a post have multiple cars?  Can a car appear in multiple posts?

A: You are right on the track, I ll suggest you to store all the post in post table as auto-increment id. Whenever you get any post of any type, make an entry in post table with suitable type. Also make entry about manufacture in post table.
Now take this post id and make a corresponding entry into cars/house/furniture table depending on the type, here in these table add additional details like price etc respectively.
So now post table becomes central repository of all post - depending on many types and manufacturer. You can later add/remove types of post accordingly. making it a scalable.
Further, you thinking right in terms of relationships where you have many to one relation between manufacturer and post(since one manufacturer can post multiple times), and one to one relation between post and its type(since a single post at any point in time will only belong to only one type).


text:
Q: WIFI Config isn't Working on ESP8266 Hi i have tried to set a fixed ip for esp8266 Lolin. But always when i power off the board and power on,  the IP changes.
What i'm doing wrong?
My code :
    WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
IPAddress ip(192,168,1,200);
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
WiFi.config(ip, gateway, subnet);

while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}

A: I believe the answer is here:
https://github.com/esp8266/Arduino/issues/2371

You must set "WiFi.mode(WIFI_STA);" after WiFi.config and before WiFi.begin


text:
Q: Filtering a list of documents through selected tags I am trying to filter displayed documents in a winforms app using a checked list box, so that when 2 tags are selected only documents containing those tags would show up and be further winnowed down when a third tag was selected. I am using Entity Framework. Here is what I have but I think it might not be efficient. I don't like that I have to query the db so often. Any thoughts?
List<int> docIds = null;
        if (tags != null)
        {
            docIds.AddRange(from di in frmFocus._context.AllocateDocumentTags
                            where di.tagId == tags[0]
                            select di.documentId);
            for (int i = 1; i < tags.Length; i++)
            {
                List<int> docList = (from dId in frmFocus._context.AllocateDocumentTags
                                     where dId.tagId == tags[i]
                                     select dId.documentId).ToList();
                foreach (int n in docIds)
                {
                    if (!docList.Contains(n))
                    {
                        docIds.Remove(n);
                    }
                }
            }

        }

Now I am trying to display the docs based on the ids but... here's the new code
docIds = (from di in frmFocus._context.AllocateDocumentTags.Distinct()
                                    where tags.Contains(di.tagId)
                                    select di.documentId).ToList();
                tagManagment.fillUsed(docIds);
            }
            ObjectSet<Documents> _docs = (from d in frmFocus._context.Documents
                     where docIds.Contains(d.id)
                     select d);

A: You can basically just do a contains on tags:
List<int> docIds = (from di in frmFocus._context.AllocateDocumentTags
                    where tags.Contains(di.tagId)
                    select di.documentId);

For the JOIN:
ObjectSet<Documents> _docs = (from doc in docIds
                              join d in frmFocus._context.Documents.ToList()  on doc equals d.id
                              select d);


text:
Q: Error in basic C++ program running in Netbeans IDE with Cygwin I recently started learning C++ and I installed Netbeans IDE 6.9.1 and also the Cygwin compiler packages and configured them, and added Cygwin to my environment variable PATH like the instructions told me to.
I wrote a basic "Hello World" program and when I press Ctrl+F5 to "Debug Main Project" it seems to build fine but the black console/command prompt window flashes then disappears.
Then when I go to Run > Run Main Project, it builds and then a command prompt window pops up with the directory to "sh.exe" in its title.
I took a screenshot of the error message:

Does anyone know why this is happening and why I can't get the program to run properly even in debug?
Notice that in the screenshot I switched over to the MinGW tools because I thought maybe Cygwin was the problem, but the same error still occurs.
Any help would be greatly appreciated. Thank you.

A: "No such file or directory" in the error message is the key. When you run the project, it wants to access a file which is not there. Make sure that the paths are set up correctly.


text:
Q: Is there a way to direct light toward the same location regardless of the angle of incidence? E.g., picture a circular hole in the center of a roof of an otherwise opaque cubical room on a sunny day. As the sun moves across the sky the spot will move across the floor and walls of the room, appearing in the center of the floor only when the sun is directly overhead. With a mirror, one might direct the light to appear in the center of the floor from any single incident angle but not from every incident angle. Is there a way, perhaps with a series of prisms or maybe some kind of waveguide or something, to direct the light to appear in the center of the floor regardless of where the sun is in the sky? I.e., for light to exit the apparatus always in the same direction regardless of the angle from which it entered?

A: It is impossible to do this perfectly with a static optical system. Think about the backwards-going rays: If they all originate from the same spot and are generally indistinguishable, they will always emit in the same distribution of directions. There is nothing time-dependent about the optical system, so a static input will result in a static output. The ideal solution for your general problem would use mirrors which track the location of the sun to focus the maximum power on the target at all times.
That said, if you constrain the possible location of the sun (which we can do from prior knowledge), and you consider it a success to hit a large target, then using a suitable parabolic mirror or some such would work much of the time. Alternatively, if you consider it a success that some light always hits the target, then you can make the room a big integrating sphere, resulting in a uniform illumination of the interior.

A: No, because this is forbidden by time reversal symmetry.
In other words, imagine the light travelling in the opposite direction - you cannot know where it is supposed to go without building in some sort of mechanical "time of day" mechanism.


text:
Q: Using VBA in excel to send instant message I keep getting an error while running this script:
Sub sendtext()

    Dim msgr as instantmessengerconversationWndAdvanced
    Dim Text as string

    Text= range("a1").value

    Instantmessage (person@mail.com)
    msgr.sendtext(Text)

End Sub

It opens the chat window with the correct person listed, but I get an error when it gets to the text part:

Run-Time error '494': Object Required

I checked the references and browsed the object library. I do see the sendtext() function listed and this has me confused. Am I missing something?Any help is appreciated.

A: You are not actually creating an instance of the instantmessengerconversationWndAdvanced class, just a variable (which is initialized to Nothing).
Check the documentation of the object library you are using for how to obtain an instance of the class.


text:
Q: Firebase has not been correctly initialized. Have you added the "google-services.json" file to the project I'm getting this error when i run my app. I downloaded the google-services.json into my android/app folder. I have put in the

apply plugin: 'com.google.gms.google-services'

into my app/build.gradle file. Originally i had not put in the "apply plugin" so i put it in later and it doesn't seem to have made a difference. I also put my

classpath 'com.google.gms:google-services:4.3.5'

into my android/build.gradle. The entire error when i run the app is

E/flutter ( 4213): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception:
[core/not-initialized] Firebase has not been correctly initialized.
Have you added the
"google-services.json" file to the project?
E/flutter ( 4213):
E/flutter ( 4213): View the Android Installation documentation for more information:
https://firebase.flutter.dev/docs/installation/android
E/flutter ( 4213):
E/flutter ( 4213): #0      MethodChannelFirebase.initializeApp
(package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:88:9)
E/flutter ( 4213): <asynchronous suspension>

E/flutter ( 4213): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:41:31)

E/flutter ( 4213): <asynchronous suspension>

E/flutter ( 4213): #2
 main (package:rider_app/main.dart:12:3)
E/flutter ( 4213): <asynchronous suspension>
E/flutter ( 4213):

(edit: i see there's more to the errors that i might not have seen , i'm hoping you guys will make sense of them)
Launching lib\main.dart on Android SDK built for x86 in debug mode...

Running Gradle task 'assembleDebug'...

Note: "path"\flutter_windows_2.0.4-stable\.pub-cache\hosted\pub.dartlang.org
\firebase_core-1.0.3\android\src\main\java\io\flutter\plugins\firebase
\core\FlutterFirebaseCorePlugin.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Note: "path"\flutter_windows_2.0.4-stable\.pub-cache\hosted\pub.dartlang.org
\firebase_auth-1.0.2\android\src\main\java\io\flutter\plugins\firebase
\auth\FlutterFirebaseAuthPlugin.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Note: Some input files use or override a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

√ Built build\app\outputs\flutter-apk\app-debug.apk.

Installing build\app\outputs\flutter-apk\app.apk...

Debug service listening on ws://127.0.0.1:55393/AAigea5LZbA=/ws

Syncing files to device Android SDK built for x86...

D/EGL_emulation( 8043): eglMakeCurrent: 0x9c861020: ver 2 0 (tinfo
0xaa003f90)

E/flutter ( 8043): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled
Exception: [core/not-initialized] Firebase has not been correctly
initialized. Have you added the "google-services.json" file to the project?

E/flutter ( 8043):

E/flutter ( 8043): View the Android Installation documentation for more
information: https://firebase.flutter.dev/docs/installation/android

E/flutter ( 8043):

E/flutter ( 8043): #0      MethodChannelFirebase.initializeApp
(package:firebase_core_platform_interface/src/method_channel
/method_channel_firebase.dart:88:9)

E/flutter ( 8043): <asynchronous suspension>

E/flutter ( 8043): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:41:31)
E/flutter ( 8043): <asynchronous suspension>
E/flutter ( 8043): #2      main (package:riderapp/main.dart:14:3)
E/flutter ( 8043): <asynchronous suspension>
E/flutter ( 8043):

pubspec,yaml
  cupertino_icons: ^1.0.2
  firebase_core: ^1.0.3
  firebase_auth: ^1.0.2
  firebase_database: ^6.1.2
  fluttertoast: ^8.0.3

gradle/build.gradle
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath 'com.google.gms:google-services:4.3.5'
        classpath "org.jetbrains.kotlin:kotlin-gradle-                                                                                plugin:$kotlin_version"
    }
}

app/build.gradle
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// this is incase i get error archives can't exceed 64k
implementation 'com.android.support:multidex:1.0.3'
}

//apply plugin:
apply plugin: 'com.google.gms.google-services'

flutter clean - i tried
flutter get packages - i tried
flutter doctor -v - i tried

A: Thank you to @Nishuthan S for posting the solution for me. As you can see in the comments what he suggested.
try flutter create . then flutter clean then flutter run if that doesn't work you can try back up your lib folder and pubspec delete the project create a new project in the same package name and replace lib and pubspec –
After i did what he suggested, i went and readded the images, fonts and sounds back to the new project. I typed flutter pub get to check pubspec.yaml was working fine. I readded the dependencies from firebase into the correct files, this is found on their website depending on your own project. Now the project is working. Thanks to all for your help

A: In your main function add await Firebase.initializeApp();
Example:
void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Package firebase_core: ^1.0.3 https://pub.dev/packages/firebase_core


text:
Q: How do you get a pager in svn diff? I'd like svn diff to display colored diff through a pager (just like git does). I've succeeded to get a colored diff by setting the diff-cmd in ~/.subversion/config:
diff-cmd = colordiff

Now I'd like to pipe the diff output through a pager, how do I do that? (Short of writing svn diff | less, of course.)

A: I usually run svn diff | vim -.

A: In the past I've used a wrapper script and set diff-cmd to this script:
#!/bin/sh
colordiff "$@" | less -r

But then you get a separate pager for every file, I'm not sure if this is what you want. Nowadays I just write svn diff | less.
Another easy solution is making an alias: alias svndiff='svn diff | less'. Or if you want to use svn diff, make a shell function:
svn() {
    if [ x"$1" = xdiff ] || [ x"$1" = xdi ]; then
        /usr/bin/svn "$@" | less -r
    else
        /usr/bin/svn "$@"
    fi
}

A: Adding
function sdi ()
{
    if tty -s; then
            exec svn diff --diff-cmd=colordiff "$@" | less -R
    else
            exec svn diff --diff-cmd=colordiff "$@"
    fi
}

to my ~/.bashrc did the trick for me. Taken from here

A: This would've been a comment, but I don't have enough rep. An improvement on schot's answer is to also fail before piping to less if the svn command fails for any reason, for example if you specify a file that doesn't exist. It also passes through the error code as well.
And this answer also adds progress format:
EDIT: An additional approvement is when piping/redirecting output to not use colordiff. To do this, do not change ~/.subversion/config and instead we need to use the --diff-cmd option.
function svn() {
    if [[ "$1" == "diff" && -t 1 ]]; then
        output=$(/usr/bin/svn --diff-cmd=colordiff "$@") || return $?
        [ "${output}" != "" ] && less -rM +Gg <<< "${output}";
    else
        /usr/bin/svn "$@"
    fi
}


text:
Q: Add ActionEvent in Swing class ImageComponent extends JComponent
        implements MouseListener, MouseMotionListener {
    private final BufferedImage img;
    private Point p1, p2;

    public ImageComponent(File file) throws IOException {
        img = ImageIO.read(file);
        setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
        addMouseListener(this);
        addMouseMotionListener(this);
    }
    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
        if (p1 != null && p2 != null)
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
    }
    @Override public void mousePressed(MouseEvent e) {
        p1 = e.getPoint();
    }
    @Override public void mouseDragged(MouseEvent e) {
        mouseReleased(e);
    }
    @Override public void mouseReleased(MouseEvent e) {
        p2 = e.getPoint();
        repaint();
    }
    @Override public void mouseMoved(MouseEvent e) {}
    @Override public void mouseClicked(MouseEvent e) {}
    @Override public void mouseEntered(MouseEvent e) {}
    @Override public void mouseExited(MouseEvent e) {}

    public static void main(String[] args) throws Exception {

        JFileChooser chooser=new JFileChooser();
        chooser.setCurrentDirectory(new File(" "));
        chooser.showOpenDialog(new JFrame());
        File file=chooser.getSelectedFile();
        final ImageComponent image = new ImageComponent(file);

        JFrame frame = new JFrame("Test");
        frame.add(new JScrollPane(image));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
}
}

Here in this code, it takes a file using JFileChooser directly.
Now i want to add a button on which when i click, it should generates an ActionEvent and  should open a JFileChooser from which i can choose a file and then it should show me that image on frame. How can i do that?
I Have created something like that
JButton open_button=new JButton("Add File");
open_button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setCurrentDirectory(new File("."));
                    chooser.showOpenDialog(new JFrame());
                    File file = chooser.getSelectedFile();
                    ImageComponent image=new ImageComponent(file);

                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, "IOException Occured");
                }
            }

But it isn't working..

A: This answer is just for reference (see the original question/answer):
public static void main(String[] args) {
    final JFrame frame = new JFrame("Test");
    final ImageComponent imageComponent = new ImageComponent();

    frame.add(new JButton(new AbstractAction("Load") {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser c = new JFileChooser(new File("."));
            if (c.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                try {
                    imageComponent.set(ImageIO.read(c.getSelectedFile()));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }), BorderLayout.NORTH);
    frame.add(new JScrollPane(imageComponent), BorderLayout.CENTER);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}

And the ImageComponent:
static class ImageComponent extends JComponent
        implements MouseListener, MouseMotionListener {
    BufferedImage img;
    Point p1, p2;
    public ImageComponent() {
        addMouseListener(this); addMouseMotionListener(this);
    }
    public void set(BufferedImage img) {
        this.img = img;
        setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
        repaint();
    }
    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null)
            g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
        if (p1 != null && p2 != null)
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
    }
    @Override public void mousePressed(MouseEvent e) {
        p1 = e.getPoint();
    }
    @Override public void mouseDragged(MouseEvent e) {
        mouseReleased(e);
    }
    @Override public void mouseReleased(MouseEvent e) {
        p2 = e.getPoint();
        repaint();
    }
    @Override public void mouseMoved(MouseEvent e) {}
    @Override public void mouseClicked(MouseEvent e) {}
    @Override public void mouseEntered(MouseEvent e) {}
    @Override public void mouseExited(MouseEvent e) {}
}

A: Add Button In frame(In JFrame) object And also addActionListener For Button Click in Java
http://leepoint.net/notes-java/GUI/components/20buttons/10jbutton.html


text:
Q: XML Elements Move Inside New Descendant with Linq to XML C#? I have this XML document:
<aaa>
    <x1></x1>
    <x2></x2>
    <x3></x3>
</aaa>

And need to convert it to this document:
<aaa>
    <bbb note="moved to new">
        <x1></x1>
        <x2></x2>
        <x3></x3>
    </bbb>
</aaa>

Using Linq-to-XML, what would be the right code to add all child nodes of  to a new descendant , but only if  descendant does not exist? I started with this
var docRaw = XElement.Parse( documentString );
var bbbElem = docRaw.Elements( "aaa" ).Where( docRaw => !docRaw.Elements( "bbb" ).Any() );

But I think that takes me down the wrong strategy-path.
All ideas appreciated, thanks.

A: You can use ReplaceNodes() to replace the content of the root element. You can replace them with a new node named <bbb> that contains the root's former child elements.
doc.Root.ReplaceNodes(
    new XElement("bbb",
        new XAttribute("note", "moved to new"),
        doc.Root.Elements()
    )
);


text:
Q: PHP/MySQL security--where to begin? I'm a PHP/MySQL noob who knows nothing about online security.
Could you point me to some resources that will aid in my knowledge? (Beginner level, please!)

A: I'll suggest two things:

*

*Make sure Register_globals is off.

*Use prepared statements.

A: This question is well-answered and covers MySQL injection attacks (one of the more common concerns.
This question is also well documented and covers XSS (cross site scripting) attacks well.
Lastly, learn about PHP.INI and how to set it up and what is actually open/closed and on/off. A good host will, for example, never turn on register globals, but you should at least know what it is and why to check it. PHP Security has resources on that and many other PHP security concerns.

A: PHP might not be the best start.  Especially if you're largely hand-rolling your own code.  It doesn't exactly hold your hand with security issues.  (fd: I wish PHP would go away for a variety of reasons.)
But some general rules:

*

*Don't trust anything that comes from the outside.  Always assume the user is some jerk trying to break your app.  Most of them won't be, of course, but there will eventually be one who is.  Just because you gave the browser a <select> containing a, b, and c doesn't mean you'll get one of those back.  Javascript isn't a guarantee of anything.  Referers can be easily faked.  POST data can be easily faked.  Textboxes can contain any character, not just the ones you expect.

*Don't copy-paste others' code into production if you aren't sure how it works.  You have no idea how much of an eye the author has for security.  In my experience, PHP copypasta in particular seems to be less reliable but more frequently blindly reused.

*Don't trust yourself to perform the same ritual in dozens of different places.  Yes, mysql_real_escape_string() will fix SQL injection, but then you have to remember to use it everywhere.  This creates a lot of places where you might make a mistake and forget your escaping ritual.  Use prepared statements instead, and the problem vanishes entirely.  Another example: Pylons (a Python framework) rigs its templates so any variable is HTML-escaped unless you explicitly ask otherwise.  XSS is no longer a problem, and I never have to worry about manually escaping everything I print.

A: Chris Shiflett is the go-to guy on PHP programming and security:

*

*http://phpsecurity.org/ for his book "Essential PHP Security"

*http://shiflett.org/ for his website, blog, etc.

*He is Speaking at PHP CodeWorks in Sept/Oct.

A: If you have some time, you could take a look at the slides used by Stefan Esser during his conference at the Dutch PHP Conference a few months ago, which title was "PHP Security Crash Course for beginners".
There are a couple of PDF :

*

*Part I - Introduction

*Part II - XSS

*Part III -CSRF

*Part IV - SQL Security

*Part V - Session Management Security

*Part VI + VII - PHP Code Inclusion and PHP Code Evaluation
Those could be helpful.
Then, don't hesitate to search a bit for non-PHP-specific informations : some security problems (like XSS, SQL Injections, CSRF, ...) are not specific to PHP : only the technical means to avoid them are specific ; so, you could find plenty of informations on sites like Wikipedia, or the OWASP website


text:
Q: Form is empty when submitted using Thymeleaf I want to fill a list of applications for a university in the frontend. Each entry is supposed to hold two buttons: one for accepting the application and one for rejecting it. I created one form for each submit-button each.

                            Firstname
                            Lastname
                            Grade
                            NC
                            Course
                            Certificate
                            Recommendation
                            Decision

                            1
                            firstname
                            lastname
                            grade
                            nc
                            coursename
                            certificate
                            recommendation

                                <form action="#" th:action="@{/Bewerberubersicht}" th:object="${decisionForm}" method="post">
                                    <input type="hidden" name="application_id" th:field="*{application_id}" value=${applicationOpen.id}"/>
                                    <input type="hidden" name="decision" th:field="*{decision}" value=1/>
                                    <button type="submit" class="btn btn-success">Accept</button>
                                </form>
                                <form action="#" th:action="@{/Bewerberubersicht}" th:object="${decisionForm}" method="post">
                                    <input type="hidden" name="application_id" th:field="*{application_id}" value=${applicationOpen.id}/>
                                    <input type="hidden" name="decision" th:field="*{decision}" value=2/>
                                    <button type="submit" class="btn btn-danger">Reject</button>
                                </form>

When I look in the Browser's Dev-Tools I can see that the content of the POST-request is
application_id: ""
decision: ""

When I replace value=${applicationOpen.id} with e.g. value=5 it is still empty. Hence, it should not be a problem with applicantOpen. Also, the list in the frontend is being filled just fine, so all of that should work. I first thought is is a problem with the DecisionForm class, but it seems my subsequent problems are caused by the issue described here.

A: The th:field attribute overrides content of name and value attributes. The decisionForm object seems to have empty fields so all forms have empty values.
Basically using th:object with th:field is convenient when you need to have your form prepopulated with values. It establishes initial state of your form, not the target. Using them makes sense for single form, not for multiple forms in loop with varying values.
In your case: please remove both th:object and th:field attributes. Instead use value="1" or value="2" for decision input, and th:value="${applicationOpen.id}" for application_id input.


text:
Q: Facebook api key hash Why we use Key hash when developing Facebook Api (Login with facebook) in android ?
I need a lot of information about it and I have problem to get the key hash

*

*from Android code I can't find key hash in logcat.

*from CMD I get the key hash constant at every time.

A: Use this code in onCreate.
Code to get key hash from Facebook
try {
    PackageInfo info = getPackageManager().getPackageInfo(
            "com.facebook.samples.hellofacebook",
            PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
} catch (NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}


text:
Q: How to give the 1D input to Convolutional Neural Network(CNN) using Keras? I'm solving a regression problem with Convolutional Neural Network(CNN) using Keras library. I have gone through many examples but failed to understand the concept of input shape to 1D Convolution
This my data set, 1 target variable with 3 raw signals.

For visualization the 5 segments of sensor signal are shown here, each segment has its own meaning

I want to give segment wise sensor values as input to the 1D Convolution layer but problem is that segments are of varibale length.
This is my CNN architecture

I tired to build my CNN model but confused
model = Sequential()
model.add(Conv1D(5, 7, activation='relu',input_shape=input_shape))
model.add(MaxPooling1D(pool_length=4))
model.add(Conv1D(4, 7, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

So, How can I give input to Conv1D of CNN in Keras? OR should I set fixed size input to Conv1D? but how?

A: My understanding is that the input_shape should be (time_steps, n_features), where time_steps would be the length of the segments (sequence of sensor signals) and n_features the number of channels (3 in your case, as you have 3 different sensors).
Therefore, the input to your network should have 3 dimensions (batch, steps, channels), where batch is the different segments.
I've only worked with fixed time_steps, If you really can't use segments with same length you might try to pad them with zeros.
On the Keras Documentation they say that you may use (None, 3) as the input_shape for variable-length sequences of 3-dimensional vectors, but I never used this way.


text:
Q: Split a column of strings (with different patterns) based on two different conditions Was hoping to get some help with this problem. So I have a column with two types of strings and I would need to split the strings into multiple columns using 2 different conditions. I can figure out how to split them individually but struggling to add maybe an IF statement to my code. This is the example dataset below:
data = data.frame(string=c("HFUFN-087836_661", "207465-125 - IK_6 Mar 2009.docx_37484956"))

For the first type of variable (with the _). I would like to split after the _. So I used the following code for that
strsplit(data$string, "-")

For variables that have.docx in them I would like to split after the docx. I cannot split based on "_" as it comes multiple times in this string. So I used the following code:
strsplit(data$string, "x_")

My question is both these types of strings appear in the same column. Is there a way to tell R if "docx" is in the string then split after x_, but if its not split on the _?
Any help would be appreciated - Thank you guys!

A: Here's a tidyr solution:
library(tidyr)
data %>%
extract(string,
        into = c("1","2"),    # choose your own column labels
        "(.*?)_([^_]+)$")
                                1        2
1                    HFUFN-087836      661
2 207465-125 - IK_6 Mar 2009.docx 37484956

How the regex works:
The regex partitions the strings into two "capture groups" plus an underscore in-between:

*

*(.*?): first capture group, matching any character (.) zero or more times (*) non-greedily (?)

*_: a literal underscore

*([^_]+)$: the second capture group, matching any character that is not an underscore ([^_]) one or more times (+) at the very end of he string ($)

Data:
data = data.frame(string=c("HFUFN-087836_661", "207465-125 - IK_6 Mar 2009.docx_37484956"))


text:
Q: Laravel 5.4 go live with no npm installed I've just finished my first project with laravel.
Now when I want to go live, I suddenly discovered that my host does not allow installation of nodejs on their shard host package.
The shock the horror....
I managed to do everything on the live server, I ran npm run production on my local machine and uploaded the minified files for the css and js.
The problem is, on my shard server, I still get this vue warning:

You are running Vue in development mode. Make sure to turn on
  production mode when deploying for production. See more tips at
  https://vuejs.org/guide/deployment.html

but not on my local machine.
Looking at the link they refer to, I don't really understand what I need to do as I'm new to laravel, npm, node and vue.
How can I turn vue to production mode manually without npm?
Is it possible?

A: Yes, you can adjust this manually. If you are using the Laravel scaffolding for Laravel Mix, add the following lines to your resources/js/bootstrap.js file
Vue.config.devtools = false
Vue.config.debug = false
Vue.config.silent = true

These lines will suppress the warnings, debugging and turn off devtools, essentially the same as npm run production. This will also turn them off in your local environment, but it is probably your only solution.


text:
Q: Average of truncated Normal Distribution $N$ points are generated independently from Normal Distribution centered at $x=1$, that is $x_i \sim \mathcal{N}(1,1)$. We define:
$$
P = \left\{x_i \ |\ \ x_i > 0\right\}
$$
As ${N\to\infty}$ what is the average of points in $P$?
It seems like simple question but I'm not managing to formulate it mathematically and solve it.

A: So you need to find $\lim_{N\to\infty} \dfrac{\sum_{i=1}^NX_i1_{(X_i>0)}}{\sum_{i=1}^N 1_{(X_i>0)}}$.
Divide the numerator and denominator by $N$, then apply SLLN to see that the above limit is $\dfrac{E(X1_{(X>0)})}{P(X>0)}$.
Now, $P(X>0)=1-\Phi(-1)=\Phi(1)$.
Also, $E(X1_{(X>0)})=E((X-1)1_{(X-1>-1})+E(1_{(X-1>-1)})=E(Z1_{Z>-1)}+P(Z>-1)=E(Z1_{(Z>-1)}+\Phi(1)$.
Now $E(Z1_{(Z>-1)})=\int_{-1}^{\infty}\dfrac{1}{\sqrt{2\pi}}z\exp(-\dfrac{z^2}{2})dz$
Now break the integral into two integrals in $(-1,1)$ and $(1,\infty)$. The first integral is $0$ due to the integrand being odd. The other integral evaluates to $\dfrac{1}{\sqrt{2\pi}}e^{-1/2}$ on using the substitution $z^2/2=t$.
Hence, $\int_{-1}^{\infty}\dfrac{1}{\sqrt{2\pi}}z\exp(-\dfrac{z^2}{2})dz=\dfrac{1}{\sqrt{2\pi}}e^{-1/2}$
So your expression is finally $\dfrac{\Phi(1)+\dfrac{1}{\sqrt{2\pi}}e^{-0.5}}{\Phi(1)}$

A: The average will converge a.s. to the expected value according to the strong law of large numbers.
Let $\phi$ denote the PDF and let $\Phi$ denote the CDF of standard
normal distribution.
Then in general:
$$\int_{a}^{b}u\phi\left(u\right)du=\frac{1}{\sqrt{2\pi}}\int_{a}^{b}ue^{-\frac{1}{2}u^{2}}du=\left[-\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}u^{2}}\right]_{u=a}^{u=b}=\phi\left(a\right)-\phi\left(b\right)\tag1$$
Consequently if $U$ has standard normal distribution then:
$$\mathbb{E}\left(U\mid a<U<b\right)=\frac{\int_{a}^{b}u\phi\left(u\right)du}{\int_{a}^{b}\phi\left(u\right)du}=\frac{\phi\left(a\right)-\phi\left(b\right)}{\Phi\left(b\right)-\Phi\left(a\right)}\tag2$$
Setting $U=X-1$ random variable $U$ has standard normal distribution and application of $(2)$ results in:
$$\mathbb{E}\left(X\mid X>0\right)=\mathbb{E}\left(U+1\mid U+1>0\right)=1+\mathbb{E}\left(U\mid-1<U<\infty\right)=1+\frac{\phi\left(-1\right)}{1-\Phi\left(-1\right)}$$


text:
Q: Ccылка на поле внешнего класса из вложенного enum Добрый день, подскажите пожалуйста. Изучаю Java и возник вопрос. Можно ли получить ссылку из вложенного Enum ссылку на поле внешнего класса? Мне компилятор советует сделать поле статическим, но мне этот вариант не подходит. {Classname}.this.{field} тоже не работает.Есть ли ещё какие нибудь способы?
Update

Хорошо, ссылку я могу передать в созданный enum, а есть ли возможность передать её в момент создания? Я делаю приложение на андроид для интернет магазина, и для всплывающего меню продукта решил использовать enum. Приблизительно так
private enum PopupAtion {
    information("Информация о продукте"),
    add_to_favorite(User.favoriteIds().contains(this.product.getProduct_id()) ? "Убрать из избранных" : "Добавить в избранные"),
    add_to_alert(User.alertIds().contains(this.product.getProduct_id()) ? "Убрать из ожидаемых" : "Сообщить о поступлении"),
    add_to_cart("Добавить в корзину");

    String action;

    PopupAtion(String action) {
        this.action = action;
    }

    @Override
    public String toString() {
        return action;
    }
}

A: Enum - это статический объект. Он не может получать доступ к не статическим полям родительского класса напрямую. Как вариант - передавайте в Enum ссылку на объект и пользуйте ее.

A: Всплывающее меню будет много раз изменяться вслед за требованиями к интерфейсу магазина. Зашивать это в enum - плохо и антипаттерн. При каждом изменении требований вам придется переписывать и перекомпилировать код. При этом совместимость версий будет нарушена. Пользователь с необновленной версией приложения скорее всего не сможет работать с изменившимся API бэкенда.
Рекомендую использовать List<SomeCustomClass>, а наполнять его динамически, получая данные от сервера в XML или JSON.


text:
Q: Can not understand behaviour by passing arguments to Javascript functions Consider following HTML Snippet with Javascript in it. Paste this code here to see that stuff running in the Tryit Editor from W3Schools.
<!DOCTYPE html>

Number with quotes

Number without quotes

Text with quotes

Text without quotes

The first link puts out 00001030.
The second: 536 Which I cant understand at all ?!
The third link does nothing (maybe no type for the parameter specified)
and the last link works well again (output: hello)
So whats with the second and third link?

A: The first one is string, the second one is interpreted as octal number because of leading 0.
EDIT: Explanation from @RobG to question: "but why can´t it alert just 00001030 or at least 1030? Why 536?"
Because Number.prototype.toString assumes a radix of 10
Update:
The 3rd link does nothing because hello is not defined. Most probably you got error in console: ReferenceError: hello is not defined


text:
Q: Show only current user's products on the frontend in Woocommerce I need to show only current user's products on the frontend, that is for the user that are logged in, he/she should be only able to view their own products across the site. I tried the code below but this limits access to all the posts and pages which current user didn't create. And I need to limit only for woocommerce products.
function shapeSpace_set_only_author($query) {
    global $current_user;
    $query->set('author', $current_user->ID);
}
add_action('pre_get_posts', 'shapeSpace_set_only_author');

A: You can use dedicated woocommerce_product_query action hook that will restrict the product displayed to:
add_action( 'woocommerce_product_query', 'shapeSpace_set_only_author', 20, 2 );
function shapeSpace_set_only_author ( $q, $query ) {
    if( is_admin() ) return;

    global $current_user;
    $q->set('author', $current_user->ID);
}

Code goes in function.php file of your active child theme (or theme).
Tested and works

A: Almost there, you just need to specify that you want to alter the query only for products.
add_action( 'pre_get_posts', 'modify_query_show_current_user_products' );

function modify_query_show_current_user_products( $query ) {
    global $current_user;

    if( ! is_admin() && $query->is_main_query() && isset( $query->query_vars['wc_query'] ) && $query->query_vars['wc_query'] == 'product_query' ) {
        $query->set('author', $current_user->ID);
    }
}


text:
Q: Active Admin resource index: showing filtered collection count I'm basically trying to show the count of the filtered collection in the resource index page title when a filter is run -- ie 'Users - 3' when someone checks to see how many Users signed up today -- much like it's doing in the pagination on the bottom of the page -- but I can't seem to figure out how to display it as part of index :title =>  x

A: Try this: index :title => collection.count or index :title => proc {collection.count} or @users instead of collection

A: If you would like to prepend the resource name, you simply need to perform the concat'ing in the proc:
index :title => proc{ "Users - #{collection.count}" }

Haven't tested it out, but that should work for you.


text:
Q: Is there any way to check whether there is an incoming message in Python Socket I am using a socket in Python and trying to find out how to check whether there is an incoming message in the code. I need it to print if there is an incoming message. If there is not an incoming message, just will write 'NO DATA'
I have tried to check with an if condition but it did not work:
import socket
import time
#AG AYARLARI
HOST = ''
PORT = 16000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))

#AGI BASLATMA

s.listen(1)
conn, addr = s.accept()
i=0
print('I:::',i)
print('Connected by', addr)
 while True:
        data=conn.recv(1024)
        if data:
            print(data)
        else:
            print (str.encode('No data'))
            break

*

*If there is a message take: "Message"

*If not: "No Data"

A: Try using select:
    import select

    timeout = 10  # in seconds
    ready_sockets, _, _ = select.select(
        [conn], [], [], timeout
    )
    if ready_sockets:
        data = conn.recv(1024)
        print(data)
    else:
        print('No data')

Read more about it here: https://docs.python.org/3.7/library/select.html


text:
Q: Proof of the Davies-Gaffney estimate in elliptic pdes? I'd like a reference to a proof of the Davies-Gaffney estimate; which is an off-diagonal decay result. See for instance assumption H2 in the paper "Hardy Spaces associated to non-negative self-adjoint operators satisfying Davies-Gaffney estimates" by Hofmann, Lu, Mitrea, Mitrea, and Yan. What I'd like to see more specifically is the proof of the estimate for the heat semigroup of a strongly elliptic operator, and under what conditions it is proven.

A: I think what you need is Theorem 5.5.6 of the book Davies, E. B. Heat kernels and spectral theory. Cambridge Tracts in Mathematics, 92.


text:
Q: Decrement value in a loop I am trying to make a query model where every time a query is posted, specific users are notified by mail and their records are decremented by 1.
Mail is working fine but the decrement is happening by the number of users identified and not 1.
Have tried various P&C.
$exclusive = DB::table('user_plans')
    ->leftJoin('companies', 'companies.id' , '=', 'user_plans.user_id')
    ->select('user_plans.*')
    ->where('user_plans.service_id' , '=', $input['project'])
    ->where('user_plans.lead_type' , '=', 2)
    ->where('user_plans.count' , '>', 0)
    ->limit(5)
    ->get();

$shared = DB::table('user_plans')
    ->leftJoin('companies', 'companies.id' , '=', 'user_plans.user_id')
    ->select('user_plans.*')
    ->where('user_plans.service_id' , '=', $input['project'])
    ->where('user_plans.lead_type' , '=', 1)
    ->where('user_plans.count' , '>', 0)
    ->limit(500)
    ->get();

$project = DB::table('services')
    ->select('services.*')
    ->where('services.id' , '=', $input['project'])
    ->get();

if (count($exclusive) > 0) {
    foreach ($exclusive as $exclusive) {
        Mail::send('emails.exclusive', array(
            'name'    => $input['name'],
            'email'   => $input['email'],
            'phone'   => $input['phone'],
            'detail'  => $input['detail'],
            'project' => $project[0]->name,
            'budget'  => $input['budget']
        ), function($message) use ($exclusive) {
            $message
                ->to($exclusive->lead_email)
                ->subject('CXO Forest Contact Us!');
        });

        //This part is not working
        $deduct =  DB::table('user_plans')
            ->where('user_plans.user_id' , '=', $exclusive->user_id)
            ->where('user_plans.count' , '>', 0)
            ->where('user_plans.type' , '=', 2)
            //->get();
            ->decrement('count', 1);
    }
} else {
    if (count($shared) > 0) {
        foreach ($shared as $shared) {
            Mail::send('emails.exclusive', array(
                'name'    => $input['name'],
                'email'   => $input['email'],
                'phone'   => $input['phone'],
                'detail'  => $input['detail'],
                'project' => $project[0]->name,
                'budget'  => $input['budget']
            ), function($message) use ($shared) {
                $message
                    ->to($shared->lead_email)
                    ->subject('CXO Forest Contact Us!');
            });

            $deductx = DB::table('user_plans')
                ->where('user_plans.user_id' , '=', $shared->user_id)
                ->where('user_plans.count' , '>', 0)
                ->where('user_plans.type' , '=', 2)
                ->decrement('count', 1);
        }
    } else {
        Mail::send('emails.exclusive', array(
            'name'    => $input['name'],
            'email'   => $input['email'],
            'phone'   => $input['phone'],
            'detail'  => $input['detail'],
            'project' => $project[0]->name,
            'budget'  => $input['budget']
        ), function($message) use ($shared) {
            $message
                ->to('amit.khare@studyspectrum.com')
                ->subject('Urgent: This lead does not have any takers');
        });
    }
}

Every time the code runs, deduct should reduce user_plans by 1 and not the number of emails sent.
Thanks guys for the help.

A: Here's the part part that is not working, try this:
DB::table('user_plans') ->where('user_plans.user_id' , '=', $exclusive->user_id) ->where('user_plans.count' , '>', 0) ->where('user_plans.type' , '=', 2)  ->take(1)->delete();


text:
Q: Nginx error 502 and 504 (upstream timed out) I have searched and looked at many answers and solutions on StackOverflow and none of them have helped me fix my issue.
For the record, I am running Laravel framework on Laravel forge, which runs on Nginx.
My application has an admin user functionality which is activated by AJAX and might take 20-30 mins to complete. I mainly need to do these while the application is still new and then probably won't use it much in the future, so I just need to make it work for now at least.
So first I was getting Error 504 such as this:
2017/10/30 18:17:21 [error] 3603#3603: *89720 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 172.68.58.80, server: www.xxxxx.com, request: "POST /api/copy-table HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.1-fpm.sock", host: "www.xxxxx.com", referrer: "https://www.xxxxx.com/copy"

Then I adjusted these PHP values:
max_execution_time = 1800
output_buffering = 65535

As well as these Nginx values:
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_connect_timeout 1800;
fastcgi_send_timeout 1800;
fastcgi_read_timeout 1800;

And now I am getting an Error 502 with this in the log:
2017/10/31 15:11:40 [error] 10795#10795: *3 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 172.68.58.80, server: www.xxxxx.com, request: "POST /api/copy-table HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.1-fpm.sock:", host: "www.xxxxx.com", referrer: "https://www.xxxxx.com/copy"

This works great on my dev machine which is using Apache instead of Nginx, so it's definitely something with Nginx/PHP configuration that's causing this. I am also running Cloudflare on the live website, so I don't know if that could have any impact too?
Does anyone have any ideas what I can try next to fix this issue?


text:
Q: Sorting lines according a column value I need to sort all of the linnes in the csv filles according to the number contained in the second column from min to max, ignoring the first (header line):
ID(Prot),   ID(lig),    ID(cluster),    dG(rescored),   dG(before), POP(before)
10V1,   lig1,   1,  0.893101,   -7.2300,    36
10V1,   lig1,   3,  1.04024,    -6.5800,    4
10V1,   lig1,   4,  1.03044,    -6.5200,    7
10V1,   lig10,  1,  0.895754,   -6.0300,    47
10V1,   lig10,  2,  0.668236,   -5.9500,    112
10V1,   lig10,  3,  1.0103, -5.8200,    19
10V1,   lig1001,    1,  0.594972,   -5.6500,    142
10V1,   lig1001,    2,  1.05779,    -5.5000,    10
10V1,   lig1001,    3,  1.11195,    -4.9500,    2
10V1,   lig3,   1,  1.01583,    -5.6000,    20
10V1,   lig3,   2,  0.972203,   -5.2600,    36
10V1,   lig3,   3,  0.694967,   -5.2400,    118
10V1,   lig8,   1,  0.931977,   -7.4000,    25
10V1,   lig8,   2,  1.00413,    -7.1100,    9

should be sorted like lig1, lig3, lig8, lig10, lig1001 etc:
ID(Prot),   ID(lig),    ID(cluster),    dG(rescored),   dG(before), POP(before)
    10V1,   lig1,   1,  0.893101,   -7.2300,    36
    10V1,   lig1,   3,  1.04024,    -6.5800,    4
    10V1,   lig1,   4,  1.03044,    -6.5200,    7
    10V1,   lig3,   1,  1.01583,    -5.6000,    20
    10V1,   lig3,   2,  0.972203,   -5.2600,    36
    10V1,   lig3,   3,  0.694967,   -5.2400,    118
    10V1,   lig8,   1,  0.931977,   -7.4000,    25
    10V1,   lig8,   2,  1.00413,    -7.1100,    9
    10V1,   lig10,  1,  0.895754,   -6.0300,    47
    10V1,   lig10,  2,  0.668236,   -5.9500,    112
    10V1,   lig10,  3,  1.0103, -5.8200,    19
    10V1,   lig1001,    1,  0.594972,   -5.6500,    142
    10V1,   lig1001,    2,  1.05779,    -5.5000,    10
    10V1,   lig1001,    3,  1.11195,    -4.9500,    2

I've tried
sort -k2.4,2n "${csv}" > sorted.csv

but it did not recognize the values in second properly ..

A: By default sort recognizes fields separated by non-blank to blank transitions. The second field of your second line (the first being the header) is not lig1 nor lig1,, it's like    lig1,.
At first it's not clear if this field contains leading spaces or a tab character, because this site converts tabs to multiple spaces when showing code. The raw source tells me the second field in each line contains one leading tab.
This tab character counts as the first character in the field, so your -k2.4,2n is off by one. It should be -k2.5,2n.
To reliably print the header first and not sort it, let something read and print it before sort processes the rest. It can be your shell:
{ IFS= read -r line; printf '%s\n' "$line"; sort -k2.5,2n; } <"${csv}"

or it can be head:
{ head -n 1; sort -k2.5,2n; } <"${csv}"

In my Debian 10 both commands work well when reading from a regular file. When reading from a pipe (e.g. cat "${csv}" | { head …), head apparently can read too much and drop excessive data (so sort won't get it, it's lost).
I guess head reads more even when reading from a regular file, it just seeks back to the right place before exiting, so the next tool can take over from there; this is obviously impossible with non-seekable input.
read is more careful and always reads one byte at a time, so it never reads too much.

A: For this purpose, I advice to use Miller (mlr), which has verbs, or subcommands, similar to well-known commands from the Unix world, as  cat, head, tail, cut, sort, etc.
You are looking for a natural ordering by the second column in a CSV file.
mlr --csv sort -t '   ID(lig)' "${csv}"

The column name for sorting must be given appropriately, notice three blank spaces in '   ID(lig)'.
Of course, we can remove the blank spaces in the header with sed, tr, awk or whatever, e.g.
sed '1 s/ //g' "${csv}" | mlr --csv sort -t 'ID(lig)'

Take a look at Miller in 10 minutes.


text:
Q: Windows Python 64 & 32 bit versions and pip I have made a simple python script and built a 64-bit Windows executable from it via pyinstaller. However, most computers at my office run 32-bit Windows operating systems, thus my program does not work. From what I have read, it is possible to make an executable for 32-bit systems as long as I use the 32-bit version of python. So I went ahead and installed the 32-bit version of python 3.5, but I can't find the way to link pip to the 32-bit version of python so I can install all the necessary modules. Every time I call pip it displays all the modules that are installed on the 64-bit version, even though by default I am running the 32-bit version python.

A: I had a similar problem with both 32 and 64-bit versions of Python installed. I found if I ran the pip install in the command prompt from the location of pip.exe it worked fine. In my case, the file path was the following:
C:\Program Files\Python\3.5\Scripts


text:
Q: Website security hole I have a website, im using sessions for the login. In every pages of my admin, I have a checker if the user has logged in or not. I have this code
if(!$_SESSION['loggedin'] && !$_SESSION['userid'])
{
  header('Location:login.php');
}
else
{
 //proceed loading the page
}

Now what happen now, someone is messing up with our site. He/She is entering some vulgar texts on the website like ... All disrespectful words and its so frustrating because the website is accessible to the public.
I believe the username and password was being hacked. So i asked all admin users to changed all passwords and i added a logger to monitor who will update the content of the website. I record the userid of the logged in user and its post. After changing passwords, the same thing happen again, content was updated by the hacker or whoever he is.
I checked my log, the user id of the hacker is 0. How is that possible and how do i stop him? Makes me wonder what did he do because it is in my condition at the very top of the page that if $_SESSION['userid'] has no value, it should redirect them to the login page.
Currently i put the website offline because the hacker is getting worst and worst. I was able to find out the ip address of it.
This is my user authentication
$user=trim($_POST['username']);
$pass=trim(stripslashes($_POST['password']));
$sql="SELECT * FROM users WHERE user='$user' AND pass='$pass'";
$qry=mysql_query($sql) or die (mysql_error());
if( mysql_num_rows($qry) )
{
  $row=mysql_fetch_assoc($qry);
  $_SESSION['userid'] =$row['userid'];
  $_SESSION['loggedin']=1;
  header('Location: welcome.php');
}
else
{
      header('Location:login.php?error=1');
}

A: Make sure to always call exit after a Header('Location: ...') call. Otherwise the script will continue execution after the header call. it will continue as far as sending everything after the header call to the browser, but regular browsers will see the location header and do a redirect. Not-so-nice users may circumvent the location call and can surf your "protected" page as they wish!
So, don't forget to always  end execution immediately:
header('Location:login.php');
exit;

A: As @nhahtdh observed, you have an obvious SQL injection. Consider what happens if someone where to enter admin' OR 1=1; -- into your username field (yes, people do indeed try these sorts of things). Your SQL string gets converted into something like this:
SELECT * FROM users WHERE user='admin' OR 1=1; -- AND pass='junk'

Which will select all of the users from your user table. The userid of 0 is, presumably, the first userid in your SQL table.
Please have a look this excellent answer that explains how to avoid SQL injections.