text:
Q: GAE Datastore ID I've created two different Entities, one a User and one a Message they can create. I assign each user an ID and then want to assign this ID to each message which that user creates. How can I go about this? Do I have to do it in a query?
Thanks

A: Assuming that you are using Python NDB, you can having something like the following:
class User(ndb.Model):
    # put your fileds here

class Message(ndb.Model):
    owner = ndb.KeyProperty()
    # other fields

Create and save a User:
user = User(field1=value1, ....)
user.put()

Create and save a Message:
message = Message(owner=user.key, ...)
message.put()

Query a message based on user:
messages = Message.query().filter(Message.owner==user.key).fetch() # returns a list of messages that have this owner

For more information about NDB, take a look at Python NDB API.
Also, you should take a look at Python Datastore in order to get a better understanding of data modeling in App Engine.


text:
Q: How to reach the upper platform on the area where an El Gigante is fought for the second time?

Shooting down the boulder almost seems to provide a pathway, but no context-sensitive prompt appears:

To clarify, there indeed are several El Gigantes in the game.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract query-object from a fasta file and store them in different fasta file, one per query gene I am running out of ideas to do this, and I will appreciate some help, please.I have 2 fasta files from two different bacterial strains with 1000 genes each. An example of files:
file A:                           fileB
    query seq.id                    query seq.id
    query seq                        query seq.id
    objA seq.id                     objB seq.id
    objA seq                          objB seq
    query_1 seq.id                query_1 seq.id
    query_1 seq                    query_1 seq
    obj_1A seq.id                obj_1B seq.id
    obj_1A seq                    obj_1B seq

What I would like to do is to get it this:
   file_1                  file_2
 query seq.id          query_1 seq.id
  query seq              query_1 seq
obj seq.id                obj_1A seq. id
  obj seq                   obj_A seq
 objB seq.id             obj_1B seq.id
 objB seq                  obj_1B seq

But I just dont know how to split the fasta files. I was trying to do this using biopython SeqIO but I am quite lost.
I'm working in this code:
for file in files:
    my_file=glob.glob(file + '/*.fa')
    #print my_file[1]
    filename='outfile%s.fasta'
    records=list(SeqIO.parse(my_file[1], 'fasta'))
    query_gene=records[0].id
    print query_gene
    for record in  range (0,len(records),2):

        with open(os.path.join('/home/results/files/', filename% query_gene), 'w') as output_handle:

            SeqIO.write(records, ouput_handle, 'fasta')
sorting_fasta_files()

This is not giving me the right output. It places all the genes in files when, and want 2 genes per file, query-obj.


text:
Q: given a set of points in cartesian plane find the point which has shortest sum of distance from all points This I have reduced to
Given a set of n points find out a point X,Y such that the $\sum_{i=1,n} (x_{i}-X)^2 + (y_{i}-Y)^2$ is minimum. Now as per the comments I found out that this is wrong. Can someone tell me the right approach please?

A: The square of the distance from a point is a quadratic polynomial, so the sum of the squares is quadratic, and the center of the resulting circular paraboloid is the center of mass of the points.
The sum of the distances is not nearly as nice of a function. The point of minimal total distance to $3$ points is called the Fermat point $P$ of the triangle $ABC$, which is either the vertex with angle greater than $\frac{2\pi}{3}$ or the unique point in the interior so that $\angle APB = \angle BPC = \angle CPA = \frac{2\pi}{3}$. The case of $4$ points is actually even easier to solve, since the total-distance minimizing point is either the intersection of the diagonals of a convex quadrilateral, or the interior point if the points are not in convex position. For more information, see the geometric median or Fermat-Weber point.


text:
Q: Excel: Find average in a range that depends on the duplicate values in another column I want to calculate the average of a range of cell entries depending on specific criteria. The criteria is: the range in which column A has the same value, I need to calculate the average in that range, but from the data entered in column B
In the attached figure-
A9:A10 has the same value (=4)
Therefore C9=average(B9:B10)
Similarly,
A11:A15 has the same value (=7)
Therefore C11=average(B11:B15)

Thanks in advance,

A: Just use AVERAGEIF():
You can put this in the specific cells where you want the average:
=AVERAGEIF($A$2:$A$18,A2,$B$2:$B$18)

Or, put this in B2 and drag down:
=IF($A2=$A1,"",AVERAGEIFS($B$2:$B$10,$A$2:$A$10,$A2))

A: I had similar problem and used this:
=IF(COUNTIF($A$2:$A$18,$A2),AVERAGEIFS($B$2:$B$18,$A$2:$A$18,$A2),"")

IF function with "logical_test" as duplication and "value_if_true" as Average of the values matching the duplicated value and the "value_if_false" as "" to get the single input already existing for the single value.
It worked successfully only that the result repeated for every duplicate value.. but after that you can remove the duplicates.


text:
Q: How to set size to Jtable using GridBagLayOut I am using GridBagLayout to position GUI components. I have used a Jtable inside a JFrame. But the table is not fitting to the frame. It appears as follows. When I drag the frame it shows the table.

Here is my code. I used this as a pop up Jframe to a button listner.
public class ViewPrescriptionHistory extends JFrame{

    private GridBagConstraints gridbBagConstraints;
    private JTable drugDetailsTable;
    HistroyTableModel drugDetailsTabelModel = new HistroyTableModel();

    public ViewPrescriptionHistory() {
        this.setLayout(new GridBagLayout());
        this.setSize(500, 500);

        this.pack();
        initialize();
    }

    private void initialize() {
        gridbBagConstraints = new GridBagConstraints();
        gridbBagConstraints.insets = new Insets(10, 0, 10, 0);
        gridbBagConstraints.ipady = 10;
        gridbBagConstraints.ipadx = 10;

        drugDetailsTable = new JTable(drugDetailsTabelModel);
        drugDetailsTable.setPreferredScrollableViewportSize(new Dimension(600, 100));
        drugDetailsTable.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(drugDetailsTable);
        scrollPane.setBounds(5, 218, 884, 194);

        this.add(scrollPane);

    }
}

Here is my table model. I used Abstract Table model.

    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.table.AbstractTableModel;
    import assignment3.prescriptionsystem.model.HistoryModel;

    public class HistroyTableModel extends AbstractTableModel{

        private String[] columnNames = { "Doctor Name", "Date", "Drug Name", "Form" , "Dosage" };
        List<HistoryModel> historyList = new ArrayList<HistoryModel>();

        public String getColumnName(int column) {
            return columnNames[column];

        }

        public int getColumnCount() {

            return columnNames.length;
        }

        public int getRowCount() {

            return historyList.size();
        }

        public void reloadDrugList(List<HistoryModel> drugsData) {
            historyList= drugsData;
            fireTableDataChanged();
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            HistoryModel drugData = historyList.get(rowIndex);
            switch (columnIndex) {
            case 0:
                return drugData.getDocName();
            case 1:
                return drugData.getDate();
            case 2:
                return drugData.getDrugName();
            case 3:
                return drugData.getFrom();
            case 4:
                return drugData.getDosage();
            default:
                return null;

            }

        }

}

