text:
Q: AR with OpenCV & OpenGL Here's the problem: I wrote a code to display the OpenGL teapot on a sheet of paper with drawing. For this, I track the 4 corners of the paper (using SURF detection & matching followed by computing the homography matrix, then moving average of the corners position to reduce the jitter). The corners coordinates are used to compute the intrinsic & extrinsic matrices of the camera (using calibrateCamera() and solvePnP(), respectively). The rotation matrix is then computed using Rodrigues(). Afterwards, I computed the rotation angles using decomposeProjectionMatrix(). Here's the OpenCV part of the code:
...
objPoints.push_back(objCorners);
scenePoints.push_back(sceneCorners);
calibrateCamera(objPoints, scenePoints, Size(640,480), camMtx, distortCoeff, RVecs, tVecs);
solvePnP(objCorners, sceneCorners, camMtx, distortCoeff, RVec, tVec);
Rodrigues(RVec, rotMtx);
getAngles(rotMtx, rotAngles);

objCorners are the corners coordinates in the template image ([1 1], [img width 1], [img width img height], [1 img height]). sceneCorners are the corners coordinates in the webcam frame, computed using the homography matrix. The function getAngles() is as follows:
void getAngles(Mat &rotCamMtx, Vec3d &angles)
{
    Mat camMtx, rotMtx, transVec, rotMtxX, rotMtxY, rotMtxZ;
    double  *r = rotCamMtx.ptr<double>();
    double projMtx[12] = {r[0], r[1], r[2], 0,
                          r[3], r[4], r[5], 0,
                          r[6], r[7], r[8], 0};

    decomposeProjectionMatrix(Mat(3,4,CV_64FC1,projMtx), camMtx, rotMtx, transVec, rotMtxX, rotMtxY, rotMtxZ, angles);
}

Then I set the element of the OpenGL model view matrix as follows:
modelViewMat[0]  = 1.0;
modelViewMat[1]  = 0.0;
modelViewMat[2]  = 0.0;
modelViewMat[3]  = 0.0;
modelViewMat[4]  = 0.0;
modelViewMat[5]  = 1.0;
modelViewMat[6]  = 0.0;
modelViewMat[7]  = 0.0;
modelViewMat[8]  = 0.0;
modelViewMat[9]  = 0.0;
modelViewMat[10] = 1.0;
modelViewMat[11] = 0.0;
modelViewMat[12] = 2*matCenter.x/639 - 641/639;
modelViewMat[13] = 481/479 - 2*matCenter.y/479;
modelViewMat[14] = -0.25;
modelViewMat[15] = 1.0;

matCenter is the center coordinate of the paper, obtained by taking the average of the 4 corners. The values in modelViewMat[12] and modelViewMat[13] are obtained by mapping the pixel coordinates ([1 640], [1 480]) to ([-1 1], [1 -1]). The OpenGL part of the code:
...
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

glMatrixMode(GL_MODELVIEW);
glLoadMatrixd(modelViewMat);

glRotated(-45, 1.0, 0.0, 0.0);
glRotated(rotAngles[2], 0.0, 1.0, 0.0);

glShadeModel(GL_SMOOTH);
glColor3f(1.0, 1.0, 1.0);
glutSolidTeapot(0.3);

I rotated the teapot -45 degrees around x-axis to make it appears "sitting" on the paper.
The result is this: if I translate the paper on the desk, the location of the teapot on the paper is more or less correct (on the same spot). If I rotate the paper, the teapot will follow the rotation correctly (around y-axis), but the location is no more correct. The question is: how to "pin" the teapot always on the same spot of the paper? I've tried using the result of Rodrigues() and solvePnP() directly in the OpenGL model view matrix (as suggested in OpenCV + OpenGL: proper camera pose using solvePnP), but the result is incorrect.

A: Solved this problem several days ago, based on the code from http://blog.yarrago.com/2011/08/introduction-to-augmented-reality.html. To display the 3D object correctly, the OpenGL projection matrix is set first, followed by the OpenGL model view matrix. The elements of the projection matrix are computed from the intrinsic matrix of the camera as follows:
calibrateCamera(objPoints, scenePoints, Size(640,480), camMtx, distortCoeff, RVecs, tVecs);
...
projectionMat[0]  = 2*camMtx.at<double>(0,0)/frameW;
projectionMat[1]  = 0;
projectionMat[2]  = 0;
projectionMat[3]  = 0;
projectionMat[4]  = 0;
projectionMat[5]  = 2*camMtx.at<double>(1,1)/frameH;
projectionMat[6]  = 0;
projectionMat[7]  = 0;
projectionMat[8]  = 1 - 2*camMtx.at<double>(0,2)/frameW;
projectionMat[9]  = -1 + (2*camMtx.at<double>(1,2) + 2)/frameH;
projectionMat[10] = (zNear + zFar)/(zNear - zFar);
projectionMat[11] = -1;
projectionMat[12] = 0;
projectionMat[13] = 0;
projectionMat[14] = 2*zNear*zFar/(zNear - zFar);
projectionMat[15] = 0;

frameW and frameH are 640 and 480, respectively. zNear is 0.1 and zFar is 100.
The elements of the OpenGL model view matrix are computed from the rotation matrix and the translation vector (obtained from solvePnP() and Rodrigues()). To get a correct positioning of the 3D object, the translation vector needs to be transformed before computing the model view matrix.
// Offset value to move the translation vector
double offsetC[3][1] = {424, 600, 0};
Mat    offset(3, 1, CV_64F, offsetC);
...
solvePnP(objCorners, sceneCorners, camMtx, distortCoeff, RVec, tVec);
Rodrigues(RVec, rotMtx);
tVec = tVec + rotMtx*offset;    // Move tVec to refer to the center of the paper
tVec = tVec / 250.0;            // Converting pixel coordinates to OpenGL world coordinates
...
modelviewMat[0]  = rotMtx.at<double>(0,0);
modelviewMat[1]  = -rotMtx.at<double>(1,0);
modelviewMat[2]  = -rotMtx.at<double>(2,0);
modelviewMat[3]  = 0;
modelviewMat[4]  = rotMtx.at<double>(0,1);
modelviewMat[5]  = -rotMtx.at<double>(1,1);
modelviewMat[6]  = -rotMtx.at<double>(2,1);
modelviewMat[7]  = 0;
modelviewMat[8]  = rotMtx.at<double>(0,2);
modelviewMat[9]  = -rotMtx.at<double>(1,2);
modelviewMat[10] = -rotMtx.at<double>(2,2);
modelviewMat[11] = 0;
modelviewMat[12] = tVec.at<double>(0,0);
modelviewMat[13] = -tVec.at<double>(1,0);
modelviewMat[14] = -tVec.at<double>(2,0);
modelviewMat[15] = 1;

The numerical values for offsetC is the pixel coordinate of the center of the paper. The OpenGL part of the code is then:
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(projectionMat);

glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(modelviewMat);

glRotatef(90, -1.0, 0.0, 0.0);  // Rotate the teapot first so that it will be displayed correctly on the paper
glutSolidTeapot(1.0);

One important thing for the correct positioning of the teapot is the transformation of tVec.


text:
Q: lxml: some XML from URL give this lxml.etree.XMLSyntaxError I have a script which is suppose to extract some terms from XML files from a list of URLs.
All the URL's give access to XML data.
It is working fine at first opening, parsing and extracting correctly but then get interrupted in the process by some XML files with this error:
File "<stdin>", line 18, in <module>
  File "lxml.etree.pyx", line 2953, in lxml.etree.parse (src/lxml/lxml.etree.c:56204)
  File "parser.pxi", line 1555, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:82511)
  File "parser.pxi", line 1585, in lxml.etree._parseFilelikeDocument (src/lxml/lxml.etree.c:82832)
  File "parser.pxi", line 1468, in lxml.etree._parseDocFromFilelike (src/lxml/lxml.etree.c:81688)
  File "parser.pxi", line 1024, in lxml.etree._BaseParser._parseDocFromFilelike (src/lxml/lxml.etree.c:78735)
  File "parser.pxi", line 569, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:74472)
  File "parser.pxi", line 650, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:75363)
  File "parser.pxi", line 590, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74696)
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1

From my search it might be because some XML files have white spaces but i'm not sure if it is the problem. I can't tell which files give the error.
Is there a way to get around this error?
Here is my script:
URLlist = ["http://www.uniprot.org/uniprot/"+x+".xml" for x in IDlist]
for id, item in zip(IDlist, URLlist):
    goterm_location = []
    goterm_function = []
    goterm_process = []
    location_list[id] = []
    function_list[id] = []
    biological_list[id] = []
    try:
        textfile = urllib2.urlopen(item);
    except urllib2.HTTPError:
        print("URL", item, "could not be read.")
        continue
    #Try to solve empty line error#
    tree = etree.parse(textfile);
    #root = tree.getroot()
    for node in tree.iter('{http://uniprot.org/uniprot}dbReference'):
        if node.attrib.get('type') == 'GO':
            for child in node:
                value = child.attrib.get('value');
                if value.startswith('C:'):
                    goterm_C = node.attrib.get('id')
                    if goterm_C:
                        location_list[id].append(goterm_C);
                if value.startswith('F:'):
                    goterm_F = node.attrib.get('id')
                    if goterm_F:
                        function_list[id].append(goterm_F);
                if value.startswith('P:'):
                    goterm_P = node.attrib.get('id')
                    if goterm_P:
                        biological_list[id].append(goterm_P);

I have tried:
tree = etree.iterparse(textfile, events = ("start","end"));
OR
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(textfile, parser)

Without success.
Any help would be greatly appreciated

A:
I can't tell which files give the error

Debug by printing the name of the file/URL prior to parsing. Then you'll see which file(s) cause the error.
Also, read the error message:
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1

this suggests that the downloaded XML file is empty. Once you have determined the URL(s) that cause the problem, try downloading the file and check its contents. I suspect it might be empty.
You can ignore problematic files (empty or otherwise syntactically invalid) by using a try/except block when parsing:
try:
    tree = etree.parse(textfile)
except lxml.etree.XMLSyntaxError:
    print 'Skipping invalid XML from URL {}'.format(item)
    continue    # go on to the next URL

