text:
Q: pax-exam (v2.5) - fails to deploy camel-xstream I am trying to understand/get a working example of PAX-EXAM. From my understanding, i need to deploy the bundle i want to test (in this case, boohoo-esb-common) and any bundles that it uses (in this case, camel-xstream).
However, when i try to run the test, pax-exam/felix fails to deploy the xstream feature. Below is the error i get in my console window when doing a: mvn clean install

ERROR: Bundle com.boohoo.boohoo-esb-common [25] Error starting file:/C:/Users/GARETH~1.HEA/AppData/Local/Temp/1346170773171-0/bundles/com.boohoo.boohoo-esb-common_1.0.0.SNAPSHOT.jar (org.osgi.framework.BundleException: Unresolved constraint in bundle com.boohoo.boohoo-esb-common [25]: Unable to resolve 25.0: missing requirement [25.0] osgi.wiring.package; (&(osgi.wiring.package=org.osgi.service.blueprint)(version>=1.0.0)(!(version>=2.0.0))))
  org.osgi.framework.BundleException: Unresolved constraint in bundle com.boohoo.boohoo-esb-common [25]: Unable to resolve 25.0: missing requirement [25.0] osgi.wiring.package; (&(osgi.wiring.package=org.osgi.service.blueprint)(version>=1.0.0)(!(version>=2.0.0)))
          at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:3826)
          at org.apache.felix.framework.Felix.startBundle(Felix.java:1868)
          at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1191)
          at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:295)
          at java.lang.Thread.run(Thread.java:662)

I've attached a simple example which should hopefully show what i mean.
Am i going about this in the right way? or am i not getting how to use pax-exam...

A: Your understanding is correct (you must provision all bundles you bundle-under-test requires), your execution is not :) You are still missing bundles. Apparently your bundle boohoo-esb-common requires a Blueprint Container.


text:
Q: Getting GetResponse() of HttpWebRequest gives ProtocolViolationException I'm tried make an http request to google page,but it not works and give an ProtocolViolationException when I try get the Response.
Here's my code:
 public CookieCollection GetTempCookies()
        {

            CookieContainer MyCookieContainer = new CookieContainer();
            CookieCollection cookies = GetGalxAndGaps();
            string postData = "foo=baa&etc..";
            byte[] data = Encoding.ASCII.GetBytes(postData);
            int postLength = data.Length;

            for (int i = 0, max = cookies.Count; i != max; i++)
            {
                Cookie tempCookie = cookies[i];
                Cookie cookie = new Cookie(tempCookie.Name, tempCookie.Value, tempCookie.Path);
                MyCookieContainer.Add(new Uri("https://accounts.google.com/ServiceLoginAuth"), cookie);
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postLength;
            req.AllowAutoRedirect = false;
            req.CookieContainer = MyCookieContainer;

            HttpWebResponse response = (HttpWebResponse)req.GetResponse(); // <- this cause the exception
            Stream stream = response.GetResponseStream();
            stream.Write(data, 0, postLength);
            return response.Cookies;

        }

Can someone point my error?
Thanks in advance!

A: You're trying to write to the response stream. You should write to the request stream, and then get the response:
using (Stream stream = req.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

using (HttpWebResponse response = (HttpWebResponse) req.GetResponse())
{
    return response.Cookies;
}

redpajama_set_name: RedPajamaStackExchange


text: Q: Cell Loses Focus When Excel VBA installed Button Clicked I have a sub-form that focuses its answer on the active cell that was chosen. BUT, once I click on the cell/button to load/show this sub-form, my choice of the 'active cell' changes to the button cell and my sub-form rejects the chosen cell. I don't have this problem if I use an ActiveX button but I' trying to avoid them on this project. Any recommendations?


text:
Q: How to execute Multiple "Create Table... " Statements in ACCESS Database I have 480 "Create table" statements to be inserted into an empty access db. I found the access has no option of multiple query executions...
I have all the create table queries in a text file
Please help me, how can this be achieved.
I am using MS Access 2007. The access db is in local harddrive
Thanks
Ramm

A: I did this java sample. It worked.. Please let me know if any simple process for this.
import java.io.*;
import java.util.*;
import java.text.*;
import java.sql.*;
import org.apache.poi.ss.usermodel.*;

public class DirReader_fat {

public static void main(String[] args) {

  String inputFilePath = "D:\\Sample.xlsx";
  String strInputQuery = "";

  try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String filename = "d:\\Empty_1.mdb";

        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
        database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end

        // now we can get the connection from the DriverManager
        Connection con = DriverManager.getConnection( database ,"","");

        // try and create a java.sql.Statement so we can run queries
        Statement s = con.createStatement();

        InputStream inputStream = new FileInputStream(new File(inputFilePath));
        Workbook wb = WorkbookFactory.create(inputStream);
        Sheet sheet = wb.getSheet("Sheet1");
        for (Row row : sheet) {

            strInputQuery = row.getCell(0).toString();
            s.execute(strInputQuery);
        }

  }catch (Exception e) {
        e.printStackTrace();
    }
 }

 }

Thanks
Ramm


text:
Q: Proving that a morphism between power series rings is regular Let $k\subset K$ be a separable field extension. As a particular case of M. André Localisation de la lissité formelle one obtains that the natural inclusion of power series rings $k[[X_1,\ldots,X_n]]\subset K[[X_1,\ldots,X_n]]$ is regular. Is there an alternative (simpler) argument that works in this particular case?

A: I believe the following works, as long as by "separable" you mean "separable algebraic." I will denote $K$ by $L$ to make $k$ and $K$ more distinct.
Proof. Consider the factorization
$$k[[X_1,\ldots,X_n]] \subseteq L \otimes_k k[[X_1,\ldots,X_n]] \subseteq L[[X_1,\ldots,X_n]].\tag{1}\label{eq:factor}$$
Since regular homomorphisms are stable under composition [EGAIV$_2$, Proposition 6.6.1(i); Stacks, Tag 07QI] it suffices to show that each homomorphism in this factorization is regular.
The first homomorphism is the direct limit of module-finite smooth homomorphisms
$$k[[X_1,\ldots,X_n]] \subseteq k_\alpha \otimes_k k[[X_1,\ldots,X_n]],\tag{2}\label{eq:kalpha}$$
where $k \subseteq k_\alpha$ ranges over all finite separable subextensions of $k \subseteq L$. Since $k \subseteq k_\alpha$ is smooth, the homomorphisms \eqref{eq:kalpha} are also smooth by base change [EGAIV$_2$, Proposition 6.8.3(iii); Stacks, Tag 00T4]. Thus, the first homomorphism in \eqref{eq:factor} is regular by the easy direction of Néron–Popescu desingularization [Swan, Lemma 1.4; Stacks, Tag 07EP].
We now show that the second homomorphism in \eqref{eq:factor} is regular. Since this homomorphism can be identified with the $(X_1,\ldots,X_n)$-adic completion of $L \otimes_k k[[X_1,\ldots,X_n]]$, it suffices to show that $L \otimes_k k[[X_1,\ldots,X_n]]$ is a $G$-ring. This follows by adapting the proof that the strict henselization of a Noetherian local $G$-ring is a $G$-ring [Stacks, Tag 07QR]. $\blacksquare$
One can also adapt the strategy of this comment by user74230 to a similar question. One first replaces $L$ by the separable closure $k^{\mathrm{sep}}$ of $k$, in which case it suffices to show $k[[X_1,\ldots,X_n]] \subseteq k^{\mathrm{sep}}[[X_1,\ldots,X_n]]$ is regular by the fact that $L[[X_1,\ldots,X_n]] \subseteq k^{\mathrm{sep}}[[X_1,\ldots,X_n]]$ is faithfully flat [Stacks, Tag 07NT]. Now the argument in the comment referenced above applies.


text:
Q: How to get sharedPreference value? I saved SharedPreference value and I need to get saved value from every class.
getUrlPreference method
Future<String> getUrlPreferences() async {
  SharedPreferences pref = await SharedPreferences.getInstance();
  String url = pref.getString("url");
  return url;
}

I need to get url from here.
usernameValidation(usernameTextField){
  String urls;
  getUrlPreferences().then((url)=> urls = url);
  print(urls);
}

But result is null
I Used this way, I can get saved value. How to assign to variable?
usernameValidation(usernameTextField){
  getUrlPreferences().then((url)=> print(url));
}

A: usernameValidation(usernameTextField){
  getUrlPreferences().then((url)=> print(url));
}

If you succeeded this way, you can try assign like this:
     usernameValidation(usernameTextField){
          getUrlPreferences().then((url) {
    getUrl = url;
    print(getUrl);
    });
        }


text:
Q: Unable to install wubi on windows 7 home premium 64bit
Possible Duplicate:
Wubi "could not retrieve the required disk image"

When I try to install wubi in a partition made on my hard disk I get a error message saying
"could not retrive the required disk image file for furthur details goto the
C:\Users\raghavadss\AppData\Local\Temp\wubi-12.04-rev269.log file"

which I have pasted in the link http://paste.ubuntu.com/1202911/

A: It appears that you are behind a proxy web server that requires authentication. Wubi is trying to download the Ubuntu image file and failing.
See this old discussion on HTTP Proxy for wubi. Also see Wubi "could not retrieve the required disk image".
One solution is to download the image manually and then tell wubi where to look for it.
Even though you plan to put Ubuntu in its own partition, Wubi will use a virtual partiton , a big file called root.disk to install the operating system and all the user data. Because of this, compared with a regular installation, a Wubi installation faces some limitations.

*

*In the Wubi installation the filesystem is more vulnerable to hard
reboots. Also, if the Windows drive is unmounted uncleanly (most
commonly because of a Windows crash), Ubuntu will not be able to
mount the Windows drive and boot until Windows has successfully
booted and shut down. If the Windows system cannot be booted after
the crash, the user also cannot boot Ubuntu.

*Performance related to hard-disk access is also slightly slower,
more so if the disk image file is fragmented, on a Wubi install
compared to a normal one.
See more at: What's the difference between Wubi and a regular "alongside Windows" installation?
Alternate Suggestion:
Since you have already created a partition for Ubuntu, it will be ideal to do a proper (not wubi) installation of Ubuntu in its own partition. This will allow you to format the Ubuntu partition ext4 and use it more effectively.


text:
Q: iterate array and add new field to each nested array I have a JSON array from an AJAX call that looks like the following:
[{field1: "Something", field2: "Other"},{field1: "Something", field2: "Other"},{field1: "Something", field2: "Other"}]

I want to use this data on DataTables, but I would like to add a text input to each row in the table based on field Title (Group). Therefore, I would like to add this column to each array, something like:
[{field1: "Something", field2: "Other", Group: "Text Input"},{field1: "Something", field2: "Other", Group: "Text Input"},{field1: "Something", field2: "Other", Group: "Text Input"}]

So that DataTables will add a text input on each new row. How is this achievable using jQuery or javascript?
I have tried by iterating trough the array:
var i, j, arrayItem;
for (i = 0; i < array.length; ++i) {
    arrayItem = array[i];
    arrayItem.push({Group: "Text Input"});
}

But this shows error, "Push" is not a function. As you can see, the JSON array has no explicit index for each nested array, and each array is not unique.

A: The entries in your array aren't arrays, they're objects. (Arrays are also objects, but those entries aren't arrays.) To add a property to an object, the simple way is just to assign to it:
arrayItem.Group = "text input";

You can use a for loop for that as you have done, which is absolutely fine, or as of ES5 and above (or with a polyfill for obsolete environments) you could use forEach:
array.forEach(function(entry) {
    entry.Group = "text input";
});

This has the advantage that you don't need those i and arrayItem variables.
In ES2015+ you could use a for-of loop:
for (const entry of array) {
    entry.Group = "text input";
}

...which has the same advantage (entry is only defined inside the loop).

A: You cannot push because it is an object. Just assign to the object.

var fields = [{
  field1: "Something",
  field2: "Other"
}, {
  field1: "Something",
  field2: "Other"
}, {
  field1: "Something",
  field2: "Other"
}]

fields.forEach(x =>
  x.Group = "Text Input"
)
console.log(fields)

A: {field1: "Something", field2: "Other"} is not an array, it's an object. Arrays are surrounded with [], objects are in {} and the elements are key: value.
You don't use push() to add to an object, you simply assign the property.
array.forEach(e => e.Group = "text Input");

or
for (var i = 0; i < array.length; i++) {
    array[i].Group = "text Input";
}


text:
Q: single-row subquery returns more than one row - how to find the duplicate? iam not a big ORACLE - SQL Expert, so i hope someone knows a good way to find the "duplicate" record wich is causing the: single-row subquery returns more than one row error.
This my Statement:
    SELECT
    CAST(af.SAP_SID AS VARCHAR2(4000)) APP_ID,
    (SELECT DR_OPTION
       FROM
          DR_OPTIONS
       WHERE DR_OPTIONS.ID = (
            select dr_option from applications where applications.sap_sid = af.sap_sid)) DR_OPTION
FROM
    APPLICATIONS_FILER_VIEW af

it works on my test system, so iam "sure" there must be an error inside the available data records, but i have no idea how to find those ..

A: Try with this query:
select applications.sap_sid, count(dr_option)
from applications
group by applications.sap_sid
having count(dr_option) > 1

This should give you the sap_sid of the duplicated rows

A: I'd suggest simplifying your query:
SELECT      CAST(af.SAP_SID AS VARCHAR2(4000)) APP_ID,
            dr.DR_OPTION
FROM        APPLICATIONS_FILER_VIEW af
INNER JOIN  applications a ON af.sap_sid = a.sap_sid
INNER JOIN  DR_OPTIONS dr ON a.dr_option = dr.ID

A: I would investigate what you get when you run:
select dr_option from applications where applications.sap_sid = af.sap_sid

but you could force only one row to be returned (I see this as being a fudge and would not recommend using it at least add an order by to have some control over the row being returned) with something like:
SELECT
CAST(af.SAP_SID AS VARCHAR2(4000)) APP_ID,
(SELECT DR_OPTION
   FROM
      DR_OPTIONS
   WHERE DR_OPTIONS.ID = (
        select dr_option
        from applications
        where applications.sap_sid = af.sap_sid
            and rownumber = 1)
   ) DR_OPTION
FROM
   APPLICATIONS_FILER_VIEW af

(not tested just googled how to limit results in oracle)
If you fix the data issue (as per A.B.Cades comment) then I would recommend converting it to use joins as per weenoid's answer. this would also highlight other data issues that may arise in the future.
IN SHORT: I have never fixed anything in this way.. the real answer is to investigate the multiple rows returned and decide what you want to do maybe:

*

*add more where clauses

*order the results and only select top row

*actually keep the duplicates as they represent a scenario you have not thought of before


text:
Q: Debug.WriteLine malfunctions in Visual Studio. How to fix it? The text sent is not seen in the Output window.
Solution Configuration is Debug.
Output window is showing output from Debug.
It's a simple command: Debug.WriteLine("abc");
Setting a Breakpoint on it succeeds, but the program breaks on the line after it, moving the Breakpoint!
Changing Platform from Any CPU to x86 solves the issue. But going back, it returns.
Creating a new solution, it does work. Even in Any CPU.
I removed the .suo file for the solution.
I emptied the %temp% folder.
Is there any solution for this?

A: 1) Go to Build -> Configuration manager and make sure you are in Debug mode, not Release.
2) Right-click on the project that you're having trouble with and choose properties.
3) Check the Build tab and make sure Define DEBUG constant and Define TRACE constant are both checked.
Note, most people make the mistake corrected by Step #1.  But in my case it was steps #2 and #3 that fixed the problem.  Despite being in DEBUG mode, for some reason those two constants were not being defined!  I think the IDE may have turned them off when I had some of the projects in a solution using one platform target, and the rest of them using a different one, because by default, they are both enabled (checked) when you are in Debug mode.


