text:
Q: Mongodb not respecting unique partial index I have some records like:

{
  name: "Acme co."
  add4: "",
  nationalNumber: "+13412768376"
}, {
  name: "Acme Inc.",
  add4: "6345",
  nationalNumber: ""
}

And I'm attempting to insert them into collection, but only if they are unique. I'm checking for unique by looking for duplicate:

*

*nationalNumber (if field isn't empty or null)

*name + add4 (if both fields aren't empty or null)

I have this code in my nodeJs app:

 await db.collection('mergedcompany').createIndex(
      { nationalNumber: 1},
      { unique: true },
      { partialFilterExpression: {nationalNumber: {$exists: true}}}
      );

    await db.collection('mergedcompany').createIndex(
      { name: -1, add4: -1},
      { unique: true },
      { partialFilterExpression:{ name: {$exists: true}, add4: {$exists: true}}}
      );

And looping over records and inserting:

try {
  await db.collection('mergedcompany').insertOne(record);
} catch (e) {
  sails.log.error(e);
}

All records are getting inserted, even if there are duplicate fields and defined in the unique index.
If I remove the "partial" filter from the index, mongo then starts throwing errors like it should. But when I include the partial, no errors are thrown and all records are inserted, regardless if duplicate data.
What do I need to do to make this work?

A: Apart from the syntax errors, it should work:
db.getCollection('mergedcompany').createIndex(
   { nationalNumber: 1 },
   { unique: true, partialFilterExpression: { nationalNumber: { $exists: true } } }
);

db.getCollection('mergedcompany').createIndex(
   { name: -1, add4: -1 },
   { unique: true, partialFilterExpression: { name: { $exists: true }, add4: { $exists: true } } }
);

db.getCollection('mergedcompany').insertOne({ name: "Acme co.", add4: "", nationalNumber: "+13412768376" });
db.getCollection('mergedcompany').insertOne({ name: "Acme co.", add4: "", nationalNumber: "+13412768376" });
WriteError({
   "index": 0,
   "code": 11000,
   "errmsg": "E11000 duplicate key error collection: so.mergedcompany index: nationalNumber_1 dup key: { nationalNumber: \"+13412768376\" }",
   "op": {
      "_id": ObjectId("601d74357aec96fa0da88319"),
      "name": "Acme co.",
      "add4": "",
      "nationalNumber": "+13412768376"
   }
})

db.getCollection('mergedcompany').insertOne({ name: "Acme Inc.", add4: "6345", nationalNumber: "" });
db.getCollection('mergedcompany').insertOne({ name: "Acme Inc.", add4: "6345", nationalNumber: "" });
WriteError({
    "index" : 0,
    "code" : 11000,
    "errmsg" : "E11000 duplicate key error collection: so.mergedcompany index: nationalNumber_1 dup key: { nationalNumber: \"\" }",
    "op" : {
        "_id" : ObjectId("601d74647aec96fa0da8831b"),
        "name" : "Acme Inc.",
        "add4" : "6345",
        "nationalNumber" : ""
    }
})

Note, when you check for { nationalNumber: { $exists: true }} then nationalNumber: "" yields true. You must skip the field entirely.

A: This will work:
If test document isn't changed after first run an error will appear.
const mongoose = require("mongoose");

const schema = mongoose.Schema({
  name: {
    type: String,
    unique: true,
    required: true,
  },
  add4: {
    type: String,
    unique: true,
    required: true,
  },
  nationalNumber: {
    type: String,
    unique: true,
    required: true,
  },
});

const model = mongoose.model("unique", schema);

const testDocument = {
  name: "Acrhrme co.",
  add4: "th",
  nationalNumber: "+1341rr2h68376",
};

const insertFunc = async () => {
  try {
    await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });
    await model.create(testDocument);
  } catch (error) {
    console.error(error);
  }
};

insertFunc().catch(err => {
    console.error(err);
});


text:
Q: Is it possible to exclude some targets from Ant targets while executing the script? In ant if want to execute more than one target, we can do it like this,
ant target1 target2 target3

Other way could be, create target4 like
<target name="target4" depends="target1,target2,target3" />

but the problem is, one of my target definition is:
<target name="buildApp" depends="init,copy-all-requiredfiles-local,wait-to-merge,compile,createWAR,deployAll"/>

and if i want to execute buildApp then it will run all associated targets too, as obvious.
Is it possible to execute the buildApp target without executing deployAll target?

A: A possibility would be add a condition to your deployAll target like this.
<target name="depolyAll" unless="doNotDeploy">
...
</target>

Then when you want to run buildApp without deployAll on the commandline just do
ant -DdoNotDeploy=true buildAll

btw. note that unless just checks if the property is set. Not what the value is.
But this behaviour should be documented and is a little obscure.
I would consider explicitly creating a second build target e.g. buildAllWithoutDeploy which just misses the deploy target

A: Why not create another target for it?
<target name="buildAppNoDeploy" depends="init,copy-all-requiredfiles-local,wait-to-merge,compile,createWAR"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check for array index to avoid outofbounds exception I'm still very new to Java, so I have a feeling that I'm doing more than I need to here and would appreciate any advise as to whether there is a more proficient way to go about this.  Here is what I'm trying to do:

*

*Output the last value in the Arraylist.

*Intentionally insert an out of bounds index value with system.out (index (4) in this case)

*Bypass the incorrect value and provide the last valid Arraylist value (I hope this makes sense).
My program is running fine (I'm adding more later, so userInput will eventually be used), but I'd like to do this without using a try/catch/finally block (i.e. check the index length) if possible.  Thank you all in advance!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Ex02 {

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

    BufferedReader userInput = new BufferedReader(new InputStreamReader(
            System.in));

    try {
        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("Zero");
        myArr.add("One");
        myArr.add("Two");
        myArr.add("Three");
        System.out.println(myArr.get(4));

        System.out.print("This program is not currently setup to accept user input. The last       printed string in this array is: ");

    } catch (Exception e) {

       System.out.print("This program is not currently setup to accept user input.  The requested array index which has been programmed is out of range. \nThe last valid string in this array is: ");

            } finally {
        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("Zero");
        myArr.add("One");
        myArr.add("Two");
        myArr.add("Three");
        System.out.print(myArr.get(myArr.size() - 1));
    }
}

}

A: Check for array index to avoid outofbounds exception:
In a given ArrayList, you can always get the length of it. By doing a simple comparison, you can check the condition you want. I haven't gone through your code, below is what i was talking-
public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("stringA");
    list.add("stringB");
    list.add("stringC");

    int index = 20;
    if (isIndexOutOfBounds(list, index)) {
        System.out.println("Index is out of bounds. Last valid index is "+getLastValidIndex(list));
    }
}

private static boolean isIndexOutOfBounds(final List<String> list, int index) {
    return index < 0 || index >= list.size();
}

private static int getLastValidIndex(final List<String> list) {
    return list.size() - 1;
}


text:
Q: Join several Optional match querion My graph:
CREATE (s1:SOME {id:'s1'} )
CREATE (s2:SOME {id:'s2'} )
CREATE (a11:ANOTHER {id:'a11', tags:["tag1", "tag2"] } )
CREATE (a12:ANOTHER {id:'a12', tags:["tag2", "tag3"] } )

CREATE (a21:ANOTHER {id:'a21', tags:["tag3", "tag4"] } )
CREATE (a22:ANOTHER {id:'a22', tags:["tag4", "tag5"] } )

CREATE (s1)-[:CONTAINS ]->(a11),
(s1)-[:CONTAINS ]->(a12),
(s2)-[:CONTAINS ]->(a21),
(s2)-[:CONTAINS ]->(a22)

I have  ( generated )  query
match (s:SOME)

with s
OPTIONAL MATCH  (a1:ANOTHER)-[r:CONTAINS]-(s)
where 'tag2' in a1.tags

with s, a1
OPTIONAL MATCH  (a2:ANOTHER)-[r:CONTAINS]-(s)
where 'tag3' in a2.tags

WITH s, COLLECT(DISTINCT a1, a2) AS aa

return s.id, aa

so there is a lot of sections  like
with s, a1
OPTIONAL MATCH  (a2:ANOTHER)-[r:CONTAINS]-(s)
where 'tag3' in a2.tags
generated dynamically
I have problem with clause
WITH s, COLLECT(DISTINCT a1, a2) AS aa
I need make somehow flatten  this multiple results in single array and distinct it to make it unique

A: You probably don't need to generate any Cypher code for your use case.
The following query takes a $tags parameter -- which should be a list of the tag values you are interested in -- and uses aggregation to return each unique id and the corresponding list of distinct a nodes. The ANY function is used to test if any tag in $tags is in a.tags.
MATCH (s:SOME)
OPTIONAL MATCH (a:ANOTHER)-[:CONTAINS]-(s)
WHERE ANY(t IN $tags WHERE t in a.tags)
RETURN s.id AS id, COLLECT(DISTINCT a) AS as;

Using this query, you just need to generate the $tags parameter value.


text:
Q: How to resolve Chef TypeError: "no implicit conversion of String into Integer" using node.normal? I'm currently testing a new chef cookbook for Zabbix monitoring, and had my first successful 'chef' using this cookbook.  I was, however, forced to make a change to one of the attributes, because it will change from server to server.  I decided to use a data bag, and I'm having difficulty retrieving and assigning the attribute.
Here are the contents of the data bag:
    [user@workstation chef-repo]# knife data bag show zabbix_psk psk_syslog
    WARNING: Unencrypted data bag detected, ignoring any provided secret options.
    id:  psk_syslog
    psk: PSK 060

I did not assign the attribute in the attributes file, but rather in the recipe:
default.rb
keyvalue = data_bag('zabbix_psk')
node.normal['zabbix_agentd']['psk_number'] = keyvalue['psk_syslog']['psk']

And then I assign it in a template:
TLSPSKIdentity=<%= node['zabbix_agentd']['psk_number'] %>

When I attempt to Chef, I receive the following error and dump:
TypeError
---------
no implicit conversion of String into Integer

Cookbook Trace:
---------------
  /var/chef/cache/cookbooks/zabbix_agentd/recipes/default.rb:28:in `[]'
  /var/chef/cache/cookbooks/zabbix_agentd/recipes/default.rb:28:in `from_file'

Relevant File Content:
----------------------
/var/chef/cache/cookbooks/zabbix_agentd/recipes/default.rb:

 21:  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 22:  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 23:  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 24:  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 25:  # THE SOFTWARE.
 26:
 27:  keyvalue = data_bag('zabbix_psk')
 28>> node.normal['zabbix_agentd']['psk_number'] = keyvalue['psk_syslog']['psk']
 29:
 30:  case node['platform']
 31:  when 'centos', 'redhat'
 32:    include_recipe 'zabbix_agentd::yum_repo'
 33:  end
 34:
 35:  package 'zabbix-agent'
 36:
 37:  directory node['zabbix_agentd']['log_dir'] do

System Info:
------------
chef_version=13.6.0
platform=centos
platform_version=7.4.1708
ruby=ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-linux]
program_name=chef-client worker: ppid=11127;start=14:18:48;
executable=/opt/chef/bin/chef-client