Or you could check just for empty files by checking the 'Content-length' header, or even by reading the resource returned by urlopen(), but I think that the above is better as it will also catch other potential errors.

A: I got the same error message in Python 3.6
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1

In my case the xml file is not empty. Issue is because of encoding,
Initially used utf-8,
from lxml import etree
etree.iterparse(my_xml_file.xml, tag='MyTag', encoding='utf-8')

changing encoding to iso-8859-1 solved my issue,
etree.iterparse(my_xml_file.xml, tag='MyTag', encoding='iso-8859-1')

redpajama_set_name: RedPajamaStackExchange


text:
Q: can't get the output from javascript var weightkg=document.getElementById('weight').value;

    var heightinm=document.getElementById('height').value;

    function bmival (weightkg,heightinm){

        var hout=heightinm*2
        var output=weightkg/hout
        //make a full number
             // var r= Math.trunc(o)

         if (output<=18.5){
            return document.getElementById('print').innerHTML=`Your BMI is ${output} you are underweight` ;
         }

         else if(output>18.5 && o<25.5){
            return document.getElementById('print').innerHTML=`Your BMI is ${output} You come under fit catogery`;
         }

         else{
            return document.getElementById('print').innerHTML=`Your BMI is ${output} you are overweight and obese`;
         }
     }

[i am making a bmi cal that take input from user but i am getting a error and don't know what i am doing wrong]
**
this is js code and when i run i get a NaN instead of Number  **

A: The values from an input field are strings so you must convert them into numbers

var heightinm = +document.getElementById('height').value; // one way to do it.

A: The value you get from
var weightkg=document.getElementById('weight').value;

seems to be a string instead of number. You need to convert values to do Math operations on them. NaN tells you output is not a number. Turn your values to number with parseInt method.
var weightkg = parseInt(document.getElementById('weight').value);

or you can just put a "+" to convert a string into number
var weightkg = +document.getElementById('weight').value;

For Example.
const input = document.getElementById('input');
const defaultStringInput = document.getElementById('input').value;
const inputConverted = parseInt(document.getElementById('input').value);
const inputConverted2 = +document.getElementById('input').value;
input.addEventListener('change', () => {

  console.log(typeof defaultStringInput); // string
  console.log(typeof inputConverted); // number
  console.log(typeof inputConverted2); // number
});


text:
Q: How to write streaming data to S3? I want to write RDD[String] to Amazon S3 in Spark Streaming using Scala. These are basically JSON strings. Not sure how to do it more efficiently.
I found this post, in which the library spark-s3 is used. The idea is to create SparkContext and then SQLContext. After this the author of the post does something like this:
myDstream.foreachRDD { rdd =>
      rdd.toDF().write
                .format("com.knoldus.spark.s3")
                .option("accessKey","s3_access_key")
                .option("secretKey","s3_secret_key")
                .option("bucket","bucket_name")
                .option("fileType","json")
                .save("sample.json")
}

What are another options besides spark-s3? Is it possible to append the file on S3 with the streaming data?

A: Files on S3 cannot be appended. An "append" means in S3 to replace the existing object with a new object that contains the additional data.

A: You should take a look into mode method for dataframewriter in Spark Documentation:

public DataFrameWriter mode(SaveMode saveMode)
Specifies the behavior when data or table already exists. Options
  include: - SaveMode.Overwrite: overwrite the existing data. -
  SaveMode.Append: append the data. - SaveMode.Ignore: ignore the
  operation (i.e. no-op). - SaveMode.ErrorIfExists: default option,
  throw an exception at runtime.

You can try somethling like this with Append savemode.
rdd.toDF.write
        .format("json")
        .mode(SaveMode.Append)
        .saveAsTextFile("s3://iiiii/ttttt.json");

Spark Append:

Append mode means that when saving a DataFrame to a data source, if
  data/table already exists, contents of the DataFrame are expected to
  be appended to existing data.

Basically you can choose which format you want as an output format by passing "format" keyword to method

public DataFrameWriter format(java.lang.String source)
Specifies the underlying output data source. Built-in options include "parquet", "json", etc.

eg as parquet:
df.write().format("parquet").save("yourfile.parquet")
or as json:
df.write().format("json").save("yourfile.json")

Edit: Added details about s3 credentials:
there are two different options how to set credentials and we can see this in SparkHadoopUtil.scala
with environment variables System.getenv("AWS_ACCESS_KEY_ID")  or with spark.hadoop.foo property:
SparkHadoopUtil.scala:
if (key.startsWith("spark.hadoop.")) {
          hadoopConf.set(key.substring("spark.hadoop.".length), value)
}

so, you need to get hadoopConfiguration in javaSparkContext.hadoopConfiguration() or scalaSparkContext.hadoopConfiguration and set
hadoopConfiguration.set("fs.s3.awsAccessKeyId", myAccessKey)
hadoopConfiguration.set("fs.s3.awsSecretAccessKey", mySecretKey)


text:
Q: Is it possible for the Python compiler to optimize away some integer arithmetic? Inspired by this question about Python caching small integers.
Is it possible for the Python compiler to replace (0 - 6) with -6 at compile time? The code below suggests that it does not. If it is not possible, why not? I don't think that the meaning of 0, -, or 6 can be different at run time.
If this is possible, why does CPython not do it?
# test_integers.py
def test_integers():
    print "-6 is -6 ?", -6 is -6 # True
    print "(0 - 6) is -6 ?", (0 - 6) is -6 # False

# import_test_integers.py
import test_integers
test_integers.test_integers()

My Python details in case this is very implementation-dependent:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2

A: First, you shouldn't be using is to compare integer values to detect optimizations.  That has nothing to do with anything, as explained in the question you linked.  If you want to know what optimizations were performed on your function, use the dis module, which produces (in 2.7.2, after fixing your -1 typo):
>>> import dis
>>>
>>> def test_integers():
...     print "-6 is -6 ?", -6 is -6 # True
...     print "(0-6) is -6 ?", (0 - 6) is -6 # False
...
>>> dis.dis(test_integers)
  2           0 LOAD_CONST               1 ('-6 is -6 ?')
              3 PRINT_ITEM
              4 LOAD_CONST               2 (-6)
              7 LOAD_CONST               2 (-6)
             10 COMPARE_OP               8 (is)
             13 PRINT_ITEM
             14 PRINT_NEWLINE

  3          15 LOAD_CONST               3 ('(0-6) is -6 ?')
             18 PRINT_ITEM
             19 LOAD_CONST               6 (-6)
             22 LOAD_CONST               2 (-6)
             25 COMPARE_OP               8 (is)
             28 PRINT_ITEM
             29 PRINT_NEWLINE
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE

and you see that the subtraction actually was optimized away.  You can see some others, too:
>>> def f():
...     x = 1+2
...     x = 2-3
...     x = 3*4
...     x = 4/5
...     x = 5**6
...
>>> dis.dis(f)
  2           0 LOAD_CONST               7 (3)
              3 STORE_FAST               0 (x)

  3           6 LOAD_CONST               8 (-1)
              9 STORE_FAST               0 (x)

  4          12 LOAD_CONST               9 (12)
             15 STORE_FAST               0 (x)

  5          18 LOAD_CONST               4 (4)
             21 LOAD_CONST               5 (5)
             24 BINARY_DIVIDE
             25 STORE_FAST               0 (x)

  6          28 LOAD_CONST              10 (15625)
             31 STORE_FAST               0 (x)
             34 LOAD_CONST               0 (None)
             37 RETURN_VALUE


text: Q: c9.io-failed to preview web page I am working on sails js project in cloud9.io and getting this problem. There is no error in my code shown by console. I have mysql connection which is establishing well and also it shows phpmyadmin's home page but it is not showing my web page when I click to "preview with web server".


text:
Q: Android How to achieve two screens,two activities,and they are independent I am a novice at Android, now, I need write a android app:two screens also shows two activities, boradcast advertising on the big screen, the small screen can be operated, and they are independent of each other.When people operate the small screen, the advertising will still play. I found the presentation class in the android 4.4 API 20,with it I can realize the two screens display different contents, I also refer to the Google demo, but Because the presentation depends on the specific activity, when the small screen operated, then intent to another activity, before playing advertising presentation disappeared. Then I came up with a method: The application only have one activity, the small screen using many fragments, but because the following screen operation is very complicated, it would be more trouble with fragment, my friends advised me not to use fragment, but I can't find other methods,who can help me?thank you very much(My English is poor,sorry)

A: Here is a detailed tutorial of Fragment. In my opinion, you'll be able to achieve what you want, only by using fragments :
http://www.vogella.com/tutorials/AndroidFragments/article.html


text:
Q: Measuring response time of external systems on Apache web server Our website has been developed in PHP, running on Apache web server. We use MySQL, Apache Solr, Memcached among other external systems.
I am looking for a server side tool / Apache module that will help us measure the response time of database, Solr and other systems while loading a page.
Thanks

A: It doesn't exist.  Any such module would need to be completely customized for the site using it.  For example, you use MySQL, Solr, and Memcahed, but some other site uses PGSQL, Redis, and APC caching.  It would be impossible for one module to support all of that.
The best you can really do is setup Icinga or similar to do some health checks.  You can combine that with one of the various graphing addons for it to generate response time graphs.  This will get you close, but it's only going to get per-server graphs, not per-page-load graphs.

A: Answering my question.
Not the same that we were looking for, but XHProf by Facebook https://github.com/facebook/xhprof provided us with a lot of statistics, including the above.


text:
Q: Max number of familiars? In Blood Brothers, what's the max number of familiars you can hold? My current limit is 50. Is there anything I can do to increase the max count?

A: As you progress through the games quests, you will unlock more formations and your capacity will increment by 2 each time you trigger that reward. When I played I had a capacity of 62 familiars.

A: I heard the limit was removed. I have 74.


text:
Q: Why does my background music stop when the player object gets destroyed? I work with Unity 5.5.4 and I'm still learning.
My problem is when the player(object) gets destroyed(destroy(gameobject)), my backgroud music stops playing, even if I place my music in Arenamanager(gameobject), not in player(gameobject).
I don't have a function like audio.stop or something like that in my script and I already untagged the player(gameobject) and I still can't solve it.
Here is my death function:
Void Death() {
    Instantiate(explosion, transform.position, transform.rotation);
    Destroy(this.gameobject);
}

A: Your player is most likely holding the AudioListener.
So when you destroy, there is nothing left to listen to your music.


text:
Q: se puede relacionar una misma tabla más de una vez en otra? EF code-first Estoy empezando a programar y tengo un problema en el cual no he logrado encontrar solución.
tengo una clase "student" y en ella necesito capturar el id de sus parientes (mamá,papá y acudiente), para almacenar estos tres datos tengo la clase llamada "terceros".
mi pregunta es, puedo almacenar varios "foreing key" en la tabla "student" de la clase "terceros"? si es así, cómo puedo hacerlo? tengo el siguiente modelo, donde FatherID, MotherID y StudentMangerID serían los campos relacionados con la tabla terceros
public class Student
    {
 otro código....

        [Display(Name = "Rh")]
        public int? RhID { get; set; }

        [Display(Name = "Padre")]
        public int? FatherID { get; set; }

        [Display(Name = "Madre")]
        public int? MotherID { get; set; }

        [Display(Name = "Acudiente")]
        public int? StudentMangerID { get; set; }
....

        public virtual ThirdParties ThirdParties{ get; set; }

        public virtual Rh Rh { get; set; }
 }

al hacer la migración me doy cuenta que en student se crea otro campo llamado ThirdParties_ThirdPartiesID, y creo que eso no debería pasar puesto que he puesto el virtual,así que siento que no lo estoy haciendo del todo bien. Muchas gracias de antemano.

A: Lo mejor seria tener una Colección de ThirdParties, para simular la relacion de uno a muchos que tienes.
Quedaría algo así.
public ICollection<ThirdParties> ThirdParties { get; set; }

De esta manera tienes la posibilidad de guardar varios parientes para un Student.


text:
Q: Are the old httpHandlers and httpModules elements needed in IIS7? I'd like to clean up the web.config and remove unneeded XML.
A default ASP.NET 3.5 web application has the follow elements in the web.config:
<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>

<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>

When running under IIS7, which has modules and handlers being registered under the system.webServer element, is the configuration above still needed?

A: Yes, if you are running only on IIS7 you may remove the httpHandlers and httModules sections.
As you can see, the same types are being registered using slightly difference schemas.


text:
Q: Leaflet toggle marker clustering I am using the Leaflet markercluster plug in, and now want to add a button to turn the clustering on/off. For that I wanted to use the leaflet button plug in, because I am already using it in my code.
I tried around with this piece of code and customized the lines with "sidebar" in it.
var button = new L.Control.Button('Toggle me', {
toggleButton: 'active'
});
button.addTo(map);
button.on('click', function () {
if (button.isToggled()) {
    sidebar.hide();
} else {
    sidebar.show();
}
});

I also have an overlay where I want to implement those layers then.
How I cluster my markers:
var extern2 = L.markerClusterGroup();
extern2.addLayer(extern);

A: You have two layers, where extern layer contains original markers and extern2 contains clustered markers. What you have to do in toggle control is just to add one layer to the map and remove the other.
Assuming that initially plain markers (non clustered) are shown, code could look something like this:
var extern2 = L.markerClusterGroup();
extern2.addLayer(extern);

map.addLayer(extern);

var button = new L.Control.Button('Show clusters', {
  toggleButton: 'active'
});
button.addTo(map);

button.on('click', function () {
  var txt;
  var controlElement = button.getContainer();
  if (button.isToggled()) {
    txt = 'Show clusters';
    map.removeLayer(extern2);
    map.addLayer(extern);
    }
  else {
    txt = 'Show markers';
    map.removeLayer(extern);
    map.addLayer(extern2);
  }
  controlElement.innerHTML = txt;
});


text:
Q: How to remotely run xcode bots There are mac osx server (slave) and another jenkins server (master). I would like to remotely order building and testing of my ios application on osx server from jenkins server.  I would like to use xcode bots on osx server but I don't know how to manage bots from terminal. How to do it ? Is it possible to use bots as a part of bigger continuous integration system, or I have to set up jenkins server on my osx server ?

A: You can now manage and edit bots from Xcode 9 by logging in to
Xcode Preferences > Accounts > + button

then go to Report Navigator to see your server

If you just want to integrate or see the status, you can actually access it from the browser. /xcode
example: https://XX.XX.XX.XX/xcode
here's a good reference: https://medium.com/xcblog/xcode9-xcode-server-comprehensive-ios-continuous-integration-3613a7973b48

A: I'm not sure you can manage OSX bots without using the Xcode connected to your Xcode server.
Anyway Xcode server is still very limited and you wont be able to do what you can do with Jenkins with multiple steps (ie if you use Cocoapods or if you want to deploy something at the end of the build)
If you are using Jenkins on a master server I think the best thing to do is to use your Mac server as slave via SSH to allow your Jenkins to build your iOS projects on it.


text:
Q: How to add additional data in the form and pass it to the POST action method without getting security error I have an login form where I have div with longitude and lattitude of the user and I would like to pass it to the POST Login action method:

            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" })) {
                @Html.AntiForgeryToken()

Use a local account to log in.

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })

                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })

                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)

 //COORDINATES ARE HERE

                        <input type="submit" value="Log in" class="btn btn-default" />

                    @Html.ActionLink("Register as a new user", "Register")

                @* Enable this once you have account confirmation enabled for password reset functionality

                        @Html.ActionLink("Forgot your password?", "ForgotPassword")