text:
Q: How do I open an existing LXD container? I have Ubuntu 16.04 installed, xfce desktop for what it's worth. I have LXD installed, with my images and containers on my large second drive, with symbolic links to said images and containers configured in /var/lib/lxd/. Everything works as expected.
I have now re-installed Ubuntu 16.04 on a new drive, Mate desktop for what it's worth. I have installed LXD and created the symbolic links (in /var/lib/lxd) to my images and containers folders on my large drive.
Neither my images nor containers are listed when using lxc list (so can't start them and use them).
Any pointers on what I need to do to get my newly installed LXD to use my pre-existing images and containers ?

A: For anybody interested, the missing piece of the puzzle was that I had to re-use the existing lxd database, lxd.db.
So the steps for me to use my pre-existing LXD containers on a fresh install are:-
Install LXD
sudo apt-get install lxd

Delete the containers and images directories
sudo rm -rf /var/lib/lxd/containers
sudo rm -rf /var/lib/lxd/images

Create symbolic links to my pre-existing containers and images directories.
sudo ln -s /media/sda10/lxd/containers /var/lib/lxd/containers
sudo ln -s /media/sda10/lxd/images /var/lib/lxd/images

Mount my original install partition and copy the lxd.db file from my original install onto my new install
sudo cp /mnt/var/lib/lxd/lxd.db /var/lib/lxd/lxd.db

My containers now show up when I list them and run as expected.
NOTE : I have multiple installations on multiple partitions, and I leap frog between new versions of Ubuntu as they become available, and don't erase an older version until I am happy. It's really easy to do and has just become second nature.
I know that's not common practice, but it has (again) saved my bacon on this occasion. For those who don't do this, making a backup of the lxd.db file would be advised.
EDIT : Further reading at https://insights.ubuntu.com/2016/04/13/lxd-2-0-remote-hosts-and-container-migration-612/ shows that it is also very easy to use a remote LXD host and simply move conatiners between hosts.
This isn't the solution for me, in this particular instance, but it is a very good read showing a very easy way to migrate containers.

A: Since my comments contain some typos, I'll recap a couple of suggestions for importing an existing container (whose storage is available) into a new DB.
First, there are (arguably) easier alternatives if one wants to copy an entire instance of LXD (by basically taking the storage of all containers, plus the DB from /var/lib/lxd). Also, if the old instance is still running and reachable by network, a more native approach is to define it as a remote as described in the Remote hosts and container migration chapter in the wonderful Ubuntu Insights LXD 2.0: Blog post series.

Now, one approach described in another chapter of that series (again, only feasible if the old instance is still running) is to make an image of an existing container using
lxc publish <my-container>@<snapshot> <my-image-name>

then export it to tarballs with
lxc image export <my-image-name> /path/to/directory

The resulting tarballs can be imported with
lxc image import <metadata-tarball> <rootfs-tarball> --alias <my-image-name>

As OP said in comments, that's quite a bit of work. What's more serious is that it fails if for some reason you can't run the old instance.
As of version 2.7 LXD stores a backup.yaml file inside each container's storage (at /var/lib/lxd/containers/<my-container>) which allows importing a container from a copy, using lxd import (see LXD Backup Strategies and this GitHub issue). Note the lxd; this is different from lxc image import.
Based on the LXD News page I presume one does that by simply moving a container's storage into the /var/lib/lxd/containers directory, and running
lxd import <my-container>

However, as Xenial official repositories currently offer version 2.0.9 of LXD, I haven't tested that last part.


text:
Q: .model invalid formula in data_grid() function in R I am trying to use the data_grid function in R and auto-fill some values with the 'standard' values. I created my model using a LASSO logit model which I've fit and finalized with the best fit as follows:
model_final <-
  finalize_workflow(workflow,
                    select_best(tuning_fit,
                                metric = "roc_auc")) %>%
  fit(data3)

When I try to put .model=model_final in my data_grid function, I get an error for invalid formula. I've also tried to put .model=model_final$fit, but this has the same error.
I've also tried the following line of code and then putting the new bit, model_fit, in the place of model_final from the above attempts in both ways. I still fail with the same error.
model_fit<-model_final%>%
extract_fit_parsnip(model_final)

I'm new to R so any help and explanations on why this is happening would be much appreciated.


text:
Q: R: What is the distance function equivalent for this formula? Hi I'm using an R package that calculates distance with this formula here,
as.dist(1 - cor(df, use = "pa"))

However I cannot seem to find an equivalent dist function from this.  I tried
"euclidean", "manhattan", or "minkowski".  thanks!

A: By default cor will compute the Pearson correlation coefficient. Subtracted from $1$ this is know as the Pearson Distance.


text:
Q: JavaScript get start of current minute I'm trying to get the value (elapsed milliseconds) equivalent of the start of the current minute using JavaScript:
let now = Date.now().setSeconds(0);

That is leading to an error:
Date.now(...).setSeconds is not a function

The same error appears if I try""
let now = Date.now();
now.setSeconds(0);

What is the correct way to make it work? I expect to return, for example, 1543484520000 for Thu Nov 29 2018 07:42:00 GMT-0200

A: This is what you want I think

let now = new Date();
now.setSeconds(0);
console.log(now.getTime());

A: Try this:

let now = new Date();
now.setSeconds(0);
console.log(now.getMilliseconds());
console.log(now.getTime());

Once you have the date object, you can get out what you need. See documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

A: Try this
To get Seconds :-

date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;
console.log("milliseconds : "+milliseconds + " seconds : "+seconds );

To set seconds :-

let date = new Date();
date.setSeconds(0);
milliseconds = date.getTime();
seconds = milliseconds / 1000;
console.log("milliseconds : "+milliseconds + " seconds : "+seconds );

A: You can use the timestamp to remove the seconds.

var timestamp = new Date(+new Date() - ((+new Date()) % 60000));
console.log(+timestamp);


text:
Q: iNotify single read How do you get iNotify to only read a file once?
I have the following code:
int settingsCheck(int &length, int &i, char * buffer, int &fd, string setRead[])
{
    int f_change = 0;

    struct pollfd pfd = { fd, POLLIN, 0 };
    /* Poll with a timeout of 100ms */
    int ret = poll(&pfd, 1, 100);
    /* Check to see the result of the poll */
    if (ret < 0) {
        fprintf(stderr, "Poll failed: %s\n", strerror(errno));
    }
    else if (ret == 0) {
        /* Timeout with no events -> move on */
    }
    else {
        /* Process the new event */
        struct inotify_event event;
        length = read(fd, buffer, BUF_LEN);
        printf("read\n");

        while (i < length)
        {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len)
            {
                if (event->mask & IN_MODIFY)
                {
                    printf("The file %s was modified.\n", event->name);
                    readSettings(setRead);
                    //f_change = 1;
                }
            }
            i += EVENT_SIZE + event->len;
        }
        //readSettings(setRead);
        return 1;
    }

    return 0;
}