Running handlers:
[2017-12-14T14:18:56-06:00] ERROR: Running exception handlers
Running handlers complete
[2017-12-14T14:18:56-06:00] ERROR: Exception handlers complete
Chef Client failed. 0 resources updated in 07 seconds
[2017-12-14T14:18:56-06:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
[2017-12-14T14:18:56-06:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2017-12-14T14:18:56-06:00] ERROR: no implicit conversion of String into Integer
[2017-12-14T14:18:56-06:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

I'm having difficulty understanding what's wrong with the node.normal assignment in default.rb.  I'm new to both Chef and Ruby, so I really appreciate the help.  I should also note that I could not use the method get_databag_item; aparently that method did not exist?

A: data_bag('zabbix_psk') returns an array of the names of the items in the bag, not the data in all the items. You want data_bag_item('zabbix_psk', 'psk_syslog') instead, and then adjust your usage of the value returned.


text:
Q: I want to use two JSON requests to finish a vb.net object I have one Vb.net object (below). It requires two JSON requests to complete the object. One request gives title and key while the other request gives me freeToPlay. How can I use both requests to create one object?
Public Class LeagueChampion
    Inherits LeagueObject
    'Public Property key As String
    Public Property title As String
    Public Property group As String
    Public Property tags As String()
    Public Property enemytips As String()
    Public Property allytips As String()
    Public Property blurb As String
    Public Property rankedPlayEnabled As Boolean
    Public Property botMmEnabled As Boolean
    Public Property botEnabled As Boolean
    Public Property active As Boolean
    Public Property freeToPlay As Boolean
End Class

  league_container = JsonConvert.DeserializeObject(Of LeagueChampionContainer)(rrm.returnFreeToPlayChampions("na"))
  league_container = JsonConvert.DeserializeObject(Of LeagueChampionContainer)(rrm.returnLeagueChampions("na"))

A: I'd recommend you to use JavaScriptSerializer over DataContractJsonSerializer. The reasons are:

*

*JavaScriptSerializer is faster over DataContractJsonSerializer.

*DataContractJsonSerializer requires more code than JavaScriptSerializer for a simple serialization.


text:
Q: Evaluate the limit $\lim_{x \to 0}\frac{2+\tan \left(e^{x}-\cos x\right)-e^{x}-\cosh x}{x(\sqrt{1+2 x}-\sqrt[3]{1+3 x})}$ Evaluate the limit $$L=\lim _{x \to 0}\frac{2+\tan \left(e^{x}-\cos x\right)-e^{x}-\cos h x}{x(\sqrt{1+2 x}-\sqrt[3]{1+3 x})}$$
By generalized binomial expansion we have
$$\sqrt{1+2 x}-\sqrt[3]{1+3 x}=\left[1+\frac{1}{2}(2 x)+\frac{\frac{1}{2}\left(\frac{1}{2}-1\right)}{2 !}(2 x)^{2}+\cdots\right]-\left[1+\frac{1}{3}(3 x)+\frac{\frac{1}{3}\left(\frac{1}{3}-1\right)}{2}(3 x)^{2}+\cdots\right]$$
$\implies$
$$\sqrt{1+2x}-\sqrt[3]{1+3x}=\frac{x^2}{2}+O(x^3)$$
$\implies$
$$L=\lim _{x \rightarrow 0} \frac{2+\tan \left(e^{x}-\cos x\right)-e^{x}-\cos h x}{x^{3}\left(\frac{\frac{x^{2}}{2}+O\left(x^{3}\right)}{x^{2}}\right)}$$
$\implies$
$$L=2 \lim _{x \rightarrow 0} \frac{2+\tan \left(e^{x}-\cos x\right)-e^{x}-\left(\frac{e^{x}+e^{-x}}{2}\right)}{x^{3}} \to (1)$$
We have $$e^{x}=1+x+\frac{1}{2} x^{2}+\frac{1}{6} x^{3}+\frac{1}{24} x^{4}+\ldots$$ and
$$\cos x=1-\frac{1}{2} x^{2}+\frac{1}{24} x^{4}-\frac{1}{720} x^{6}+.$$
Thus we have
$$e^x-\cos x=x+x^2+\frac{x^3}{6}+O(x^4)$$
Now we have the Maclaurin's series expansion of $\tan x$ as:
$$\tan x=x+\frac{1}{3} x^{3}+\frac{2}{15} x^{5}+...$$
So we get
$$\tan(e^x-\cos x)=x+x^2+\frac{x^3}{6}+\frac{1}{3}x^3+O(x^4) \to (2)$$
Also we have
$$e^{x}+\cosh x=e^{x}+\frac{e^{x}+e^{-x}}{2}$$
$$e^x+\cos hx=\begin{aligned}
\frac{3}{2}(1+x+&\left.\frac{x^{2}}{2!}+\frac{x^{3}}{3 !}+..\right)
+\frac{1}{2}\left(1-\frac{x}{1 !}+\frac{x^{2}}{2!}-\frac{x^{3}}{3 !}+\cdots^{}\right)
\end{aligned}$$
$\implies$
$$e^x+\cos hx=2+x+x^2+\frac{x^3}{6}+O(x^4) \to (3)$$
Using $(2),(3)$ in $(1)$ we get
$$L=\frac{2}{3}$$
Is there any alternate way?

A: There is one right way to do this limit:
$$ \lim_{x \to 0} \frac{
\frac{1- \cosh x}{x}+  \left[ \frac{\tan(e^x - \cos x)}{x} -\frac{1-e^x}{x} \right]}{
\sqrt{1 +2x}- (1+3x)^{\frac13}}=\lim_{x \to 0} \frac{\left( - \frac{x}{2!} - \frac{x^3}{4!}+O(x^5)\right)+ \left[ \frac{\left(2e^x -1- \cos x  \right)+\frac{(e^x - \cos x)^3}{3}}{x}.. \right]}{\left[ 2-1\right] \frac{x^2}{2!} +O(x^3)}$$
Note that:
$$ (2e^x - 1 - \cos x)= \frac{x^2}{2} + \frac{x^3}{3} + O(x^4)$$:
Hence,
$$ \lim_{x \to 0}\frac{ \left( - \frac{x}{2!} - \frac{x^3}{4!}+O(x^5) \right)+ \left[ \frac{\frac{x^2}{2} + \frac{x^3}{3} + O(x^4) }{x}.\right]}{ \frac{x^2}{2!} +O(x^3)} $$
$$ \lim_{x \to 0}\frac{\frac{x^2}{3} + O(x^3)}{\frac{x^2}{2!}+O(x^3)}= \frac23$$
Idea: I first rearranged the expression to make them all look like derivatives, for the denominator I tried to find the first non zero term of in it's expansion and then expanded numerator in that.
It is still a mess, but it reduces solving the question in an algorithim.

*Arrange the expressions to look like known limits on numerator and denominator

*Find deg denominator

*Expand numerator till deg denominator

*Careful algebra

*Take the limit


text:
Q: AdMob Notification About Google Mobile Ads SDK Version. Need Explanation As you already know that

"Beginning Jan 23, 2018, Google Mobile Ads SDK versions older than
  7.0.0 for Android and 7.0.0 for iOS will no longer be supported".

Above statement mean this ? ===>
"compile 'com.google.android.gms:play-services-ads:10.0.1'"

I am confuse that I am using correct Google Mobile Ads SDK Version or not? OR I need to check something else?

A: No need to do anything, you already using 10.0.1 version which is greater then 7.0.0, however you can update to current latest version which is 11.8.0.

Google Mobile Ads SDK offered for Android through Google Play services which is available from the Google maven repository.

Google Mobile Ads          com.google.android.gms:play-services-ads:11.8.0

Google Mobile Ads API dependency injection
apply plugin: 'com.android.application'
...

dependencies {

    implementation 'com.google.android.gms:play-services-ads:11.8.0'
}


text:
Q: Error with connection with adodb in php Hello a trying connect to database and i cant do this , i run the program with laragon and show this errors.
the database connection is with adodb with mysql.
Thanks for help.

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; ADODB_Cache_File has a deprecated constructor in C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\adodb.inc.php on line 233

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; ADOConnection has a deprecated constructor in C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\adodb.inc.php on line 327

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; ADORecordSet has a deprecated constructor in C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\adodb.inc.php on line 2854

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; ADORecordSet_array has a deprecated constructor in C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\adodb.inc.php on line 3872

Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\drivers\adodb-mysql.inc.php:383 Stack trace: #0 C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\adodb.inc.php(588): ADODB_mysql->_pconnect('localhost', 'root', 'black44265769', 'cal24412_dte') #1 C:\laragon\www\FacturaElectronicaAlumgo\sistema\conexion.php(3): ADOConnection->PConnect('localhost', 'root', 'black44265769', 'cal24412_dte') #2 C:\laragon\www\FacturaElectronicaAlumgo\sistema\validar.php(8): include('C:\\laragon\\www\\...') #3 {main} thrown in C:\laragon\www\FacturaElectronicaAlumgo\sistema\adodb5\drivers\adodb-mysql.inc.php on line 383

A: What PHP version? I'm assuming 7.x here (possibly) due to the 'deprecated' messages and the last 'fatal' error.
It's a two part matter...

*

*The deprecated:
PHP has made a change to use __construct()
(two leading underscores) as the constructor instead of having the same name as the class itself. See the PHP 4 style constructors section (first section on the page) for more information.
For example: In the file to ADOConnection has a deprecated
constructor... the constructor likely looks like this:
ADOConnection( ... ); // constructors with or without parameters

...but all of those can be replaced with:
__construct( ... );

You can make that change locally to resolve the deprecated messages.

*The fatal error:
With PHP 7.x, the mysql_* based functions are
removed. See this API info.


text:
Q: JS HTML CSS: how to make a function dynamically repeat with different variables each time while not repeating the same variables inside de function Intertwining Functions
I've been trying to make functions different but both have have the same original function.
Here are my selectors:
const popControl = document.getElementById("pop");
const popHeader = document.getElementById("header");
const popButton = document.getElementById("close");
const popTitle = document.getElementById("title");
const popBody = document.getElementById("body");

const popControl2 = document.getElementById("pop2");
const popHeader2 = document.getElementById("header2");
const popButton2 = document.getElementById("close2");
const popTitle2 = document.getElementById("title2");
const popBody2 = document.getElementById("body2");`

With all my id's selected, I create my first function, called verifyPosition:
function verifyPosition(circleLeftPosition, circleRightPosition, moveBy) {
   console.log(circleLeftPosition, circleRightPosition);
   if (circleLeftPosition == "550px" && circleRightPosition == "75px") {
      popButton.addEventListener("click", closePosition);
      openPosition();
   }
}

Now, I must create the other, malfunctioning func, verifyPosition2:
function verifyPosition2(circleLeftPosition, circleRightPosition, moveBy) {
       console.log(circleLeftPosition, circleRightPosition);
       if (circleLeftPosition == "550px" && circleRightPosition == "75px") {
          popButton2.addEventListener("click", closePosition2);
          openPosition2();
       }
    }

For some reason, my verifyPosition2 does not work, and it does not matter what you put in it.
This brings me to my final questions:

*

*Why is it not working?

*And how can I make it work?

Thanks and thanks all!

Hint: [!ch.edit] tag means I have edited this question.

A: You may try the below approach
function verifyPosition(circleLeftPosition, circleRightPosition, moveBy, selector_extension) {
    if (circleLeftPosition == "550px" && circleRightPosition == "75px") {
        const popButton = document.getElementById("close" + selector_extension);
        // Checkout the below code, if verifyPosition is called multiple times on same element, there is chance of setting multiple click events on popButton
        popButton.addEventListener("click", function (e) { return closePosition(e, selector_extension); });
        openPosition(selector_extension);
    }
}
function closePosition(e, selector_extension) {
    // access the required elements using `selector_extension`
}
function openPosition(selector_extension) {
    // access the required elements using `selector_extension`
}


text:
Q: Counting dimension of hypersurfaces in $\mathbb{P}^3$ containing three disjoint lines Assume $k$ is algebraically closed field of char zero.
Let $l_1,l_2,l_3$ be three disjoint lines in $\mathbb{P}^3_k $.
The dimension of the $k$-vector $\operatorname{Homog}_2
k[x_0, x_1, x_2, x_3]$ of degree $2$ homogeneous polynomials in
$4$ variables is $10$ by usual Stars and Bars trick. We can associate to every such homogeneuos
polynomial $P_2(x)$ of degree $2$ a hypersurface $H_{P_2} \subset
\mathbb{P}^3_k $ which equals on each affine chart $D(L)$ with linear polynomial $L= \sum a_i x_i$ the vanishing set
of points of the obtained polynomial after localization in $L$.
Question: Is there a combinatorical argument (in spirit of stars and bars trick) why
the subvector space of $\operatorname{Homog}_2
k[x_0, x_1, x_2, x_3]$ consisting of all homog polynomials of degree $2$ which have
associated hyperplanes containing all three disjoint lines
$l_1,l_2,l_3$ is non zero.
Can it be derived more cenceptionally?
Say we have an arbitrary point $p \in \mathbb{P}^3_k $ and a
line $l \subset \mathbb{P}^3_k $. What is the dimension of
subspace of $\operatorname{Homog}_2
k[x_0, x_1, x_2, x_3]$ which have associated hyperplanes
containing point $p$? Or the line $l$? Or both? If we know it how
to approach combinatorically this problem we can also ask the
natural question about the dimension of subspace of homog polynomials
which have hyperplanes contain two oder more points, lines
or more dimensional linear subspaces of $\mathbb{P}^3$?
Similary can such combinatorial argument be generalized to say $\mathbb{P}^n $, $\operatorname{Homog}_m
k[x_0, x_1, ..., x_n]$ with $m \le n$ and one asks what is the dimension of $k$-subspace of polynomials which have associated hyperplanes all containing certain linear subspace $L_1 \subset \mathbb{P}^n $ or some subspaces $L_1,..., L_r \subset \mathbb{P}^n $ simultaneously?

A: This is a beautiful subject that gets hard very quickly. To answer your initial question: notice that if we fix a line $\ell \subset \mathbb P^3$, it meets every hyperplane; the intersection is either a point, or the entire line (obviously this latter case is when the line lies in the hyperplane). On the other hand, if we fix a point $p \in \mathbb P^3$, there is a codimension $1$ subspace of hyperplanes which contain $p$ (in the Grassmannian/dual projective space $\mathbb P^{3\vee} = \mathbb G(2,3) = G(2,4)$ of hyperplanes in $\mathbb P^3$). Since a different point $q$ determines a different codimension $1$ subspace, their intersection has codimension $2$. A third point results in a codimension $3$ linear space, which in $\mathbb P^3$ is a point: in other words, $3$ general points determine a $2$-plane, which you've known since high school.
The space of quadrics containing a given line $L$ can be computed by supposing that we have homogeneous coordinates $(W:X:Y:Z)$ on $\mathbb P^3$ such that $L$ is $W=X=0$. Then the equation for such a quadric has the form $Q = W\cdot L_1(W,X,Y,Z) + X \cdot L_2(W,X,Y,Z)$ where $L_1,L_2$ are linear forms. The (projective) space of linear forms is $3$-dimensional, so overall you have a $6$-dimensional space of quadrics containing $L$. This has codimension $3$ in the $9$-dimensional projective space of quadrics. Choosing two other general lines, you get two more codimension $3$ subspaces, so the intersection is codimension $9$ (codim. is additive over intersections of generic subspaces) a.k.a. dimension $0$, hence we get not just non-emptiness of the space of quadrics containing the three lines, but in fact that the quadric is unique.


text:
Q: How can i solve this errors in python django? Hi im very novice at python django.
This is my django views.py codes
def post_list(request):
request.session['lat'] = request.POST['user_lat']
request.session['lon'] = request.POST['user_lon']
userpoint = GEOSGeometry('POINT('lat' 'lon')', srid=4326)
list_total = list_1
i=1
while i:
    list_i = Post.objects.filter(point_distance__lte = userpoint, D(km=i)
    list_total = 'list_total' + ',' + 'list_i')
    result_list = list(chain(list_total))
    if len(result_list) >= 50 :
        break

template = loader.get_template('blog/index.html')
context = {
    'post_list': post_list,
}

return HttpResponse(template.render(context, request))

First of all, I want make list to using request.session[]=request.POST[] to make coordinates and this coordinates will be used on my pointfield at 'model.py' is it possible? or is it has any problems?
And Second, in terminal(ubuntu16.04), i used python3 manage.py makemigrations command, it gave me messages as follows,
from codes like this,
request.session['lat'] = request.POST['user_lat']
request.session['lon'] = request.POST['user_lon']
userpoint = GEOSGeometry('POINT('lat' 'lon')', srid=4326)

error occured like this->
userpoint = GEOSGeometry('POINT('lat' 'lon')', srid=4326)
                                  ^
                               SyntaxError: invalid syntax

from code like this ,
list_i = Post.objects.filter(point_distance__lte = userpoint, D(km='i'))
                                                                                ^

SyntaxError: positional argument follows keyword argument
this SyntaxError occoured.
Last, from this code,
while i:
    list_i = Post.objects.filter(point_distance__lte = userpoint, D(km=i))
    list_total = 'list_total' + ',' + 'list_i')
    result_list = list(chain(list_total))
    if len(result_list) >= 50 :
        break

-> This SyntaxError occoured.
list_total = list_total + ',' + 'list_i'
         ^

SyntaxError: invalid syntax
How can i solve this problems?
while i:
    list_i = Post.objects.filter(point_distance__lte = userpoint, D(km=i))
    list_total = 'list_total' + ',' + 'list_i')
    result_list = list(chain(list_total))
    if len(result_list) >= 50 :
        break

ps. I want make my own result_list using list(chain()) function, but i wonder it is valid.
itertools - python doc : https://docs.python.org/3.3/library/itertools.html
i was according to GEOdjango codes :
https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#distance-lookups
Im using python3 (maybe 3.5) , django 1.9
thanks for reading my questions.

A: You can not instantiate a GEOSGeometry object with that mis-formed string. Use
userpoint = GEOSGeometry('POINT('+ latvariable + ' ' + lonvariable +')', srid=4326)

A: You've missed the closing backet at line:
list_i = Post.objects.filter(point_distance__lte = userpoint, D(km=i)


text:
Q: WSO2 DSS : Rest call to database with null values I'm trying to call a service in the DSS with this configuration :
<query id="getAllPerformancesQuery" useConfig="lta_catalogue">
    <sql>select idperformance, name, description from performance</sql>
    <result element="performances" rowName="performance">
        <element column="idperformance" name="idperformance" xsdType="integer"/>
        <element column="name" name="name" xsdType="string"/>
        <element column="description" name="description" xsdType="string"/>
    </result>
</query>
<resource method="GET" path="performances">
    <call-query href="getAllPerformancesQuery"/>
</resource>

With a soap call the dss responds well :
<performances xmlns="com.lta.catalog.CatalogDSS">
    <performance>
        <idperformance>1</idperformance>
        <name>Introduction</name>
        <description xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    </performance>
</performances>

But with a rest call, the null value in the column description respond :
{"Fault":{"faultcode":"soapenv:Server","faultstring":"Error while writing to the output stream using JsonWriter","detail":""}}

with this exception in the log :
Caused by: java.lang.IllegalStateException: Dangling name: description
    at com.google.gson.stream.JsonWriter.close(JsonWriter.java:302)
    at com.google.gson.stream.JsonWriter.endObject(JsonWriter.java:277)
    at org.apache.axis2.json.gson.GsonXMLStreamWriter.writeEndElement(GsonXMLStreamWriter.java:394)
    at org.wso2.carbon.dataservices.core.engine.XMLWriterHelper.endElement(XMLWriterHelper.java:110)
    at org.wso2.carbon.dataservices.core.description.query.Query.writeResultEntry(Query.java:400)
    at org.wso2.carbon.dataservices.core.description.query.SQLQuery.processNormalQuery(SQLQuery.java:857)
    ... 54 more

Any idea ?

A: Editing the respository/conf/axis2/axis2.xml and changing the right messagebuilder and formatter
    <messageFormatter contentType="application/json"
                  class="org.apache.axis2.json.JSONMessageFormatter"/>
<!--messageFormatter contentType="application/json"
                          class="org.apache.axis2.json.gson.JsonFormatter" /-->

<messageBuilder contentType="application/json"
                class="org.apache.axis2.json.JSONOMBuilder"/>
<!--messageBuilder contentType="application/json"
                        class="org.apache.axis2.json.gson.JsonBuilder" /-->

A: This issue is fixed in the DSS 3.2.2 release. The related JIRA can be found from here


text:
Q: POST request with the `request` library in Python so that the body has the required format I'm a noob in http requests.
I need to perform POST request whose body should have the following format: list[id1]=value1&list[id2]=value2&...
 with the request library in Python.
I've already tried different ways to form data, for example like this:
import requests

data = {'list': {'1': '2', '3':'4'}}
r = requests.post(url=URL, data=data)

with result:
> r.request.body
list=1&list=3

How do I get list[1]=2&list[3]=4?

A: What you doing here is sending the data in dict format so this is the result you get for sending that in post request (the dict and its keys)
Try importing the json library and send that as json, e.g:
import requests
import json

data = json.dumps({'list': {'1': '2', '3':'4'}})
r = requests.post(url=URL, data=data)

result:
r.request.body
'{"list": {"1": "2", "3": "4"}}'

After that you can parse the json sent received on that post call and get the required keys and values.


text:
Q: Filter rows based on a threshold by grouping ID column I have a data frame that I got from
ID <- c("A","A","A","B","B","B","C","C","C")
Type <- c(45,46,47,45,46,47,45,46,47)
Point_A <- c(10,15,20,8,9,10,35,33,39)
df <- data.frame(ID,Type,Point_A)

    ID  Type    Point_A
1   A   45        10
2   A   46        15
3   A   47        20
4   B   45        8
5   B   46        9
6   B   47        10
7   C   45        35
8   C   46        33
9   C   47        39

I want to calculate the median of the Point_A column grouping by ID and then remove the rows based on a threshold.
For example, lets say my threshold is 11. I want to remove the rows grouped by ID having median less than the threshold and so the desired output would be
    ID  Type    Point_A
1   A   45        10
2   A   46        15
3   A   47        20
4   C   45        35
5   C   46        33
6   C   47        39

While I am able to calculate the medians but I am not knowing how to remove the rows.
func <- function(x) (median(x,na.rm=TRUE))
df1 <- df %>%
  group_by(ID) %>%
  mutate_each(funs(.=func(.)),Point_A)
  summarise(Point_A = f(Point_A))

Kindly let me know how to go about doing this.


text:
Q: onclick для div в методе класса js Здравствуйте, прошу помощи, объяснений, примеров..) Пишу слайдер своими силами для сайта (намеренно не использую библиотеки) на чистом js по возможности универсальный.
Решил сделать прототип класса для слайдера, их несколько на странице, вроде бы все нормально работает, но не могу повесить (или понять почему не работает) событие onclick на div при котором будет отрабатываться метод экземпляра класса - scrollLeft(arrg). Этот же метод используется и в другом методе - enableAutoScroll(), который работает! Должно быть дело в оформлении кода.
В общем разметка такая:

        // Слайдер

      // Адаптива

                    // Контент

        // Кнопка - влево

                         // Пикчи
            // image
            //     ...

       // Кнопка - вправо

Класс и проблемный метод setButtonsEvent:
Slider = function(id_name) {
    this.id_name = id_name;
    this.auto_scroll = 0;
    this.offset = 0;
    this.timeoutId = undefined;
    this.number_of_childes = this.getSlidesLine().children.length;
    this.getSlidesLine().style.left = this.offset + "%";
    this.setButtonsEvent();
}

Slider.prototype.setButtonsEvent = function() {
    this.getLeftButton().addEventListener('click', this.scrollLeft(3));
    //    Property 'handleEvent' is not callable.
    this.getRightButton().onclick = this.scrollRight();
    //    Не работает
    //    Пробовал просто "this.scrollRight;" - тогда при загрузке страницы просто выполняется эта функция (прокручивает слайдер один раз) и по нажатию также ничего не происходит. Но при этом сообщает, что "this.getSlidesLine is not a function"
    return this;
}

В классе присутствуют методы для получения объектов, типа:
Slider.prototype.getSlidesLine = function() {
    return document.querySelector("#" + this.id_name + " > .relation_content > .slides_line");
};

Slider.prototype.getLeftButton = function() {
    return document.querySelector("#" + this.id_name + " > .relation_content > .slider_btn.slider_left");
};

Slider.prototype.getRightButton = function() {
    return document.querySelector("#" + this.id_name + " > .relation_content > .slider_btn.slider_right");
};

ну и сам scrollLeft:
Slider.prototype.scrollLeft = function(divider = 3) {
    if(Math.abs(this.offset) / 100 >= this.number_of_childes / divider - 1) this.offset = 0;
    else this.offset -= 100;
    this.getSlidesLine().style.left = this.offset + "%";
    return this;
};

Так же буду рад замечаниям по поводу оформления строк кода.


text:
Q: HTTP Headers - Cache Question I am making a a request to an image and the response headers that I get back are:
Accept-Ranges:bytes
Content-Length:4499
Content-Type:image/png
Date:Tue, 24 May 2011 20:09:39 GMT
ETag:"0cfe867f5b8cb1:0"
Last-Modified:Thu, 20 Jan 2011 22:57:26 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET

Note the absence of the Cache-Control header.
On subsequent requests on Chrome, Chrome knows to go to the cache to retrieve the image.  How does it know to use the cache?  I was under the impression that I would have to tell it with the Cache-Control header.

A: You have both an ETag and a Last-Modified header. It probably uses those. But for that to happen, it still needs to make a request with If-None-Match or If-Modified-Since respectively.

A: To set the Cache-Control You have to specify it yourself. You can either do it in web.config , IIS Manager for selected folders (static, images ...) or set it in code. The HTTP 1.1 standard recommends one year in future as the maximum expiration time.
Setting expiration date one year in future is considered good practice for all static content in your site. Not having it in headers results in If-Modified-Since requests which can take longer then first time requests for small static files. In these calls ETag header is used.
When You have Cache-Control: max-age=315360000 basic HTTP responses will outnumber If-Modified-Since> calls and because of that it is good to remove ETag header and result in smaller static file response headers. IIS doesn't have setting for that so You have to do response.Headers.Remove("ETag"); in OnPreServerRequestHeaders()
And if You want to optimize Your headers further You can remove X-Powered-By:ASP.NET in IIS settings and X-Aspnet-Version header (altough I don't see in Your response) in web.config - enableVersionHeader="false" in system.web/httpRuntime element.
For more tips I suggest great book - http://www.amazon.com/Ultra-Fast-ASP-NET-Build-Ultra-Scalable-Server/dp/1430223839


text:
Q: :focus styling on custom radio input I have a custom radio input style that is implemented more or less like this:
<input type="radio" id="testradio" class="visuallyhidden custom-radio">
...

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.
I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.
Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?
Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.
http://jsfiddle.net/7Ltcks3n/1/

A: I believe this is what you are looking for, my friend. Ability to mimic default browser outlines. You should be able to use the below technique within your code to get the effect.
Demo code below, read more at source article: https://ghinda.net/article/mimic-native-focus-css/
.unreal-focus {
  outline-width: 2px;
  outline-style: solid;
  outline-color: Highlight;
}

/* WebKit gets its native focus styles.
 */
@media (-webkit-min-device-pixel-ratio:0) {
  .unreal-focus {
    outline-color: -webkit-focus-ring-color;
    outline-style: auto;
  }
}

A: The issue is that apparently Blink browsers maintain focus on radio elements after they are clicked, but Firefox and Safari don't.
As a workaround, you could add a class to the document on mousedown and touchstart that hides your added ring, and remove it on keydown.
Working example:

var className = 'focus-radio-hide-ring';
var add = function() {
    document.documentElement.classList.add(className);
};
var remove = function() {
    document.documentElement.classList.remove(className);
};
window.addEventListener('mousedown', add, true);
window.addEventListener('touchstart', add, true);
window.addEventListener('keydown', remove, true);
.custom-radio {
 position: absolute;
 opacity: 0;
}
.custom-radio + label {
 cursor: pointer;
}
.custom-radio + label:before {
 content: "";
 display: inline-block;
 vertical-align: middle;
 width: 0.75em;
 height: 0.75em;
 margin-right: 0.25em;
 background: #EEEEEE;
 border: 1px solid #AAAAAA;
 border-radius: 50%;
}
.custom-radio:checked + label:before {
 background: #6666FF;
}

/* Add styles here: */
.custom-radio:focus + label:before {
 box-shadow: 0 0 4px 1px rgba(0, 0, 0, 1);
}
/* Add disable them again here: */
.focus-radio-hide-ring .custom-radio:focus + label:before {
 box-shadow: none;
}

<input placeholder="Tab from here">

<input id="testradio" type="radio" class="custom-radio">
Example

A: I have Faced This Problem so long here i got the solution
https://jsfiddle.net/hahkarthick/nhorqnvt/3/

input:focus, input:hover{
    outline: 2px auto rgb(229, 151, 0);
    outline-offset: -2px;
 }
<input id="inp" type=radio>radio1
<input type=radio>radio2
<input type=radio>radio3
<input type=radio>radio4
<input type=radio>radio5

input:focus, input:hover{
outline: 2px auto rgb(229, 151, 0);
outline-offset: -2px;

}

A: I put together the snippet below based on your original code, not the fiddle example you provided. From what I gather, you are trying to replace the default radio button with your own styled element (label:before).
Since it wasn't specified how the default radios are hidden, I just used opacity: 0 and adjusted the position of the label element to cover it. The same effect can be achieved by moving the radio off the screen: position: absolute; top: -999; left -999; (or something similar).
I tried using display: none and vibility: hidden on the radios, but this is a problem because apparently the focus action isn't triggered when they aren't visible.
I also gave the label:before element some styling just so that it shows up.
To address your issue:
.custom-radio:focus + label:before {
  outline: 1px solid black;
  outline: 1px auto -webkit-focus-ring-color;
}

The outline:0 1px solid black; gives a default outline when the label is clicked. This works fine for FF and IE, but for Chrome, you need to change the color to -webkit-focus-ring-color because it uses a blue color for the radio outline.

.visuallyhidden {
  opacity: 0;
}
.custom-radio + label {
  position: relative;
  left: -25px;
  margin-right: -15px;
}
.custom-radio + label:before {
  content: "X";
  margin: 5px;
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
  outline: 1px auto -webkit-focus-ring-color;
}
<input type="radio" name="testradio" id="testradio1" class="visuallyhidden custom-radio">
radio 1
<input type="radio" name="testradio" id="testradio2" class="visuallyhidden custom-radio">
radio 2
<input type="radio" name="testradio" id="testradio3" class="visuallyhidden custom-radio">
radio 3

A: You can achieve this behavior through scripting. First you need bind keypress event to radio and add the outline style in that handler whenever the radio gets focused or active(by means of adding your custom-radio class to active input). so that you can omit the outline style on mouse click.

A: This will not fix your issue at the moment, but there is actually a selector coming which does exactly what you need: :focusring (https://github.com/w3c/csswg-drafts/pull/709). Right now it only works in Firefox, but should be coming to other browsers as well.
You could use JS like sumankumarg suggests, but you can also use the border of the fake input to show focus state like so:
http://jsbin.com/rofawiginu/edit?html,css,output

A: I'm not sure if this is possible in your set up, but a wrapper div if available is very handy in this caase.
This is the html I am working with:

  <input type="radio" id="amount-to-give--25" name="hvf-radios-amount" class="hvf__radio" required value="25">
  €25

Having the wrapper div allows me to then use :focus-within to add an outline to each radio element.
.hvf__form-item--radio:focus-within {
  outline: 2px dashed var(--color-grey--darkest);
  outline-offset: 4px;
}


text:
Q: How to set a step for dynamic size of an eöement in CSS? I have a form, that has optically two sides (left and right). The height of the input fields is constant, so the left and the right fields are placed exactly on the same "lines".

Now I want to add description/comment blocks under some of the fields. The "lines" may not be broken. It's no problem for short comment, that need only one "line". I can simply set the min-height to the height of the input fields. But longer texts will need multiple line breaks and so destroy my imaginary "lines".
So what I need, is a way to define something like a "step" for the comment blocks. so that if a comment block contains multiple lines of text, it grows by one or more heights (e.g.: the height is 20px; then the block can become greater to contain more text, but only in 20px steps like 40, 60 80, etc.).
How to do this with pure CSS (without JavaScript)?


text:
Q: Drools Rule structure Hi i am new to Drools fusion and I have been developing some sample rules to understand working of drools fusion.
I need some help in understanding drools
My rule:
rule "Sample Rule"

    when
     $t:Test (num == 10) from entry-point Stream
    then
        System.out.println($t.str);

end

Test is a class having a str String and num Integer.
 I need event to be fired by some correlation such that it keep inserting test objects and fire event as num of those objects have sum more than 100 like:
rule "Your First Rule"
    when
     $t:Test ($tmp:num) from entry-point Stream //store num's value

     ($tmp>100)      // fire if sum of num's more than 100
    then
        System.out.println($t.str);

end

My code is:
WorkingMemoryEntryPoint entryPoint1=ksession.getWorkingMemoryEntryPoint("Stream")
        def eg=new Test()
        eg.str="Test"
        eg.num=10
        EventFactHandle factHandle = (EventFactHandle)entryPoint1.insert(eg)

Ques 2: I want to understand the working of fireAllRules(). Do i need to trigger by this method everytime I insert an object into drools runtime(entrypoint or session).?
I hope you understand my situation.Please help and thanks in advance

A: I don't know what question #1 was supposed to be. I can see that the line
($tmp>100)

is syntactically incorrect; the condition should be part of the preceding pattern or enclosed in eval().
Question #2: You can insert any number of facts and call fireAllRules(), or you can call fireAllRules() after each insertion. Note, however, that the result may not be the same. Consider a scenario, where a rule removes a fact X() as soon as it triggers on a single X, and where another rule triggers as soon as there are two facts of type X(). The second rule may never fire if fireAllRules() is called after each insertion,


text:
Q: Azure REST PUT or DELETE  returns 401 I've just uploaded my WCF REST based service to Azure.
When I try to use PUT or DELETE I get a 401, Unauthorized: Access is denied due to invalid credentials.
It runs fine in my local and Azure development environments
I've seen other posts referencing Certificates and Permissions.
401 Unauthorized with OData Update and Delete (PUT and DELETE verbs are enabled in IIS, by default)
http://goneale.com/2009/10/22/wcf-the-http-request-is-unauthorized-with-client-authentication-scheme-anonymous/ (doesn't apply because of Azure)
I'm running default settings

A: I had to add
<authentication mode="None" />

to my web.config
http://social.msdn.microsoft.com/Forums/en-US/windowsazuretroubleshooting/thread/514f2e2d-54a8-4516-976d-94a879209173


text:
Q: how to add boxshadow only at the top side in flutter I wanted to add shadow to a box inside BoxDecoration only on top side. Is it possible in flutter ? This is my approach so far but not getting the desired results. Thanks in advannce.
class SectionHeaderDelegate extends SliverPersistentHeaderDelegate {
  final String title;
  final double height;

  SectionHeaderDelegate(this.title, [this.height = 50]);

  @override
  Widget build(context, double shrinkOffset, bool overlapsContent) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 5 * SizeConfig.widthMultiplier),
      decoration: BoxDecoration(
        color: AppColors.colorWhite,
        borderRadius: BorderRadius.only(
            topRight: Radius.circular(30), topLeft: Radius.circular(30)),

         boxShadow: <BoxShadow>[
           BoxShadow(
               color: AppColors.colorLightGrey,
               blurRadius: 20.0,
               offset: Offset(0.0, 1.0))
         ],
      ),
      child: Text(title, style: AppStyles.complaints),
    );
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) => false;
}```


text:
Q: Zeroes of derivative of Weierstrass's elliptic function I'm asked to show that the Weierstrass's elliptic function $\wp: \mathbb{C}/\Gamma \rightarrow \mathbb{C}P^1$ has exactly 4 branch points. My problem is that I don't see why there are 4 branch points and not just 3.
I looked at the zeroes of the derivative $\wp '$. Since $\wp '$ is doubly periodic and odd this implies that $\frac{w_1}{2}$, $\frac{w_2}{2}$ and $\frac{w_1+w_2}{2}$ are zeros of $\wp '$, where $w_1,w_2$ span $\Gamma$. But I know that an elliptic function has the same number of poles as it has zeros (where the order of the poles / zeroes matters). Since $\wp '$ has only one pole (of order 3) I know that the three zeros are all of order 1 and in particular there can't be a fourth zero.
Where is my mistake?

A: The final branch point is at $z = 0$, and the reason for this is a bit subtle.
The image of $z = 0$ under $\wp$ is the "point at infinity" on $\mathbb {CP}^1$. In fact, $z = 0$ is the unique point on $\mathbb C / \Gamma$ whose image under $\wp$ is the point at infinity on $\mathbb {CP}^1$. Since the map $\mathbb C/\Gamma \to \mathbb {CP}^1$ is of degree two, this observation alone is enough for us to conclude that $z = 0$ is a branch point.
For an alternative perspective, recall that our map $\mathbb C / \Gamma \to \mathbb {CP}^1$ is given by $z  \mapsto [1 : \wp(z)] $ for $z \neq 0$. But to define the map at $z = 0$, we need to rewrite the map as $z \mapsto [\wp(z)^{-1} : 1]$. Now $\wp(z)$ has a double pole at $z = 0$, so $\wp(z)^{-1}$ has a double zero at $z = 0$, hence $z = 0$ is a branch point of our covering with ramification index equal to two.


text:
Q: CreateDataFrame with F# I'm trying to create a simple Spark DataFrame with F# as it is used in Spark.Net test
let schema =
    StructType (
        [|
            StructField("Name", new StringType())
            StructField("Age", new IntegerType())
            StructField("Date", new DateType())
        |] )

let rows: obj[][] =
    [|
        [| "Alice"; 20; new Date(2020, 1, 1) |]
    |]

session.CreateDataFrame(rows |> Array.map GenericRow, schema).Show(10, 0, false)

eventually, this code fails (as exactly the same code using .NET collections)
JVM method execution failed: Nonstatic method 'createDataFrame' failed for class '7' when called with 2 arguments ([Index=1, Type=GenericRow[], Value=Microsoft.Spark.Sql.GenericRow[]], [Index=2, Type=JvmObjectReference, Value=8], )

A: The above runs well for me
+-----+---+----------+
|Name |Age|Date      |
+-----+---+----------+
|Alice|20 |2020-01-01|
+-----+---+----------+

*

*Please check you're using Spark < 2.4.5   I did the test with 2.4.1

*Java > 1.8

*Also check you are providing all parameters

$SPARK_HOME/bin/spark-submit --class org.apache.spark.deploy.dotnet.DotnetRunner --master local bin/Debug/netcoreapp3.1/microsoft-spark-2.4.x-0.11.0.jar dotnet bin/Debug/netcoreapp3.1/yourLibrary.dll


text:
Q: Showing that $(a,a')\in R\implies f(a)=f(a')$ From https://arxiv.org/pdf/1612.09375.pdf (p.130):

I'm confused by the proof given at the end. Namely, I don't understand why the statement "so these statements are equivalent" follows. And also I don't understand what for the author defines the third relation (I don't know how to type that symbol here).
Can one prove the original claim as follows?
Let $\sim$ be the equivalence relation generated by $R$. We need to show that $(a,a')\in R\implies f(a)=f(a')$, knowing that $(a,a')\in \sim \implies f(a)=f(a')$ [which is (5.19)]. So assume $(a,a')\in R$. Since $\sim$ is the equivalence relation generated by $R$, the relation $\sim$ contains $R$. Thus $(a,a')\in \sim$. Now by (5.19), $f(a)=f(a')$.
I don't see what's wrong with my proof, but it doesn't use that $\sim$ is the smallest equivalence relation generated by $R$.

A: For the original proof you need to show that $R ⊆ \approx$ implies $\sim ⊆\approx$ (the other direction is obvious since $R ⊆ \sim$).
Well, since $\sim$ is the smallest equivalence containing $R$, and $\approx$ contains $R$ by assumption, we must have that $\sim$ is smaller than $\approx$, ie. that $\sim ⊆ \approx$.
(This is completely analogous (and formally the same) to how you'd argue that eg. the statements $A ⊆ F$ and $\operatorname{Cl} A ⊆ F$ are equivalent for a closed set $F$.)
In your proof you only show that 5.19 implies 5.20, and not the converse, which is the more important part.
Finally, for LaTeX, you can usually google the symbols you need (in this case "latex relation symbols" would suffice), and there are also tools like detexify that can help.


text:
Q: Creating custom requestParam in springboot controller i have a use case where the user can send following params with get request

GET localhost/8080/users?filter=alex
OR
GET localhost/8080/users?suffixFilter=lex
OR
GET localhost/8080/users?prefixFilter=a

is it possible to add only one request param instead of 3 in controller
e.g.
instead of
@GetMapping("/users")
@ResponseBody
public String getFoos(@RequestParam String filter, @RequestParam String prefixFilter , @RequestParam String suffixFilter) {
    return "ID: " + id;
}

is it possible to create a dynamic one which includes those three variantes? I was thinking creating class like this
public class FilterCreteria {
    private String filter;
    private String suffixFilter;
    private String prefixFilter;
}

and then passing this to controller
 @GetMapping("/users")
    @ResponseBody
    public String getFoos(@RequestParam FilterCreateria filter) {
        return "ID: " + id;
    }

the problem is if i send filter=alex the other attributes in the class FilterCreteria is null and i want to avoid this null.
What i searching for:
is there other way of making this possible?
if my suggestion is ok, how to avoid null attributes when the user only sends one queryparam like filter=alex?


text:
Q: How to concatenate a string and a list? I have a list and a string:
fruits = ['banana', 'apple', 'plum']
mystr = 'i like the following fruits: '

How can I concatenate them so I get
'i like the following fruits: banana, apple, plum'

Keep in mind that the enum may change size.

A: You can use str.join.
result = "i like the following fruits: "+', '.join(fruits)

(assuming fruits only contains strings).  If fruits contains a non-string, you can convert it easily by creating a generator expression on the fly:
', '.join(str(f) for f in fruits)

A: Join the list, then add the strings.
print mystr + ', '.join(fruits)

And don't use the name of a built-in type (str) as a variable name.

A: You can use this code,
fruits = ['banana', 'apple', 'plum', 'pineapple', 'cherry']
mystr = 'i like the following fruits: '
print (mystr + ', '.join(fruits))

The above code will return the output as below:
i like the following fruits: banana, apple, plum, pineapple, cherry

A: You're going to have a problem if you name your variables the same as Python built-ins. Otherwise this would work:
s = s + ', '.join([str(fruit) for fruit in fruits])

A: The simple code below will work:
print(mystr, fruits)


text:
Q: Advantage of wrapping in monad Look at mapM function:
class (Functor t, Foldable t) => Traversable (t :: * -> *) where
  ...
  mapM :: Monad m => (a -> m b) -> t a -> m (t b)

As you can see, the result is in the monad context.
What is the sense, that t b get wrapped in the monad? What kind of power do I get of that?

A: I think, it is not about a power, but usefulness.
You could use map over some action :: a -> m b, but then you'd get a [m b] (if we forget about a Traversable for a moment). The mapM does basically the same, but also converts [m b] into m [b] by performing each action sequentially and collecting results. The last operation is called sequence, BTW.


text:
Q: Who is good at scraping websites? I have a tough one I'm a very amateur data analyst. I'm trying to get the information off of a GIS map on this website:
http://www.gimsys.net/irep/SIG/th_Reseau/default.asp
I'd like to get the raw data for the layers on the map, but it seems like the website can't be scraped because it just loads images.
Any tips?
Much appreciated!

*

*Laurent


text:
Q: Get selected chart object or text frame or table using C# VSTO addon? I was trying to get a current selected object present in PPTX file for an VSTO addon.
I was using the below package for creating a chart,tables and text in slides.
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;

I have a button present in the Ribben bar. Once the user clicks it I wanted to get the current selected object in any slide. How do I do this? Is there any way present in the interop package.

A: If you are selecting one or more shapes, you could do something like this
if (Globals.ThisAddIn.Application.ActiveWindow.Selection.ShapeRange.Count > 0)
                {
                    //iterate over all the shapes selected by the user
                    foreach (PowerPoint.Shape shp in Globals.ThisAddIn.Application.ActiveWindow.Selection.ShapeRange)
                    {
                        if (shp.HasTable == Office.MsoTriState.msoTrue)
                        {
                            //Do something
                        }
                        if (shp.HasChart == Office.MsoTriState.msoTrue)
                        {
                            //Do something
                        }
                        if (shp.HasTextFrame == Office.MsoTriState.msoTrue)
                        {
                            //Do something
                        }

                        //or you could just return the shp object
                    }
                }


text:
Q: How do I install khttpd and run it and view its source code? I am using Ubuntu 20.04.1 LTS
I want to get started with khttpd but am unable to find much useful information on line.
How do I verify khttpd is installed on my ubuntu machine? How do I install it if it isn't? How do I run it? How do I verify it's running? How do I download/view the relevant source code?
thanks in advance for any answers.
EDIT:
The official website for khttpd is http://www.fenrus.demon.nl/
What I've found so far is that khttpd is a kernel module that must be configured and inserted into the kernel. What is lacking is instructions of how to do that on Ubuntu.


text:
Q: DNS resolution failure error while connecting to grpc server running on docker I am trying to access the grpc server which exposes 9000 port and is running as docker container.
I am using .net core client to connect to the server.It works perfectly fine when GRPC server is not running as a docker container.
I have tried using both the "localhost","dockerconatiner-ip" while creating the channel from client.I am running the grpc server on "0.0.0.0"and port 9000.
docker commands:
docker run -p 9000:9000  -a stdin -a stdout -it
Error:
Status(StatusCode=Unavailable, Detail="DNS resolution failed")
dockerfile:
FROM mcr.microsoft.com/dotnet/core/runtime:3.0
COPY Sample/bin/Release/netcoreapp3.0/publish/ app/
WORKDIR /app
EXPOSE 9000
ENTRYPOINT ["dotnet", "Sample.dll"]

Service Main:
static void Main(string[] args)
    {
        try
        {
            Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            const int Port = 9000;
            Server server = new Server
            {
                Ports = { new ServerPort("0.0.0.0", 9000, ServerCredentials.Insecure) },
                Services = { BindService(new TestService()) }
            };
            server.Start();

            Console.WriteLine("starting server");
            Console.WriteLine("Press any key to shut down");
            Console.ReadKey();
            server.ShutdownAsync().Wait();
            Console.WriteLine("Grpc Server stopped");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

Test service has a method to print received text to console.


text:
Q: JDBC connectivity issue My code for connection with access database is this...its working fine here... i have tried to connect my database with java derby embedded database but always getting sql exception assuming the same table what changes do i need to connect my application with java derby embedded database??
 package database;
    import java.sql.*;
    import javax.swing.JOptionPane;

       public class database {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {

            try
            {
                String url = "jdbc:odbc:personnew";
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con=DriverManager.getConnection(url);
            Statement st=con.createStatement();
            String sql="SELECT * FROM Person";
            ResultSet rs=st.executeQuery(sql);
            while(rs.next()){
            String id=rs.getString("id");
            String name=rs.getString("name");
            String fathername=rs.getString("fathername");
            JOptionPane.showMessageDialog(null,id+"\t"+name+"\t"+fathername);
            }
            // TODO code application logic here
        }catch(Exception sqlEx){
            System.out.println("Sql exception");
        }
    }
    }

A: For one thing, You would need to use the correct JDBC driver; org.apache.derby.jdbc.EmbeddedDriver
http://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
The tutorial in general is probably where you want to start as it tells you everything you need to know:
http://db.apache.org/derby/papers/DerbyTut/index.html


text:
Q: How can I include Bash in the cross-compilation of NetBSD using build.sh? I'm looking for the best practice for including GNU Bash in the cross-compilation of NetBSD using the build.sh script.  Right now, my plan is to include it in usr/src/gnu/dist and then create the relevant Makefiles in usr/src/gnu/usr.bin but I was wondering if there was an easier/better way to do this?

A: The new way is to place files under src/external//.  For bash, it's src/external/gpl3/bash.  (This directory is called ${EXTTOPDIR.bash} hereafter.)
The original source is expanded into ${EXTTOPDIR}/dist as is.  Other files and directories are made at ${EXTTOPDIR}.  Start with copying src/external/gpl2/xcvs for example.  (BSD) makefiles that are placed (out of the original source) are called "reach-over"; meaning that build procedures are kept without disturbing the original source.  This helps to ease maintaining of the original source.  (And no, all of these are not documented at all, unfortunately.)
If you need to hook the build as "tools", you'll need something more to care.  The procedure is also not documented.  Just learn from the source.
If you work on the official NetBSD tree, you have something more to learn about CVS; use vendor branch, etc.
HTH,
Masao


text:
Q: Problem with mutate keyword and functions in R I got a problem with the use of MUTATE, please check the next code block.
output1 <- mytibble %>%
  mutate(newfield = FND(mytibble$ndoc))
output1

Where FND function is a FILTER applied to a large file (5GB):
FND <- function(n){
  result <- LARGETIBBLE %>% filter(LARGETIBBLE$id == n)
  return(paste(unique(result$somefield),collapse=" "))
}

I want to execute FND function for each row of output1 tibble, but it just executes one time.

A: Never use $ in dplyr pipes, very rarely they are used. You can change your FND function to :
library(dplyr)

FND <- function(n){
   LARGETIBBLE %>% filter(id == n) %>% pull(somefield)  %>%
                  unique %>% paste(collapse = " ")
}

Now apply this function to every ndoc value in mytibble.
mytibble %>% mutate(newfield = purrr::map_chr(ndoc, FND))

You can also use sapply :
mytibble$newfield <- sapply(mytibble$ndoc, FND)

A: FND(mytibble$ndoc) is more suitable for data frames. When you use functions such as mutate on a tibble, there is no need to specify the name of the tibble, only that of the column. The symbols %>% are already making sure that only data from the tibble is used. Thus your example would be:

output1 <- mytibble %>%
  mutate(newfield = FND(ndoc))

FND <- function(n){
  result <- LARGETIBBLE %>% filter(id == n)
  return(paste(unique(result$somefield),collapse=" "))
}

This would be theoretically, however I do not know if your function FND will work, maybe try it and if not, give some practical example with data and what you are trying to achieve.


text:
Q: Image Loading seems to slow down Javascript execution I am working on a straightforward web app, purely Javascript.
One of the core functionalities is loading and viewing images.
When a lot of big images are loaded, the script execution often slows down or even halts until some of them are done loading, this is especially noticeable with large .gifs (HTML5 video is not as bad for some reason).
The images are loaded by setting the background-image css attribute of divs with jQuerys .css(), there are no sort of blocking events or sleep / wait time until images are loaded.
Weirdly, on OSX, scrolling (with the Macbook trackpad) temporarily relieves the halt / slowdown, even while in fullscreen (OSX browsers leave wiggle room for the trackpad), which makes me think that it's a problem of rendering or resource allocation of some sort. It feels like the browser does not have the need to redraw, and is only forced to do so because of the scrolling.
I'd like to force it to redraw constantly, 60 FPS.

A: The issue is with the loading of lot of big images and showing them in the application.
You can try for Image lazy loading concept where images are loaded/fetched as soon as you scroll the window.
May be this link would be helpful. This plugin will take care of loading images when user scrolls and its very easy to use.
Someone can try the concept of WebWorker. Its multithreading in javascript.

A: I would like to add, to not forget image optimization.


text:
Q: USSD Mutilevel menu creation in php Am developing a USSD menu in php which is intended to be a multilevel menu
The structure is like this:
When a user dials *2000*22# it displays eg:

*

*Household items

*Electronic Devices

*Exit.

When a user responds with "1" a submenu of Household items displays as seen below:
1. Couch
2. Lawn mower
My question is how do I display a second submenu for "1. Couch" if the user selects "1" again. Below is my code:
 $ussdRequest = json_decode(file_get_contents('php://input'), true);
    $obj = json_decode($json);
    $timestamp   = $ussdRequest["timestamp"];
    $sessionId   = $ussdRequest["sessionId"];
    $serviceCode = "*2000*22#";
    $phoneNumber = $ussdRequest["MSISDN"];
    $cpId = $ussdRequest["cpId"];
    $cpPassword = $ussdRequest["cpPassword"];
    $opType = $ussdRequest["opType"];
    $msgCoding = $ussdRequest["msgCoding"];
    $ussdContent=$ussdRequest["ussdContent"];

      //Display main menu

    $response  = "Reply with: \n";
    $response .= "1. Household Items \n";
    $response .= "2. Electronic Devices \n";
    $response .= "3. Exit \n";

    $date = new DateTime($date, new DateTimeZone('UTC'));
    $newtimestamp = $date->format('YmdHmsn');

    $cpPassword2 = "7809834";
    $hashparams = $cpId.$cpPassword2.$newtimestamp;
    $hashpasswd = md5($hashparams);

    $data = [ "sessionId" => $sessionId, "cpId" => $cpId,"cpPassword" =>$hashpasswd,"serviceCode"=>$serviceCode,"msgType"=>1,"opType"=>$opType,"msgCoding"=>$msgCoding,"ussdContent"=>$response,"timeStamp"=>$newtimestamp,"MSISDN"=>$phoneNumber];

    $ussdc = $ussdContent;

switch($ussdc){
      // if the user responds with "1" the ussd content shows menu below
      case "1":
          $response2  .= "1. Couch \n";
          $response2  .= "2. Lawn mower\n";

    $data2 = [ "sessionId" => $sessionId, "cpId" => $cpId,"cpPassword" =>$hashpasswd,"serviceCode"=>$serviceCode,"msgType"=>1,"opType"=>1,"msgCoding"=>$msgCoding,"ussdContent"=>$response2,"timeStamp"=>$newtimestamp,"MSISDN"=>$phoneNumber];

    //API URL

$url = '58.278.901.54:8581/push_ussd';
    //create a new cURL resource
    $ch = curl_init($url);

    $decoded_data = json_encode($data2);

    //attach encoded JSON string to the POST fields
    curl_setopt($ch, CURLOPT_POSTFIELDS, $decoded_data);

    //set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

    //return response instead of outputting
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //execute the POST request
    $result = curl_exec($ch);

  break;

//API URL
$url = '58.278.901.54:8581/push_ussd';
//create a new cURL resource
$ch = curl_init($url);

$decoded_data = json_encode($data);

//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $decoded_data);

//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the POST request
$result = curl_exec($ch);
if ($result === FALSE) {
    echo curl_error($ch);
    //ini_set("error_log", "/tmp/php-error.log");
    exit();
}
//close cURL resource
curl_close($ch);
 $response = [ "sessionId" => $sessionId, "msisdn"=>$phoneNumber,"errorCode"=>"200","errorMsg"=>"Success"];
header('Content-type: application/json');
echo json_encode($response);

?>

A: You can use relationships to fetch the related items based on the menu selected by a user.

A: For USSD we have levels. We check the level the dialer is to be able to know is on which Menu. This is how you should do
Initialize the $parts and $level
        $text = $_POST['text'];//this is text the user has dialed

        $level = 0;
        $parts = [];

        if(strlen($text) == 0 ) {

            $level = 0;

        } else {

            $parts = explode("*", $text);
            $level = count($parts);
        }

The first time the user dials the code
if ($level == 0){
   //Display main menu
    $response  = "CON Reply with: \n";
    $response .= "1. Household Items \n";
    $response .= "2. Electronic Devices \n";
    $response .= "3. Exit \n";
}

The second time the user dials the menu
elseif($level == 1){
  //get the number he dialed
if ($parts[0] == 1){

//Display menu
    $response = "CON 1. Couch\n";
    $response .= "2. Lawn mower";

}elseif ($parts[0] == 2){

//Display other menus and so on
}else{
//bla bla
}

The third time the user dials the menu
elseif($level == 2){
  //get the number he dialed
if ($parts[0] == 1){

//Display menu
    $response = "CON 1. Couch";

}elseif ($parts[0] == 2){

//Display other menus and so on
}else{
//bla bla
}

Hope that helps. If any question please feel free to ask


text:
Q: Conditioning by a random function Let $W_t$ denote the standard Wiener process (zero mean).
Let $B$ be a uniform binary random variable taking values $\pm 1$ independent of the stochastic process $\{W_t\}$.
We define
$$Y_t = B + W_t ,\quad 0\leq t\leq 1$$
Suppose I observe the sample path $Y_t,\ 0\leq t\leq 1$.
How do I calculate the conditional distribution of $B$ given the sample path $Y_t,\ 0\leq t\leq 1$?


text:
Q: How to update git's remote address/port in local machine In my company, whenever I want to push to git server from within the company, I have no problem as the .git/config file is like:
[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = me@172.x.x.x:/home/git/repositories/YYY

our company has a public IP and they say the access to our git server is from :
137.a.a.a:bbb

I need to push to the remote branch from home, but I dont know how to configure the git using this IP, I tried to change the above url to
[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = me@137.a.a.a:bbb/home/git/repositories/YYY

but there was no luck.the error says:
ssh: connect to host 137.a.a.a port 22: Connection timed out
fatal: The remote end hung up unexpectedly

There problem could be a firewall or other networking issue. But before that, I want to make sure if my change is correct or not.
thank you

A: Instead of changing your existing remote, I suggest adding a new one. In the end they will point to the same server, but I personally prefer to use local IPs when possible.
To add a new remote, you simply execute git remote add <name> <Address>
You can then access the remote like origin, just replace any occurrence of origin with your new name.
This will not fix your problem, however. The problem seems to be that you don't get a connection.
My guess is, that you are trying to use a port, but use wrong syntax, try this:
url = ssh://me@137.a.a.a:bbb/home/git/repositories/YYY
This turns it into a real url, the way you did it before does accept ports afaik.
Source


text:
Q: Strange Issue with computer shutdown and cable outage This problem first showed signs a few days ago. I was working on my iMac, and suddenly it shut off immediately without showing any warning signs. So, I powered it back on and my ethernet connection was not working (Wi-Fi was still okay on the same router). I found out there was a problem with an ethernet switch in this house. I unplugged that and plugged it back in and I had my ethernet connection working again.
Now today, my mac shutoff again. This time, the ethernet AND Wi-Fi was not working. I figured that the problem was with the router this time. So I plugged a direct connection from the modem into the computer. There was no internet, so the entire cable connection to the house was offline. Even the TV was not working because it uses the same cable connection.
So the problem is either originating from my Mac and causing the internet to go out OR there is some external force causing problems with the internet and remotely shutting down my computer. There are many wired computers in the house and only mine shut off while I was using it. Also, it is not a power problem.
I called my ISP and the neighbourhood is still online. This is only affecting me and I am not with TWC. This has noting to do with the recent outage. I am expecting a technician tomorrow, but I would like to hear what anyone here thinks of this strange issue and what might be causing it.


text:
Q: Rails 5.1: refresh partial within partial with AJAX I have partial _navigation.html.erb where there is this piece of code:

          <%= render 'users/user', user: current_user %>

<%= link_to t('.profile'), edit_user_path(current_user), remote: true %>

<%= link_to t('.logout'), logout_path %>

I render User name in this _user.html.erb partial:
<%= user.name %>

When I login, I see my current_user name in navigation partial as expected. However when I try to Update my User name (modal window), I don't see my current_user value changes in _user.html.erb partial.
My users_controller.rb Update action looks like this:
  def update
    @user.update(user_params)
    respond_to do |format|
      format.json { update_flash }
      format.js { update_flash }
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation,
                                 :locale, :menu_role, :psw_change,
                                 {company_ids: []}, {user_group_ids: []})
  end

  def correct_user
    users = User.where(id: helpers.users_all)
    @user = User.find(params[:id])
    redirect_to(errors_path) unless users.include?(@user)
  end

  def update_flash
    flash[:notice] = "#{@user.name.unicode_normalize(:nfkd)
                                  .encode('ASCII', replace: '')} ", t(:updated)
  end

update.js.erb looks like this:
$('#dialog').modal('toggle');
$('#userprofile %>').replaceWith('<%= j render (@user) %>')

I see clearly in my console Update action is done, my files are rendered, no errors:
  Rendering users/update.js.erb
  Rendered users/_user.html.erb (0.6ms)
  Rendered users/update.js.erb (8.5ms)
Completed 200 OK in 126ms (Views: 41.1ms | ActiveRecord: 16.0ms)

What am I doing wrong here, please? It would be nice to be able to show updated current_user name in profile. I'll be happy for any hint, where should I be looking at. Thank you.

A: In update.js.erb, you have a typo. You should delete the %>. Try this:
$('#userprofile').replaceWith('<%= j render (@user) %>')

Also, instead of replacing the entire #userprofile node, you may want to change the html inside of it instead:
$('#userprofile').html('<%= j render (@user) %>')


text:
Q: Cross Correlation: using to detect signal patterns? I understand correlation is defined as below and have questions on using the concept for signal pattern detection.  I'm relatively new to this topic so appreciate anyone sending me in the best direction.
$$
a,f,g : S \rightarrow Y
$$
$$
a(t) = (f \star g)(t) = \int_{-\infty}^{\infty} f(\tau) g(\tau + t) d\tau
$$
I would like to find the best shifted matches of $g$ over $f$, so I:
$$
F = argmax_{x \in S}(a(t))
$$
Is it an exact match:
$$
D(f,g,t) = \forall \tau\in S(\delta_{f(\tau)g(\tau+t)} = 1)
$$
$$
MatchesShift = \{t : t \in F \land D(f, g, t)\}
$$
Does this look correct to find best correlation and then exact matches?
I'm assuming more complex matching is performed by testing all the subsets of $g$.  Appreciate any guidance there


text:
Q: Why doesn't this seeder class code work in production? I have this seeder class that works/runs in my development setup:
class OwnerSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        if(config('owner.owner_first_name')) {
            $user = User::firstOrCreate(
                 ['email' => config('owner.owner_email')], [
                     'first_name' => config('owner.owner_first_name'),
                     'last_name' => config('owner.owner_last_name'),
                     'mobile_phone_number' => config('owner.owner_mobile_phone_number'),
                     'password' => bcrypt(config('owner.owner_password')),
                     'email_verified_at' => now(),
                     'identity_verified_at' => now(),
                 ]
             );
         }

         $user->assignRole('owner')
         ->givePermissionTo(Permission::all());
    }
}

But when I run it in production, I get the error 'Undefined variable $user'. What can I do to resolve this?

A: What I can see there is that your config is different in production and your local: the owner.owner_first_name key doesn't seem to exist in production, which means that the code within the if statement will never be executed and will jump straight to the $user variable, which of course won't be set (that happens only if the if gets executed.
Take a review on your config and start from there.
Good luck!


text:
Q: How do I make Import-Clixml read a custom credentials XML file? I'm obtaining credentials for a Xen pool master server using Get-Credentials. I'm saving the credentials to an XML file using Export-Clixml. I want to add an element to the XML file created by Export-Clixml to store the Xen pool name and the Xen pool master URL to the XML file.
Problem: I create the credentials XML file using Export-Clixml and then modify the XML file to add the extra element. However, when I read the XML file using Import-Clixml, it throws an error: Import-Clixml : Obj XML tag is not recognized.
How do I make Import-Clixml read my custom credentials XML file to obtain the credentials without throwing an error due to my custom object?

A: My original approach was to locate the XML schema for the XML file produced by Export-Clixml with the hope that the schema supports some kind of generic string element. However, I was unable to locate the schema.
The solution was to use the -first argument of the Import-Clixml cmdlet.
First, I created an XML file using Export-Clixml, and then I added a second Obj element (<Obj RefId="99" xmlns="">)
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCredential</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Management.Automation.PSCredential</ToString>
    <Props>
      <S N="UserName">UUUUU</S>
      <SS N="Password">PPPP...PPPPP</SS>
    </Props>
  </Obj>
  <Obj RefId="99" xmlns="">
    <my-element-name my-element-attribute="AAAAA">EEEEEE</my-element-name>
  </Obj>
</Objs>

To obtain the credentials, I read the XML like this:
$creds = $Import-Clixml -first 1 -path <fq path to xml file>

-first 1 forces Import-Clixml to read only the <Obj RefId="0"> element (and ignore my custom element)
Then, I re-read the XML file using an XMLReader to obtain my custom element
Edit 1
Changed approach as per Jeroen Mostert's suggestion
Notes:
$ExportXmlFile.FileName comes from system.windows.forms.savefiledialog
$cred is loaded with output from get-credentials
$cred | Export-Clixml -Path $ExportXmlFile.FileName -Force

$xml = [xml] (type $ExportXmlFile.FileName)

[System.Xml.XmlElement]$root = $xml.DocumentElement

[System.Xml.XmlComment]$c = $xml.CreateComment(("poolName="+$textBoxXenPoolName.Text + "," + "poolMasterUrl="+$textBoxXenPoolMasterUrl.Text))
$xml.InsertBefore($c, $root);

$xml.Save($ExportXmlFile.FileName)

produces an xml file with a 'structured' comment that I can read and parse:
<!--poolName=nnnnn,poolMasterUrl=https://###.##.#.#-->
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCredential</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Management.Automation.PSCredential</ToString>
    <Props>
      <S N="UserName">uuu</S>
      <SS N="Password">pppp...pppp</SS>
    </Props>
  </Obj>
</Objs>


text:
Q: Creating a Diamond Object Graph in Guice (without Singleton) I am using Guice for Dependency Injection and want to create an object graph that looks like this:

   d1        d2
  /  \      /  \
b1    c1  b2    c2
  \  /      \  /
   a1        a2

*

*a1 and a2 denote instance of class A etc.

*class A depends on classes B and C

*classes B and C each depend on class D

*However, the instance of D used in B and C should be the same

So I want to create two instances of the A class, each with this structure.
A use case could be D being some kind of data object (say, a DB connection) that is used by the two clients B and C, that both are used in a servlet A.
Minimal Java class definition:
public class A {
    @Inject A(B b, C c) {}
}

public class B {
    @Inject B(D d) {}
}

public class C {
    @Inject C(D d) {}
}

public class D {}

Now I can create two instances of A:
Injector injector = Guice.createInjector(new DiamondModule());
A a1 = injector.getInstance(A.class);
A a2 = injector.getInstance(A.class);

However, if I do this, I will get four different instances of D, which is not what I want. Notice that declaring D a singleton will not help, as then I will get only a single instance of D.
I have seen the following question, but the answer to that one doesn't work here, or at least I do not know how: Guice inject single instance into multiple objects without using @Singleton
Does anyone have an idea how to solve this? Or is this design somehow wrong? Or is this already an instance where I have to declare my own scope?

Solution
Meanwhile I noticed that this question is a duplicate of Dependency injection: Scoping by region (Guice, Spring, Whatever), and based on the anwers to that question I came up with a solution.
The basic idea is to create a new injector for every instance of the diamond, like this:
public class MainModule extends AbstractModule {
    @Override
    protected void configure() {
    }

    @Provides
    A createA() {
        return Guice.createInjector().getInstance(A.class);
    }
}

Now make D an singleton, which is scoped to the particular injector.
// class D is a singleton
@Singleton
public class D {}

A: This is called the "robots leg" problem (creating similar graphs with slightly different instances) and is handled  here.
class LegModule extends PrivateModule {
   private final Class<? extends Annotation> annotation;

   LegModule(Class<? extends Annotation> annotation) {
   this.annotation = annotation;
}

@Override protected void configure() {
   bind(Leg.class).annotatedWith(annotation).to(Leg.class);
   expose(Leg.class).annotatedWith(annotation);

   bindFoot();
}

abstract void bindFoot();
}
public static void main(String[] args) {
   Injector injector = Guice.createInjector(
      new LegModule(Left.class) {
        @Override void bindFoot() {
          bind(Foot.class).toInstance(new Foot("leftie"));
        }
      },
      new LegModule(Right.class) {
        @Override void bindFoot() {
          bind(Foot.class).toInstance(new Foot("righty"));
        }
      });
 }


text:
Q: Issues with Access parsing double quotes in a CSV file I have a large CSV file that I am trying to import into Microsoft Access but I am running into issues. Assume pipes represent different cells in the database
Assume my content is the below. The second entry will only parse the word my with default settings and will not import the word content into the database even though the import wizard implies that it will. The default settings being , delimiter and " text qualifier.
|my content is good|
|my|

Now if i change the text qualifier to NONE it parses the entire second entry and my content will be imported into the database however the first entry will wind up being in 3 different cells in the data base and will show up as
my|content|is|good.
|my content

I used pipes to imply different cells.
This seems like a limitation in Microsoft Access. Is anyone familiar with a workaround for this?
Original content:
,"my,content,is,good","",

,my"content","",

I am using the import wizard

A: Yes, this is a limitation of the CSV import capabilities in Access. For whatever reason, Access has always been more restrictive than Excel in its abilities to parse CSV files.
So, one workaround would be to open the CSV file in Excel, save the file as an actual Excel sheet, and then import the Excel sheet into Access. For example, the CSV file
this,is,a "test",CSV file,"Ugly, yes, but still parsable."

is "non-standard" (if one is willing to concede that there is such a thing as a CSV "standard"), and Access cannot import it directly. (It either complains of an "Unparsable Record" or it splits the last field on the commas, depending on the "Text Qualifier" setting.)
However, we can open it in Excel

save the file as "foo.xlsx", and then import the .xlsx file into Access


text:
Q: Definition of partition of set regarding countability In Stochastic Processes, we define a partition of a set as:

A countable collection of sets $U=\{A_1,A_2,A_3,...\}$(which may be a finite collection) which are pairwise disjoint is a partition of a set $D$ if
$\bigcup A_i=D$

My question laying here is that, does the countability matter? Maybe both countable and uncountable collection are infinite, so there is no significant difference between them.
And many Stochastic Processes theories are fiddling with the concept of countability, I don't understand the meaning of that. Could someone help me out?

A: If you try to define an uncountable sum it does not work out so well. So if you are summing over collections of sets it makes sense to restrict yourself to countable collections.


text:
Q: prevent default working in Firefox but not in chrome For the click of this link

I have written this code
$('#c2c').click(function(event){
    event.preventDefault();
        window.location.href = "http://google.com";
     $.get("test.php?testnum=121212121",function(data){
        if(data == "no") window.location.href = "failure.html";
        else {
               window.location.href = "http://www.abc.com/get_data.php?data="+data;
                     }
});

On this click of link, I am
1 - prventing default behaviour
2 - setting href location
3 - sending a get request with some params to another page
They all are working fine in FireFox but when I use try this code in Chrome/opera , it is not 3- sending the get request and in error console I can see that Browser shows that 'Request Aborted'.Any help?
NOTE: As far as I investigate it is due to not working of event.preventDefault(); ,If I am right then How can I make this working OR what what would be the solution?

A: you have to remove the location.href:
('#c2c').click(function(event){
  event.preventDefault();
  // window.location.href = "http://google.com"; remove this line or move it somewhere in the response callback of your ajax request
  $.get("test.php?testnum=121212121",function(data){
    if(data == "no") {
      window.location.href = "failure.html";
    } else {
      window.location.href = "http://www.abc.com/get_data.php?data="+data;
    }
});

Chrome aborts the ajax request because window.location.href = "http://google.com"; makes the browser load google.com.
i can't give you a full code sample because i'm not sure what you are trying to achieve

A: Change the anchor href
href="#"

to
href="javascript:void(0);"


text:
Q: Hosting two SSL sites (different host name) on same server with different certificates and without ports (i.e. 443) We have a SharePoint site https://example.com hosted on port 443.
There is another site https://anotherexample.com that should be hosted on same server and without port (i.e. 443).
Both the certificates are issued to different host names (i.e. not wildcard certificate).
How can I achieve above scenario?
Any help is much appreciated!
Edit: I'm working on IIS 8.

A: Best way to achieve this on IIS 8 is to use Server Name Indication. It allows the server to host multiple certificates for multiple sites under a single IP address.
For more detailed instructions, please refer here.


text:
Q: Как обновить версию php на Ubuntu 16.04 Пытался обновить версию php на сервере Ubuntu 16.04 до 7.3. После установки пишет:

NOTICE: Not enabling PHP 7.3 FPM by default.
NOTICE: To enable PHP 7.3 FPM in Apache2 do:
NOTICE: a2enmod proxy_fcgi setenvif
NOTICE: a2enconf php7.3-fpm

При проверке версии на сервер пишет что версия php 7.3. При проверке через какталог в корне сайта пишет, что версия 7.0. Wordpress тоже видит 7.0. После удаления версии php 7.0 с сервера на открываются сайты (500 Internal Server Error).
Как мне обновить  и включить последнюю версию php ?


text:
Q: How can I estimate how much elemental Damage over time I'll cause? The hardest part of playing Siren is figuring out exactly how much Elemental Damage you're dealing with Damage Over Time (DOT) effects. They're complicated. I'd like to put together a formula to judge about how much damage per second I'm doing over a period of time. I know all the stats that go into DOT, but I can't quite piece it all together into a function.
What I really want to know is how much DOT damage will happen over a given Length of time, given DOT damage, DOT % (per shot), Rate of Fire (chances to add DOT). I don't care about bullet damage, that's easy to work out. And yes I know any estimation will be overly optimistic, but so are simple bullet damage DPS stats.
First we have the damage per second listed on the gun. This damage in reality is going to be affected by level of target - attacker then multiplied by the multiplication factor as noted in this damage table. We're going to ignore all of that as those multipliers can be added after our equation. We'll call this DOT damage.
Second we have our chance to add a Status Effect DOT. This is made up of the value on the gun plus the value added from skills, plus the Badass Rank bonuses, plus any relevant  Percentages are combined additively, though the value is always 0 if the gun's effect chance is 0. We'll just call this combined chance DOT %.
Third we have the DOT length which I spell out here; 5 seconds for fire, 2 for Shock, 8 for Corrode. We'll call this DOT Length. Each DOT lasts only this long, so DOT stacks will constantly be added and expire after this time has been reached for the first stack.
Fourth we have Rate of Fire; the bullets hitting the target per second. We'll go ahead and assume 100% of the bullets hit the target since this is a theoretical measure.
Finally we have the Length of time the target is under fire, from the first bullet's impact to the last. This is what we'll divide total damage by and how we'll know
So putting it together we have DOT Damage multiplied by the current number of stacks, stacks expiring by DOT Length after they start and spawning by (Rate of Fire multiplied by DOT %) for period Length. The stacks starting and stopping is the hardest part. I'm not sure if that can be modeled, but a measure using something like "average stacks at any given time" would be acceptable.
I have all the pieces (if I'm missing something just ask, I probably know it), I just can't figure out how to put them together considering DOT expiration. If anyone can put together a formula for all this that would be a very valuable resource for Sirens everywhere. Can this be modeled?

A: As you said, these are all the pieces already. If what I'd figure is your question it's easy to answer:
"How much damage would I do if I fire for $Length time?"
$Length * $RoF = X rounds
X rounds * $damage = gunDamage
X rounds * $DOT% = avgDotAmount
DoTs are smart in this game, they all have their separate timers and can stack independently from one another. This makes the damage as intuitive as possible:
dotDamage = avgDotAmount * ticks(element)
totalDamage = (gunDamage + dotDamage) * multiplier(element)
As this was far too easy to answer, I can only assume your question would be like
"When can I stop firing, knowing that my DoTs will kill the enemy?"
To which the answer would be "Never, unless the target isn't currently affected, then keep firing."
To us human player at least; for all the data is there in the fountain of numbers that spew from the target you are perforating with bullets. Would we be perfect computers, we could see when a new dot starts ticking(it wouldn't have a previous tick before it) and thus know exactly how many ticks are left. Being human, all we can say is "it's on fire" or "it's not on fire." This makes knowing for SURE your target is going to die impossible, the best one could do is make a normal distribution  graph(wiki) with the probabilities if your target will die.
If that's really what you'd want, I could run it through some model, but it's still gonna be a pretty useless graph.  Input the specific gun and skills you're using, and you could get a graph with probabilities mapped vs dotDamage. Even if you could watch that while shooting things, you can only guess how much health your target has left.
If instead, and my final guess, the question would be "How much do I overkill?" that amounts to the same, as that is also "Amount of dotDamage still to be done."


text:
Q: Looking for a way to make a loop that rejects an input with any other hour format other than the one specified Im having trouble creating a code on C that after letting the user input an hour it determines if the hour is in a valid 24 hour format and written as HH:MM, in the case it isn't it loops back and lets him input the hour indefinitely until it is a possible hour, any help would be greatly appreciated. Here's my code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

bool format_correct(char format[]);
int looper;
char hour[] = "11:11";

int main()
{
while (looper == 1);{

printf("insert time in format HH:MM\n");
scanf("%s", &hour);

  if ((hour < 25) && format_correct(hour)){
    printf("%s is a correct hour",hour);
    looper ++;
    }
  else
    printf("incorrect format, introduce time in format HH:MM \n");

  return 0;
  }
}

bool format_correct(char format[])
{
  if (strlen(format) != 5) return false;
  if (!isdigit(format[0])) return false;
  if (!isdigit(format[1])) return false;
  if (format[2] != ":") return false;
  if (!isdigit(format[3])) return false;
  if (!isdigit(format[4])) return false;

}