*@

            }

Which translates to:

The action method looks like:
 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {
            if (ModelState.IsValid) {
                var user = await UserManager.FindAsync(model.Email, model.Password);
                if (user != null) {
                    //MY CODE
                    //Request.ServerVariables["REMOTE_ADDR"] alternatywnie aby pobrac ip uzytkownika
                    ApplicationUser userSecondInstance = db.Users.Find(user.Id);
                    ApplicationUserAction action = new ApplicationUserAction { Description = "Logged in at " + DateTime.Now + " from IP " + Request.UserHostAddress + ".", TimeStamp = DateTime.Now, Actor = userSecondInstance };
                    db.ApplicationUserActions.Add(action);
                    db.SaveChanges();
                    //END OF MY CODE
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                } else {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

I would like to pass to the action methods contents of the

. How to grab them on the server side?

EDIT:
I have tried that in the form:
<input type="hidden" id="coordinates" name="coordinates">

then
 public async Task<ActionResult> Login(LoginViewModel model, string returnUrl, string coordinates) {
            System.Diagnostics.Debug.WriteLine("HERE " + coordinates);

but unfortunately I get an exception:
Wykryto potencjalnie niebezpieczną wartość Request.Form pochodzącą z klienta (coordinates="...52.1372583
Longitude: 20.66...").

Which means:
Potentailly dangerous value of Request.Form has been detected: (coordinates="...52.1372583
Longitude: 20.66...").

A: I don't know asp.net
Nevertheless you can make use of Hidden input elements inside the form.
in pure html format:
<input type="hidden" name="Longitude" value="12.22323231">
<input type="hidden" name="Lattitude" value="77.11235813">

Hope this helps. Else comment, I will delete the answer

A: First of all, create a properties for Latitude, Longitude, and Accuracy in LoginViewModel. Then, use Html.HiddenFor to render it. It will automatically post and bind it to LoginViewModel
Edit:
View Model:
public class LoginViewModel
{
    public string Email {get; set;}
    ...
    public double Latitude {get; set;}
    public double Longitude {get; set;}
    public double Accuracy {get; set;}

}

View:

            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" })) {
                @Html.AntiForgeryToken()

Use a local account to log in.

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })

                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })

                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)

            @*Include these*@
            @Html.HiddenFor(m => m.Latitude)
            @Html.HiddenFor(m => m.Longitude)
            @Html.HiddenFor(m => m.Accuracy)

 //COORDINATES ARE HERE

                        <input type="submit" value="Log in" class="btn btn-default" />

                    @Html.ActionLink("Register as a new user", "Register")

                @* Enable this once you have account confirmation enabled for password reset functionality

                        @Html.ActionLink("Forgot your password?", "ForgotPassword")

*@

            }

Controller Action:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    ...
}


text:
Q: Map Reduce - How to group and aggregate multiple attributes in a single job I am currently struggling a bit with MapReduce.
I have the following dataset:
1,John,Computer
2,Anne,Computer
3,John,Mobile
4,Julia,Mobile
5,Jack,Mobile
6,Jack,TV
7,John,Computer
8,Jack,TV
9,Jack,TV
10,Anne,Mobile
11,Anne,Computer
12,Julia,Mobile

Now I want to apply MapReduce with grouping and
aggregation on this data set, in order that the output
doesn't only show how many times which person bought something,
but also what the product is, which the person ordered most.
So the output should look like:
John 3 Computer
Anne 3 Mobile
Jack 4 TV
Julia 2 Mobile

My current implementation of the mapper as well as reducer
looks like that, which perfectly returns how many orders were
made by the individuals, however, I am really clueless how
to get the desired output.
static class CountMatchesMapper extends Mapper<Object,Text,Text,IntWritable> {
    @Override
    protected void map(Object key, Text value, Context ctx) throws IOException, InterruptedException {
        String row = value.toString();
        String[] row_part = row.split(",");

            try{
                ctx.write(new Text(row_part[1]), new IntWritable(1));

            catch (IOException e) {
            }
            catch (InterruptedException e) {
            }

        }

    }
}

static class CountMatchesReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context ctx) throws IOException, InterruptedException {
        int i = 0;
        for (IntWritable value : values) i += value.get();
        try{
            ctx.write(key, new IntWritable(i));
        }
        catch (IOException e) {
        }
        catch (InterruptedException e) {
        }
    }
}

I would really appreciate any efficient solution and help.
Thanks in advance!

A: If I understand correctly what you want, I think the 2nd output line should be:
Anne 3 Computer

based on the input. Anne has bought 3 products in total: 2 Computers and 1 Mobile.
I have here a very basic and simplistic approach, which doesn't take into account edge cases etc, but could give you some direction:
    static class CountMatchesMapper extends Mapper<LongWritable, Text, Text, Text> {
    private Text outputKey = new Text();
    private Text outputValue = new Text();

    @Override
    protected void map(LongWritable key, Text value, Context ctx) throws IOException, InterruptedException {
        String row = value.toString();
        String[] row_part = row.split(",");
        outputKey.set(row_part[1]);
        outputValue.set(row_part[2]);
        ctx.write(outputKey, outputValue);
    }
}