This uses poll to make sure the function does not block with read. When a file is modified, "read\n" is printed twice and the file is read twice (my guess is the first read is for clearing of the file and the second for writing to it). I made sure that my php code that accesses the file only does one "fprintf" statement, thus only a single write, yet the iNotify checking for modify reads twice, perhaps because of the clear and then write?
Is there a way to work around this??


text:
Q: Stringformat concatenates databinding and resource's value I want to concatenate in my window title a property from my viewmodel and a value that cames from a resources file.
This is what I have working without the string from resources:
Title="Binding Path=Description, StringFormat=Building: {0}}"

Now I want to remove the "Building" string and put a value from a resource like I use on other places:
xmlns:res="clr-namespace:Project.View.Resources"
{res:Strings.TitleDescription}

How can I define both? Can I define like a {1} parameter?

A: I've seen the MultiBinding answer in several places now, and it is almost never necessary to use it. You can define your resource as the string format instead, and as long as there is only one string format argument, no MultiBinding is required. Makes the code a lot more succinct:
<TextBlock Text="{Binding Description, StringFormat={x:Static res:Strings.TitleDesc}}" />

And the TitleDesc resource is obviously "Building: {0}".

A: Yes, you can. Simply use a MultiBinding.
The MSDN article on StringFormat has an example.
In your case, the code would look something like this:
  <TextBlock>
    <TextBlock.Text>
      <MultiBinding  StringFormat="{}{0} {1}">
        <Binding Source="{x:Static res:Strings.TitleDescription}"/>
        <Binding Path="Description"/>
      </MultiBinding>
    </TextBlock.Text>
  </TextBlock>


text:
Q: How to forge this mysql request? I need to forge a request sql which is called by a php page but I get stuck on the way to write it...
i want make a request called by script :
http://localhost/script.php?Societe=&Nom=rgegr&Ville=&....
I have a table named : client

and a another table named suivi

I want this

i have try this :
SELECT client_id,Societe,Nom,SUM(suivi.Suivi),COUNT(suivi.num_client)

FROM client,suivi

WHERE num_client IN (select client_id from client WHERE client_id LIKE '%$id%' and Societe LIKE '%$Societe%' and Nom LIKE '%$Nom%' and Ville LIKE '%$Ville%' and Adresse LIKE '%$Adresse%' and Departement LIKE '%$Departement%' and Site LIKE '%$Site%' and Tel LIKE '%$Tel%');

Can you give me some advice
Thanks


text:
Q: Using just one pointer to initialize elements in an array? How do I go about using only one pointer, p2, to initialize values of an array of 2 elements?
I know that the array name, a, is a pointer pointing to the address of the first element in the array so I did this:
int a[2];
p2 = a; //set pointer to address of a[0]
*p2 = x; //set value of a[0] to value of x
cout << "The address of the first element in a is: " << &p2 << endl;

Now my problem comes with trying to use the same pointer to initialize the second element in a to the value of y. Here is what I've tried:
p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << &p2 << endl;

When I print out the address of both elements, they come out with the same address but they should be different since they are at different addresses with different values. Any help is appreciated. Thanks.
Edit: Thank you for your responses everyone. They were very helpful. This is what I ended up doing:
int a[2];
p2 = a;
*p2 = x;
*(p2+1) = y;
cout << "The address of the first element in a is: " << p2 << endl;
cout << "The address of the second element in a is: " << p2+1 << endl;

A: I assume you defined int * p2;
Then, what you mean to do is
int a[2];
p2 = a; //set pointer to address of a[0]
*p2 = x; //set value of a[0] to value of x
cout << "The address of the first element in a is: " << p2 << endl;  // (1)
p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << p2 << endl; // (2)

In the following table I show the contents of various expressions, at points (1) and (2)
            p2                    &p2
(1)   address of a[0]   address where p2 is stored
(2)   address of a[1]   address where p2 is stored

&p2 does not contain the address of a[0] (that is p2), but the address where that value (i.e., that address) is stored.
So when you increment p2 (you could have done p2++ as well), &p2 does not change.
The fact that p2 is a pointer and you mean to use it to traverse array elements may lead to confusion, but it is irrelevant.


text: Q: How to handle expired sessions in NodeJs I'm using Express and Passport.js in my project. I handle login and logout users. But, if the user does not logout, i don't handle expired session. I want to handle expired session or i want to access current session list in the server. Are there any methods for this?


text:
Q: OCaml: the variant type unit has no constructor :: I'm trying to implement sets through lists.. This is the code with the implementation (I omitted the interface):
module MySet : Set =
  struct
    type 'a set = 'a list
    let empty : 'a set = []
    let add (x: 'a) (s: 'a set) : 'a set =
      if not(List.mem x s) then x::s
    let remove (x: 'a) (s: 'a set) : 'a set =
      let rec foo s res =
    match s with
    | [] -> List.rev res
    | y::ys when y = x -> foo ys res
    | y::ys -> foo ys (y::res)
      in foo s []
    let list_to_set (l: 'a list) : 'a set =
      let rec foo l res =
    match l with
    | [] -> List.rev res
    | x::xs when member x xs -> foo xs res
    | x::xs -> foo xs (x::res)
      in foo l []
    let member (x: 'a) (s: 'set) : bool =
      List.mem x s
    let elements (s: 'a set) : 'a list =
      let rec foo s res =
    match s with
    | [] -> List.rev res
    | x::xs -> foo xs (x::res)
      in foo s []
  end;;

This is the error I get
Characters 162-164:
        if not(List.mem x s) then x::s
                                   ^^
Error: The variant type unit has no constructor ::

I can't understand the error

A: It's a very confusing message that we got since 4.01 that stems from the fact that you have no else branch and that () is a valid constructor for unit.
Since you have no else branch the whole if must type to unit and thus the then branch aswell and it tries to unify the expression in the then branch with a value of type unit and detects that :: is not a constructor for values of type unit.
What you wanted to write is:
if not (List.mem x s) then x :: s else s

Without an else branch your add function needs to type to 'a -> 'a set -> unit
The strange error message is being bug tracked in OCaml's issue tracker, see PR 6173.


text:
Q: Lubuntu with an Ubuntu desktop: system menu not visible 14.04 These are the steps I followed:

*

*install Lubuntu 14.04

*install Ubuntu desktop 14.04

*install ubuntu-tweak-tool

*install unity-tweak-tool (this did not work, it asked me to install missing packages)

*install gnome-tweak-tool

*download and install the macbuntu theme from www.noobslab.com

Result: when I start the Ubuntu desktop, the system menu in the upper right corner isn't visible and I have to shut down/restart from a terminal.
Can anyone help?

A: The mac doesn't have a system menu in the upper right corner so please uninstall the mac theme first...
We'll take it from there and update your question and my answer to take you further.


text:
Q: Chat UI let us reply to deleted messages until we reload the page I just noticed I can reply to a deleted message in chat, while this wasn't possible before, i.e. the reply function used to disappear when the message was deleted.
Evidence can be found here, here and here. It seems that the reply doesn't ping the author of the deleted message, but it does convert to their name, so it gives me the smell of a bug. There may be something more serious broken.
If it helps, I'm using Chrome version 47.0.2526.111 m, though I doubt that's relevant.

Update: It seems if the message was deleted before you loaded the chat page, the reply isn't possible. Nonetheless, the previous functionality is missing and it would be surprising to see this as a new feature.


text:
Q: CSS: How to make a block to cover all width of parent block I've come across the same issue several times already. When I display one block with the float property, the next block starts to overlape the first one. e.g.
Following block of code
.row_item{
width: 30%;
display: block;
float: left;
padding: 4px;
margin-left: 5px;

}
So if in html I have:

Paul Merfy

Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и ...

Александр Алехин, первый русский чемпион

Ten years ago a crack commando unit was sent to prison by a military court for a crime they didn't commit. These men promptly escaped from a maximum security stockade to the Los Angeles underground. ...

Vishi Anand, чемпион с родины шахмат

Ten years ago a crack commando unit was sent to prison by a military court for a crime they didn't commit. These men promptly escaped from a maximum security stockade to the Los Angeles underground. ...

top 100
This word top100, starts to be displayed in the row with those 3 divs....
Actually, the problem is that, I can't understand, how to make height of these blocks controllable in some way... Because if I add borders for them, (or for element which displayed after), I see that these borders are higher...
Here some screens:
http://img.skitch.com/20100121-rxb82873i6aeyuyj1aetdu8uie.png
Will be really happy if someone will help

A: Looks like you need to clear your floats.
Enclose all
 ...
 in a parent DIV and give apply following CSS:
#row_items {
  width:100%;
  overflow:hidden;
}

OR
After the last
 ...
 add the following:


text:
Q: Macbook crashes during start up My 13" macbook pro mid 2012 won't get through halfway the loading bar. After pressing the power button, the apple logo appear , i hear the chime, it would load halfway then just shuts off.
I have tried to login with different keyboard commands, but it doesn't even reach the login window. Please help


text:
Q: Reference-Request: Symmetric Product Schemes Is there a good reference for the theory of symmetric product schemes? (I only need a few basic things, the construction, etc.)
Googling it turned up a lot of papers which use it as if it's common knowledge, so I suspect there should be a reference somewhere, but I can't find any.

A: I don't think there is a reference addressing exactly your question, so I'll just try my best to answer your question using more general knowledge and providing a number of references.

*

*If we have a finite group $G$ acting on a finitely generated algebra $A$ over a field $k$, we know by the Artin-Tate lemma that $A^G$ is also noetherian (it is a finitely generated algebra over $k$ in case $A$ is).  You can find this e.g. in Atiyah & Macdonald, Introduction to Commutative Algebra.  The idea is that $A$ is an $A^G$-module of finite type.  It is easy to see that $K^G$ is the quotient field of $A^G$, in the case where $A$ is a domain.

*For actions of finite groups on schemes: when we have a scheme $S$ and a finite group $G$ acting on $X$, one may reduce with some generality to the affine case, solved above.  Indeed, this is the case for $X$ quasiprojective scheme over a ring $A$ (we will take $A$ to be Noetherian).  I know that this result is due to Michael Artin, but I saw it in James Milne's Etale Cohomology book.
I would say that a good reference in general is Mumford's Geometric Invariant Theory.
IMPORTANT: The condition that is required to ensure the reduction to the affine case is the following.  If any $G$-orbit admits an affine open set containing it, then we may construct $X/G$ by reduction to the affine case.  If $X$ is quasiprojective over an affine ring, this is the case for any finite set of points.

*

*It is easy to see that, if $X$ is normal, so is $X/G$ provided $X$ is quasiprojective over a field or so (i.e. provided we fall under the above hypotheses).

*In the case of a smooth curve $C$, you may consider the symmetric product $S^d(C).$  This is smooth, and the proof is done via local coordinates, as follows.
1) In the case where $C={\mathbb A}^1$, we are still in the affine case.  We know by the theorem on elementary symmetric polynomials (Waring) that (here $X=(X_i)_{i\leq n}$)
$$k[X]^{S_n}=k[s_1, \cdots , s_n],$$
where $s_i$ are defined by
$$T^n-s_1T^{n-1} + \cdots +(-1)^ns_n= \prod (T-X_i).$$
2) In the case of a smooth curve $C$, consider a point  $\sum n_i P_i$, where $P_i \in C$ and $\sum n_i=d.$  Without much effort (but by proceeding carefully) one may reduce to the above by choosing local coordinates and considering the decomposition group of a point of $C^d$ above our chosen point in $S^dC$.