Here is my model class
public class HistoryModel {
    String docName;
    String date;
    String drugName;
    String dosage;
    String from;
    public String getDocName() {
        return docName;
    }
    public void setDocName(String docName) {
        this.docName = docName;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getDrugName() {
        return drugName;
    }
    public void setDrugName(String drugName) {
        this.drugName = drugName;
    }
    public String getDosage() {
        return dosage;
    }
    public void setDosage(String dosage) {
        this.dosage = dosage;
    }
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
}

How to fix this issue?

A: Firstly you should be adding your components to, and setting the GridBagLayout on, the JFrame's content pane, rather than the JFrame itself. Consider this image of the containment hierarchy taken from an Oracle tutorial:

You should also be calling pack() after you have added your components, not before:
The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
Because pack() handles the sizing of the JFrame, you do not need to explicitly call setSize()
So your code should look like:
getContentPane().setLayout(new GridBagLayout()); // Set the layout on the content pane rather than the JFrame

gridbBagConstraints = new GridBagConstraints();
gridbBagConstraints.insets = new Insets(10, 0, 10, 0);
gridbBagConstraints.ipady = 10;
gridbBagConstraints.ipadx = 10;

drugDetailsTable = new JTable(drugDetailsTabelModel);
drugDetailsTable.setPreferredScrollableViewportSize(new Dimension(600, 100));
drugDetailsTable.setFillsViewportHeight(true);

JScrollPane scrollPane = new JScrollPane(drugDetailsTable);
scrollPane.setBounds(5, 218, 884, 194);

getContentPane().add(scrollPane); // Add the scroll pane to the content pane rather than the JFrame

pack(); // Call pack at the end

And the resulting GUI looks like:


text:
Q: Why need first save to Files then to Photos? I have this image: http://t44-post-cover.s3.eu-central-1.amazonaws.com/bixw.mp4
When it is loaded to browser on an iPhone, I can not download directly to Photos, it is not among sharing options, but first I need to save into Files then to Photos. Why? Is it any workaround for it?


text:
Q: C++ application with JNI throws an error "jvm.dll not found . re-installing the application could fix ...." I have written a plain C++ application in VC6 that is using jni to call up a method in java. For doing so, I have included jni.h and other lib folders in the project directories.
the code compiles but when i run teh application it fails saying "jvm.dll is not found. reinstalling the application would fix it". But the jvm.dll is present in my pc.
If i set the working directory of the application to the location where the jvm.dll is, then it works like a charm. I cannot set the working directory of the application to the directory of jvm.dll as this application is going to be a dll in future.
I tried also updating the PATH variable in the system variables to the location of jvm.dll, but nothing works..
I suspect that the jvm.lib is loading the jvm.dll from certain directory location which is not provided by my application .. hence its failing,..
Please suggest me what is going wrong.
Thanks in advance.
Regards
Raghavendra

A:
it fails saying "jvm.dll is not found. reinstalling the application would fix it".

Obviously that's your own error message, or Windows': not Java's, and it's incorrect. Reinstalling the application can't possibly have any effect on whether jvm.dll can be found.
You need to ensure that jvm.dll is on your PATH.

A: I got the same error even though my PATH is configured as StockB describes. Copying and pasting the DLL into my working directory fixed the issue. In my case, this was ../x64/Debug.


text:
Q: If stars are ionized, where are the electrons? As far as I know, universe is electrically neutral so,
If stars are ionized, where are the electrons?

A: The electrons are still inside the stars. A stellar plasma is electrically (almost) neutral, the electrons in a plasma are simply not bound to individual nuclei. If we could take some plasma out of a star and we would let it cool down to room temperature, most of the matter in that gas (at least from main sequence stars) would be ordinary neutral hydrogen and helium gas.

A: I learned that the electrons which are separated from their nuclei are being annihilated by the positrons. These positrons are the product of the weak interaction that emits photons from the sun.
So, the sun is producing photons by destroying the electrons (and of course, by converting protons into neutrons.
Source : https://www.youtube.com/watch?v=zS-LsjrJKPA&list=PL93B3DDC89C085C1C#t=827
Edit: Although the correct answer is the another one, I'll keep my answer here for the comments below this.


text:
Q: How to detect GET parameters in URL, and place values according to that,? I am working on a project in PHP and JavaScript, where i have to create a value from my end, and pass the same in URL query string on redirect from my URL, Below is Description:
I have a URL, https://abc.amindfad.com/c.php?id={abdid}
on above URL I want redirection, and pass value from my end by detecting where is {abdid}
The above URL will be redirecting from (my URL) :-
https://console.adcashod.net/click.php
i have not done anything yet, Because i am little confused in Code which should be used here.
in Results I want that, when I click on
(my URL) :-
https://console.adcashod.net/click.php
it get redirects to :-
https://abc.amindfad.com/c.php?id={abdid} but,
replace {abdid} with a value which is defined by me. for it.
Waiting for suggestions.

A: Take a look at this https://www.php.net/manual/en/function.str-replace.php
$value = 'value_defined_by_me';
$url = 'https://abc.amindfad.com/c.php?id={abdid}';
$url = str_replace('{abdid}', $value, $url); //output: https://abc.amindfad.com/c.php?id=value_defined_by_me

A: As in simple
let url = new URL('https://abc.amindfad.com/c.php?id=value&name=john');

let searchParams = new URLSearchParams(url.search);

console.log(searchParams.get('id'));  // outputs "value"

console.log(searchParams.get('name'));  // outputs "john"


text:
Q: maximal unramified extension of Breuil ring in $A_{cris}$ Here is the notation. Let $k$ be a perfect field of characteristic $p$, $W=W(k)$ the ring of Witt vector and $\mathfrak{S}:=W[[u]]$, $\mathcal{O}_{\mathcal{E}}$ is the $p$-adic completion of $W[1/u]$ which is DVR. Denote $R=\lim_{\leftarrow}\mathcal{O}_{
\bar{K}}/p$ where the transition map is Frobenius. The ring of Witt vector $W(R)$ has a canonical surjection $W(R) \xrightarrow{\theta} \mathcal{O}_{C_K}$ where $C_K$ is the completion of $\bar{K}$. The ring $A_{cris}$ is a divided power envelope of $W(R)$ with respect to $\ker \theta$.
One can embed $\mathcal{O}_{\mathcal{E}}$ into $W(R)\subset A_{cris}$ by sending $u\mapsto [\underline{\pi}]$ ($\underline{\pi}=(\pi,\pi^{1/p}, \cdots)$). In this paper, Kisin defines $\mathcal{E}^{un}$ as the maximal unramified extension of $\mathcal{E}=Frac(\mathcal{O}_{\mathcal{E}})$ contained in $W(Frac(R))[1/p]$ and $\mathfrak{S}^{un}:=\mathcal{O}_{\mathcal{E}^{un}}\cap W(R)$ (which must be done by Breuil earlier).
Here is my question. Consider $\mathfrak{S}^{un}$ as a subring of $A_{cris}$ by composing the Frobenius on $\mathfrak{S}^{un}$ and the inclusion to $W(R)$ as above.(In particular, $u\mapsto [\underline{\pi}]^p$) In the same paper of Kisin, it says that $\mathfrak{S}^{un}\cap pA_{cris}=p\mathfrak{S}^{un}$ when $p>2$.(proof of Theorem 2.2.7.) Why is this true? He mentions a paper of Brueil(proof of 3.3.2.), but I don't see why this helps the assertion. Also, the structure of $\mathfrak{S}^{un}$ is somewhat mysterious to me. Naively it should be a subring of $\mathcal{O}_{\mathcal{E}^{un}}$ consists of elements "without $u$ in the denominator", as $\mathcal{O}_{\mathcal{E}^{un}}$ is a DVR with residue field $k((u))^{sep}$. However, as the residue field is not perfect, this description is not concrete.

A: It is false that $\mathfrak{S}^{un}\cap pA_{cris}=p\mathfrak{S}^{un}$. For example, $E(u)\in\mathfrak{S}\subset\mathfrak{S}^{un}$ is not divisible by $p$ in $\mathfrak{S}^{un}$ but gets mapped to $\varphi(\xi)$ where $\xi$ is a generator of $\theta:W(R)\to\mathcal{O}_C$ which is divisible by $p$ in $A_{cris}$ because $\varphi(\xi)-\xi^p\in pW(R)$.
The claim in the article is weaker: Kisin says that if the image of a Frobenius-equivariant map $f:\mathfrak{M}\to \mathfrak{S}^{nr}$ from a height $1$ Breuil-Kisin module becomes divisible by $p$ in $A_{cris}$, then it was divisible by $p$ already in $\mathfrak{S}^{nr}$. Here is how we can prove such statement(the proof of course uses the assumption on the height of $\mathfrak{M}$):
The ring $\mathfrak{S}^{nr}/p$ can be identified with the ring of Puiseaux series $\{\sum c_{\alpha}u^{\alpha}|\alpha\in \mathbb{Z}[1/N]\cap\mathbb{R}_{\geq 0}\text{ for some }N\text{ coprime to }p\}$. Suppose that for every $x\in\mathfrak{M}$ the image $\varphi(f(x))$ is inside $pA_{cris}$, but there exists $x$ such that $f(x)$ is not divisible by $p$ in $\mathfrak{S}^{un}$. Among such $x$ choose one for which $\overline{f(x)}\in\mathfrak{S}^{un}/p$ has the minimal lowest exponent of $u$ in the expansion. Denote this exponent by $\alpha$ so that $\overline{f(x)}=c_{\alpha}u^{\alpha}+\sum\limits_{\beta >\alpha}c_{\beta}u^{\beta}$.
Using that $A_{cris}/p\to\mathcal{O}_C/p$ is the universal characteristic $p$ divided power thickening of $\mathcal{O}_C/p$ we can identify $A_{cris}/p$ with the divided power envelope $\mathcal{O}_C/p\langle x\rangle/(x-p^{1/p})$ of the ideal $(p^{1/p})\subset\mathcal{O}_C/p$ via the map that sends $x$ to $[p^{\flat}]$ and an element $a\in\mathcal{O}_C/p$ to $\tilde{a}^p\in A_{cris}/p$ where $\tilde{a}$ is an arbitrary preimage of $a$ under $\theta$. Since $\pi^{\flat}$ is equal to $(p^{\flat})^{1/e}$ in $R$ up to a unit, an element of the form $c_{\alpha}u^{\alpha}+\sum\limits_{\beta >\alpha}c_{\beta}u^{\beta}$ dies under the map $\mathfrak{S}^{nr}/p\xrightarrow{\varphi} A_{cris}/p$ if and only if $\alpha\geq e$.
By the assumption on $\mathfrak{M}$ there exists $y=\sum\limits_{i=0}^{p-1} y_i\otimes u^i\in\varphi^*\mathfrak{M}=\mathfrak{M}\otimes_{\mathfrak{S},\varphi}\mathfrak{S}$ such that $\varphi_{\mathfrak{M}}(y)=E(u)x$. It means that for at least one $i$ the element $\overline{f(y_i)}$ has expansion of the form $c'_{\gamma}u^{\gamma}+\sum\limits_{\beta>\gamma}c'_{\beta}u^{\beta}$ with $p\gamma\leq \alpha+e$. It follows that $\gamma\leq \frac{2}{p}\alpha<\alpha$. By the minimality assumption on $\alpha$ and $x$, the reduction $\overline{f(y)}$ must be zero, hence $\varphi_{\mathfrak{S}^{un}}(\overline{f(y)})=E(u)\overline{f(x)}$ is zero which implies the vanishing of $\overline{f(x)}$ itself. That gives us a contradiction.


text:
Q: How can I combine my controllers AngularJS? I have my MainCtrl(called from $routeProvider and also from html):
function MainCtrl($scope, $routeParams){
  //send data(see below) to AngularTemplate for apdate page
}

and I have my function, which fetch any data:
function getData($scope, $http){
  /*
  * Nav Data(here my navigate-structure fo site)
  */
  $http({method: 'GET', url: 'data/main.json'}).
  success(function(data){
    //work with data and send it to MainCtrl
  });
  /*
  * News Data(Here my news)
  */
  $http({method: 'GET', url: 'data/news.json'}).
  success(function(data){
    //work with data and send it to MainCtrl
  });
}

Now I understand how can I send my data from one Ctrl to other using .$on and .$broadcast. But getData is not Angular Controller(it is a js-function) and it doesn't understend my args($scope and $http).
Tell me plese, how I can call getdata the first page load and send data to MainCtrl.
And also if you know, tell me please what can I do with my MainCtrl, that he call only from $routeProvider. Now at first it called from html(ng-controller), and after from $routeProvider.

A: put the getData function inside angular controller.
and it will understand the $scope and $http services
or make a protoype method set() of mainCtrl.... and pass $scope.var = value in it
       MainCtrl.prototype = {
        set = function(value){
            $scope=value;

         }

    }

A: Wrap your data fetching code in a service.  Here are two good SO answers that show how to do this:

*

*https://stackoverflow.com/a/12513509/215945

*https://stackoverflow.com/a/14530508/215945
The examples above also show how to inject the service you create (e.g., myService) into a controller.  You can inject this service into as many controllers as necessary.  Since Angular services are singletons, there will only be one instance of your data fetching code, no matter how many controllers are injected with your service.
Your service can also cache the results of the $http request.


text:
Q: Error catching a form in Access using VBA So i have a form that's updating a table in Microsoft Access. I'm using a BeforeUpdate event call to stop the form from updating if the 'first name' hasn't been filled in.
I basically only want the form to be saved once everything has been filled in, and then switch to see the updated table (the bit under If not cancel).
Currently the popup box to say 'You must enter a First Name' correctly fires, the next pop up box asking if the user wants to undo any changes fires. But then a pop up box saying 'No current record' appears and then the view changes to the table. I'm not sure why this is all happening.
Option Compare Database

Private Sub Form_BeforeUpdate(Cancel As Integer)

   Cancel = False

' perform data validation
If IsNull(Me.customer_f_name) Then

   MsgBox "You must enter a First Name.", vbCritical, "Data entry error..."
   Me.customer_f_name.BorderColor = vbRed
   DoCmd.GoToControl "customer_f_name"

   Cancel = True

End If

If Not Cancel Then

    DoCmd.SelectObject acTable, "ticket_tracker_table"
    DoCmd.Requery
    DoCmd.GoToRecord acDataTable, "ticket_tracker_table", acLast

End If

' if the save has been canceled or did not pass the validation , then ask to Undo changes
If Cancel Then

    If MsgBox("Do you want to undo any changes?", vbYesNo, "Confirm") = vbYes Then
        Me.Undo
    End If

End If

End Sub

A: Review https://learn.microsoft.com/en-us/office/vba/api/Access.Form.BeforeUpdate(even)
Instead of GoToControl, use SetFocus.
I did a very simple test with the Undo question and it does work:
Private Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(Me.customer_f_name) Then
    MsgBox "Must enter customer name."
    Cancel = True
    If MsgBox("Do you want to undo edits?", vbYesNo) = vbYes Then Me.Undo
    Me.customer_f_name.SetFocus
End If
End Sub

Suggest you put table code in AfterUpdate event.

A: so to supplement J7, with some big picture view: "basically only want the form to be saved once everything has been filled in" …. that is swimming against the tide; which is why you are having to write a lot of code.  The product enters data as you go fundamentally.  that is it's core design.
it is very normal to do field checks as you go - typically in the AfterUpdate event, the check code is applied and if invalid - generate a message box and invoke an Undo plus reset the focus back to the field they were attempting to leave.
A totally different design, in some cases it may justify a temp local duplicate table just for the purposes of holding form input data - - this approach allows a very elaborate check(s) against data in the production database; where upon if valid an Append Query then writes the data into the permanent table.


text:
Q: Measurability of the floor function Let $u(x)=⌊x⌋$, i.e  the largest integer not greater than $x$ . Determine $\{u≥a\}$ for all $a\in \mathbb{R}$. Show that $u$ is Borel-measurable. Can anyone help me with this problem?

A: An idea to show that $u$ is measurable is that you can express a floor function as a simple one (a limit of simple functions)
$$ u(x) = \sum_{n=-\infty}^\infty n \, \chi_{[n,n+1)}(x)$$
alternatively $u^{-1}[a,\infty) = \{ x \mid a \leq \lfloor x \rfloor \} = [ \lfloor a \rfloor +1 , \infty)$
EDIT: it is not right $u^{-1}[a,\infty) = [\lceil a \rceil,\infty)$
EDIT:Mainly intuition... i know that if there is an expression for it, it must be an interval written in terms of $a$ , and some type of roof or ceil function. For the proof
$$ a \leq \lfloor x \rfloor \implies  \lceil a \rceil \leq \lfloor x \rfloor  \leq x$$
$$ \lceil a \rceil  \leq x \implies a \leq \lceil a \rceil  \leq \lfloor x \rfloor $$


text:
Q: How to look for CH340 usb drivers I need to install the CH340 usb driver on this page; it attaches to the Arduino machine.
The instructions were given for Windows and I am using Ubuntu Linux.
The help page says the CH341 driver should already be installed.

Drivers are almost certainly built into your Linux kernel already and it will probably just work as soon as you plug it in.  If not you can download the Linux CH340 Driver (but I'd recommend just upgrading your Linux install so that you get the  "built in" one).

lsusb doesn't mention anything:
$ lsusb
Bus 001 Device 002: ID 8087:8001 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 005: ID 0cf3:e300 Qualcomm Atheros Communications
Bus 002 Device 004: ID 5986:0701 Acer, Inc Lenovo EasyCamera
Bus 002 Device 003: ID 04f3:2052 Elan Microelectronics Corp. Touchscreen
Bus 002 Device 002: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Then lsmod | grep ch34 returns nothing.  So I'm guessing it's not installed?


text:
Q: Recover control buttons in xfce running backbox Recently i was running XFCE desktop environment in Back box 4.6 based on Ubuntu 16.04, But later the window control buttons on the title bar of all applications disappeared after i ran a software update,I need to restore them.

A: Run this in a terminal xfce4-settings-manager and look around for the control buttons settings. You can also use this manager to change appearance settings, mouse settings etc..


text:
Q: Select data, resample and join horizontally in Python I have two dataframes df1 and df2.
df1:
    Id  Date         Remark
0   28  2010-04-08   xx
1   29  2010-10-10   yy
2   30  2012-12-03   zz
3   31  2010-03-16   aa

df2:
        Id  Timestamp                Value  Site
0       28  2010-04-08 13:20:15.120  125.0  93
1       28  2010-04-08 13:20:16.020  120.0  94
2       28  2010-04-08 13:20:18.020  135.0  95
3       28  2010-04-08 13:20:18.360  140.0  96
                   ...
1000    29  2010-06-15 05:04:15.120  16.0   101
1001    29  2010-06-15 05:05:16.320  14.0   101
                   ...

I would like to select all Value data 10 days before/including the Date in df1 from df2 for the same Id. For example, for Id 28, Date is 2010-04-08, so select Value where Timestamp is between 2010-03-30 00:00:00 and 2010-04-08 23:59:59(inclusive).
Then, I want to resample the Value data using forward fill ffill and backward fill bfill at 1min frequency so that there will be 10 x 24 x 60 = 14400 values exactly for each Id.
Lastly, I'd like to rearrange the dataframe horizontally with transpose.
Expected output looks like this:
    Id  Date         value1  value2 ...  value14399  value14400  Remark
0   28  2010-04-08   125.0   125.0       ...         ...         xx     (value1 and value2 and following values before "2010-04-08 13:20:15.120" are 125.0 as a result of backward fill since the first value for Id 29 is 125.0)
1   29  2010-10-10   16.0    16.0        ...                     yy
        ...

I am not sure what's the best way to approach this problem since I'm adding "another time series dimension" to the dataframe. Any idea is appreciated.


text:
Q: Firebase - how to set custom claim from the console In my application I use firebase authentication and Google account as credentials provider. I would like to assign roles to users. In order to do it I would like to add custom claims to the authentication token a user gets during login. And here is my problem because I don't know how to add claims to existing user from the firebase console.

A: There is currently no way to set custom claims for a user in the Firebase console. If you think this would be a useful addition, file a feature request for it.
In the meantime the easiest way to add a custom claim is to do so from the a terminal window/command prompt using a small Node.js script like this:
admin.auth().setCustomUserClaims(uid, {admin: true})

Also see:

*

*How to create Firebase Authentication claims?


text:
Q: Vector Bundles Over a Manifold Show that if a manifold $M$ is contractible, then every vector bundle over $M$ is equivalent to the trivial bundle.
Got this as homework but I'm kind of lost in the hole vector bundle subject, so if anyone could give some hints to this one as well as to understanding the subject, it would be highly appreciated.

A: Show that if $f,g:X\to Y$ are two maps between manifolds which are homotopic, and if $E$ is a vector bundle on $Y$, then $f^{-1}(E)$ and $g^{-1}(E)$ are isomorphic vector bundles on $X$. (You don't really need that both $X$ and $Y$ be manifolds: you can get by if they are just spaces and $X$ is paracompact...)
(You should really provide information about your background, otherwise it is more or less impossible to come up with a useful answer, you see!)

A: Here are a couple of things that I found helpful when thinking about vector bundles:

*

*Over nice spaces they they can be classified up to isomorphism. So by nice here we mean compact manifold, or CW complex. The idea is that every finite dimensional vector bundle $\xi: E \to X$ is isomorphic to the pull back of the universal bundle $EG \to BG$ where $G$ is some particular structure group. (for $\xi$ a real $n$ dimensional bundle $G=GL_n(\mathbb{R})$, note though that $O(n)$ is homotopy equivalent to $GL_n(\mathbb{R})$). You can learn a lot about a vector bundle by examining the map that classifies it. For example, $\xi: E \to X$ is orientable if and only if the map that classifies it can be lifted over the fibration $BSL_n(\mathbb{R}) \to BGL_n(\mathbb{R})$.

*Vector bundles are really nicely behaved families of vector spaces over $X$. We usually use them to keep track of some important data about $X$. In fact, most operations on vector spaces extend to operations on vector bundles over $X$. Things such as tensor products, direct sums, exterior and symmetric powers pop up all the time.

*Surprisingly enough every vector bundle $\xi: E \to X$ is a homotopy equivalence since the fibers are contractible. It seems like this makes vector bundles sort of silly, but it illustrates that they are inherently geometric objects. While we use them for certain constructions in homotopy theory, they are really about the geometry of the base space. That being said, homotopy theory can say a lot about vector bundles, consider Chern-Weil Theory which relates cohomology classes (a gadget that can only see homotopy theory) to things like curvature.
A big help for learning about bundles for me was thinking about them like objects, like when you think about a manifold you want to think about the manifold not its parametrizations.
Mariano's answer is dead on, I am just adding some helpful facts. Let me know if you want me to clarify something.

A: This may be a repetition of what Mariano and Sean were suggesting: you will most likely
   ultimately need to either: produce a bundle morphism between your bundle and
   the trivial bundle, or produce a global trivialization of your top space.


text:
Q: How to file a bug on Ubuntu GNOME? There is a cups problem and I don't know how or where I could submit a bug report.

A: Bug reports can be submitted using the apport-bug application from a terminal.
Open a terminal and use the command apport-bug package_name and press enter.
In your case, for cups you would use :
apport-bug cups

For more options and instructions you can read the apport-bug man page using :
man apport-bug

A: Quite alot of packages include information about who maintains them and where to file bugs - you can view this information for a package by running sudo apt-cache show PACKAGENAME - so for cups (on Ubuntu 14.04 64bit)
$ apt-cache show cups
Package: cups
...
Maintainer: Ubuntu Developers <ubuntu-devel-di...
Original-Maintainer: Debian Printing Team <debian-printi...
...
Homepage: http://www.cups.org
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Origin: Ubuntu
....

Emails removed - find them and the bug URLs by running the apt-cache ... command
So you should be able to file a bug at the given URL, or you could even email the maintainer of the package (filing a bug would likely be better). However, please check and verify whether this a bug, and not a problem with another package, misconfiguration, etc.


text:
Q: Efficient weighted cross-product in Armadillo I'm trying to find an efficient way to compute X^T * W * X where X is a dense mat of size e.g. 10,000 x 10 and W is a diagonal matrix (I store only the diagonal in an vec).
For now, I use this function
arma::mat& getXtW(const arma::mat& covar,
                  const arma::vec& w,
                  arma::mat& tcovar,
                  size_t n, size_t K) {
  size_t i, k;

  for (i = 0; i < n; i++) {
    for (k = 0; k < K; k++) {
      tcovar(k, i) = covar(i, k) * w(i);
    }
  }

  return tcovar;
}

and compute
tcovar = getXtW(covar, w, tcovar, n, K);
cprod = tcovar * covar;

Yet, this seems not optimal.
PS: You can see the whole code there.
Edit1: Seems I can use covar.t() * (covar.each_col() % w), but this doesn't seem to be much faster.
Edit2: If I implement it myself with loops in Rcpp:
arma::mat testProdW2(const arma::mat& x, const arma::vec& w) {

  int n = x.n_rows;
  int K = x.n_cols;
  arma::mat res(K, K);
  double tmp;
  for (int k = 0; k < K; k++) {
    for (int j = k; j < K; j++) {
      tmp = 0;
      for (int i = 0; i < n; i++) {
        tmp += x(i, j) * w[i] * x(i, k);
      }
      res(j, k) = tmp;
    }
  }

  for (int k = 0; k < K; k++) {
    for (int j = 0; j < k; j++) {
      res(j, k) = res(k, j);
    }
  }

  return res;
}

This is slower than the first implementation.

A: According to BLAS matrix by matrix transpose multiply there is no BLAS routine that does this directly. Instead there is the suggestion to loop over the rows of X and use dsyr. I found this an interesting question since I know how to link BLAS in Rcpp, but have not done so using RcppArmadillo. Stack Overflow knows an answer for that as well: Rcpparmadillo: can't call Fortran routine "dgebal"?. Note: I have not checked but I expect that dsyr is not part of the BLAS subset that come with R. So this will only work if your R is linked to a full BLAS implementation.
Combining this we get:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rcpp/Benchmark/Timer.h>

#ifdef ARMA_USE_LAPACK
#if !defined(ARMA_BLAS_CAPITALS)
 #define arma_dsyr dsyr
#else
 #define arma_dsyr DSYR
#endif

extern "C"
void arma_fortran(arma_dsyr)(const char* uplo, const int* n, const double* alpha, const double* X, const int* incX, const double* A, const int* ldA);

#endif

// [[Rcpp::export]]
Rcpp::NumericVector getXtWX(const arma::mat& X, const arma::vec& w) {
  Rcpp::Timer timer;
  timer.step("start");

  arma::mat result1 = X.t() * (X.each_col() % w);
  timer.step("Armadillo result");

  const int n = X.n_rows;
  const int k = X.n_cols;
  arma::mat result(k, k, arma::fill::zeros);
  for (size_t i = 0; i < n; ++i) {
    F77_CALL(dsyr)("U", &k, &w(i), &X(i,0), &n, result.memptr(), &k);
  }
  result = arma::symmatu(result);
  timer.step("BLAS result");
  Rcpp::NumericVector res(timer);
  return res;
}

/*** R
n <- 10000
k <- 10
X <- matrix(runif(n*k), n, k)
w <- runif(n)
Reduce(rbind, lapply(1:6, function(x) diff(getXtWX(X, w))/1e6))
*/

However, for me the BLAS solution is quite a bit slower:
> Reduce(rbind, lapply(1:6, function(x) diff(getXtWX(X, w))/1e6))
     Armadillo result BLAS result
init         1.291243    6.666026
             1.176143    6.623282
             1.102111    6.644165
             1.094917    6.612596
             1.098619    6.588431
             1.069286    6.615529

I tried to improve this by first transposing the matrix, in the hope that memory access would be faster when looping over column matrices, but this did not make a difference on my (low-powered) system.


text:
Q: Visual Studio steps over constructors and functions while debugging .NET Framework code I wanted to step through and study MS implementation of data structures in System.Collections.Generic. Setted-up Visual Studio 2015 debugger to options you see below.
First issue: while trying to step into LinkedList<int> list = new LinkedList<int>(); debugger steps over LinkedList constructor. This particular constructor is empty. Is this a default behavior of VS debugger to step over empty constructors ?
Second issue: debugger steps over internal LinkedListNode(LinkedList<T> list, T value) constructor, instead of stepping in.
How do I force debugger to step into constructors ?

A: Have you looked here: How to: Debug.Net Framework Source
Make sure you have the symbols loaded

A: I debug it in my side, it couldn't step into the LinkedList even if I use the correct debugging .NET framework source code steps here, actually if I use the "Go To Definition" and visit the System.Collections.Generic.LinkedList, I also could step Into it even if I add a breakpoint firstly, so I think we couldn't step Into it.


text:
Q: Creating new One Note 2010 page from C# I'm a relative c# amateur, and I'm having trouble getting up to speed with what I guess is Office Interop (correct me if I'm wrong):
I want to have a console app that creates a new page in One Note 2010.  The new page will always go into the same section, which will already exist.  The page title will be a string in the Windows clipboard.  I know how to do the clipboard part (the program also creates a folder in a specified path and names it using the string in the clipboard), but I'm having trouble getting started with the One Note part.
I've been trying to understand these articles (the second one has examples in VB only, so I also have to deal with that):
http://msdn.microsoft.com/en-us/library/gg649853.aspx
http://code.msdn.microsoft.com/windowsdesktop/OneNote-2010-Create-New-880f8ee3
But I'm still basically lost.  I don't need to find the names of any sections or anything, I know that my new pages will always go into a notebook called Tasks in a section called Notes, at least in the first version/while I'm still learning.
I'm looking for nice, focused explanation of how to create a new One Note page from C#.  The MSDN articles assume all sorts of prior knowledge that I don't have, and I'd rather get a jump start and learn by doing than spend a month reading.  Once the basic program works, I'll spend lots of time tweaking it, which should be a great way to learn.

A: For a detailed article, check out this MSDN Magazine link.
I used the sample code there to create a quick snippet for you to create a new page in a given section in a given notebook.
If you are using Visual Studio 2010, there are a couple of "gotchas" listed in the article:

First, due to a mismatch of the OneNote interop assembly that shipped
  with Visual Studio 2010, you should not directly reference the
  Microsoft.Office.Interop.OneNote component on the .NET tab of the Add
  Reference dialog, but instead reference the Microsoft OneNote 14.0
  Type Library component on the COM tab. This still results in the
  addition of a OneNote interop assembly to your project's references.
Second, the OneNote 14.0 Type Library is not compatible with the
  Visual Studio 2010 "NOPIA" feature (in which primary interop
  assemblies are not embedded in the application by default). Therefore,
  make sure to set the Embed Interop Types property to False for the
  OneNote interop assembly reference.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Office.Interop.OneNote;

namespace OneNote
{
    class Program
    {
        static Application onenoteApp = new Application();
        static XNamespace ns = null;

        static void Main(string[] args)
        {
            GetNamespace();
            string notebookId = GetObjectId(null, HierarchyScope.hsNotebooks, "Tasks");
            string sectionId = GetObjectId(notebookId, HierarchyScope.hsSections, "Notes");
            string pageId = CreatePage(sectionId, "Test");
        }

        static void GetNamespace()
        {
            string xml;
            onenoteApp.GetHierarchy(null, HierarchyScope.hsNotebooks, out xml);

            var doc = XDocument.Parse(xml);
            ns = doc.Root.Name.Namespace;
        }

        static string GetObjectId(string parentId, HierarchyScope scope, string objectName)
        {
            string xml;
            onenoteApp.GetHierarchy(parentId, scope, out xml);

            var doc = XDocument.Parse(xml);
            var nodeName = "";

            switch (scope)
            {
                case (HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
                case (HierarchyScope.hsPages): nodeName = "Page"; break;
                case (HierarchyScope.hsSections): nodeName = "Section"; break;
                default:
                    return null;
            }

            var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();

            return node.Attribute("ID").Value;
        }

        static string CreatePage(string sectionId, string pageName)
        {
            // Create the new page
            string pageId;
            onenoteApp.CreateNewPage(sectionId, out pageId, NewPageStyle.npsBlankPageWithTitle);

            // Get the title and set it to our page name
            string xml;
            onenoteApp.GetPageContent(pageId, out xml, PageInfo.piAll);
            var doc = XDocument.Parse(xml);
            var title = doc.Descendants(ns + "T").First();
            title.Value = pageName;

            // Update the page
            onenoteApp.UpdatePageContent(doc.ToString());

            return pageId;
        }
    }
}


text:
Q: How can I speed up this row-by-row operation in data.table I have a data.table with xe5 rows and approx 100 columns. I am looking to find the first 3 column index such that the value is not NA or 0.
m <- matrix(rep(NA_integer_, 1e6), ncol=10)
for(i in 1:nrow(m)){
    set.seed(i);
    m[i, sample(1:10, 5)] =  1L:5L
}
DT <- data.table(m);
DT
        V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
     1: NA  5  1  2  3 NA  4 NA NA  NA
     2: NA  1 NA NA  3  5  2 NA NA   4
     3: NA  1  4  3 NA NA NA  2  5  NA
     4:  2  4  3 NA  5  1 NA NA NA  NA
     5:  5  4  1 NA NA NA  2  3 NA  NA
    ---
 99996: NA NA  2  3  5  1 NA NA  4  NA
 99997:  2 NA NA NA  1 NA NA  3  5   4
 99998:  5 NA  4  2 NA  1  3 NA NA  NA
 99999: NA  5 NA  1 NA  4 NA  2 NA   3
100000:  5 NA NA NA  2  3  1 NA NA   4

f <- function(x){return(list(which(!is.na(x) & x!=0L)[1:3L]))}

#Here is what apply do
system.time(test <- apply(m, FUN=f, MAR=1))
utilisateur     système      écoulé
       1.30        0.00        1.29

I find it very slow, this might not be a task for data.table, I am looking for a fast way of getting this answer (any method is welcome).

A: First, you could use the fact that 0 /0 is NaN which will also give TRUE for is.na. This'll reduce to condition to one !is.na. Second, you can vectorise using which with arr.ind = TRUE that'll give a row and col index. We can use that to split by row and get the first three col values as follows:
system.time(tt <- data.table(which(!is.na(DT[, lapply(.SD, function(x) x/0)]),
             arr.ind=TRUE), key="row")[, col[1:3], by="row"])
   user  system elapsed
  0.360   0.000   0.359

Edit: an alternative way:
DT <- DT[, lapply(.SD, function(x) !is.na(x/0))]
out <- data.table(matrix(numeric(3e5), ncol=3))
system.time({
for (i in as.integer(seq_along(DT))) {
    for (j in 1:3) {
        zeros <- .subset2(DT, i) & (out[[j]] == 0)
        out[zeros, names(out)[j] := i]
        DT[zeros, c(names(DT)[i]) := FALSE]
    }
}
})

Not sure if it's the fastest though.


text:
Q: Best way to delete an item from a JSON string using JsonUtility in Unity 3d What is the best way to delete an item from a JSON file using Unity 3d's JsonUtility?
I'm assuming you must load it, but: does it need to be parsed or converted to a list?
Once the operation is done, save it.
Any help for the middle part would be helpful.
Thanks!

A:
I'm assuming you must load it, but: does it need to be parsed or
  converted to a list?

Yes, with JsonUtility you must load it, convert it to  List then remove the item from it. First of all, the item must have a variable you can use to identify and remove it. Let's say that the name of the item to delete is "ken";
Test data to load serialize and de-serialize:
[Serializable]
public class PlayerData
{
    public string name;
    public int score;
}

Load(Must be loaded as array then converted back to List):
string jsonToLoad = PlayerPrefs.GetString("Data");
//Load as Array
PlayerData[] _tempLoadListData = JsonHelper.FromJson<PlayerData>(jsonToLoad);
//Convert to List
List<PlayerData> loadListData = _tempLoadListData.OfType<PlayerData>().ToList();

Remove all "ken" Items:
for (int i = 0; i < loadListData.Count; i++)
{
    if (loadListData[i].name == "ken")
    {
        loadListData.Remove(loadListData[i]);
    }
}

or with Linq:
loadListData.RemoveAll((x) => x.name == "ken");

Then you can save it:
string jsonToSave = JsonHelper.ToJson(loadListData.ToArray());
PlayerPrefs.SetString("Data", jsonToSave);
PlayerPrefs.Save();

Of-course, you will need JsonHelper as mentioned in your other post.


text:
Q: Creating a list of deduplicated lists based on matches in loop? - Python, Openpyxl I'm trying to accomplish this with Pycharm 2017.1.3., Openpyxl 2.4.7, and Excel 2016.
Here is a smaller version of my data set, for starters:
SHEET1:
| partID |    keywordcategory |keyword|
| 4849348| searchkeyword1     |Hobbock
| 4849348| searchkeyword1     |Lentso*
| 4849348| searchkeyword2     |Lentso|
| 4849348| searchkeyword3     |LENTSO-EIEMR                            |
| 4849348| searchkeyword3     |Hobbock
| 4849346| searchkeyword1     |protein
| 4849346| searchkeyword3     |ion

The result I want to achieve is, for each unique part number, to:
A. Get a list of the unique search terms at each keyword category, AND
B. A combined list of each part number's keywords across all keywordcategories. Heres an example of what I'd love to end up with:
| partID |searchkeyword1  |searchkeyword2|searchkeyword3|combined
| 4849348| Hobbock;Lentso*|Lentso        |LENTSO-EIMER  |Hobbock;Lentso*;
                                                        |Lentso;
                                                        |LENTSO-EIMER
| 4849346| protein        |              |ion           |protein;ion

This is what I've been working on so far, but it doesn't seem to be creating new lists at each row.
    import openpyxl
print('Opening file...')
wb = openpyxl.load_workbook('keywords.xlsx')
sheet1 = wb.get_sheet_by_name('Sheet1')
sheet2 = wb.get_sheet_by_name('Sheet2')
maxRow1 = sheet1.max_row + 1
maxRow2 = sheet2.max_row + 1
print('Processing...')

for rowNum in range(1, maxRow2):
for col in sheet1.iter_cols(min_row=1, min_col=2, max_col=2, max_row=1000):
    for cell in col:
        keywordlist = []
        if cell.value == sheet2.cell(row=rowNum, column=1).value:
            if sheet1.cell(row=rowNum, column=3).value == 16985323:
                #if sheet1.cell(row=rowNum, column=4).value not in keywordlist and 'None' not in sheet1.cell(row=rowNum, column=4).value:
                keywordlist.append(sheet1.cell(row=rowNum, column=4).value + ';')
                sheet2.cell(row=rowNum, column=2).value = str(keywordlist)

Any ideas or help would be greatly appreciated! Thanks in advance!
EDIT:
Charlie's help has gotten me a lot further than I was!
The issue I'm having now is that when I try to use the defaultdict(list) on my actual project, it doesn't seem to be removing the duplicates.
It works when I try the examples I've found online, but not with my actual project.
I think the issue is likely how I'm generating the dictionary. This is what I'm doing now:
for rownum in range(1,maxRow):
    partnum = str(sheet1.cell(row=rownum, column=1).value)
    keyword1 = str(sheet1.cell(row=rownum, column=3).value)

s = [(partnum,keyword1)]
    print(s)
    d = defaultdict(list)
    for k, v in s:
    d[k].append(v)

If you have any help you might be able to offer, I would greatly appreciate it! Thankyou!

A: You should probably tackle this in two stages: first build a dictionary of the search terms: I've written elsewhere on how to do this but you'll want to extend it for your purposes. The easiest way would be to have a dictionary like {1: ['Hobbock' 'Lentso'], 2:['Lentso'],…} use defauldict with the default of a list for this.
You can then loop through the list or dictionary of parts to write the rows.


text:
Q: zip selected directories recursively in linux I would like to zip only selected directories(and its child directories as well)
I have many directories in the current folder like app, content, db, library etc.
But I would like the zip only app and content and its child folders. I am trying the following.
zip -r ../backups/code/20110625 -i app/* -i content/* . *

But I am getting the following error.

zip error: Invalid command arguments (nothing to select from)

What is the correct syntax to achieve this?

A: Try:
zip -r myzipfile.zip ../backups/code/20110625 app/* content/* . *

You need to put the name of the zipfile first.


text:
Q: WCF Service works with IIS Express but Not IIS7 on server (same domain) Following several walkthroughs I created a WCF Service using EF to connect the Northwind db. Visual Studio 2010, SQL Server 2012 Express and IIS 7.5 Express on a single development machine were used.
Using IE9 I am able to connect to the service and request individual tables as in:

Further, using OData Explorer (a Silverlight Application) I can add a new connection to the local IIS and also see the Northwind tables; for example the employees table:

However, when I move the service to a server on the same domain running IIS 7.0, I can browse to the service root as below:

However, whe I request the Customers table there is no response from the service:

And while I can create the new connection in OData Explorer, when I request a single table, an unknown error ocurrs:

The full description of the error is shown but the link is outdated and not available:

[HttpWebRequest_WebException_RemoteServer]
  Arguments: NotFound
  Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=5.1.10411.0&File=System.Windows.dll&Key=HttpWebRequest_WebException_RemoteServer
  at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
     at SL_OData_Explorer.Views.ODataExplorer.<>c__DisplayClass1e.<>c__DisplayClass20.b__1d()

After googling around, I came across several posts relating that clientaccesspolicy.xml and crossdomain.xml files should be placed at the root of the website. And while I understand this is specific to silverlight and did place said files, they had, as expected no effect.
When I compare the Response from the local machine:

to that of IIS on the server, case it is clear that the service is there but it can't find the tables.

So, in both cases I can browse to the root of the service but only locally can I get beyond the root and look at individual tables.
It would appear to be a configuration issue to be sure but trying to find information on this undisclosed error is difficult at best. Does anyone have any idea what's going on in this instance?
Thanks,
Greg


text:
Q: On click drop down input: unable to goto top item on click I've created a drop down input that when you click on the items it goes to the page.
<form id="work" action="" method="post">
    <select id="work-list" class="sub-topics" name="work">
    <?php $id = get_the_ID();
    $pages = get_pages(array('child_of' => $id, 'sort_column' => 'menu_order'));
    foreach($pages as $post) {
    setup_postdata($post);
    $fields = get_fields(); ?>
        <option class="work-dropdown" value="<?php echo the_permalink(); ?>"><?php echo the_title(); ?></option>
    <?php } wp_reset_query(); ?>
    </select>
</form>

Jquery:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
   $('select[name="work"]').change(function(){
        window.location = $(this).val();
    })
});
</script>

At the moment the top page is the drop down has a tick next to it so when clicking it, it doesn't goto the page. If you click the second item then that works fine, it's just it think the top item is selected.
How can I make the top item clickable like the rest?
If possible I want to avoid putting in a selection at the top like "click here to choose a page" or anything along those lines.

A: Try
window.location.href = $(this).val();

instead of
window.location = $(this).val();

A: you can add the 1st item item to the drop-down list as click below to choose a page to visit


text:
Q: LDAPConnection Bind timeout in .net core I am unable to found anything for LdapConnection Bind timeout in .net core. one solution is LdapConnection Bind Timeout but it is not working in .net core.
LdapConnection timeout and bind timeout seems to be different thing.
my code is something like following
   var credentials = new NetworkCredential(obj.AdminBindUserName, obj.AdminBindPassword);

            if (obj.LDAPAddressPort.HasValue && obj.LDAPAddressPort > 0)
            {
                connection = new LdapConnection(new LdapDirectoryIdentifier(obj.LDAPAddress, obj.LDAPAddressPort.Value, false, false));
                //connection = new LdapConnection(new LdapDirectoryIdentifier(obj.LDAPAddress, obj.LDAPAddressPort));connection = new LdapConnection(new LdapDirectoryIdentifier(obj.LDAPAddress, obj.LDAPAddressPort));
            }
            else
            {
                connection = new LdapConnection(obj.LDAPAddress);
            }
             //connection.Timeout = new TimeSpan(0,0,5);
            connection.SessionOptions.ProtocolVersion = 3;
            connection.AuthType = AuthType.Basic;
            connection.Bind(credentials);

I have tried connection timeout but looks like no effect of it.
I am getting exception message ExceptionCode: 81,Message: The LDAP server is unavailable at random time interval. sometime 18 seconds, sometime more then a minute.
I am reproducing the problem via help of vpn connectivity. my local ldap is connected via first connecting to some vpn.
with vpn connection every thing works fine. but without vpn my call to Bind() method wait indefinitely

A: A timeout can be set using Task and once that timeout in second is reached a cancellation event will occur to get out of this as show below
if (obj.IsBindTimeLimit)
            {
                int timeoutSecond = obj.BindTimeOutInSeconds;
                if (timeoutSecond <= 0)
                {
                    timeoutSecond = 5;
                }
                CancellationToken tscancel = new CancellationToken();
                Task t = Task.Run(() =>
                {
                    var credentials = new NetworkCredential(obj.AdminBindUserName, obj.AdminBindPassword);
                    if (obj.LDAPAddressPort.HasValue && obj.LDAPAddressPort > 0)
                    {
                        connection = new LdapConnection(new LdapDirectoryIdentifier(obj.LDAPAddress, obj.LDAPAddressPort.Value, false, false));
                    }
                    else
                    {
                        connection = new LdapConnection(obj.LDAPAddress);
                    }
                    connection.SessionOptions.ProtocolVersion = 3;
                    connection.AuthType = AuthType.Basic;
                    connection.Bind(credentials);
                });

                if (!t.Wait(timeoutSecond * 1000, tscancel))
                {
                    throw new TimeoutException("The timeout interval elapsed");
                }

            }
            else
            {
                var credentials = new NetworkCredential(obj.AdminBindUserName, obj.AdminBindPassword);
                if (obj.LDAPAddressPort.HasValue && obj.LDAPAddressPort > 0)
                {
                    connection = new LdapConnection(new LdapDirectoryIdentifier(obj.LDAPAddress, obj.LDAPAddressPort.Value, false, false));
                }
                else
                {
                    connection = new LdapConnection(obj.LDAPAddress);
                }
                connection.SessionOptions.ProtocolVersion = 3;
                connection.AuthType = AuthType.Basic;
                connection.Bind(credentials);
            }


text:
Q: Document sets in SharePoint App for Android I downloaded the SharePoint App for Android and tried to access my files. I can see them in normal document libraries. But whenever I enter a document set, the files are not shown.
Is this a common problem? Did anybody experience the same behaviour? Are doc sets supported by the app?

A: Perhaps you could configure a new view>under the Folders header select show all items without folders.
Are your documents visible this way?  If so, you could try setting this as the mobile view.
Here is a related post on a similar subject.


text:
Q: How to make HTML table into a grid? I'm retrieving data from my database into a table, but the data is piling up to the left rather than a grid view.
    include_once ('includes/db_connect.php');
    $res = mysql_query("SELECT * FROM inventory ORDER BY id DESC");

    echo "
";
    while ($row = mysql_fetch_array($res)) {
        echo "
"; echo "";?> <img src="<?php echo $row["image"]; ?>" height="200" width="280">  <?php echo "
";
        echo "
"; echo ""; echo $row['make']; echo "  "; echo $row['model']; echo "	";  echo "
";
    }
    echo "
";

Any help will be highly appreciated.

A: You just need closing /td tags for every opening td tag. Your first line is missing a /td:
echo "
"; echo "";?> <img src="<?php echo $row["image"]; ?>" height="200" width="280">  <?php echo "
";

echo "
"; echo ""; echo $row['make']; echo "  "; echo $row['model']; echo "
";

You probably also want to style your table with this inside the head tags:

Or inline styles:

A: In your code, the end of the first line closes off the table row without actually closing off the cell. I have also spaced out your code as to improve readability. I believe the issue was the missing 	 at the end of the first row.
$res = mysql_query("SELECT * FROM inventory ORDER BY id DESC");

echo "
";

while ($row = mysql_fetch_array($res)) {
    ?>

    <img src="<?php echo $row["image"]; ?>" height="200" width="280">

    <?php echo $row['make']; echo "  "; echo $row['model'];?>

    <?php
}
echo "
";

It also should be noted that your mysql_query should be switched over to mysqli or pdo.


text:
Q: Getting warning while using struts.xml file. I am using Struts2.0. When i am writting a program, in struts.xml file getting warning "the file cannot be validated as there was a connection problem " at the line:-" !DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" "
When i am executing the application first page is loaded but after submitting,the next page is not loaded and showing error like: "The requested resource (/TestProject/login) is not available."
I am using struts2.0,Tomcat6.0, and including jar files are :

*

*commons-logging-1.1

*freemarker-2.3.8

*ognl-2.6.11

*struts2-core-2.0.6

*xwork-2.0.1

plz help me why this error is coming either due to warning or some other reason.

A: The first error may be because your project is not able to find tld's.
-Check your sturts-core.jar contains struts-2.0.dtd
-Your struts.xml starts like this
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

Second error is because when you are deploying your application and struts.xml is not getting deployed, seems you are using eclipse and your struts.xml is in resources folder.
Ensure that your resources folder is added in the src directories,
Project - > Build Path - > Configure Build Path - > Source (If resources is not present here click on Add Folder and select Resources.

If you are just starting with Struts, please upgrade to latest version which is Struts2.3


text: Q: How to map kinect skeleton onto avatar joints by Unity3D I want to know how to map kinect skeleton to a 3D avatar joints by unity3D, I use kinect v2, I design a humanoid figure in .obj, is there any tutorial for beginner?


text:
Q: BOOTSTRAP tooltip multi instances not working I'm trying using tooltip() and opening multinstances as follow:
$("*").tooltip({
    selector: "*[rel=tooltipTOP]",
    placement: "top"
  });
  $('*').tooltip({
    selector: "*[rel=tooltipBOTTOM]",
    placement: "bottom"
  });

then in html i do for example
tooltip TOP
tooltip BOTTOM

so tooltip TOP is ok but tooltipBOTTOM doesn't shows the tooltip ... why?
i tryed also to put specific class for tooltipBOTTOM but it doesn't works, it instances only the tooltipTOP rel :/
JSFIDDLE http://jsfiddle.net/BH2GM/1/

A: HTML

Tooltip on top

Tooltip on right

Tooltip on bottom

Tooltip on left

JS
$('a').tooltip();

DEMO

A: First of all, why are you doing that based on rel? You really should use class.
tooltip TOP
tooltip BOTTOM

and then
$(".tooltipTOP").tooltip({
    placement: "top"
});
$(".tooltipBOTTOM").tooltip({
    placement: "bottom"
});

EDIT: But if you have to use rel, here's the solution:
$("*[rel=tooltipTOP]").tooltip({
    placement: "top",
    trigger: "hover"
});
$('*[rel=tooltipBOTTOM]').tooltip({
    placement: "bottom",
    trigger: "hover"
});

A: I find that problem is with Jquery selector.
If you have 2 instances of tooltip you can do this
$("body").tooltip({
    selector: "*[rel=tooltipTOP]",
    placement: "top"
  });
  $('html').tooltip({
    selector: "*[rel=tooltipBOTTOM]",
    placement: "bottom"
  });

Note jquery selectors are different. First is BODY second is HTML

A: Your Problem is maybe that you use your tooltips on elements that are dynamically generated?
I had the same Problem an used "live" to get it working...
$(document).live("mouseover", function () {
    $('.tooltipTop').tooltip({
        placement: "top"
    });
    $(".tooltipBottom").tooltip({
        placement: "bottom"
    });
    $(".tooltipRight").tooltip({
        placement: "right"
    });
    $(".tooltipLeft").tooltip({
        placement: "left"
    });
});

A: For me it solved by increasing z-index of element on which i assigned tooltip.


text:
Q: Is it possible to retain the form(html) content data after page refreshed? Please give me a good suggestion but without using Ajax.
I mean to say is it possible to do in JavaScript/J query or else.
My Issue : When i am submitting one page, the action class again return to this same page
now as per my requirement i have to retain the state of some radio button and checked boxes checked as it checked before.
Any help will be appreciated.

A: If the form action redirects to the same page, i.e. you want to repopulate the same field that was just sent on the same page, you can just enter the form data as default value:
<form action="form.php" method="post">
    <input type="text" name="name" placeholder="Enter your name" value="<?=$_POST['name']?>" />
</form>

A: You need to save the form data (state of the form) in a session, which will involve setting cookies or local storage, some of which may be implemented using JavaScript.
If I were doing it, I would store the values from my form in session variables and then repopulate the form when I return to the page.
This can be done using a server side scripting language such as PHP or JSP or .net
An example of how to get started with JSP, I suggest the following tutorial:
http://www.jsptut.com/sessions.jsp


text:
Q: git lfs ls-files -I filter doesn't work with non-ASCII folder names git lfs ls-files -I filter seems not to work with non-ASCII folder names even when the filter is passed in octal encoding, as can be confirmed with the bash script below:
mkdir LfsTestRepo
cd LfsTestRepo
git init
git lfs -v # git-lfs/2.7.2 (GitHub; windows amd64; go 1.12.2; git 08a08ae0)
git lfs install
echo "*.dll filter=lfs diff=lfs merge=lfs -text" > .gitattributes
# ASCII
mkdir "A B"
echo "some binary data" > "A B/C.dll"
# Non-ASCII
mkdir "А Б"
echo "some binary data" > "А Б/В.dll"
git add --all
git commit -m "DLLs added"

git lfs ls-files # Shows both files
git lfs ls-files -I "/A B/*" # ASCII - shows the file with folder filter
git lfs ls-files -I "/А Б/*" # Non-ASCII - doesn't show the file with folder filter

git ls-files -s ":(attr:filter=lfs)А Б" # Non-ASCII native ls-files shows the file (octal encoding)

git lfs ls-files -I "/\320\220 \320\221/*" # Non-ASCII - doesn't show the file even with octal encoding

While in our particular case folders with non-ASCII characters shouldn't probably be ever encountered, it is still a minor nuisance and a potentially valid use-case.
So, am I doing something wrong, or is it just that git lfs ls-files -I doesn't support filters with non-ASCII characters?

A: Currently, specifying a file name with -I using non-ASCII characters is broken.  There's an open pull request to fix it which will be included in Git LFS 2.9.0.


text:
Q: Load custom position of page when create viewpager fragment I got a problem with viewpager fragment.
Example: i got an array: 1-2-3-4-5-6.
I want when i create viewpager fragment, it will jump to fragment position 3.
Now the way viewpager do is: load all the list seriated like (1 and 2 and 3 and..), after that this set viewpager.setCurrentItem(3,false).
But with the way like that, it take more time when user click to open viewpager, is any way to do like:
When create viewpager, it will load fragment with position 3 first, after finish build UI of fragment(3), it will load another position of fragment, so when user click to open viewpager, they will not have waiting for viewpager create.
So please give me the ideal for that case.


text:
Q: Show that this matrix is unitary and compute its eigenvalues. Unitarily diagonalize this matrix Show that this matrix is unitary and compute its eigenvalues.
Unitarily diagonalize this matrix
\begin{bmatrix}0&i&0\\-1&0&0\\0&0&-i\end{bmatrix}
is got the eigenvalues $\lambda = -i, \sqrt{i}, -\sqrt{i}$
but I can't find the eigenvectors

A: $$UU^*=\begin{pmatrix}0&i&0\\\!-1&0&0\\0&0&\!-i\end{pmatrix}\begin{pmatrix}0&\!-1&0\\\!-i&0&0\\0&0&i\end{pmatrix}=\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}$$
so $\;U\;$ is unitary. Its eigenvalues are
$$\det(xI-U)=\begin{vmatrix}x&\!-i&0\\1&x&0\\0&0&x+i\end{vmatrix}=x^2(x+i)+i(x+i)=(x+i)(x^2+i)=0\iff$$
$$x=-i\,,\,\,\pm\frac1{\sqrt2}\left(1-i\right)\;,\;\;\text{so for example}$$
$$\lambda=-i:\;\;\begin{cases}-i(x+y)=0\\{}\\x-iy=0\end{cases}\;\;\implies\,x=y=0\;,\;\;\text{so for example}\;\;\begin{pmatrix}0\\0\\1\end{pmatrix}$$


text:
Q: Как вывести события по дням, начиная с сегодняшнего дня? У меня есть база данных с такими полями:

*

*id - ид,

*title - название,

*startdate - начало события,

*enddate - окончание события.

Мне нужно сформировать запрос на вывод событий по датам.
Да, и самое важное. Если, например, сегодняшняя дата попадает в промежуток между датой startdate (начало события) и enddate (окончание события), это событие тоже должно выводиться.
Поиск на этом сайте и на других ничего не дал. Буду очень благодарен.
A: Если надо вывести события в каком-то интервале дат, то так:
select
  *
from
  `tablename`
where
  `startdate` between __начало_интервала__ and __конец_интервала__
  or `enddate` between __начало_интервала__ and __конец_интервала__
order by `startdate`

Если события, начиная с сегодняшнего дня, то так:
select
  *
from
  `tablename`
where
  NOW() between `startdate` and `enddate`
order by `startdate`

A: select id , title from tablename where startdate ='2012-01-12' and enddate = '2012-01-31'

подставляй значения начала и окончания событий в запрос и все.
A: Как и писал @Shrek подставляешь нужные даты.
Т.е. допустим пришел запрос: выбрать между first_date и second_date, и плюс нужно выбрать событие, происходящее в этот момент, то получаем:
SELECT
  id,
  title
FROM
  tablename
WHERE (startdate = 'first_date' AND enddate = 'second_date')
  OR (startdate < NOW() AND enddate > NOW())

A: Если нужно с группировкой по дням, то есть функция TO_DAYS. По ней можно сгруппировать, или даже сделать отдельное поле и хранить в нем уже результат функции, для ускорения запроса.
добавить поле и сделать UPDATE set days=TO_DAYS(startdate);
потом делаем например так
SELECT ... FROM ... WHERE days>=TO_DAYS(NOW())
ORDER BY days
этим запросом я выбираю все события от текущего дня и больше. Только за текущую дату - выводим days=TO_DAYS(NOW()) Такой вариант позволяет сделать по полю days индекс (если прямо в запросе сделать TO_DAYS(startdate) индекс не применится.
получаем массив
id title startdate days
1 новость 2012-11-20 10:50:33 735192
2 новость2 2012-11-20 12:10:22 735192
3 новость3 2012-11-21 17:10:22 735193
Соответственно при каждой смене значения в поле days выводим новый заголовок и т.п.


text:
Q: PHP curl script not closing connection I have a cron job on my website that runs every so often that downloads the contents of a text file.  Everything worked fine until this morning when I got an e-mail from my web host that I was using up all my (allocated) processes. They narrowed it down to this file and told me to fix it stat because it wasn't closing properly.  Any help for this php newbie would be most welcome.
#!/usr/bin/php

<?php
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "http://www.address.com/textfile.txt");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //$output contains the output string
        $output = curl_exec($ch);

        // We need to check whether the data is valid.
        // We check for the 'Client Error' string
        // inside the output data.  If it exists, we don't want
        // to overwrite the previous (good) data.

        if (strpos($output,'Client Error') !== false) {

            echo $output;
                //echo 'Client Error, no data.';

        }else{

            $outputFile = '/home/hostingacct/public_html/outputTextFile.txt';

            $fh = fopen($outputFile,'w') or die("can't open");
            fwrite($fh,$output);
            fclose($fh);
        }

        // close curl resource to free up system resources
        curl_close($ch);

?>

Edit:
Added ps xauf results - vds-status.php is my php file that I am working with.
ryan 11678  0.0  0.0 335380  6216 ?        Ss   Dec14   0:13 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan 11663  0.0  0.0 335640  6100 ?        Ss   Dec12   0:19 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan 11509  0.0  0.0 335380  6220 ?        Ss   Dec14   0:13 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan 11244  0.0  0.0 335640  6128 ?        Ss   Dec13   0:16 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan 11173  0.0  0.0 335640  6264 ?        Ss   Dec14   0:14 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan 10718  0.0  0.0 335380  6004 ?        Ss   Dec12   0:20 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan  9397  0.0  0.0 335380  6020 ?        Ss   Dec13   0:16 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan  9379  0.0  0.0 335380  6216 ?        Ss   Dec13   0:14 /usr/local/bin/php /home/ryan/etc/vds-status.php
ryan  9333  0.0  0.0 335640  6128 ?        Ss   Dec13   0:16 /usr/local/bin/php /home/ryan/etc/vds-status.php

When I posted my question previously, I had had my webhost delete all processes immediately because it was blocking my site.  The problem has occurred again 2 months later, processes still running, etc.  I ran ps xauf per Antoan and the results are above.
It looks like the problem started on the 12th and kept happening for two days.  Can anyone shed some light on how this could happen?  It seems like this happens just after midnight on those problem days. Is this possibly because the server (via cURL) is unreachable --causing the php script to not exit? Thanks everyone.

A: Most probably this is wrong assumption.
Do you have ssh access to this host?
If yes do ps xuaf and check what processes there are there for real.
If you post the list here we will be able to help you more.
Update
Looks like some kind of communication problem. Can you add those:
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // Setting the amount of time (in seconds) before the request times out
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // Setting the maximum amount of time for cURL to execute queries

Adjust the timings if needed.


text:
Q: How can I refer to the input field while using jQuery's UI autocomplete? I have a form with many inputs, all of them with the class "field". On my JavaScript file, I have something like this:
$(".field").autocomplete({
    source:"search.php",
    select:function(event,ui){$(???).doStuff();}
    });

What I need is some way to refer to the input field where the user is writing (that is, some selector in place of the "???"), so that I can do some stuff with the surrounding elements. I am guessing that the answer is something like "ui.field", "ui.input" or "ui.element", but I tried those and others with no luck, and I couldn't find the answer in the documentation nor here, so I turn to you. Thanks!

A: It's this (that's the raw element, not wrapped), as with most jQuery events. This could be documented better. :-) So in your case:
$(".field").autocomplete({
    source:"search.php",
    select:function(event,ui){
        // Here, `this` is the raw DOM element of the field
        $(this).doStuff();
    }
});

Example (live copy):
HTML:

Type a t then pick a choice. The field will turn green briefly.

<input class="ac" type="text">
<input class="ac" type="text">
<input class="ac" type="text">

JavaScript:
jQuery(function($) {
  $(".ac").autocomplete({
    source: ["two", "three", "thirty"],
    select: function(event, ui) {
      var $this = $(this);
      $this.css("color", "green");
      setTimeout(function() {
        $this.css("color", "");
      }, 500);
    }
  });
});

A: I'm pretty sure that this.id would do the trick here.
$(".field").autocomplete({
source:"search.php",
select:function(event,ui){$("#" + this.id).doStuff();}
});

A: Have you tried ui.item (ui.item.value, ui.item.id etc)?


text:
Q: Why am I getting this error when using glmnet in R When trying to predict I am getting this error
  error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Cholmod error 'X and/or Y have wrong dimensions' at file ../MatrixOps/cholmod_sdmult.c, line 90

Here is my code so far
library(data.table)
library(caret)
library(Metrics)
library(glmnet)
library(plotmo)
library(lubridate)

#Reading in the necessary data needed for this project

train <- fread("project/volume/data/processed/start_train.csv")
test<-fread("project/volume/data/processed/start_test.csv")
example_sub<-fread("project/volume/data/processed/example_submission.csv")
card_tab <- fread("project/volume/data/processed/card_tab.csv")

#Merging the card_tab dataset with both my train and test datasets to add more variables to each

train = merge(train, card_tab, by = "id")
test = merge(test, card_tab, by = "id")

train$power = as.numeric(train$power)
train$toughness = as.numeric(train$toughness)
test$power = as.numeric(test$power)
test$toughness = as.numeric(test$toughness)

train$powerovertough = train$power/train$toughness
test$powerovertough = test$power/test$toughness

train$current_date<-as_date(train$current_date)
train<-train[order(-current_date)]

test$current_date<-as_date(test$current_date)
test<-test[order(-current_date)]

#Handling NA values in both train and test. The NA values will be set to 0

train[is.na(train)] <- 0
test[is.na(test)] <- 0

# Specifying which columns of our model we will be dropping and applying it to our train and test datasets

drops<- c('id','future_date','current_date','card_name','power','loyalty','cmc','type','colors','mana_cost','subtypes', 'text','set','set_name')

train<-train[, !drops, with = FALSE]
test<-test[, !drops, with = FALSE]

#Saving the response variable in the train dataset

train_y<-train$future_price

test$future_price<-0

#Using dummies to train model

dummies <- dummyVars(future_price ~ ., data = train)
train<-predict(dummies, newdata = train)
test<-predict(dummies, newdata = test)

train<-data.table(train)
test<-data.table(test)

#Cross validating the model to fin the best lamda value

train<-as.matrix(train)
test<-as.matrix(test)

gl_model<-cv.glmnet(train, train_y, alpha = 1,family="gaussian")

bestlam<-gl_model$lambda.min

# Fitting the full model

gl_model<-glmnet(train, train_y, alpha = 1,family="gaussian")

plot_glmnet(gl_model)

saveRDS(gl_model,"./project/volume/models/gl_model.model")

test<-as.matrix(test)

#use the full model
pred<-predict(gl_model,s=bestlam, newx = test)

I am trying to predict future_price for my test set. The error is saying my dimensions are wrong but I don't know what could be causing them to be different. I have tried observing the data sets as it runs through the code and they seem to have the same variables.
Here is the dput
> dput(head(train))
structure(c(0.25, 0.1, 0.1, 0.1, 0.25, 0.25, 1, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 3, 0, 2, 0, 0, 0, 0.333333333333333,
0, 1, 0), .Dim = c(6L, 20L), .Dimnames = list(NULL, c("current_price",
"typesArtifact", "typesArtifact Creature", "typesCreature", "typesEnchantment",
"typesEnchantment Artifact", "typesEnchantment Creature", "typesInstant",
"typesLand", "typesPlaneswalker", "typesSorcery", "supertypes",
"supertypesBasic", "supertypesLegendary", "rarityCommon", "rarityMythic",
"rarityRare", "rarityUncommon", "toughness", "powerovertough"
)))

> dput(head(test))
structure(c(0.15, 0.16, 2, 0.39, 0.16, 0.19, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0,
1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0), .Dim = c(6L, 18L), .Dimnames = list(
    NULL, c("current_price", "typesArtifact", "typesArtifact Creature",
    "typesCreature", "typesEnchantment", "typesInstant", "typesLand",
    "typesPlaneswalker", "typesSorcery", "supertypes", "supertypesBasic",
    "supertypesLegendary", "rarityCommon", "rarityMythic", "rarityRare",
    "rarityUncommon", "toughness", "powerovertough")))


text:
Q: Dukto terminates it self when opened I'm using manjaro
When I opened dukto nothing appeared. then I opened task manager and it showed that dukto wasn't running. so I opened dukto again and I saw that it was in red in task manager indicating that it's being terminated

I previously installed dukto using snap store so I tried uninstalling and reinstalling it , restarting the computer
I also tried to install dukto from AUR but it didnt work
snap run dukto

gives following output
error: cannot find app "dukto" in "dukto"

So does anyone know why it closes it self and how i could fix this
update:
Another time i opened it i saw the follwing task getting terminated


text:
Q: Regex caracteres especiais obrigatório Preciso criar um regex para validar senha.
Ela deverá conter no mínimo 8 caracteres, dos quais deve possuir no mínimo 1 letra, 1 número e 1 caractere especial.

A: Regex Usada
Essa regex faz a validação, você pode testa-la aqui:
(?=.*[}{,.^?~=+\-_\/*\-+.\|])(?=.*[a-zA-Z])(?=.*[0-9]).{8,}

Lembrando que você deve usar duplo escape aonde tem o caractere \, então no código Java todos as barras invertidas devem ser duplas, ficando \\.

Aplicação no código Java
No código Java você pode fazer a validação com String.matches, do jeito que mostrei abaixo:
public class JavaFiddle
{
   public static void main(String[] args)
   {
     System.out.println("A{123456".matches("(?=.*[}{,.^?~=+\\-_\\/*\\-+.\\|])(?=.*[a-zA-Z])(?=.*[0-9]).{8,}")); //exemplo que passa
     System.out.println("ASD1ASDA".matches("(?=.*[}{,.^?~=+\\-_\\/*\\-+.\\|])(?=.*[a-zA-Z])(?=.*[0-9]).{8,}")); //exemplo que nao passa (falta caractere especial)
     System.out.println("ASDAS^^?".matches("(?=.*[}{,.^?~=+\\-_\\/*\\-+.\\|])(?=.*[a-zA-Z])(?=.*[0-9]).{8,}")); //exemplo que nao passa (falta numero)
     System.out.println("123^8542".matches("(?=.*[}{,.^?~=+\\-_\\/*\\-+.\\|])(?=.*[a-zA-Z])(?=.*[0-9]).{8,}")); //exemplo que nao passa (falta letra)
     System.out.println("WWEA^^1".matches("(?=.*[}{,.^?~=+\\-_\\/*\\-+.\\|])(?=.*[a-zA-Z])(?=.*[0-9]).{8,}")); //exemplo que nao passa (nao tem minimo de 8 caracteres)
   }
}

Este código exibe true no console quando for um padrão válido, e false para padrões inválidos.
Você pode testar esse código no JavaFiddle como eu fiz também, só copiar e colar o código dessa resposta.
OBS: Como não foi especificado quais seriam os caracteres especiais eu utilizei como válidos os seguintes caracteres (,.^?~=+-_/*\+)
Você pode alterar os caracteres que entram como caracteres especiais nessa parte da regex:
(?=.*[}{,.^?~=+\-_\/*\-+.\|]), só não retire a parte (?= ... ), pois isso sinaliza um positive lookahead, que é necessário para validar que existe pelo menos um dos caracteres sinalizados no grupo antes de iniciar a captura.

Explicação da Regex

*

*(?=.*...) - É um positive lookahead que irá garantir que o grupo de caracteres a seguir DEVE estar na string para que ela seja validada.

*[}{,.^?~=+\-_\/*\-+.\|] - É o set que define quais caracteres podem ser capturados pelo positive lookahead.

*(?=.*...) - É um positive lookahead que irá garantir que o grupo de caracteres a seguir DEVE estar na string para que ela seja validada.

*[a-zA-Z] - É o set que caracteriza qualquer caractere de letra sendo maiúscula ou minúscula.

*(?=.*...) - É um positive lookahead que irá garantir que o grupo de caracteres a seguir DEVE estar na string para que ela seja validada.

*[0-9] - É o set que caracteriza qualquer número entre 0 e 9.

*.{8,} - Após essas validações, será capturado uma sequencia de qualquer caractere que não contenha quebra de linhas(sinalizado pelo .). E que seja de comprimento mínimo de 8 caracteres (sinalizado pelo {8,}), sem limite máximo (caso queira definir um limite você pode colocar o número máximo de caractere após a ,).

EDITADO
Obrigado ao usuário @hkotsubo por me avisar do meu erro

A: Boa tarde.
Estou usando o FluentValidation e fiz algumas validações para senha hoje. Vê se isso te ajuda (Caso tive alguma dúvida do código me fale):
using FluentValidation;
using System.Linq;
using System.Text.RegularExpressions;

namespace SaleTheaterTickets.Models.ViewModelValidators
{
    public class RegisterViewModelValidator : AbstractValidator<RegisterViewModel>
    {
        public RegisterViewModelValidator()
        {
            RuleFor(x => x.Email)
                .NotEmpty().WithMessage("Informe o e-mail")
                .EmailAddress().WithMessage("Digite um e-mail válido (ana@gmail.com)");
            RuleFor(x => x.Password)
                .NotEmpty().WithMessage("Informe a senha")
                .Length(6, 20).WithMessage("Senha deve ter no mínimo 6 e no máximo 20 caractéres")
                .Must(RequireDigit).WithMessage("Senha deve ter pelo menos 1 número")
                .Must(RequiredLowerCase).WithMessage("Senha deve ter pelo menos 1 caracter minúsculo")
                .Must(RequireUppercase).WithMessage("Senha deve ter pelo menos 1 caracter maiúsculo")
                .Must(RequireNonAlphanumeric).WithMessage("Digite pelo menos 1 caracter especial (@ ! & * ...)");
            RuleFor(x => x.ConfirmPassword)
                .NotEmpty().WithMessage("Confirme a senha")
                .Equal(x => x.Password).WithMessage("Senhas não conferem");
        }

        private bool RequireDigit(string password)
        {
            if (password.Any(x => char.IsDigit(x)))
            {
                return true;
            }
            return false;
        }

        private bool RequiredLowerCase(string password)
        {
            if (password.Any(x => char.IsLower(x)))
            {
                return true;
            }
            return false;
        }

        private bool RequireUppercase(string password)
        {
            if (password.Any(x => char.IsUpper(x)))
            {
                return true;
            }
            return false;
        }

        private bool RequireNonAlphanumeric(string password)
        {
            //if (password.Any(x => char.IsSymbol(x)))
            //{
            //    return true;
            //}
            //return false;

            if (Regex.IsMatch(password, "(?=.*[@#$%^&+=])"))
            {
                return true;
            }
            return false;
        }
    }
}

OBS: Os métodos estão inglês, mas eles servem para o seguinte:
RequireDigit - pelo menos 1 número na senha
RequiredLowerCase - pelo menos 1 letra minúscula na senha
RequireUppercase - pelo menos 1 letra maiúscula na senha
RequireNonAlphanumeric - pelo menos um caractere especial na senha
OBS: O Asp.Net Core Identity já faz essas verificações, porém eu não estava conseguindo traduzir as mensagens que vinham como padrão, então peguei e criei cada validação por conta própria (seguindo as validações que vi na documentação que o Identity faz para senha) para poder gerar minhas frases em português.
Espero que te ajude de alguma forma!


text:
Q: multiple input does not work on Tensorflow 2 installation on MAC OS M1 - AttributeError: 'tuple' object has no attribute 'shape' I have a Tensorflow (sequence) model where the model takes 2 input streams. Here is the part of the code where the model is defined:
generic_in  = Input(shape=(sequence_length, nr_features), name='generic_input')
input1_in     = Input(shape=(sequence_length, nr_features), name='input1_input')
input2_in = Input(shape=(sequence_length, nr_features), name='input2_input')

generic_out, generic_state_h, generic_state_c =      LSTM(50,
                                                          return_sequences = False,
                                                          return_state = True,
                                                          dropout = 0.15,
                                                          recurrent_dropout = 0.15,
                                                          name="generic_lstm")(generic_in)

concatenated_gen_out = Concatenate()([ generic_state_h, generic_state_c ])

gen_dense_out = Dense(100,
                      activation='relu',
                      name="generic_dense")(concatenated_gen_out)

gen_dense_out = BatchNormalization()(gen_dense_out)
gen_dense_out = Dropout(0.15)(gen_dense_out)

generic_model = Model( inputs  = [ generic_in ], outputs = [ gen_dense_out ] )

input1_dense_out     = generic_model(input1_in)
input2_dense_out = generic_model(input2_in)

concatenated_out      = Concatenate()([ input1_dense_out, input2_dense_out ])

dense2_out = Dense(100,
                   activation='relu',
                   name="dense_2")(concatenated_out)

dense2_out = BatchNormalization()(dense2_out)
dense2_out = Dropout(0.2)(dense2_out)

softmax_out = Dense(nr_classes,
                    activation='softmax',
                    name="final_output_layer")(dense2_out)

model = Model(inputs  = [ input1_in,    input2_in ],
              outputs = [ softmax_out             ])

#opt = tf.keras.optimizers.Adam(lr=0.00008, decay=0.000001)
opt =  tf.keras.optimizers.Adam(lr=0.0001)

model.compile(loss='categorical_crossentropy',
              optimizer=opt,
              metrics=['accuracy'])

history = model.fit(x=train_x,
                    y=train_y,
                    batch_size=BATCH_SIZE,
                    epochs=80,
                    verbose=2,
                    validation_data=(dev_x, dev_y),
                    shuffle=True)

Please note that train_x which is the input to the model.fit method is a list containing 2 inputs as defined in model = Model(inputs  = [input1_in, input2_in], outputs = [softmax_out]).
This works perfectly fine in my Tensorflow v1.13.1 installation on Windows. I am trying to migrate my project to MAC OS Big Sur v11.3.1 with M1 chip. The Tensorflow version on the MAC OS is 2.4.0-rc0.
I obviously made some changes to make it work with Tensorflow 2 but these changes are mainly API call updates based on the new API.
The error I get on MAC Tensorflow installation:
Traceback (most recent call last):
      File "/Users/me/Developer/AI_Projects/Football/M1_FULL_TIME_MR/src/train_fit_v2.py", line 288, in <module>
        history = model.fit(x=train_x,
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py", line 1100, in fit
        tmp_logs = self.train_function(iterator)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 828, in __call__
        result = self._call(*args, **kwds)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 871, in _call
        self._initialize(args, kwds, add_initializers_to=initializers)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 725, in _initialize
        self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 2969, in _get_concrete_function_internal_garbage_collected
        graph_function, _ = self._maybe_define_function(args, kwargs)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3361, in _maybe_define_function
        graph_function = self._create_graph_function(args, kwargs)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3196, in _create_graph_function
        func_graph_module.func_graph_from_py_func(
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 990, in func_graph_from_py_func
        func_outputs = python_func(*func_args, **func_kwargs)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 634, in wrapped_fn
        out = weak_wrapped_fn().__wrapped__(*args, **kwds)
      File "/Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 977, in wrapper
        raise e.ag_error_metadata.to_exception(e)
    AttributeError: in user code:

        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
            return step_function(self, iterator)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:795 step_function  **
            outputs = model.distribute_strategy.run(run_step, args=(data,))
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
            return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
            return self._call_for_each_replica(fn, args, kwargs)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
            return fn(*args, **kwargs)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:788 run_step  **
            outputs = model.train_step(data)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:758 train_step
            self.compiled_metrics.update_state(y, y_pred, sample_weight)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py:387 update_state
            self.build(y_pred, y_true)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py:317 build
            self._metrics = nest.map_structure_up_to(y_pred, self._get_metric_objects,
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/util/nest.py:1159 map_structure_up_to
            return map_structure_with_tuple_paths_up_to(
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/util/nest.py:1257 map_structure_with_tuple_paths_up_to
            results = [
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/util/nest.py:1258 <listcomp>
            func(*args, **kwargs) for args in zip(flat_path_gen, *flat_value_gen)
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/util/nest.py:1161 <lambda>
            lambda _, *values: func(*values),  # Discards the path arg.
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py:418 _get_metric_objects
            return [self._get_metric_object(m, y_t, y_p) for m in metrics]
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py:418 <listcomp>
            return [self._get_metric_object(m, y_t, y_p) for m in metrics]
        /Users/me/miniforge3/envs/tf_dev/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py:439 _get_metric_object
            y_t_rank = len(y_t.shape.as_list())

        AttributeError: 'tuple' object has no attribute 'shape'

I am totally out of solutions. What am I supposed to do to make it work?

A: As per the error you posted y_t is of type tuple. Tuple has attribute shape.
You can try casting y_t.

numpy.array(y_t)


text:
Q: What is the best way to initialize a SortOrder column (e.g. 0, 1, 2, 3) where there are multiple groups based on another field? I have a table of list items. There is a ListID column used as an identifier to group the list items together. Is there a sane way to give every item a sort order, starting at 0 per list and incremental by one per item.
Basically, I need to populate the following SortOrder Column values for a large number of entries/ListIDs.
ID    ListID    SortOrder
1     1         0
2     0         0
3     1         1
4     0         1
5     1         2
6     0         2
7     2         0
8     2         1
9     2         2

A: You can use ROW_NUMBER() with a PARTITION on the ListId field for this:
Select   Id, ListId,
         Row_Number() Over (Partition By ListId Order By Id) -1 As SortOrder
From     YourTable
Order By Id

A: I think you want:
WITH toupdate as (
      SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY ListId Order By id) as new_SortOrder
      FROM tableName
     )
UPDATE toupdate a
    SET sortorder = new_sort_order;

SQL Server has the nice ability to update a subquery or CTE under some circumstances.

A: Do you need to persist the order of lists containing items that are shared between lists? If so, perhaps variations on this schema would work for you.
Item
id    label
1     A
2     B
3     C
4     D

List
id    listName
1     abc list
2     cbd list
3     aaa list

ListMembership
id    listId   itemId   order
1     1        1        1
2     1        2        2
3     1        3        3
4     2        2        2
5     2        3        1
6     2        4        3
7     3        1        1
8     3        1        2
9     3        1        3

usage:
select i.label from listMembership as lm
   join Item as i on i.id=lm.itemId
   where lm.listId=2
   order by lm.order

yields:
label
C
B
D


text:
Q: How to define element size with ToBoundaryMesh? I am trying to make a mesh for finite element analysis with shell elements: I have to define 2D finite elements in 3D space. My code is:
mesh = ToBoundaryMesh[Polygon[{{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {2, 0, 0.2}, {0, 0, 0.2}}], "MaxBoundaryCellMeasure" -> 0.01];

However, the produced mesh does not seem to consider the prescribed "MaxBoundaryCellMeasure", since the result is the same regardless the prescribed value for "MaxBoundaryCellMeasure":

Is this possibly a bug? I can solve the problem for the presented simple case with other possible definitions of my domain (e.g. ImplicitRegion). However, I would like to be able to prescribe mesh density when I define domain as Polygon, since I will have to define some more complex domains (with imperfect holes etc.)
Thank you in advance for the answer!

A: Yes, this is seems to be a short coming of ToBoundaryMesh. But you can work abound that with:
dg = DiscretizeRegion[
   Polygon[{{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {2, 0, 0.2}, {0, 0,
      0.2}}], MaxCellMeasure -> {"Area" -> 0.005}];
ToBoundaryMesh[dg]["Wireframe"]


text:
Q: Tkinter - How to remove the background of a widget? I simply just want to have a button with an image (say an apple) and place it on my window without the background of the button.
Here is some sample code I've rushed:
from tkinter import *

root = Tk()

testbutton = Button(root, text="If this was an image I should be able to click the image only").pack()

root.mainloop()

This makes a button but it has a grey background that a. conflicts with my window background and b. allows users to click the image background.
I'm okay with the solution being windows specific however if there are mac and linux solutions as well i want those too.
I also dont want to use root.overridedirect(True) either.
Thanks in advance!