static class CountMatchesReducer extends Reducer<Text, Text, Text, NullWritable> {
    private Text output = new Text();

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context ctx) throws IOException, InterruptedException {
        HashMap<String, Integer> productCounts = new HashMap();

        int totalProductsBought = 0;
        for (Text value : values) {
            String productBought = value.toString();
            int count = 0;
            if (productCounts.containsKey(productBought)) {
                count = productCounts.get(productBought);
            }
            productCounts.put(productBought, count + 1);
            totalProductsBought += 1;
        }

        String topProduct = getTopProductForPerson(productCounts);
        output.set(key.toString() + " " + totalProductsBought + " " + topProduct);
        ctx.write(output, NullWritable.get());
    }

    private String getTopProductForPerson(Map<String, Integer> productCounts) {
        String topProduct = "";
        int maxCount = 0;
        for (Map.Entry<String, Integer> productCount : productCounts.entrySet()) {
            if (productCount.getValue() > maxCount) {
                maxCount = productCount.getValue();
                topProduct = productCount.getKey();
            }
        }
        return topProduct;
    }
}

The above will give the output that you described.
If you want a proper solution that scales etc then probably you need a composite key and custom GroupComparator. This way you will be able to add Combiner as well and make it much more efficient. However, the approach above should work for an average case.


text:
Q: React google-charts callback I want to create an event handler for Chart component from react-google-charts
Off. documentation has an example.
<Chart
    chartType="ScatterChart"
    rows={this.state.rows}
    columns={this.state.columns}
    options={this.state.options}
    graph_id="ScatterChart"
    width="100%"
    height="400px"
    chartEvents={this.chartEvents} // <- this is event handler
   />

chartEvents looks like
this.chartEvents=[
  {
    eventName : 'select',
    callback  : function(Chart) {
        console.log("Selected ",Chart.chart.getSelection());
    }
  }
];

How can I refer to class context from the callback function? I want to change my local state.
this.chartEvents=[
  {
    eventName : 'select',
    callback  : function(Chart) {
        // here I want to refer to this.setState
        console.log("Selected ",Chart.chart.getSelection());
    }
  }
];

A: I had the same need as you and was able to do it.
You can create a variable (superClass in the example below) and assign the value of the class (this) to it. This way you can still access it inside the scope of the callback.
const superClass = this;
this.chartEvents = [
  {
    eventName: 'select',
    callback(Chart) {
        // here you can refer to superClass.setState
        console.log("Selected ",Chart.chart.getSelection());
    },
  },
];


text:
Q: The AND gate 7408 electrical engineering I put an AND gate on my breadboard with all connections correct. I also mounted two  switches (SPST switches) at the inputs. My problems is when my two switches are on (the button pressed) the LED is off, when I turn the switches off (the button up) the LED is on.
I want to fix this, I want the led to turn on when the switch is on (the button is pressed) and vise versa.  Any suggestions?

A: If you can tie your switches to the +5V rail instead of ground, and put pull-down resistors from each of the inputs to ground you could make this work without extra gates.  Assuming what you want is for the output to go high when BOTH switches are on at the same time.

A: Add inverters in front of the gate inputs. For example, 1/6 of a 7404 on each. The switch is best used to pull a TTL input LOW so you have an inherently inverted function.

simulate this circuit – Schematic created using CircuitLab
Note that if you'd used a 7400 quad NAND gate you could have used one gate as an inverter on the output, giving you the AND function and the remaining two gates on the inputs.
Non inverting gates are not as flexible, which is probably why they're not as popular.

simulate this circuit
Note also that the equivalent to an AND gate with inverters on the inputs is a NOR gate.


text:
Q: is there any bug with math.sum(series, period)? when I use the math.sum() to sum the last several values, it gives me the wrong answer.only the period is 1, it will be ok.
for example:
// MACD hist
hist = [series]
math.sum(hist, 7)

does anyone also get the problem?

A: now I use this way to replace:
sumup := 0.0
for i = 1 to 7
    sumup := sumup + hist[i]


text:
Q: BCP File not loaded completely when Numeric value out of range error occurs for 10 times I am trying to import a tab delimited file in to SQL. One of the field in DB is decimal(15,2). But the file that I receive may have some exponential values like -2.702159776E17 which clearly does not fit for the field I have in DB.
The problem is if there are more than 10 records of that exponential file, BCP is not loading in the complete data. As soon as it is encountering the 10th instance of the exponential value, it is skipping the rest of the file.
I am using below BCP command to load the data:
dbname.dbo.tablename in "filelocation" -c -F 2 -b 10000 -h "TABLOCK" -T -S servername

The file I am trying to import has 200,000 records. But we can clearly see that it has processed only 18,000 records, rest are skipped. Output from the BCP as below.
Starting copy...
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range
SQLState = 22003, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Numeric value out of range

18149 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total     : 265    Average : (68486.79 rows per sec.)

A: Look into the following BCP option:

-m max_errors Specifies the maximum number of syntax errors that can occur before the bcp operation is canceled. A syntax error implies a
  data conversion error to the target data type. The max_errors total
  excludes any errors that can be detected only at the server, such as
  constraint violations.
A row that cannot be copied by the bcp utility is ignored and is
  counted as one error. If this option is not included, the default is
  10.

You can see that the default is 10 errors. Specify this parameter and supply a very large value if you want to skip all errors.
If you want to import all the records, you could import the records to a staging table that has the FLOAT data type instead of the DECIMAL(15,2). Then afterwards, copy the data from the staging table to the table you want the data in, by converting the float value to a decimal value.


text:
Q: programmatic access to "ip route show" Is there a way to access information available in
ip route show

command via some special file (or other method), the same way that output of
route -n

can be read from /proc/net/route? I know that I can just parse the output, but I am looking for something in more machine-readable format.

A: strace shows ip route show creating a NETLINK_ROUTE socket to get that: http://man7.org/linux/man-pages/man7/netlink.7.html

A: Same information is on "/proc/net/route". You could check that file, instead of capture standar output information from "netstat -n" command.

A: What specific information are you trying to get?
This is the perfect thing to use either cut, awk to pull the specific fields you want out of it.
Example:
ip route show |  awk '{print $1 " " $9 }'

Returns network subnet and source IP.

A: More recent versions of iproute2 support the -j argument that formats the output as JSON. Then you can extract the relevant data not with sed or awk, but with the jq tool.
$ ip route show dev eno1
default via 192.168.1.1 proto dhcp src 192.168.1.5 metric 1002
192.168.1.0/24 proto dhcp scope link src 192.168.1.5 metric 1002

$ ip -j route show dev eno1 | jq -r '.[].dst'
default
192.168.1.0/24

If you need it to be more machine readable than that (e.g. no default, no optional keys, separate netmask and destination), you might as well read from /proc/net/route directly, as others have suggested.


text:
Q: How to troubleshoot failed API calls to .NET project running over localhost? I have an API in a .NET project that I'm running with Visual Studio Mac (8.4.3). I run it in release mode, and it opens a browser window with localhost:5000. The browser window says "ok". However, when I try to hit endpoints in that API, it fails very quickly. When I ran this API (ie. same code) from another server and accessed it via proxy, it ran fine. For example, when I ran it on a server whose IP was 162.250.198.98 and proxied into it, I would hit an endpoint like 162.250.198.98:3000/api/user and it would work, but now when I try to run localhost:5000/api/user, either from my app or from Postman, it fails almost instantaneously. When running it in Postman, I tried what it suggested by turning off 'SSL certificate verification' in Settings, but no change.
Can anyone advise me on how to approach troubleshooting this?

A: Wait, so You are saying that while trying to call API on 162.250.198.98:3000/api/user You are fine but while trying to do the same thing on localhost:5000/api/user You are getting an error? Would it might be possible You have Your API configured to receive calls at 3000? :)?
No, but really - please chech it out, maybe it is that simple, I'm couting on it :).
You can change/check it in Visual Studio: main project > Properties > Debug > App URL.


text:
Q: Is it possible to kill a process based on its environment, from the command line? Scenario: Let's assume I have a script that spawns a few processes. There may be times when the script has to be aborted. Most times this is fine. However, sometimes one or two of the spawned processes remain running, and are orphaned, because the script has been killed.
Is there any way to find the processes based on their environment (specific environment strings and values set when the script ran/spawned them), and kill them?
OS: Windows 7

A: Powershell would be a good approach to tackling this problem. You can search the currently running processes and filter them by a number of fields. By storing the processes you want to kill in a variable you can kill them all in one swoop
Here is a TechNet Entry explaining about how to get processes in powershell:
https://technet.microsoft.com/en-us/library/ee176855.aspx
As seen in the image you can pipe in a where statement to filter the information that you need.


text:
Q: Vue 3 returns an error after running my project and compiling it with npm run dev Good day. I tried installing the dependencies of a Vue.JS app repository npm install.
Then, I run the Vue.JS app using npm run dev. However, after running it, it shows the following error in the terminal:
PS G:\malaysia-coronavirus> npm run dev

> malaysia-coronavirus@0.0.0 dev
> vite

node:events:504
      throw er; // Unhandled 'error' event
      ^

Error: spawn G:\malaysia-coronavirus\node_modules\esbuild\esbuild.exe ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:283:19)
    at onErrorNT (node:internal/child_process:478:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)
    at onErrorNT (node:internal/child_process:478:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'spawn G:\\malaysia-coronavirus\\node_modules\\esbuild\\esbuild.exe',
  path: 'G:\\malaysia-coronavirus\\node_modules\\esbuild\\esbuild.exe',
  spawnargs: [ '--service=0.12.15', '--ping' ]
}

How do I fix this? Did I do something wrong with the dependencies?
Are there any missing installation that I accidentally skipped?

A: I found a way to fix it. I just had to simply run:
node ./node_modules/esbuild/install.js
Answer from this thread: https://github.com/vitejs/vite/issues/1361#issuecomment-754442599