*

*If $X$ is a smooth projective surface, then the desingularisation of $S^dX$ (which is always non-smooth for $\dim X\geq 2$ as the branch locus is a union of diagonals which has codimension $\leq 2$) has a correspondence with the Hilbert scheme of zero-dimensional subschemes of $X$ of length $d$.  The standard reference is H. Nakajima's book:

http://books.google.com.br/books/about/Lectures_on_Hilbert_Schemes_of_Points_on.html?id=pjjgNhDVgcgC&redir_esc=y

*

*I remember that I.G. Macdonald has a book on symmetric functions, which perhaps is of some use to you, though it won't be the answer you seek, as your question stands.

*There is a paper by E. Freitag on J. Crelle on actions of finite groups on varieties (it contains some results on numerical invariants in the case of complex smooth projective varieties).
http://www.researchgate.net/publication/243110046_Die_Struktur_der_Funktionenkrper_zu_hyperabelschen_Gruppen._II
Finally, maybe you have heard of the Molien series (related to finite group actions on projective schemes over a field).


text:
Q: Python Freezegun giving different values when freezing time to datetime.datetime.now() Im trying to use freezegun to set the clock back 10 seconds for a unit test.
I've found that setting the time to now with freezegun results in the expected behavior for datetime.datetime.now() but somewhat different behavior for time.time() in that the "frozen" time is ~30,000 seconds behind (8 hours).
Using datetime.datetime.utcnow(), its off by 3600 seconds (1 hour).
What do I need to do to appropriately mock the time to be used with time.time()?
Using now(): 8 hours off
def test_freezegun(self):
  """ Test that freezegun can set time.time() back 10 seconds. """

  with freezegun.freeze_time(datetime.datetime.now()):
    print time.time()
    print datetime.datetime.now()

  print time.time()
  print datetime.datetime.now()

# Output
[08:09:32] 1436339372
[08:09:32] 2015-07-08 08:09:32.119516
[08:09:32] 1436368172
[08:09:32] 2015-07-08 08:09:32.175031

Using utcnow(): 1 hour off
def test_freezegun(self):
  """ Test that freezegun can set time.time() back 10 seconds. """

  with freezegun.freeze_time(datetime.datetime.utcnow()):
    print time.time()
    print datetime.datetime.now()

  print time.time()
  print datetime.datetime.now()

# Output
[08:08:56] 1436364536
[08:08:56] 2015-07-08 15:08:56.589202
[08:08:56] 1436368136
[08:08:56] 2015-07-08 08:08:56.655346

UPDATE:
This works, but I'd like to understand why:
Using utcnow() + 1 hour:  identical time.time() output, as expected
def test_freezegun(self):
  """ Test that freezegun can set time.time() back 10 seconds. """

  with freezegun.freeze_time(datetime.datetime.utcnow() + datetime.timedelta(hours=1)):
    print time.time()
    print datetime.datetime.now()

  print time.time()
  print datetime.datetime.now()

#Output
[08:22:27] 1436368947
[08:22:27] 2015-07-08 16:22:27.268315
[08:22:27] 1436368947
[08:22:27] 2015-07-08 08:22:27.339116


text:
Q: Cross-Origin Resource sharing error: Header Disallowed by preflight response i am learning how to use react as a front end and django as a backend. i am getting these cors issue everytime im hitting post method to django server. It is a very application. Sending a value from react to django server and printing it. In Django server terminal it shows  "OPTIONS /sample HTTP/1.1" 200 0
and in react it is showing cors error. i added all the different kinds but the problem still exists
enter code here
React Component Code
import axios from 'axios'
import React, { Component } from 'react'
import App from '../App';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "XCSRF-TOKEN";

class addProduct extends Component {
 constructor(props) {
    super(props)
    this.state  = {
        testId : '12324',
      }

    this.ButtonClicked = this.ButtonClicked.bind(this)
}
ButtonClicked =(e) => {
  e.preventDefault()
  console.log(this.state)
  axios({
        method: 'post',
        url: 'http://127.0.0.1:8000/sample',
        data: this.state.testId,
        crossDomain: true,
        mode : 'CORS',
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
            "Access-Control-Allow-Headers": "Origin, Content-Type",
            "Access-Control-Max-Age" : "200"
          }

    })
    .then(Response => console.log(Response.data))
  }

   render() {

    return (
        <div className = "addProduct">

            <button  type = "submit" onClick = {this.ButtonClicked} >Start</button>

        </div>
      )
    }
   }

 export default addProduct

   Django Code:
   from django.shortcuts import render
   from django.http import HttpResponse
   # Create your views here.
  def showsample(request):
     username = request.POST.get('testId')

     print("the value is " ,username)

     return HttpResponse("hello world")

In the browser Network options it shows :
Requested url: http://127.0.0.1:8000/sample
Referrer Policy: strict-origin-when-cross-origin
Request Headers:
with a warning symbol : Provisional headers are shown
Accept: application/json, text/plain, /
Access-Control-Allow-Headers: Origin, Content-Type
Access-Control-Allow-Origin: *
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:4200/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36
When  double click on the "sample" which is highlighted in red color.
Then the post request is passing and I can see the output on the Django terminal and HTTP Response of helloworld

A: I found the answer after struggling a lot.
I imported django.views.decorators.csrf import csrf_exempt
and in the url pattern added this
urlpatterns = [
path('sample', csrf_exempt(views.showsample))

]
  from django.urls import path
  from django.views.decorators.csrf import csrf_exempt
  from . import views

  urlpatterns = [

       path('sample', csrf_exempt(views.showsample))
    ]

A: I had the same problem with react and ajax and i tried to pass those headers with my request but didnt worked, i installed Allow CORS chrome extension which solved my problem.
In your case im not sure but try this two methods.

*

*in your Django project settings.py file set ALLOWED_HOSTS to "*". like this:
ALLOWED_HOSTS = ["*"]

*install Allow CORS for chrome, or if you use any other browser there must be other cors related extensions for them too...
and if non of this helped please share the error you get, with us.


text:
Q: Largest of the smallest angles of incidence from arbitrary point to tetrahedron vertex/centroid line Picture a regular tetrahedron where each vertex has a line through the centroid and a plane normal to it.  I need to show that the range of the smallest angles of incidence from an arbitrary point to one of these planes, as measured at the centroid, falls within $-arccos(1/3)/2$ to $+arccos(1/3)/2$.
i.e. the angles are measured at each plane/centroid intersection and the smallest of these never exceeds the above range.
I can model it, just not prove it. Any help is much appreciated.
[edit]
An analogous question is what is the minimum angle $\theta$ such that four spherical segments defined by +/- $\theta$ as subtended from the centroid in each of the 4 normals to the surface of a sphere will give 100% coverage of that sphere.
I apologise for the possibly vague form of the question. It's just that I'm an IT guy and not a mathematician.
[\edit]
[edit]
I'm struggling with a way to present this question such that it is clear to others.  The best that I can come up with at the moment is an analogy.
Imagine that I construct a regular tetrahedron inside a larger sphere.  On this tetrahedron I place poles that go from the vertex to the centroid.  At the centroid I mount a spotlight on, but perpendicular to, each of these poles.  These spotlights being free to rotate 360 degrees around the pole. Forgetting for a moment the impossibility of having all four in the same place at one time, my question would be, what is the minimum beam angle that I would need in order to be able to illuminate any part of the inside of the sphere.
[\edit]

A: My computations confirm that the maximal angle is
$$
arcsin(1/\sqrt{3})=\frac{1}{2}arccos(1/3).
$$
You can always put a coordinate system such that the origin is at the centroid and the vertices of the tetrahedron are
$$
(1,1,1),\quad (1,-1,-1),\quad (-1,1,-1)\quad\text{and}\quad (-1,-1,1).
$$
This means, they are four corners of a 3D cube of sidelength 2 centered at the origin, with faces parallel to the coordinate planes. We claim (proof below) that the maximal angle is attained at the center of any of the faces. On the other hand the angle between the center of a face and an adjacent corner is $arccos(1/\sqrt{3})$. For example if you take the corner to be $A=(1,1,1)$ and the center of the face $M=(0,0,1)$, then
$$
\cos(\sphericalangle MOA)=\frac{M\cdot A}{\|A\|\|M\|}=\frac{1}{\sqrt{3}\cdot 1}.
$$
Hence the angle we are searching for is the complementary angle $\pi/2-arccos(1/\sqrt{3})$  which gives
$$
arcsin(1/\sqrt{3})=arccos(\sqrt{2/3})=\frac 12 arccos(1/3),
$$
as desired.
$\textbf{ Proof of the claim:}$ For any point in the sphere the straight line from the origin to the point intersects the surface of the cube at a unique point. Hence, it suffices to show that for any point on the cube, there exists a corner, such that the angle between them is lower than or equal to $\pi/2$ and greater than or equal to $arccos(1/\sqrt{3})$. This shows that the angle to the orthogonal plane, which is the complementary angle, is $\ge 0$ and at most $arcsin(1/\sqrt{3})$.
For this we cover a face of the cube with four symmetric trapezoids. Each trapezoid is opposed to a corner in the following way:
If $A=(1,1,1)$, $B=(-1,1,1)$, $C=(-1,-1,1)$ and $D=(1,-1,1)$, the trapezoid opposed to $A$ is formed by $B,D,E,F$, where $E=(0,-1,1)$ is the midpoint of the segment $BC$ and $F=(-1,0,1)$ is the midpoint of the segment $CD$. Then for any point $P$ in this trapezoid opposed to $A$ the angle between the point $P$ and $A$ (the central angle $\sphericalangle POA$) is lower than or equal to $\pi/2$ and greater than or equal to $arccos(1/\sqrt{3})$:
For the first inequality it suffices to compute the internal product $P\cdot A\ge 0$, which follows from
$$
E\cdot A=(0,-1,1)\cdot (1,1,1)=0\quad\text{and}\quad F\cdot A=(-1,0,1)\cdot (1,1,1)=0.
$$
 For the second inequality we proceed in two steps.