text:
Q: Generating permutations for all possible lengths I know there is a lot about permutations but I am looking for a more extended version.
Say in this very simple example I have {1,2,3,4} and my resulting set would be:
{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{2,3,4}

So you can see I am looking for an algorithm or solution that would help me find all permutations of length 1,2,...,n-1.
I hope I have provided enough information for you to help me.


text:
Q: Create index of title in a text box I am using text boxes into a document and each of them has a title with an increasing counter. I would like to create an index of the text boxes including therefore title, number and page.
An example of the code I use is the following:
    \begin{center}
    \fbox{
        \begin{minipage}[c]{0.85\textwidth}
            \textbf{\DoanString{TITLE OF BOX WITH NUMBER }:\\
                detailed title of box}
            \begin{itemize}
                \item text 1
                \item text 2
                \item text 3
            \end{itemize}
        \end{minipage}
    }
\end{center}


text: Q: Why does visual studio development server give 404 errors for some file types? I'm trying to test out visual studio development server and I get 404 errors for some file types.  For example if I have a file /Views/Users/SignIn.js it is rejected, where css are allowed. This same project works correctly in IIS Express.  I think it has something to do with allowed file types but I can't figure out how to enable them in isual studio development server. Any help would be appreciated.  Thanks


text:
Q: python azure sdk - To list storage account SKU I am using Python3 SDK for azure.
Here is version details of all the modules currently installed.
I want to list the Storage Account Types/SKU using SDK. Not sure how to do it.
azure-common (1.1.26)
azure-core (1.10.0)
azure-identity (1.5.0)
azure-keyvault-secrets (4.2.0)
azure-mgmt-compute (18.2.0)
azure-mgmt-core (1.2.2)
azure-mgmt-resource (15.0.0)
azure-mgmt-storage (16.0.0)
azure-storage-blob (12.7.1)
msrestazure (0.6.4)

Here is official link from Azure.But I want to list this information via code .

A: From azure-mgmt-storage==16.0.0, there is a list() method in the SkuOperations class. Since the method will return multiple skus for every region and storage kind available, you can use a set to remove duplicate SKU names.
from azure.mgmt.storage import StorageManagementClient
from azure.identity import DefaultAzureCredential

storage_client = StorageManagementClient(
    credential=DefaultAzureCredential(),
    subscription_id="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
)

skus = {sku.name for sku in storage_client.skus.list()}

print(skus)

Which outputs the following set:
{'Standard_GZRS', 'Standard_GRS', 'Standard_ZRS', 'Standard_RAGZRS', 'Premium_LRS', 'Premium_ZRS', 'Standard_LRS', 'Standard_RAGRS'}

If you simply want to list these skus, then you can iterate the set:
for sku in skus:
    print(sku)

Which outputs the SKUs on newlines like so:
Premium_LRS
Standard_GRS
Standard_GZRS
Premium_ZRS
Standard_LRS
Standard_RAGRS
Standard_RAGZRS
Standard_ZRS


text:
Q: Create User with Endpoint - Routing error User must be created from an API endpoint it has only one attribute :nick
I sent the Post request with PostMan but I have a routing error
Here are my routes:
  resources :users

In Users Controller I have  new and createaction, like so:
    def new
        @user = User.new
    end

    def create
    @user = User.new(user_params)

    if @user.save!
      head :created
    else
      head :no_content
    end
  end

In Postman :
I have selected Post and the url is http://localhost:3000/users/new
In Header I have:
Key                Value
Content-Type       Application/Json

Here is the body:
{
    "data": {
        "type": "user",
        "attributes": {
        "nick": "Liwis"
        }
    }
 }

When I send the request it returns that:
ActionController::RoutingError (No route matches [POST] "/users/new"):

actionpack (6.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:36:in `call'
web-console (4.0.1) lib/web_console/middleware.rb:132:in `call_app'
web-console (4.0.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (4.0.1) lib/web_console/middleware.rb:17:in `catch'
web-console (4.0.1) lib/web_console/middleware.rb:17:in `call'
actionpack (6.0.0) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (6.0.0) lib/rails/rack/logger.rb:38:in `call_app'
railties (6.0.0) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (6.0.0) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.0) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.0) lib/active_support/tagged_logging.rb:80:in `tagged'
railties (6.0.0) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (6.0.0) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (6.0.0) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.2.2) lib/rack/method_override.rb:24:in `call'
rack (2.2.2) lib/rack/runtime.rb:22:in `call'
activesupport (6.0.0) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (6.0.0) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.0) lib/action_dispatch/middleware/static.rb:126:in `call'
rack (2.2.2) lib/rack/sendfile.rb:110:in `call'
actionpack (6.0.0) lib/action_dispatch/middleware/host_authorization.rb:83:in `call'
webpacker (4.2.2) lib/webpacker/dev_server_proxy.rb:23:in `perform_request'
rack-proxy (0.6.5) lib/rack/proxy.rb:57:in `call'
railties (6.0.0) lib/rails/engine.rb:526:in `call'
puma (4.3.3) lib/puma/configuration.rb:228:in `call'
puma (4.3.3) lib/puma/server.rb:682:in `handle_request'
puma (4.3.3) lib/puma/server.rb:472:in `process_client'
puma (4.3.3) lib/puma/server.rb:328:in `block in run'
puma (4.3.3) lib/puma/thread_pool.rb:134:in `block in spawn_thread'


text:
Q: Is calling malloc() necessary for this example code? Assume following example code:
//open some file

char* data[10];

for ( int i=0; !feof(file) && i < 10; i++ )
{
    fgets( data[i], 100, file );
}

//close file

AFAIK using a pointer array without allocating memory to individual pointers like this is unsafe and if works, it's because there happens not to be any vital information contained at that memory region.
But I have seen many people using it like this and I doubted myself.
Is this a proper use?

A: Your code has undefined behavior and is extremely unsafe.
The elements of your data arrays are pointers, and their initial values are garbage. They could point to memory that's in use for some other purpose, or to memory that doesn't exist. I'd be surprised if your program didn't crash.
You don't need to call malloc. You could define
char data[10][100];

Furthermore, you shouldn't use feof to determine when you've finished reading input. feof returns a true value if the previous input function has failed due to running out of input. If there's an error other than running other than running out of input, ferror will return true and feof will not. Use the value returned by fgets to determine whether it succeeded.


text:
Q: Including row in left join where data doesn't exist I'm trying to create a query that shows me combined data between 2 tables
Currently the tables look like so:
person:ID,
Name,
Age

Form
ID,
Person_ID,
question,
answer

Example data would be
1 |Brandon| 55
2 |John |88
3 |Bob| 100

Form:
1 |1 |do you have diabetes |Y
2 |1 |do you take medications| Y
3 |1| how many times a week |7
4 |2|do you have diabetes |N

What I've tried is the following:
SELECT
p.Name
er1.answer,
er2.answer,
er3.answer
from person p
LEFT JOIN form er1 ON p.ID = er1.Person_ID
LEFT JOIN form er2 ON p.ID = er2.Person_ID
LEFT JOIN form er3 ON p.ID = er3.Person_ID
where er1.question='do you have diabetes'
and er2.question='do you take medications'
and er3.question='how many times a week'

The issue is that person 2 doesn't show up, because they answered No, the database didn't take in the other 2 questions. Is there a way to have the query search and pull the data and just have a null value there if it doesn't exist.

A: Move the conditions in the ON clauses and remove the WHERE clause:
SELECT
  p.Name,
  er1.answer,
  er2.answer,
  er3.answer
from person p
LEFT JOIN form er1 ON p.ID = er1.Person_ID AND er1.question='do you have diabetes'
LEFT JOIN form er2 ON p.ID = er2.Person_ID AND er2.question='do you take medications'
LEFT JOIN form er3 ON p.ID = er3.Person_ID AND er3.question='how many times a week'

It would be better if you gave proper aliases to the columns:
SELECT
  p.Name,
  er1.answer as `do you have diabetes`,
  er2.answer as `do you take medications`,
  er3.answer as `how many times a week`
from person p
LEFT JOIN form er1 ON p.ID = er1.Person_ID AND er1.question='do you have diabetes'
LEFT JOIN form er2 ON p.ID = er2.Person_ID AND er2.question='do you take medications'
LEFT JOIN form er3 ON p.ID = er3.Person_ID AND er3.question='how many times a week'

See the demo.
Results:
| Name    | do you have diabetes | do you take medications | how many times a week |
| ------- | -------------------- | ----------------------- | --------------------- |
| Brandon | Y                    | Y                       | 7                     |
| John    | N                    |                         |                       |
| Bob     |                      |                         |                       |

Now consider another way of getting the results you want with conditional aggregation:
select
  p.Name,
  max(case question when 'do you have diabetes' then answer end) as `do you have diabetes`,
  max(case question when 'do you take medications' then answer end) as `do you take medications`,
  max(case question when 'do you have diabetes' then answer end) as `how many times a week`
from person p LEFT JOIN form f ON p.ID = f.Person_ID
group by p.ID, p.Name

See the demo.


text:
Q: add css to :last-child but only if it's not :odd I have a list of dynamically generated divs and I have this script in order to make alternating background colors - for IE's sake.

My html:

...

I would like to apply a special css style to the :last-child, but only if the :last-child is not :odd - meaning only if it has a white background.
How do I do that?

A:  $(".box:last").not(':odd').css("background-color", "#f1f1f1");

A: CSS only:
.box:last-child:nth-child(even) { /* Special CSS here */ }

It's better than using jquery.

A: You can try this:
$(document).ready(function () {
    if($('.box').length-1%2!=0){
        $(".box:odd").filter(":last").css({"background":"red"});
    }
});

here is the fiddle:
http://jsfiddle.net/jYxeA/


text:
Q: PouchDB: is a destroy clean while doing live replication? I am having data corruption in my mobile app (Ionic 1), in very occasional cases.
The app is working with users logging to a remote CouchDB server. Each user has its own db in the server. There is only one session at a time in the app, but it may happen that user A uses the app, logs out, then user B logs in to use the app.
Locally, the app has one unique PouchDB, which is created on login, then live-synchronized with the user's remote couchDB, then destroyed on logout.
Problem: in very random and unfrequent cases that I cannot reproduce, some data of user A appear in the data of user B! and more over, some data of user A are destroyed (maybe transferred to B, not sure).
So, I was wondering what happens if I call PouchDB.destroy while a live sync is running (PouchDB.replicate with options { live: true, retry:true, continuous:true } in both ways: local to remote and remote to local). Is destroy doing something to cleanly stop the replication? If not, it might explain that some data are transferred from old-local A database to new-local B database (I have tried to browse the PouchDB source code but got lost in it. I could just see that Replication.cancel is called from its onDestroy method, but not sure it handles things right for my case).
Many thanks for any help!

A: The safest way to destroy a database during replication is to first call cancel() and then wait for the complete event. For instance:

var sync = db.sync(otherDB, {live: true, retry: true});
sync.on('complete', function () {
  db.destroy().then(/* ... */);
});
/* ... */
sync.cancel(); // will trigger a 'complete'

Hope that helps!


text:
Q: An error occurred while calling o2864.collect I have a RDD object(bid) that get from map, and then I just do a simple bid.count(). Then I received the following error. Can someone tell me what this error might be? I try to google what it means but got no answer.
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-10-0283df3b1938> in <module>()
----> 1 bid.count()

/home/username/spark-1.0.0-bin-hadoop2/python/pyspark/rdd.pyc in count(self)
    706         3
    707         """
--> 708         return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
    709
    710     def stats(self):

/home/username/spark-1.0.0-bin-hadoop2/python/pyspark/rdd.pyc in sum(self)
    697         6.0
    698         """
--> 699         return self.mapPartitions(lambda x: [sum(x)]).reduce(operator.add)
    700
    701     def count(self):

/home/username/spark-1.0.0-bin-hadoop2/python/pyspark/rdd.pyc in reduce(self, f)
    617             if acc is not None:
    618                 yield acc
--> 619         vals = self.mapPartitions(func).collect()
    620         return reduce(f, vals)
    621

/home/username/spark-1.0.0-bin-hadoop2/python/pyspark/rdd.pyc in collect(self)
    581         """
    582         with _JavaStackTrace(self.context) as st:
--> 583           bytesInJava = self._jrdd.collect().iterator()
    584         return list(self._collect_iterator_through_file(bytesInJava))
    585

/home/username/spark-1.0.0-bin-hadoop2/python/lib/py4j-0.8.1-src.zip/py4j/java_gateway.py in __call__(self, *args)
    535         answer = self.gateway_client.send_command(command)
    536         return_value = get_return_value(answer, self.gateway_client,
--> 537                 self.target_id, self.name)
    538
    539         for temp_arg in temp_args:

/home/username/spark-1.0.0-bin-hadoop2/python/lib/py4j-0.8.1-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    298                 raise Py4JJavaError(
    299                     'An error occurred while calling {0}{1}{2}.\n'.
--> 300                     format(target_id, '.', name), value)
    301             else:
    302                 raise Py4JError(

Py4JJavaError: An error occurred while calling o148.collect.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1.0:9 failed 4 times, most recent failure: TID 7 on host 08.bm-hadoope-datanode.dev.lax1 failed for unknown reason
Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1033)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1017)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1015)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1015)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:633)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:633)
    at scala.Option.foreach(Option.scala:236)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:633)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessActor$$anonfun$receive$2.applyOrElse(DAGScheduler.scala:1207)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
    at akka.actor.ActorCell.invoke(ActorCell.scala:456)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
    at akka.dispatch.Mailbox.run(Mailbox.scala:219)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

And then I join the bid table with another table, then get a new RDD. It seems going smooth, but when I do first() for this new RDD. I received the following error:
Py4JJavaError: An error occurred while calling o274.collectPartitions.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 9.0:6 failed 4 times, most recent failure: Exception failure in TID 32 on host 05.bm-hadoope-datanode.dev.lax1: java.io.IOException: Filesystem closed
        org.apache.hadoop.hdfs.DFSClient.checkOpen(DFSClient.java:629)
        org.apache.hadoop.hdfs.DFSInputStream.readWithStrategy(DFSInputStream.java:735)
        org.apache.hadoop.hdfs.DFSInputStream.read(DFSInputStream.java:793)
        java.io.DataInputStream.readFully(DataInputStream.java:195)
        java.io.DataInputStream.readFully(DataInputStream.java:169)
        parquet.hadoop.ParquetFileReader$ConsecutiveChunkList.readAll(ParquetFileReader.java:599)
        parquet.hadoop.ParquetFileReader.readNextRowGroup(ParquetFileReader.java:360)
        parquet.hadoop.InternalParquetRecordReader.checkRead(InternalParquetRecordReader.java:100)
        parquet.hadoop.InternalParquetRecordReader.nextKeyValue(InternalParquetRecordReader.java:172)
        parquet.hadoop.ParquetRecordReader.nextKeyValue(ParquetRecordReader.java:130)
        org.apache.spark.rdd.NewHadoopRDD$$anon$1.hasNext(NewHadoopRDD.scala:122)
        org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:39)
        scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
        scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
        scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
        org.apache.spark.api.python.PythonRDD$.writeIteratorToStream(PythonRDD.scala:293)
        org.apache.spark.api.python.PythonRDD$WriterThread$$anonfun$run$1.apply$mcV$sp(PythonRDD.scala:200)
        org.apache.spark.api.python.PythonRDD$WriterThread$$anonfun$run$1.apply(PythonRDD.scala:175)
        org.apache.spark.api.python.PythonRDD$WriterThread$$anonfun$run$1.apply(PythonRDD.scala:175)
        org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1160)
        org.apache.spark.api.python.PythonRDD$WriterThread.run(PythonRDD.scala:174)
Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1033)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1017)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1015)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1015)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:633)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:633)
    at scala.Option.foreach(Option.scala:236)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:633)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessActor$$anonfun$receive$2.applyOrElse(DAGScheduler.scala:1207)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
    at akka.actor.ActorCell.invoke(ActorCell.scala:456)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
    at akka.dispatch.Mailbox.run(Mailbox.scala:219)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)


text:
Q: JS: what's the difference between function vs method on function expressions? Lately I've been learning JS module pattern and I've seen at least 3-4 ways to create function expressions with public and private properties. My problem is I don't understand what's the best difference between them and what's the best approach / best practice.
The syntax on the 4 examples below are different but all of are invoked the same way. Can you explain me what's the difference between them?
Example A - I declare function func() and return only the method/function name.
var funcA = function() {
    var hi = "hello";

    function bye() {
        return 'bye';
    }

    function hello() {
        return hi;
    }

    return {
        hello: hello
    }
}();

Example B - here I declare foo = function() and return only the method/function name.
var funcB = function() {
    var hi = "hello";

    var bye = function() {
        return 'bye';
    }

    var hello = function() {
        return hi;
    }

    return {
        hello: hello
    }
}();

Example C - here I declare foo = function() inside the return
var funcC = function() {
    var hi = "hello";

    var bye = function() {
        return 'bye';
    }

    return {
        hello: function() {
            return hi;
        }
    }
}();

Example D - same as prev but all the function is wrapped in ().
var funcD = (function() {
    var hi = "hello";

    var bye = function() {
        return 'bye';
    }

    return {
        hello: function() {
            return hi;
        }
    }
})();

In each case if I want to call hello() I just write funcX.hello() and all of them return "hello"
But all of them are created by different ways. What's the correct one? If there is a correct way.
Thanks.

A: It's worth noting first, that leaving out the var keyword from bye and hello will actually make them global.
Now the difference between:
var hello = function () {}

return {
  hello: hello
};

And
return {
  hello: function () {}
};

Is none, because you're just passing the function either way. Storing the function in a variable has the advantage where you can use it in another place in scope.
Now one difference to be aware of is declaring the function.
var myFunc = function () {}

vs
function myFunc () {}

The ones with the keyword infront get brought into scope immediately, so they are available before you reach the declaration. With a var, that's not the case. For example
function a() {
  b();
}

a();

var b = function () {
  console.log('hi')
}

When a is invoked, it will throw an error because b is not defined. If you do it like this though:
function a() {
  b();
}

a();

function b() {
  console.log('hi')
}

It will work fine. This is known as hoisting. The first is called a function expression var thing = function() {} where the last is called a function declaration function thing() {}


text:
Q: Find best correlation between two vectors of data I am trying to find the best correlation (i.e. highest r squared value) between two lists of data within a specified range (i.e. find the range of 'x' values that have the best correlation with their corresponding 'y' values). Basically I am looking for the linear range in the data. This is what I have so far:
 #Example data - actually have a much more complicated data set
    x <- c(1,2,3,4,5,6,7,8,9)
    y <- c(0.25,1.5,3,4,5,6,6.5,7,7.5)
    data.range <- 0 #create a new variable which will contain the
    r.sq <- 0
    for (i in 1:length(x)) {
      r.sq[i] <- round(cor(x[i:(i+5)], y[i:(i+5)],4)
      data.range[i] <- paste(x[i], x[i+5], sep = " - ")
      output <- data.frame(na.omit(cbind(data.range, r.sq)))
    }
#Example read out
head(output)
  data.range    r.sq
  1 - 6         0.9963
  2 - 7         0.9906
  3 - 8         0.9885
  4 - 9         0.9839

Here, I have the output set to give me a dataframe containing the ranges of 'x' data that are being correlated with the associated 'y', and the cor() value corresponding to that range of 'x' data. Right now, I am projecting the correlation between 'x' and 'y' using 5 points (hence the i+5), but in the end I don't want to have to define the "5" as the linear range may span 6 or 8 points. So I want to do all possible correlations of 'x' and 'y' and result a list of the ranges of data (data.range) with the corresponding cor() value (r.sq).
data.range     r.sq
1 - 4          0.9999
1 - 5          0.9808
1 - 6          0.9805
1 - 7          etc...
1 - 8
1 - 9
2 - 5
2 - 6
2 - 7
2 - 8
etc....

Any advice is welcome!

A: Sure. You have an i loop that goes from 1 to the length(x). So:
for (i in 1:length(x)) {
    for (j in desired_start:desired_finish) {
        r.sq[i] <- cor(x[i:j], y[i:j], n)

You get the rest. There are more ways to do this, but if you're new this is a really nice start and you seem to have a nice grasp on loops. This will loop through i first and capture each possible value of j for each i


text:
Q: how to make the Cell in the react-big-calendar flexible? how can i make the Cell of the react-big-calendar flexible depend on the how many events that we have and enable the scrolling .
here i will provide a screen shot to my issue

A: Sounds like you're already using the showAllEvents prop, to make the cell scrollable. This applies to all cells, and can not be controlled at an individual cell level.
RBC determines layout based on the overall height you've applied to the container element.


text:
Q: DNN indexer fails with 2sxc content modules On a recent DNN/2sxc installation, the DNN index functions fail with a GeneralException: "The given key was not present in the dictionary."
The stack error is:

Message:Search: Error while indexing module 458 on tab 50, portal 1
StackTrace:
at

ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo
    moduleInfo, DateTime beginDate) in
    C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\2sxc
    Dnn\Environment\Dnn7\DnnBusinessController.cs:line 89 at
    DotNetNuke.Services.Search.ModuleIndexer.IndexSearchDocuments(Int32
    portalId, ScheduleHistoryItem schedule, DateTime startDateLocal,
    Action`1 indexer)