First, if $P$ is not on the segment $BD$, then there is a straight line from $P$ to $A$ that intersects the segment $BD$ at one point, let us call it $Q$. Then we can add angles
$$
\sphericalangle POA=\sphericalangle POQ+\sphericalangle QOA,
$$
and so $\sphericalangle POA\ge\sphericalangle POQ$.
Hence it suffices to prove the second inequality for points $Q$ on the segment $BD$.
If $A=(1,1,1)$, $B=(-1,1,1)$ and $D=(1,-1,1)$, the points on the segment $BD$ are parametrized by
$$
Q(t)=(0,0,1)+t(1,-1,0),\quad \text{for $t\in[-1,1]$}.
$$
Then
$$
cos(\sphericalangle QOA)=\frac{Q(t)\cdot A}{\|Q(t)\|\|A\|}=\frac{1}{\sqrt{3(2t^2+1)}},
$$
which attains its maximum $1/\sqrt{3}$ at $t=0$, i.e., at the midpoint of $BD$, which is the center of the face. Therefore all angles $\sphericalangle POA$ of points in the trapezoid are greater than or equal to $\sphericalangle QOA$ for a point $Q$ on $BD$, and $\sphericalangle QOA\ge arccos(1/\sqrt{3})$, as desired.


text:
Q: Ubuntu 18.04 alternating between successful boot and failed boot I have a fresh install of Ubuntu 18.04 which has this strange behaviour:
First boot fails - black screen after grub. After a force power-off the next one succeeds. Another reboot would bring it to the first state - failed boot (and so on).
The machine is a i9-9820x (ASUS X299) with dual nvidia GPUs (1080 Ti). Boot device is nvme ssd.
OS: Ubuntu 18.04.3 LTS
Kernel details:
$ uname -a
Linux sbimage1804 5.0.0-36-generic #39~18.04.1-Ubuntu SMP Tue Nov 12 11:09:50 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

A few things that were tried:

*

*kernel parameter: nomodeset: display changes accordingly but it still fails first boot

*blacklisting nouveau driver: display changed to lower resolution, first boot fails (nvidia drivers haven't been installed yet)

*Trying rescue mode on first boot: first boot hangs, last writing on the screen: Loading initial ramdisk

*Also didn't help: setting recordfail=0 in grub

*kernel parameter: acpi=off did not help either

Any ideas of how to solve / debug this situation? I tried adding debug earlyprintk=efi,keep kernel parameters but it doesn't add any output before the machine hangs (even in rescue mode)

A: So it seems this is an issue caused by a faulty update of intel microcode (relative to the affected hardware).
Working around it is done by adding dis_ucode_ldr as kernel parameter. This eliminates the hanged boots.
Note that this workaround comes with a risk of missing a fix to a CPU bug. The price looks like keep following on errata/bugs relevant to the CPU model and and perform BIOS updates to the latest version in a hope that the vendor addresses those bugs. Hopefully a future update of intel-microcode package would fix that issue.
Edit:
I discovered that the default package of intel-microcode that comes with Ubuntu 18.04.3 doesn't cause this issue. A newer version of that packages coming from sudo apt upgrade is the problematic one. Marking that package as 'hold' prevents it from being upgraded, and avoids the need to put the dis_ucode_ldr kernel parameter:
$ sudo apt-mark hold intel-microcode


text:
Q: Why is a margin-top percentage using height and how can I work around it? I have a CSS slide down menu that can vary in the number of elements displayed.
I use an overflow: hidden wrapper and margin-top: -100% to hide the menu, and a CSS transition with margin-top: 0 to animate the slide down.
The problem appears to be that margin-top: -100% seems to be picking up the explicit width of any parent element and ignoring the content height.

.outer {
  overflow: hidden;
  border: 10px solid red;
  cursor: pointer;
}
.outer > .slide {
  margin-top: -100%;
  transition-property: margin-top;
  transition-duration: 1s;
}
.outer:hover > .slide {
  margin-top: 0;
}
.outer.bug {
  width: 100px;
}

        Ayy

        Bee

        See

        Dee

        Eee

        Eff

        Gee

        Ayy

        Bee

        See

        Dee

        Eee

        Eff

        Gee

Run that snippet and you should see two red boxes, mouse over either to get the slide down menu.
The problem is the second box - the only difference is that the parent has width: 100px; set.
If you inspect the second box you should see that the margin-top: -100%; has been calculated as -100px.
In fact any explicit or inherited width against the parent div will become the negative margin.
The only way I've found round it is to explicitly set the margin-top to be the same as the height of the sliding menu, but that involves DOM layout and JS that I don't really want to do for each menu.
Is this a bug in how browsers handle negative percentages on margin-top? IE11, Chrome and FX all seem to treat it the same way.
Is there a better way around it that doesn't require an explicit height calculation and additional Javascript?

A: To move an element (regardless of it's height) in relation to its own dimensions you can use a transform:translate() instead of margin.
So your requirement to move the element up by its own height would require a translation in the Y-axis of -100%. Like so:

* {
  margin: 0;
  padding: 0;
}
.outer {
  /* overflow: hidden; */
  padding: 10px;
  background: red;
  cursor: pointer;
  position: relative;
}
.outer > .slide {
  position: absolute;
  top: 0;
  left: 0;
  transform: translateY(-100%);
  transition-property: transform;
  transition-duration: 1s;
}
.outer:hover > .slide {
  transform: translateY(0%);
}

Ayy

Bee

See

Dee

Eee

Then we can use absolute positioning to remove the child from the document flow.

A: margin-top:-100% works only when we remove border of 20px assigned .outer which is used twice 10px + 10px. So we can make use of CSS calc() function over-here to get our output.
ul has a default padding-top:40px so this too is used twice 40px + 40px, which we have to set to 0px.
So ul and border is the reason for not working of margin-top:-100%;
Default ul properties :
ul{
display: block;
list-style-type: disc;
margin-before: 1em;
margin-after: 1em;
margin-start: 0;
margin-end: 0;
padding-start: 40px;
}

.outer {
  overflow: hidden;
  border: 10px solid red;
  cursor: pointer;
  width:auto;
  height:auto;
}
.outer > .slide {
  margin-top: calc(-26px + (-100%));
  transition-property: margin-top;
  transition-duration: 1s;
  background:#ccc;
}
.outer > .slide > ul{
  padding:0;
  margin:0;
}
.outer:hover > .slide {
  margin-top: 0;
}
.outer.bug {
  width: 100px;
}

Ayy

Bee

See

Dee

Eee

Eff

Gee

Ayy

Bee

See

Dee

Eee

Eff

Gee


text:
Q: jQuery : How to get an element by id which has been created in jQuery after DOM ready? I'm a in the wonderful world of jQuery and today i faced a problem.
I have a list of app that user can select. To select an app they have to click on a button (id="add_app_#{app_id}"). When someone add an app i create a row on a table that list all selected apps. In this row (created in jQuery) there is a button (id="remove_app_#{app_id}") to remove the app from the table.
My issue is that i don't know how to get my remove_app button's click event (certainly because it's added to the DOM after the DOM is ready).
Though, i used .on() jQuery function...
Here is my code:
jQuery(function() {
    $('[id^=add_app_]').click(function() {
        var app_id, version_id;
        version_id = 0;
        app_id = this.getAttribute('data-app_id');

        $("#app_versions_" + app_id + " option:selected").each(function() {
            version_id = $(this).val();
        });

        hide_app_from_selector(app_id);
        display_app_in_table(app_id, version_id);
    });

    $('[id^=remove_app_]').on('click', function() {
        // I NEVER GET HERE !
        var app_id;
        app_id = this.getAttribute('data-app_id');
        remove_app_from_table(app_id);
        display_app_in_selector(app_id);
    });
});

A: Simple answer: You use Event delegation.
You can achieve that by passing a selector as second argument to jQuery's .on().
$( document.body ).on( 'click', '[id^=add_app_]', function() {
});

Instead of document.body you should use the closest shared parent possible to prevent unnecessary event bubbling.

A: You can use the on() method to assign an event handler to an ancestor of a dynamically created element which exists when the method was first called. What you're doing by simply using $('[id^=remove_app_]').on(...) is assigning the event handler to that element which doesn't exist when called.
To rectify this, find an ancestor of your [id^=remove_app_] element which exists when you first assign the event handler and assign on() to that:
$('body').on('click', '[id^=remove_app_]', function() { ... });

With this particular code, you delegate the event handler to body (which presumably exists prior to calling your on() function) rather than assigning it directly to your dynamically created element. From jQuery's on() documentation:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

To make your code as performant as possible, you'll want to assign the delegation to the closest ancestor which isn't dynamically created, for instance:
<div id="non-dynamic-container">
    ...
    <elem id="remove_app_123"></elem>
</div>

$('#non-dynamic-container').on('click', '[id^=remove_app_]', function() { ... });


text:
Q: Accessing elements of querySelectorAll in vba One of the users have helped me to know the topic of Locating HTML elements with CSS selectors : querySelector() method is much more easier than getElementsBy() https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll#obtaining_a_list_of_matches...In code below, I want to access elements of all  with innerText View Listing. For that purpose I wrote code below where querySelectorAll takes the parent div with class module(as an array, or collection, list call how you want) successfully. But after I was not able to go on element by element neither with querySelect() nor within for loop;
Public Sub newEditionQry()

    Const URL As String = "https://cooperatordirectory.com/search_results?location_value=Florida&adm_lvl_1_sn=FL&stateSearchLN=Florida&country_sn=US&location_type=administrative_area_level_1&stateSearch=FL&swlat=24.396308&nelat=31.000968&swlng=-87.634896&nelng=-79.974306&lat=27.6648274&lng=-81.5157535&faddress=Florida%2C+USA&place_id=ChIJvypWkWV2wYgR0E7HW9MTLvc"
    Dim ie As SHDocVw.InternetExplorer

    Set ie = New SHDocVw.InternetExplorer

    With ie
        .Visible = True
        .navigate URL
        Do While .readyState <> READYSTATE_COMPLETE Or .Busy: DoEvents: Loop

        Set a = .document.querySelectorAll(".module")

        For Each element In a
            Debug.Print a.querySelector("a.btn").innerText ' err line
        Next element

    End With

End Sub

What will I do if I will be able to catch  elements with viewListing Texts. I will manipulate each of them ( if you give a look the website, you see they are dozens of them) by method click.

                View Listing

                    Send Message

A: You have a typo (?) where you are calling .querySelector on the parent nodeList a. This is not a valid method call.
Instead, you wanted:
element.querySelector("a.btn").innerText

However, element.querySelector is an oddity as the shift to Edge was enacted. And here, by element, I mean html element i.e. a node within the DOM (not the document node), or element interface, rather than the iteration variable named element.
Your code with the above change will then error if the selector list in the loop call to querySelector returns nothing as you don't test the return to ensure there are matches.
Given what it seems you are after, the solution requires merging the two selector lists to produce a single parent nodeList satisfying both original conditions. Iterate that and simply access the .innerText property directly.
Also, the typical method for looping a nodeList is to loop from 0 to nodeList.Length - 1 and index into nodeList during the loop. There was a bug, maybe still present, with the enumeration method called by using a For Each on a static DispNodeList, in VBA, that can crash the calling application.

Public Sub newEditionQry()

    Const URL As String = "https://cooperatordirectory.com/search_results?location_value=Florida&adm_lvl_1_sn=FL&stateSearchLN=Florida&country_sn=US&location_type=administrative_area_level_1&stateSearch=FL&swlat=24.396308&nelat=31.000968&swlng=-87.634896&nelng=-79.974306&lat=27.6648274&lng=-81.5157535&faddress=Florida%2C+USA&place_id=ChIJvypWkWV2wYgR0E7HW9MTLvc"
    Dim ie As SHDocVw.InternetExplorer

    Set ie = New SHDocVw.InternetExplorer

    With ie
        .Visible = True
        .navigate URL
        Do While .readyState <> READYSTATE_COMPLETE Or .Busy: DoEvents: Loop

        Set a = .document.querySelectorAll(".module a.btn")

        For Each element In a
            Debug.Print element.innerText
        Next element

    End With

End Sub

Document.querySelectorAll()

The Document method querySelectorAll() returns a static (not live)
NodeList representing a list of the document's elements that match the
specified group of selectors.

Element.querySelector()

The querySelector() method of the Element interface returns the first
element that is a descendant of the element on which it is invoked
that matches the specified group of selectors.


text:
Q: does it have missing word after "up and down"? Does it have Missing word In the following sentence?

If I were, would I have shooting pains up and down my left arm?

I consider up and down an adverbial, but in this sentence it's more like a preposition...

A: No missing words.  They are prepositions.  "Up and down my left arm" = in the upper areas of the arm (closer to the shoulder) and the lower areas of the same (closer to the wrist).


text:
Q: PostGIS query works as SELECT but not UPDATE I want to clip the geometries of my table by a polygon.
I have a query that does this just fine as a SELECT query:
WITH
    clip AS
    (
        SELECT ST_GeomFromEWKT('SRID=26915;POLYGON ((379308.073398988 5232934.49102113,377638.690726783 5102722.64258913,537899.427258473 5097714.49457251,541238.192602883 5236273.25636554,379308.073398988 5232934.49102113))') AS geom
    ),
    new_geom AS
    (
        SELECT
            input.gid,
            CASE
                WHEN ST_CoveredBy(input.geom, clip.geom) THEN input.geom
                ELSE ST_Multi( ST_Intersection(input.geom,clip.geom) )
            END AS geom
        FROM "rail_lines" AS input
        INNER JOIN clip
        ON ( ST_Intersects(input.geom, clip.geom)
        AND NOT ST_Touches(input.geom, clip.geom) )
    )
SELECT * FROM new_geom;

However, when I use this same query to UPDATE the geometry of the input table the query either does not complete or does nothing (ie. does not alter the geometries of the input table):
WITH
    clip AS
    (
        SELECT ST_GeomFromEWKT('SRID=26915;POLYGON ((379308.073398988 5232934.49102113,377638.690726783 5102722.64258913,537899.427258473 5097714.49457251,541238.192602883 5236273.25636554,379308.073398988 5232934.49102113))') AS geom
    ),
    new_geom AS
    (
        SELECT
            input.gid,
            CASE
                WHEN ST_CoveredBy(input.geom, clip.geom) THEN input.geom
                ELSE ST_Multi( ST_Intersection(input.geom,clip.geom) )
            END AS geom
        FROM "rail_lines" AS input
        INNER JOIN clip
        ON ( ST_Intersects(input.geom, clip.geom)
        AND NOT ST_Touches(input.geom, clip.geom) )
    )
UPDATE rail_lines
SET geom = new_geom.geom
FROM new_geom
WHERE new_geom.gid = rail_lines.gid;

Does anyone know what is happening here?
I'm also open to other (simpler) means to clipping a table's geometry in-place without creating a new table.
Update
I'll update my question based on the suggestion by @JohnPowellBarca.
Updating the table still doesn't work but it might help to illustrate the issue.
Here's the query I'm using. First, I create a new table based on the intersection with my area of interest. Then I use that new table to attempt to update the geometry of the original table.
CREATE TABLE rail_lines_clip AS
SELECT in_table.gid, in_table.geom
FROM
    rail_lines AS in_table,
    aoi AS clip
WHERE ST_Intersects(in_table.geom, clip.geom);

UPDATE rail_lines
SET geom = rail_lines_clip.geom
FROM rail_lines_clip
WHERE rail_lines_clip.gid = rail_lines.gid;

And here's a visual of the result after running the query:

The area of interest (ie. aoi) is in black.
The new table (ie. rail_lines_clip) is in green.
And the original table (ie. rail_lines) is in red.
From my understanding, the geometry of rail_lines should be identical to that of rail_lines_clip.
Maybe I should just use that new table, and then drop the old table, and rename the new to old.  Such as:
CREATE TABLE rail_lines_clip AS
SELECT in_table.gid, in_table.geom
FROM
    rail_lines AS in_table,
    aoi AS clip
WHERE ST_Intersects(in_table.geom, clip.geom);

DROP TABLE IF EXISTS rail_lines;

ALTER TABLE IF EXISTS rail_lines_clip
RENAME TO rail_lines;

(Which works as expected, by the way).
But, I'm still curious: Has anyone else had success updating the geometry of a table in place?

A: Try
WITH
  clip AS (
    SELECT ST_GeomFromEWKT('SRID=26915;POLYGON ((379308.073398988 5232934.49102113,377638.690726783 5102722.64258913,537899.427258473 5097714.49457251,541238.192602883 5236273.25636554,379308.073398988 5232934.49102113))') AS geom
  )

UPDATE rail_lines
  SET geom = ST_Multi(ST_Intersection(geom, clip.geom))
  FROM clip
  WHERE ST_Relate(geom, clip.geom, 'T*T******')
RETURNING rail_lines.gid

I´m using a DE-9IM matrix and ST_Relate here (check this blog for some good explanation); your lines have to intersect, but may not either be contained by or only touch the polygon, so that the line interior has to intersect the polygon's interior and exterior in some way.
Finally, with RETURNING you can check if something has been updated; in this case, it will return all rail_lines.gid where an update happened. If there are no updates listed, your polygon might just not be where you expect it to be (double checked the coordinates? correct SRID?)

A: The examples I see, are always updating inside the "with"
https://www.postgresql.org/docs/9.6/static/queries-with.html
WITH t AS (
  UPDATE products SET price = price * 1.05
  RETURNING *
)
SELECT * FROM t;

I don't have the database to test it, but you can try something like this:
WITH
clip AS
(
    SELECT ST_GeomFromEWKT('SRID=26915;POLYGON ((379308.073398988 5232934.49102113,377638.690726783 5102722.64258913,537899.427258473 5097714.49457251,541238.192602883 5236273.25636554,379308.073398988 5232934.49102113))') AS geom
),
new_geom AS
(
    SELECT
        input.gid,
        CASE
            WHEN ST_CoveredBy(input.geom, clip.geom) THEN input.geom
            ELSE ST_Multi( ST_Intersection(input.geom,clip.geom) )
        END AS geom
    FROM "rail_lines" AS input
    INNER JOIN clip
    ON ( ST_Intersects(input.geom, clip.geom)
    AND NOT ST_Touches(input.geom, clip.geom) )
)
 UPDATE rail_lines
 SET geom = new_geom.geom
 WHERE new_geom.geom IN(SELECT geom FROM clip)


text:
Q: The sdk platform-tools version (26.0.2) is too old to check APIs compiled with API 27; please update I'm using IntelliJ Idea Community Edition 2017.2.5 and am building an Android app.
My problem is that even if in my app (Gradle) I have:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.0"
    defaultConfig {
        applicationId "com.app.mtvtr"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.0.0'
    compile 'com.android.support:design:27.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.android.support:support-v4:27.0.0'
    testCompile 'junit:junit:4.12'
}

Also, on first build of the project, compile for the appcompat, design and support was set to 27+ (which IMHO is bad practice and is already pointed by the Studio as a bad idea), so using which tools that I have, I have set it to 27.0.1, and later to 27.0.0 just for the testing if it might work..
In my Fragments and Activities I have:

And the warning says:

The sdk platform-tools version (26.0.2) is too old to check APIs
  compiled with API 27; please update

Now, I know that there are topics on SO regarding old and new versions, but I have (to my belief) set the Gradle properly and I am nowhere using platform-tools version 26 or even 26.0.2...
I have tried Restarting and invalidating caches three times.
The project properly builds onto the device and everything works. But, of course, I want to fix the warning. (And not hide it like some would suggest..)
Two things that come to mind are:

*

*I missed somewhere that I should have updated the version, maybe?

*I need to start a new project from scratch.

Any ideas? :)

A: Android Studio 3.0 will be merged into IntelliJ IDEA 2017.3 version, which will make the com.android.tools.build:gradle:3.0.0 plugin compatible with it. That will make this error to go away.
For those of you who are experiencing this issue in Android Studio, check your root build.gradle file and make sure it is updated to the above mentioned plugin version (3.0.0), in order to be able to compile against API 27 with the current latest build tools (26.0.2).
You may consequently also have to update the Gradle wrapper to the latest (4.1 at the time of this answer).

A: You have just to launch the SDK Manager and download the Android SDK Platform Tools and SDK Tools.
Here the official doc.

A: It seems that it was an IDE problem because it worked without warnings inside Android Studio 3.0 as it was suggested by CrazyCoder.
It seems that at this moment IntelliJ Idea isn't updated enough to make this work properly. So even while I have been using Idea from the start, I will switch to AS for now. :)
Thanks for your input guys. :)


text:
Q: How input resistance related to better amplification in transistor circuit These figures are from book by Sedra/smith.
I have a doubt regarding input impedence or resistance (Rin) shown in figure.
In book it is written that "The input resistance (Rin) represents the loading effect of the amplifier input on the signal source. It is found from Rin=Vi/Ii"(in figure).
it started with   common emitter configuration (small signal π model shown in 1st figure  ) and then author  introduces another model( CE amplifier with an emitter resistance Re ) with slight modification shown in figure2 and one of the  main motive to add emitter resistance  is increase input  resistance(Re)
I am not sure  ,how increasing input resistance lead to a better amplifier (specially bjt circuits shown in figures )?
Specially after adding emitter resistance , voltage drop across Rπ (π model of CE with emitter resistance)  decreases which causes lower amplification that's why I asked this question
There are lot of questions of input impedence on web but i hope someone  answer it for that particular  amplifier circuit rather than general one.

A: Constant input impedance implies a FLAT FREQUENCY RESPONSE, very useful in amplifiers with feedback where high_frequency poles causes poor phase_margin.


text:
Q: Quickest way to parse through nested Ruby arrays / YAML What's the cleanest way to extract third level elements from this structure provided that it's not symmetrical:
   yaml = [
    {"Collection"=>[
       {"Jeans"=>[
          {"Trends"=>[
             {"Building on basics"=>"Jeans"},
             {"Unexpected pairings"=>"Jeans"},
             {"Retro chic"=>"Jeans"}    # extract me
          ]},
          {"Styles"=>[
             {"Straight Leg"=>"Straight Leg"},
             {"Bootcut"=>"Bootcut"},
             {"Trouser"=>"Trouser"},
             {"Slim Leg"=>"Slim Leg"}
          ]},
          {"Wash"=>[
             {"Blues"=>"Blues"},
             {"Black/Grey"=>"BlackGrey"},
             {"Whites"=>"Summer Whites"},
             {"Colors"=>"Colors"},
             {"Resin"=>"Resin"}
          ]},
          {"Details"=>[
             {"Embroidered"=>"Embroidered"},
             {"Tuxedo"=>"Tuxedo"},
             {"Jeweled"=>"Jeweled"}
          ]}
       ]},
       {"Bodyshapers"=>[
          {"All"=>[
             {"All"=>"BodyShapers"}
          ]}
       ]}
    ]},
    {"Lift Tuck"=>nil},
    {"Find Us" =>[
       "By City",
       "International Websites",
       "Online Retailers"
    ]},
    {"Your Stories"=>nil},
    {"The Skinny"=>[
       "Trends",
       "Behind the Scenes",
       "VIP Events",
       "In the News",
       "Win a Pair"
    ]}
  ]

A: I don't know about the easiest way, but something like this would work:
class NthElements
  include Enumerable

  def initialize(yaml, n = 3)
    @yaml = yaml
    @n = n
  end

  def each(&block)
    traverse(@yaml, 0, &block)
  end

  private
  def traverse(value, level, &block)
    if level == @n + 1
      block.call(value)
      return
    end

    case value
    when Array
      value.each { |next_value| traverse(next_value, level + 1, &block) }
    when Hash
      value.values.each { |next_value| traverse(next_value, level, &block) }
    end
  end
end

NthElements.new(yaml).each{|val| p val }


text:
Q: Deserialize XML documents with multiple specialization / inheritance in C# I have a XML document that several cases of specialization of entries, I managed to get a solution from here to deserialize it . I have done the exact same of the example and works as a charm, however It only works if a single specialized class appears. In the links example(shown above), imagine there is another class specialized from Instrument (for example, Drums). How can I use this method to tell the deserializar when to cast to each of the specialized classes?
Serialized object:
public class Orchestra
{
   public Instrument[] Instruments;
}

public class Instrument
{
   public string Name;
}

public class Brass:Instrument
{
   public bool IsValved;
}

Example of deserialization:
 public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Create an XmlElementAttribute to override the Instrument.
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the XmlElementAttribute to the collection of objects.
      attrs.XmlElements.Add(attr);

      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* The difference between deserializing the overridden
      XML document and serializing it is this: To read the derived
      object values, you must declare an object of the derived type
      (Brass), and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments)
      {
         b = (Brass)i;
         Console.WriteLine(
         b.Name + "\n" +
         b.IsValved);
      }
   }