InnerMessage:The given key was not present in the
  dictionary.
InnerStackTrace:

at System.ThrowHelper.ThrowKeyNotFoundException() at
    System.Collections.Generic.Dictionary'2.get_Item(TKey key) at
    ToSic.SexyContent.ContentGroup.get_Template() in
    C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\ToSic.Sxc\SexyContent\ContentGroup.cs:line
    70 at
    ToSic.SexyContent.ContentBlocks.ModuleContentBlock..ctor(IInstanceInfo
    instanceInfo, Log parentLog, ITenant tenant, IEnumerable`1
    overrideParams) in
    C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\ToSic.Sxc\SexyContent\ContentBlocks\ModuleContentBlock.cs:line
    82 at
    ToSic.SexyContent.Environment.Dnn7.Search.SearchController.GetModifiedSearchDocuments(IInstanceInfo
    instance, DateTime beginDate) in
    C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\2sxc
    Dnn\Search\SearchController.cs:line 55 at
    ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo
    moduleInfo, DateTime beginDate) in
    C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\2sxc
    Dnn\Environment\Dnn7\DnnBusinessController.cs:line 85
    Source:ToSic.Sxc.Dnn

Recycling the application pool revives the application but the problem will occur again and again.
I found these solutions:
Delete the DNN index files and reindex
Remove and give back rights to the application pool to the index files
Convert the site in English then set it back in French

but nothing works. The problem only occurs with 2sxc modules (basic contents) and not with other modules (HTML for exemple).
Any idea to solve that?
Environment: DNN 9.1.1 2SXC 9.23

A: Just fyi: this really seems to be an issue - we're working on it, check out I'm guessing this is related to https://github.com/2sic/2sxc/issues/1564 and https://github.com/2sic/2sxc/issues/1561
Note that this is fixed in 9.31, and we'll release 9.32 with some more fixes.

A: The good news is that I don't have the problem anymore...
The bad news is that I don't know why...
As a really bas scientist, I did several actions at the same time and one of them (or in conjonction) solved the problem. What I did :

*

*upgrade to 2sxc version 9.30

*set the recycling time of the application pool to 10080 minutes (7 days)

*unchecked both static and dynamic cache in IIS

*installed the Windows Server updates (and rebooted the server)

Also, I'm connecting to the server using RDP. When I start my connection, I now uncheck the use of the local printers, the clipboard, and the local drives (in fact, I don't bind any local resources to the distant server). I realized that there were errors because the driver of my local printer was not installed on the remote server. Not sure it has to do with it but as I don't need these bindings anymore, I deactivated them.
Next step is to try to set back the cache and set a shorter time for recycling the application pool.
If I find something, I'll update this post.

A: I imagine this has to do with the reference to a path that does not exist on the server.  We have been experiencing this every night after our nightly backup runs.  Cycling the AppPool brings it back (as you have indicated), but we plan to upgrade to 9.30 (which was just released today - https://github.com/2sic/2sxc/releases).  May the 4th be with you!
By the way, we noticed 9.23 was marked as a "Pre-Release", so this may have not been so smart to use this version?  :)


text: Q: Opening a specific folder using PowerShell I am trying to create a workspace in Visual Studio Code using PowerShell. However, the code . command is not working the way I need it to. I have created a path variable in the following location: AppData\Local\Programs\Microsoft VS Code\bin. However, this only works when code . is the first command I run which opens a huge workspace. When I try to cd into specific folders and then use the code . command I get an error that says the system cannot find the path specified.


text:
Q: PRNG to generate a known set of values Say I want the first N numbers generated by PRNG to be some list [n1, n2, n3, n1, nx...]. Is there any way to accomplish this (basically find the appropriate seed for the PRNG?) in some efficient manor, short of bruteforcing it?

A: What's the point? If you have a random number generator g, you can write your own random number generator h that returns n1,n2,... for the first N calls and thereafter returns the same as g.
But to answer your question: if the PRNG is any good, then you will have to brute-force it, which will be impractical if N is more than about four or five.


text:
Q: Как вызвать метод getINN public static class InnGenerator {
    private long inn12;
    private boolean inn_true;
    private  byte[] spep10 = {2, 4, 10, 3, 5, 9, 4, 6, 8};
    private  byte[] spep12_n2 = {7, 2, 4, 10, 3, 5, 9, 4, 6, 8};
    private  byte[] spep12_n1 = {3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8};

    public boolean isInn_true() {
        return inn_true;
    }

    public long getInn12() {
        return inn12;
    }

    public boolean bool;

    public InnGenerator(long a) {
        bool = this.Check_inn(a);
    }

    public InnGenerator(int i) {
        if (i == 12) {
            inn_true = false;
            while (inn_true != true) {
                inn12 = Inn_12_gen();
                inn_true = Check_inn(inn12);
            }
        }
    }

    private long Inn_12_gen() {
        long gen12 = 100000000000L + (long) (Math.random() * 899999999999L);
        return gen12;
    }

    private boolean Check_inn(long in) {
        String str = String.valueOf(in);

        if (str.length() == 12) {
            int sum_12 = 0;
            int control_number = 0;
            for (int i = 0; i < spep10.length; i++) {
                sum_12 = sum_12 + (Integer.parseInt(String.valueOf(str.charAt(i))) * spep10[i]);
            }
            if (sum_12 % 11 == 10) control_number = 0;
            else control_number = sum_12 % 11;

            if (control_number == Integer.parseInt(String.valueOf(str.charAt(9)))) return true;
            else return false;
        } else if (str.length() == 12) {
            int sum_12_2 = 0;
            int control_number_n1 = 0;
            int control_number_n2 = 0;

            for (int i = 0; i < spep12_n2.length; i++) {
                sum_12_2 = sum_12_2 + (Integer.parseInt(String.valueOf(str.charAt(i))) * spep12_n2[i]);
            }

            if (sum_12_2 % 11 == 10) control_number_n2 = 0;
            else control_number_n2 = sum_12_2 % 11;

            int sum_12 = 0;
            for (int j = 0; j < spep12_n1.length; j++) {
                sum_12 = sum_12 + (Integer.parseInt(String.valueOf(str.charAt(j))) * spep12_n1[j]);
            }
            if (sum_12 % 11 == 10) control_number_n1 = 0;
            else control_number_n1 = sum_12 % 11;

            if ((control_number_n1 == Integer.parseInt(String.valueOf(str.charAt(11))))
                    && (control_number_n2 == Integer.parseInt(String.valueOf(str.charAt(10)))))
                return true;
            else return false;
        } else return false;
    }
}

}
Добрый день, есть отдельный класс InnGenerator
Я хочу в другом месте генерировать Inn, как мне его можно вызвать
RandomUtils.InnGenerator innG = new RandomUtils.InnGenerator();
//$("#case_number").val(innG.getInn12);

A: Уберите static в InnGenerator.
Создайте объект
InnGenerator innG = new InnGenerator(12);

innG.getInn12()

A: Вариантов всего 2: либо метод должен быть статический, но тогда из него можно обращаться только к статик полям и методам; или создать объект класса и вызвать метод из созданного объекта.


text:
Q: Database schema issue with custom module and l10n I've created .install file for my own module for Drupal 7 with following schema:
$schema['press_release_email'] = array(
'fields' => array(
  'id'   => array(
    'type' => 'serial',
    'not null' => TRUE
  ),
  'email_name' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ),
  'email_address' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ),
),
'primary key' => array('id'),
);

When I install it via Drush, I receive error message:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 column name is not >unique: INSERT INTO {l10n_update_project} (name, project_type, core, version, >l10n_server, l10n_path, status) VALUES (?, ?, ?, ?, ?, ?, ?); Array
  (
     [0] => drupal
     [1] => core
     [2] => 7.x
     [3] => 7.22
     [4] =>
     [5] => http://ftp.drupal.org/files/translations/7.x/drupal/drupal-7.22.%language.po
     [6] => 1
  )

At first my first schema field had a name 'name', then I renamed it, but that didn't help. I cleared cash too.
I hope someone can direct me.
Thank you for attention.
EDIT
<?php
function press_release_schema() {
$schema = array();

$schema['press_release_email'] = array(
  'fields' => array(
  'id'   => array(
    'type' => 'serial',
    'not null' => TRUE
  ),
  'email_name' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ),
  'email_address' => array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ),
),
'primary key' => array('id'),
);

 return $schema;
}

function press_release_install() {
}

?>


text:
Q: List all extension-only files and folders I'd like to list all files and folders that only have an extension, like .bashrc, .cache/, and so forth. This seems like it should be straightforward. When I try ls .*, I don't get the expected result:
jacob@jacob-Precision-Tower-3620:/home/jacob$ ls .*
.bash_history  .bash_logout  .bashrc  .ICEauthority  .profile

.:
Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos

..:
jacob  lost+found

.cache:
event-sound-cache.tdb.d35b7efbc4794c7998a81437c01c41ec.x86_64-pc-linux-gnu  evolution  fontconfig  gnome-getting-started-docs  gnome-software  gstreamer-1.0  ibus  logrotate  media-art  thumbnails  totem  tracker  update-manager-core  upstart  yelp

.config:
dconf  evolution  gnome-session  goa-1.0  gtk-3.0  ibus  libaccounts-glib  nautilus  parcellite  pulse  totem  update-notifier  upstart  user-dirs.dirs  user-dirs.locale  yelp

.gconf:

.gnupg:
private-keys-v1.d  S.gpg-agent

.local:
share

.nano:

.nv:
GLCache```

A: You can use ls -A, to show also hidden files (but not . and ..: to include thest you may use ls -a).
For your case: * is expanded by the shell, so ls will see some files and some directories. If a directory is put as argument, it will list the files on that directory. You may use ls -d * to force to list files in argument, and not to list files in the directories in the arguments. Note: ls -d .* is not much different from echo .* (but for some formatting).


text:
Q: What does this norm $|| \cdot ||_{{C^0} (K) }$ mean? $$ || A ||_{C^0 (K)} $$
Here $A$ is $ n \times n $ Hermitian, Positive definite matrix, and $K \in \mathbb R^n$.

A: As the notations may suggest, $K$ is compact and $A(x)$ is a matrix when $x\in K$ and the entries are continuous functions. Then
$$\lVert A\rVert_{C^0(K)}=\max_{r,c}\sup\{A_{r,c}(x),x\in K\}.$$


text:
Q: Accessing ASP.NET MVC Variables in Elastic Beanstalk Web.config I'm trying to update my elastic beanstalk configuration with custom web.config keys for our production servers, passwords, etc.
According to these .NET docs, I can use ConfigurationManager.AppSettings to access these variables.  I have some defaults that are in there for my local machine, and these are what get read, instead of the overrides in the web UI.

Specify up to five additional key-value pairs by entering them in the
  PARAM boxes.
You might have a code snippet that looks similar to the following to
  access the keys and parameters:
NameValueCollection appConfig = ConfigurationManager.AppSettings;
string param1 = appConfig["PARAM1"];

How do I access my web.config overrides in Elastic Beanstalk?

A: It turns out that the configuration variables will only be added if they do not previously exist in web.config.  This is a different behavior than I have experienced in Azure, where parameters would override web.config.
You can validate this by RDP'ing into an EC2 instance, and viewing web.config.  New parameters will be added, but ones that exist in web.config will be ignored.
You can replicate the override behavior by using the xdt "Remove" Transform in Web.Release.Config
 <add key="foo" xdt:Transform="Remove" xdt:Locator="Match(key)"/>

Then set the "foo" parameter in Elastic Beanstalk using the web tool, file config, or CLI


text:
Q: Can't set the CAN baud rate to 500 Kbps for MINI M4 STM32 on Cube IDE I am currently using MINI M4 STM32, with an STM32F4RG15 MCU.
I am facing issues wherein I can't increase the CAN baud rate beyond 250 kbps. Whenever I try to change the parameters to set the baud rate to 500 kbps or even 1 Mbps, CAN stops working and no messages are sent on the bus from the STM32.
I have tried the following calculators and used all the bit timing parameters suggested by them,
however, none of them have worked:

*

*http://www.bittiming.can-wiki.info/

*MikroElectronica's CANculator

I am using the following bit timing parameters for 250 kbps:

*

*SJW: 1 Tq

*Prescaler: 4

*TS1: 13 Times

*TS2: 2 Times

This is the code I am using in the main function:
HAL_Init();
SystemClock_Config();

MX_GPIO_Init();
MX_CAN1_Init();
MX_ADC2_Init();
CAN_TxHeaderTypeDef header1;
CAN_RxHeaderTypeDef rxheader;
uint8_t rxdata[8];

int a;

HAL_CAN_Start(&hcan1);
uint32_t mailbox1;

while (1) {
    uint8_t txdata[8];

    uint32_t mailbox1;
    header1.StdId = 32;
    header1.ExtId = 2;
    header1.DLC = 8;
    header1.IDE = CAN_ID_STD;
    header1.RTR = CAN_RTR_DATA;
    header1.TransmitGlobalTime = ENABLE;
    uint16_t time= HAL_CAN_GetTxTimestamp(&hcan1,mailbox1);
    txdata[7]=time;

    HAL_CAN_AddTxMessage(&hcan1, &header1, txdata, &mailbox1);

}

A: For unable to receive any CAN message, you might need to check following points:

*

*Source clock for CAN module: What is your source and frequency? Without this, no one can help you check the bit timing.

*Output measurement between CANH and CANL by osciloscope Or you could measure the pin CAN-TX (before transceiver) with high speed logic analyzer. This is for checking if you have any error in calculating bit timing.

Additionally, please note that for STM32F4, the BS1 = TS1 + 1, BS2 = TS2 + 1. From your config for 250Kbps, if the clock source is 16MHz so you lost 2 tq for calculating the bit timing. So the actual clock is ~222kbps (correct me if the clock is not 16MHz). For slow speed, may be it is accepted by the device so you could transmit/receive message.


text:
Q: How can I order my UITableView Alphabetically? I created a UITableView that gets its data from a txt.file.
However, although the txt-File is sorted alphabetically the UITableView is not.
Does anybody know how to order/sort it alphabetically?
I am using Swift 3 and Xcode 8.
var dictA = [String:String]()
var filtereddictA = [String:String]()
var visibleA = [ String ]()
var searchController =  UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    let path = Bundle.main.path(forResource: "a", ofType:"txt")

    let filemgr = FileManager.default
    if filemgr.fileExists(atPath: path!) {
        do {
            let fullText = try String(contentsOfFile: path! ,encoding: String.Encoding.utf8)

            let readings = fullText.components(separatedBy: "\n")

            for abteilungen in readings {
                let aData = abteilungen.components(separatedBy: "\t")

                if abteilungenData.count > 1 {
                    dictA[aData[0]] = aData[1]
                }
            }
            filtereddictA = dictA

        } catch let error {
            print("Error: \(error)")
        }

        searchController = UISearchController (searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()

        tableView.tableHeaderView = searchController.searchBar

        definesPresentationContext = true
    }

    self.title = "A"

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filtereddictA.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let key = Array(filtereddictA.keys)[indexPath.row]

    cell.textLabel?.text = key
    cell.detailTextLabel?.text = filtereddictA[key]

    return cell
}

@available(iOS 8.0, *)
public func updateSearchResults(for searchController: UISearchController) {
    guard let searchText = searchController.searchBar.text?.lowercased() else {
        return
    }

    let keyPositions = Array(filtereddictA.keys)
    filtereddictA = [:]
    var removeArray = [ IndexPath ]()
    var addArray = [ IndexPath ]()
    for ab in dictA {
        if abteilung.key.lowercased().range(of: searchText) != nil || a.value.lowercased().range(of: searchText) != nil || searchText.isEmpty {
            filtereddictA[ab.key] = ab.value
        } else {
            if let index = keyPositions.index(of: abteilung.key) {
                removeArray.append(IndexPath(row: index, section: 0))
            }
        }
    }

    if removeArray.count > 0 {
        removeArray.sort(by: { (p1,p2) -> Bool in
            return p1.row > p2.row
        })
        tableView.deleteRows(at: removeArray, with: .bottom)
    }
    var i = 0
    for ab in filtereddictA.keys {
        if !keyPositions.contains(ab) {
            addArray.append(IndexPath(item: i, section: 0))
        }
        i += 1
    }
    if addArray.count > 0 {
        addArray.sort(by: { (p1,p2) -> Bool in
            return p1.row < p2.row
        })
        tableView.insertRows(at: addArray, with: .bottom)
    }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filtereddictA.count
}

A: You should set proper order of the elements in the data source.
I can make assumption that filtereddictAbteilungen is dictionary that is you're datasource.
So sort it firstly and that populate via tableView.
Example:
let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = dictionary.sorted(by: { $0.0 < $1.0 })


text:
Q: Cannot import bootstrap in nuxt vue component I can't import bootstrap in any vue component (using latest nuxtjs). I get :

My (simple) component is :
<template>

Empty index page

</template>

I am really stuck. Do you have any idea or suggestion ?

A: You should use bootstrap-vue, they fix a lot of issues and their tree-shacking works amazing.
your code will be
<template>
  Launch demo modal

Empty index page

</template>

more info in the bootstrap-vue guide


text:
Q: Uncaught (in promise) ReferenceError: data is not defined in react component I'm passing a simple JSON object from the back-end to the front-end {data: "test"}. I got the following error on the react side Uncaught (in promise) ReferenceError: data is not defined. I'm pretty sure I'm missing something obvious. Here is my Component:
export default class App extends Component {
  state = { data: null };

  componentDidMount() {
    fetch('/data',    {
          method: 'GET',
          withCredentials: true,
          headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Accept': 'application/json' }})
      .then(res => res.json())
      .then(data => this.setState({ data }));
  }

  render() {
    const { data } = this.state;
    console.log(data)
    return (
      <div>
      <p> test </p>
      </div>
    );
  }
}

A: you try to set the state to data which does not exist, although the json is passed in as argument user.
You might want to use user
.then(user => this.setState({ data: user }));

or rename the argument to data
.then(data => this.setState({ data }));


text:
Q: Adding rows to SQLite data base using dplyr I'm trying to add rows to a SQLite data base using dplyr. Based on StatSandwich's answer to this post I would have thought that the following may work:
library(dplyr)
data1 <- filter(mtcars, cyl == 6)
data2 <- filter(mtcars, cyl == 4)

my_db <- src_sqlite(path="Test.DB", create = TRUE)
copy_to(my_db, data1, temporary = FALSE)
db_insert_into(my_db, table=data1, values=data2) # Error

However, I get the following error:

Error in UseMethod("db_insert_into") :
    no applicable method for 'db_insert_into' applied to an object of class "c('src_sqlite', 'src_sql', 'src')"

Would anyone be able to point out what I'm doing wrong?
Thanks, Philipp


text:
Q: How to get name of captured image in android onActivityResult how to get image name from captured image/intent data. any one suggest me. i need through intent data only
Here is my code:
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
             if(resultCode == RESULT_OK && data != null){
                Bitmap photo = (Bitmap) data.getExtras().get("data");
             }
     }

A: AS from the Android documentation here you could not get any name for your image since android wont name for your file but you could get the time when the image was taken and the dimension of the image from This answer You could name the image by yourself and send that bitmap.