I have tried adding another attribute override but it does not work, I have also tried making two separate deserializers (each with an attribute override with the property I would like to cast to an object) it neither works as it fails to cast objects of the other type resulting in an type exception.
Any ideas?

A: If you have control of the .cs files you can add the attributes directly to the main class like this, serialization can be fully controlled using attributes, and in extreme cases you can implement the IXmlSerializable interface.
I've written a simple example here, but you should provide an example of what it is not working for you and the exception you are getting in order to see your concrete problem. There are many things that can fail while serializing and deserializing and the exception will tell you why. For example, if the class is not public it will throw an exception.
public class Program
{

    public class Orchestra
    {
        public Instrument[] Instruments {get; set;}
    }

    [XmlInclude(typeof(Brass))]
    [XmlInclude(typeof(Guitar))]
    public class Instrument
    {
        public string Name { get; set; }

        [XmlIgnore]
        public string DoNotSerialize { get; set; }
    }

    public class Brass : Instrument
    {
        public bool IsValved { get; set; }

        public override string ToString()
        {
            return string.Format("This is a{0} Brass.",IsValved?" valved":"n unvalved");
        }
    }
    public class Guitar: Instrument
    {
        public int Strings { get; set; }

        public override string ToString()
        {
            return String.Format("This is a {0} string Guitar.", Strings);
        }
    }

    static XmlSerializer s;

    static void Main(string[] args)
    {
        s = new XmlSerializer(typeof(Orchestra));
        serialize("%temp%test.xml");
        deserialize("%temp%test.xml");
        Console.ReadLine();
    }

    static void serialize(string filename)
    {
        Orchestra o = new Orchestra();
        o.Instruments = new Instrument[]
        {
            new Brass
            {
                IsValved=true
            },
            new Brass {IsValved=false },
            new Guitar {Strings=12 }
        };

        using (FileStream fs = new FileStream(filename, FileMode.Create))
        {
            s.Serialize(fs, o);
        }
    }

    static void deserialize(string filename)
    {
        Orchestra band;
        using (FileStream fs = new FileStream(filename, FileMode.Open))
        {
            band = (Orchestra)s.Deserialize(fs);
        }

        foreach (Instrument i in band.Instruments)
        {
            Console.WriteLine("{0}: {1}", i.GetType(), i.ToString());
        }
    }
}


text:
Q: Metrics on Euclidean spaces I vaguely remember a theorem that says that any two metrics on the Euclidean space $\mathbb{R}^n$ are equivalent in some sense, but probably not in the sense of metric equivalence: two metrics $d_1$ and $d_2$ are said to be metrically equivalent if there are positive numbers $c_1$ and $c_2$ such that
$c_1 d_1(x,y) \le d_2(x,y) \le c_2 d_1(x,y)$, $\forall$ $x,y \in \mathbb{R}^n$
Can somebody confirm which kind of equivalence there might be?
Thanks.

A: The correct statement is that any two metrics derived from norms on $\Bbb{R}^n$ are equivalent in this sense. There are plenty of metrics that are not equivalent: for example, the discrete metric is not equivalent to the standard Euclidean metric, but this is because the discrete metric doesn't come from a norm.


text:
Q: Загрузка нескольких файлов на сервер php Подскажите как загрузить на сервер и в базу данных несколько картинок. Ниже привел код у меня не получилось, подскажите как поправить код чтобы можно было загрузить несколько картинок. В Базу я загружаю пути файлов, формат примерно такой /i/название_картинки.jpg

*

*В бд есть два поля id (int 10 A_U) и name(varchar 255).
код формы

 Выберите файл для загрузки:

вывел массив
if(isset($_POST['upload']))
{
    ?>
<?print_r ($_FILES['userfile']['name']);?>

    <?
}

получил такой вид
Array
(
    [0] => nRLOalVq36k.jpg
    [1] => t1.jpg
    [2] => t2.jpg
)

прочитал статьи где написано что нужно циклом записывать данные. Попробовал так
if(!empty($_POST) && !empty($_FILES)){

$uploaddir = '/i/';
foreach ($_FILES['userfile']['name'] as $k=>$v){

if(($_FILES['userfile']['type'] == 'image/gif' || $_FILES['userfile']['type'] == 'image/jpeg' || $_FILES['userfile']['type'] == 'image/png') && ($_FILES['userfile']['size'] != 0 and $_FILES['userfile']['size']<=1024000))
{
    $ex = explode('.',$_FILES['userfile']['name']);
    $ex= end($ex);
    $apend=date('YmdHis').rand(100,1000).'.'.$ex;
    $uploadfile = "$uploaddir$apend";
    file_put_contents($_SERVER["DOCUMENT_ROOT"]."/_.txt","\n\r".__FILE__.":".__LINE__."\n\r".print_r($uploadfile,true));
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $_SERVER[DOCUMENT_ROOT].$uploadfile))
   {
        $c="INSERT INTO images (name) VALUES('$uploadfile') ";
        $q=$dbh->prepare($c);

        $q->execute();

    }       echo $uploadfile;
}
}
}

A: У вас множественная загрузка файлов, о чем говорит параметр multiple в инпуте.
if(($_FILES['userfile']['type'] == 'image/gif' || $_FILES['userfile']['type'] == 'image/jpeg' || $_FILES['userfile']['type'] == 'image/png') && ($_FILES['userfile']['size'] != 0 and $_FILES['userfile']['size']<=1024000))

Это условие не проходит проверку, так как все эти элементы - массивы значений, а не значения. Напишите
var_dump($_FILES['userfile']['type']);

сразу после проверки и поймете о чем я говорю.
Вам нужно подставить индекс обрабатываемого в данный момент файла (в Вашем случае $k)
if(($_FILES['userfile']['type']**[$k]** == 'image/gif' || //и так далее

а еще сюда
$ex = explode('.',$_FILES['userfile']['name']**[$k]**);

и сюда
if (move_uploaded_file($_FILES['userfile']['tmp_name']**[$k]**,  //и так далее

Не стал длинные строки целиком писать, чтоб лучше было видно, что пропустили в коде


text:
Q: Is flagging good for answers that don't add any value? I often see late answer to some post which already has decent number of votes which has accepted answer, and these new answers (mostly by new users) don't any any value and just eat the screen-space + the precious memory of SE hosting + the money + the maintenance cost + time of the user coming/reading the post in future (most important for me).
I thought flagging these for deletion should be good. But, I am not sure what should be the right course of action. What do the meta users have to say about these? Your views?

A: If you feel that an answer is not useful you can provide that feedback by voting on the post.  You can also comment if you would like.
You should not be flagging a post just because you feel that it's not a useful answer.

A: Maybe everybody agrees that answers that add nothing should be deleted. The problem however is with the "add nothing" bit. People differ about where the bar lies between something and nothing.
On the one hand there is this feature request that comes from a moderator on SO. The feature would be (in brief) to add a way to vote to delete an answer as a duplicate of an earlier one on the same question.
On the other hand, when I've flagged answers as duplicates of earlier ones on SO, I've rarely been able to get the desired results. Maybe I did not make enough of a case for it, or the moderator who handled the flag placed the bar between something and nothing somewhere else than I do, which is likely. The closest the duplicate answer is to be a cut-and-paste of an earlier answer with minor modifications (yes, some folks do this), the greater the chances of success. And there has to be a significant time difference between the time the answers were posted. Simple problems don't have very many significantly different solutions, combined with the Fastest Gun in the West phenomenon you get a bunch of similar answers posted in a short time span. This cannot be helped.
In the meantime, you can downvote, which is unlikely to do much in the grand scheme of things (even with a comment), as the mass of users (on SO at least) tends to upvote anything which is not untrue, irrespective of whether or not it is adding anything to the earlier answers, pertains to the question, etc.

A: Flagging is a bad idea if the answer:

*

*answers the question and

*isn't jibberish, spam or crap.

Just being 'low quality' (note: not 'very low quality' as in the definition of the second bullet), isn't a reason to flag.
It might be a reason for you to downvote. Also the late answer queue has some people in place to check if the quality is decent enough. I often see they also judge the answer on the quality relative to the other answers (whether this is good or not).
Also, privileged users can protect a question. This prevents it from attracting more low quality answers.

A: Stack Exchange is designed to deal with low-quality answers without moderator intervention. The screen space these answers eat up is at the bottom of the page. Downvote them to make sure they stay anchored there. There's just not enough moderator bandwidth in the world to deal with every answer that adds no value.


text:
Q: Django - Upload / Template I'm trying to display an image on my template but it's a little difficult.
I don't know how to get my images on my static folder. In this foder, there's an "Image" folder where's all my images.
Here's the code :
{% for document in documents %}

{% if document.actif %}

{% endif %}

{% endfor %}

I know the model and form are good, and I tested a normal src but with the template it's a little difficult.
Here is the model :
class Documents(models.Model):
docTypeId = models.ForeignKey('DocType', null=True)
entrepriseId = models.ForeignKey('Entreprise', null=True)
name = models.CharField(max_length=50)
description = models.CharField(max_length=250)
fileName = models.CharField(max_length=250)
actif = models.BooleanField()
url = models.CharField(max_length=250, null=True)

def docFileName(self):
    return "documents/" + str(self.entrepriseId.id) + "/" + str(self.id) + ".jpg"
docFileName = property(docFileName)

If you have some ideas, i'm open with it :)
Have a nice day :)

A: This line:

is going to throw an error because of the quotes around and within the static tag.
Try:


text:
Q: Redefining a value at index of recursive lazy array I'm having a <<loop>> error for trying to redefine a value on an already defined index.
Simplified example:
ghci > let axs = array (1,5) [(1,1),(2,2),(3,3),(4,4),(5,5),(1, 1 + axs!1)]
ghci > axs
array (1,5) [(1,^CInterrupted.

This will loop. I'm assuming that the lazy nature of Data.Array is what is causing that behaviour.
This, on the other hand, won't loop and will work as expected (redefines index 1).
ghci > array (1,5) [(1,1),(2,2),(3,3),(4,4),(5,5),(1,6)]
array (1,5) [(1,6),(2,2),(3,3),(4,4),(5,5)]

Is there any way to redefine an indexed value with recursion to self?
I'm assuming I need to force the evaluation of the wanted index to be able to "update" the value again using the previous one.
Is that possible or I shouldn't/can't use the array this way?

A: In a recursive definition, the meaning of the thing being defined on the right is its final value.  So
x = x + 1

will be an infinite loop.  In an array definition (in GHC), the value of an index is its last appearance, so
axs = array (1,5) [(1,1),(2,2),(3,3),(4,4),(5,5),(1, 1 + axs!1)]

is the same as
axs = array (1,5) [(2,2),(3,3),(4,4),(5,5),(1, 1 + axs!1)]

the important part of this is
axs' = array (1,1) [(1, 1 + axs!1)]

which is the same idea as
x = 1 + x

Note that "redefinition" in array definitions is not permitted by the Haskell standard at all, and should always loop or throw an exception.  GHC allows it, but that is not strictly is agreement with the standard.
Even in GHC the "redefinition" is not imperative.  You are not one by one setting the values in the array.  Rather, an array definition is a declarative specification for the entire array.
If you want an imperative approach to constructing arrays, use the st monad
This is not tested:
arr = runSTArray $ do
  retArr <- newArray (1,5) [(1,1),(2,2),(3,3),(4,4),(5,5)]
  curVal <- readArray retArr 1
  writeArray retArr 1 (curVal + 1)
  retArr


text:
Q: Add date and Time to Android calendar I am converting this String Mon, 11 Feb 2013 08:00:00 CST to date using the following code
Date date = null;
long starttime,endtime;
try {
    date = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:Ss z").parse(tit1);

} catch (java.text.ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

and adding this date to calendar using the below code
try{
    Calendar cal = Calendar.getInstance();
    starttime=date.getTime();
    endtime=date.getTime();
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime",starttime);
    intent.putExtra("allDay", true);
    intent.putExtra("rrule", "FREQ=YEARLY");
    intent.putExtra("endTime", endtime);
    intent.putExtra("title",tit);
}
catch(Exception e)
{
}

the event is adding like Mon, 11 Feb 2013.
I need to add the event look like the following
From: Mon, 11 Feb 2013 08:00AM
To:   Mon, 11 Feb 2013 08:30AM

how can I do it with the following String and Simple Date Format style.
P.S. :: starttime & endtime are long datatype

A: I think there is problem in getting date format.please check it and do as like following
if your are getting the data as follows Date = May 05, 2012, 07:10PM, then convert the date to be in number format a May to be 05 and pass the value in the following code.
Calendar beginCal = Calendar.getInstance();
beginCal.set(year, mnth, day, hrs, min);
startTime = beginCal.getTimeInMillis();

Calendar endCal = Calendar.getInstance();
endCal.set(year, mnth, day, hrs, min);
endTime = endCal.getTimeInMillis();

Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(Events.TITLE, summary);
intent.putExtra(Events.DESCRIPTION, summary);
intent.putExtra(Events.EVENT_LOCATION, "");
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginCal.getTimeInMillis());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endCal.getTimeInMillis());
intent.putExtra(Events.ALL_DAY, allDayFlag);
intent.putExtra(Events.STATUS, 1);
intent.putExtra(Events.VISIBLE, 0);
intent.putExtra(Events.HAS_ALARM, 1);
startActivity(intent);


text: Q: Uninstall a program and Install a new program in the same msi/setup project How can I uninstall a program using MSIEXE command line .exe and install a new program in the same setup/msi project? I don't want to use a .bat file and execute two separate .exe files.


text:
Q: How to make native-base Modal works well with KeyboardAvoildingView in Android? I try to add KeyboardAvoidingView to the Modal Component.
But when i call the keyboard up, the modal doesnt move and still be covered by keyboard.
This is my code : https://snack.expo.dev/@tikkhun/joyous-blueberries

A: After searching and asking. I get a way to work well: just use behavior: "position"
Here is My example Component:
/**
 * @file: 弹出框
 */
import React, { useRef, useEffect, useState } from 'react';
import { Center, Button, HStack, Input, KeyboardAvoidingView, Modal, Spacer, Text } from 'native-base';
import { useTranslation } from 'react-i18next';

export default function ModalContent({ isOpen, onClose, title, defaultValue, type = 'input', onSave }) {
  const { t } = useTranslation();
  const [value, setValue] = useState();
  const inputRef = useRef(null);
  useEffect(() => {
    // 这里的 setTimeout 是为了让键盘正常弹出
    setTimeout(() => {
      if (inputRef?.current) {
        inputRef.current.focus();
      }
    }, 10);
  });
  useEffect(() => {
    setValue(defaultValue);
    return () => {
      setValue('');
    };
  });

  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <KeyboardAvoidingView style={{ width: '100%' }} behavior="position">
        <Center>
          <Modal.Content style={{ width: '100%' }}>
            <Modal.Header>
              <HStack space="3" alignItems="center">
                <Text fontSize="md">{title}</Text>
                <Spacer />
                <Button
                  _text={{ fontSize: 'md' }}
                  variant="ghost"
                  onPress={() => {
                    onSave && onSave(value);
                  }}>
                  {t('settings.save')}
                </Button>
              </HStack>
            </Modal.Header>
            <Modal.Body>
              <Input size="2xl" ref={inputRef} defaultValue={value} onChangeText={v => setValue(v)} />
            </Modal.Body>
          </Modal.Content>
        </Center>
      </KeyboardAvoidingView>
    </Modal>
  );
}


text:
Q: Freemarker embed image on ftl I am trying to embed an image on a Freemarker ftl template to send as an email, I've based on this question Feemarker writing images to html, I did the exact same thing as this question said, but the email is being generated like this
What may be causing this error, and how to fix it?
My template looks like this
<img alt="My image" src="${imgAsBase64}" />

The image is a Chart, and I get the Base64 String, which I called imageBase64Str, via a Primefaces JavaScript function that generates the Base64 of the chart image, I pass it to the the bean and pass the parameter to the template like this
String encoded = imageBase64Str.split(",")[1];
byte[] decoded = Base64.decodeBase64(encoded);
String imgDataAsBase64 = new String(decoded);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
emailParams.put("imgAsBase64", imgAsBase64);

A: String encoded = imageBase64Str.split(",")[1]; is suspicious. Looks like you are changing the base 64 string generated in some different way. Is the image actually a png or it's in another format? I think that if you remove that split and just do emailParams.put("imgAsBase64", imageBase64Str); it may work.
However you need to consider that this solution won't work for many email clients. According to this link https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/ Base64 embedded images are not supported on a few major email clients, web and standalone, including Gmail and Outlook. Given that they are the most common email clients you don't want to deliver a solution that doesn't work on them or most of your users are gonna be unhappy.
IMO your best bet is to host the images in a server and use fully qualified URLs in your freemarker template.
An alternative is using the attachment and reference them in the html source as explained here: https://stackoverflow.com/a/36870709/2546299 but it require changes on the way the emails are sent (need to add the attachments) so it may not be suitable for your case.


text:
Q: Redis TimeoutException on VPN Whenever I try to run my app through VPN I get a TimeoutException on my call to IDatabase.StringGet (Timeout performing GET).  When directly connected to the network I have no problem.
I have confirmed there is no firewall issue because I can telnet to the Redis server on port 6379 even when connected through VPN.

A: You actually just can change localhost to 127.0.0.1 on your apps.