text:
Q: svg external stylesheet not work I am new svg learner and try to animate svg file with external style sheet but fail fail to style my object 'Cube'.
[index.html file]

        <link rel="stylesheet" type="text/css" href="cube.css">

SVG Cube Animation</h>

[cube-motion.svg file]
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="cube.css" ?>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 200 200" style="enable-background:new 0 0 200 200;" xml:space="preserve">

<g>
    <polygon id="l1" class="st0" points="105.3,92.7 86.3,103.3 67.3,92.9 67.1,71.9 86,61.2 105.1,71.6   "/>
    <polyline id="l2" class="st1" points="67.1,71.9 86.2,82.5 86.3,103.3 67.1,93.1 66.9,71.9    "/>

    <animateTransform
        attributeName="transform"
        type="translate"
        from="0 0"
        to="0 75"
        begin="0s"
        dur="3s"
        repeatCount="indefinite"
        />
</g>

</svg>

[external stylesheet file cube.css]
 .st0 {
        fill:#FF00FF;
        stroke:#000000;
        stroke-miterlimit:10;
    }

.st1 {
        fill:#23D83C;
        stroke:#000000;
        stroke-miterlimit:10;
    }

.logo {
    position: absolute;
    left: 400;
    top: 150;
  }

A: You are on the right track with the inclusion of the external stylesheet inside the SVG:
<?xml-stylesheet type="text/css" href="cube.css" ?>

The reason it doesn't work is because the SVG is loaded in the HTML as an  which - rightfully - does not allow additional external assets to be processed.
If you're adamant on having the CSS from an external file, you have two options, either embed the SVG inside the html or use <object data=file.svg type=image/xml+svg></object>.
Depending on your use case, you basically have three ways to use CSS for styling:

Images are not interactive and are not allowed to load any other assets within themselves. Simple presentation of the referenced image file only.
It does allow to use CSS, but only from a


text:
Q: PdfDocument - Cut page at the end of the layout I'm creating a Pdf file using the Android PdfDocument class. I'm inflating the layout from an XML file (a LinearLayout inside a ConstraintLayout), which is then completed at run-time by adding new rows with external data.
The problem is that the output pdf can be very long or short. I would like to avoid specifying the page height before inflating the layout. However, I can't find a solution to measure the height of the layout before adding it to the page
This is the actual code:
PdfDocument document = new PdfDocument();

//set page width and height
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(227,992, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);

//inflating the layout
View v = getLayoutInflater().inflate(R.layout.rapportino, null);

//add data to layout
//...

//measure the layout, draw it and finish page
int measureWidth = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getWidth(), View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getHeight(), View.MeasureSpec.EXACTLY);
v.measure(measureWidth, measuredHeight);
v.layout(0, 0, measureWidth, measuredHeight);
v.draw(page.getCanvas());
document.finishPage(page);

//write to file..

Is there a way to create the pdf depending on the height of the view?
EDIT: this is the layout i'm inflating
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/rapportino_indirizzo_textview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:gravity="end"
            android:textColor="#000000"
            android:textSize="@dimen/rapportino_global_textsize" />

        <!--
            other textview, linearlayout and imageview
            ..
            ..
        -->

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

A: So, I solved with a quite strange solution. Since adding a layout to a view causes the height to be calculated, I created an invisible view in the activity where I'm creating the pdf (with the width of the pdf):
<!-- add this to your activity -->
<LinearLayout
    android:visibility="invisible"
    android:id="@+id/output_pdf_view"
    android:orientation="vertical"
    android:layout_width="226dp"
    android:layout_height="wrap_content" />

Then I added the inflated layout to the invisible view (after having filled it with external data). With an observer you can get the height at the time it is calculated.
//inflating the layout
View v = getLayoutInflater().inflate(R.layout.rapportino, null);

//add data to layout (rows, images etc.)
//...

//find the invisible view
LinearLayout invisibleOutputPdfView = findViewById(R.id.output_pdf_view);

//add the pdf layout and observe changes
invisibleOutputPdfView.addView(v);
invisibleOutputPdfView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //remove the listener
            invisibleOutputPdfView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            int height = invisibleOutputPdfView.getHeight();
            createPDF(height, ..);
        }
    });

NOTE: for some reason it seems that there is a 1:1 ratio between dp and pt in the generation of the pdf. So no conversions are needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access value in OpenCV Mat object UINT16 How can I access particular cell in Opencv Mat, type UINT16
I have tried the ones below, but nothing works.
depthV = depthIm.at<int>(i, j);
depthV = depthIm.at<UINT16>(i, j);
depthV = depthIm.at<float>(i, j);
depthV = depthIm.at<double>(i, j);

A: int depthV = depthIm.at<unsigned short>(i, j);


text:
Q: Sending integers via serial port and printing to LCD I am trying to send integers via the a USB serial port from MATLAB to an Ardunio Uno and then subsequently display them on an LCD. I have a problem with numbers from 128 to 159 displaying as 63 on the Arduino display.
Here is my MATLAB code:
q = serial('COM4'); % set com port location
set(q,'BaudRate',9600); % set baud rate
fopen(q); % open the port
fprintf(q,a_number) % send the integer

Here is my Arduino code:
int incomingByte = 0; // storage for integer
void serialRead () //
{
   incomingByte = Serial.read(); // read the serial port
   if (Serial.available() > 0) // if there is data print it to LCD
   {
      lcd.setCursor(0,1);  // set the cursor to column 0, line 1
      lcd.print("Boot:     %");
      delay(500);
      lcd.setCursor(6,1);
      lcd.print(incomingByte,DEC); // print the Integer to the LCD
      delay(500);
   }
}

All numbers from 0 to 255 are displayed correctly apart from numbers 128 to 159 which are displayed as the value 63.
Update:  I tested the serial port on my from my computer using a serial analyzer and it looks like MATLAB is responsible for sending the data incorrectly. I tested the Arduino code separately and it works perfectly.

A: Solved the problem added the following line in my MATLAB code in place of the fprintf line:
fwrite(q,a_number,'uint16','sync');


text:
Q: How to create a new thread I'm new in programming so this may not sound very well, butt, after I did some research in understood that I can create a new thread so multiple blocks of codes can run i parallel. Can someone explain me how can I create a new thread. I'm using Visual studio on Windows.

A: Using the pthread_create function we can create the thread.
   #include<stdio.h>
   #include<stdlib.h>
    #include<pthread.h>

pthread_t tid;
       pthread_t tid1;
    void *thrd(void *a)
     {
        printf("thread created\n");
    printf("%u\n",(unsigned int )tid);
  }
    void *thrd1(void *a)
 {
    printf("second thread created\n");
    printf("%u\n",(unsigned int)tid1);
   }

   main()
   {

    int a=pthread_create(&tid,NULL,thrd,NULL);
    int b=pthread_create(&tid1,NULL,thrd1,NULL);
    sleep(1);

  }

A: Just try that code
       #include<stdio.h>
       #include<pthread.h>

       void *hello(void *arg)
       {
         printf("thread id=%u\n",(unsigned)pthread_self());
        printf("hello welocme Thread created \n");
       }

      main()
     {
       pthread_t tid;

        tid=pthread_create(&tid,NULL,hello,NULL);

    }

compile:
cc filename.c -pthread


text:
Q: Criminals commit a crime and people commit suicide. Why can't we omit the article 'a' before crime and include 'a' before suicide? Why can't we say criminals commit crime and people commit a suicide?

A: Leaving aside suicide for the moment, when it comes to committing crimes you may hear either:

*

*he committed murder

*he committed a murder

*he committed an act of murder

I'm sure you know that the use of articles can make something unique, or countable. When it comes to crimes, they are counted in different ways depending on the context. For example, if someone kills two people at the same time, they have committed an act of murder, but two counts of murder.
It also depends very much on whether the language used is legal language (eg in a courtroom) or everyday speech. In the field of law you might hear "two counts of murder", or a "double murder", but in everyday speech many people would say "committed two murders" or more likely "they murdered two people".

When it comes to suicide, I should point out that in recent times there has been much effort to replace the expression "committed suicide" with "took his/her life" or similar, as it is felt the language could be hurtful or insensitive to those affected by it. However, the logical reason why "committed suicide" would never have an article is because it could never be counted - no person can commit any suicide but their own, so an article would be redundant.


text:
Q: AND-OR Graph from Horn clauses Does anyone know if there is a way to generate a nice graph from Horn clauses? for example:

Ideally, I would like to generate AND-OR graphs like this directly from Horn clauses written in Latex; however, if you know another way such as from rules written in RDF, I will also appreciate it.
Also, generated graphs do not have to be exactly like this one I show. It just have to illustrate the inference relation between my data.

A: Here's a potential solution using neato from the graphviz package.  It requires a more difficult input format and the output isn't as nice as your example, but I think it conveys the right information.
A file named sample.dot as follows...
graph G
{
    P -- Q [dir=forward];

    L -- LM;
    M -- LM;
    LM -- P [dir=forward];

    B -- BL;
    L -- BL;
    BL -- M [dir=forward];

    A -- AP;
    P -- AP;
    AP -- L [dir=forward];

    A -- AB;
    B -- AB;
    AB -- L [dir=forward];

    LM [shape=point];
    BL [shape=point];
    AP [shape=point];
    AB [shape=point];
}

processed with the following command...
neato -Tpdf sample.dot -o sample.pdf

gives...


text:
Q: ColdFusion Lucee Or Railo RestFull Webservice Mapping issue Creating my first RestFul Webservice on ColdFusion Lucee.
These are the steps which I followed.

*

*Created folder on ROOT Named "RestAPI"

*Created sub-Folder under RestAPI/API (For CFC)

*Created CFC RestAPI/API/Hello.cfc

Hello.cfc
<cfcomponent rest="true" restpath="/hello">
    <cffunction name="formPost" access="remote" returnType="String" httpMethod="POST" restPath="/form">
        <cfargument name="firstname" type="String" restArgSource="Form">
        <cfargument name="lastname" type="String" restArgSource="Form">
        <cfset res="firstname : " & #firstname# & " lastname : " & #lastname#>
        <cfreturn res>
    </cffunction>
</cfcomponent>

*Created CFM Call.cfm

Call.cfm
<cfhttp url="http://mydev:8888/rest/Example/hello/form" method="POST" result="res" port="8888">
    <cfhttpparam type="formfield" name="firstname" value="Dan">
    <cfhttpparam type="formfield" name="lastname" value="Bin">

*Created a mapping in lucee admin server. /Example
When I run the Call.cfm I am getting this output

no rest service for [/RestAPI/call.cfm] found in mapping [/Example]

Please see the attached screen shots
Just want to know why it is not working in root folder

A: From your initial screenshot I found that the issue seems to be how you are calling your call.cfm template. The error message being reported is:

no rest service for [/RestAPI/call.cfm] found in mapping [/Example]

That tells me that it is looking for a service through your REST API instead of simply calling the template. I think this is because you referenced your call.cfm template using /rest/ in the URL. Again from the screenshot I saw this in your browser's address bar:
mydev:8888/rest/RestAPI/call.cfm

This is when I suggested moving your call.cfm template out of that sub-folder and into the web root.  However, I think it will also work if you reference it correctly when the call.cfm file is contained in your /RestAPI/ folder. You should be able to reference it like so:
mydev:8888/RestAPI/call.cfm

Notice that I have removed the /rest/ reference from this URL for the browser request. You do still need the /rest/ reference within your <cfhttp> call though.
one last question please answer in answer box. i can keep multiple component (cfcs) files in one folder & map?
Yes you can keep multiple CFCs within your API folder.


text:
Q: How to resolve generic types in C# If I have the following interfaces:
public interface IQuery<out TResult>
{
}

public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult>
{
    TResult Handle<TResult>(TQuery query);
}

public interface IDispatcher
{
    TResult Query<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>;
    TResult Query<TResult>(IQuery<TResult> query);
}

and I then implement IDispatcher as follows:
public class Dispatcher : IDispatcher
{
    // Insert IoC container of your choice here:
    // I've tried StructureMap, SimpleInjector and Grace so far,
    // they all have the same issue
    private readonly Container _container;

    public TResult Query<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>
    {
        var handler = _container.Resolve<IQueryHandler<TQuery, TResult>();
        return handler.Handle(query);
    }

    public TResult Query<TResult>(IQuery<TResult> query)
    {
        var handler = _container.Resolve<IQueryHandler<IQuery<TResult>, TResult>();
        return handler.Handle(query);
    }
}

The first method works OK when I register my query handler instances using open generics:
var dispatcher = new Dispatcher();
var results = dispatcher.Query<TestQuery, TestResult>(new TestQuery());

but if I use the less-wordy version:
var dispatcher = new Dispatcher();
var results = dispatcher.Query(new TestQuery());

then the container fails to resolve the type - it can't go from IQuery<TestResult> and find an implementation of IQueryHandler<IQuery<TestResult>, TestResult>, while it can go from TQuery where TQuery : IQuery<TResult> and find an implementation of IQueryHandler<TQuery, TResult>. So I'm guessing I'm bumping up against the limits of what generics can do in C#, but is there a way that I can get my second example to work without explicitly stating the query type and response type?
Update: Proof of concept available here.


text:
Q: Makefile.in:12: *** commands commence before first target. Stop When I try to run "make clean"  it gives me make: ** No rule to make target clean'.  Stop.
So I do make -f Makefile.in clean
and it tells me Makefile.in:12: *** commands commence before first target.  Stop.
I went into the Makefile.in and removed the tab on line 12 and retried
make -f Makefile.in clean
but then it gives me Makefile.in:12: *** missing separator.  Stop.
Does anyone know what is going on here? I would really appreciate some help.
This was too long for a comment:
checking for Tcl library... not found checking for Tcl header... found /usr/local/include/tcl.h checking whether the Tcl system has changed... yes configure: error:
Tcl cannot be found on this system.
Eggdrop requires Tcl and the Tcl development files to compile. If you already have Tcl installed on this system, make sure you also have the development files (common package names include 'tcl-dev' and 'tcl-devel'). If I just wasn't looking in the right place for it, re-run ./configure using the --with-tcllib='/path/to/libtcl.so' and --with-tclinc='/path/to/tcl.h' options.
See doc/COMPILE-GUIDE's 'Tcl Detection and Installation' section for more information.
I am following this guide to get tcl installed correctly. http://botlending.com/docs/eggdrop/compile/19#19

A: Makefile.in is not a makefile.  It's input to for the configure script, which will convert it into a makefile.
Please read the INSTALL or README file that came with the software for instructions, but typically you need to first run configure:
./configure

Then you can run make and/or make install:
make


text:
Q: How to remove first character from string without using any function in PHP? Suppose it's my string "Hi, you are goood developer". How can i remove first character without using any php function.

A: I don't really get why you don't want to use any php functions but the easiest way would be doing it like this:
$str = "Hi, you are goood developer";
$str = substr($str, 1);
echo $str;

Output:
i, you are goood developer

A: Although I'm not sure I understand why you wouldn't wish to use a built-in PHP function to help with this, you can do this by treating the string as a character array:
$myString = "Hi, you are goood developer";
for ($i = 1; $i < 27; $i++)
    echo $myString[$i];

If you want to store the result in another variable, the following will do it:
$myString = "Hi, you are goood developer";
$newString = "";
for ($i = 1; $i < 27; $i++)
  $newString .= $myString[$i];
echo $newString;

The output for both the above:
i, you are goood developer

The problem with this is that you must know in advance the length of the string for it to work.
Using built-in functions
If you can use strlen, a built-in function to determine the length of the string it becomes somewhat easier:
for ($i = 1; $i < strlen($myString); $i++)
    ...

Of course, a better approach is to use substr, which is a built-in PHP function:
$myString = "Hi, you are goood developer";
$newString = substr($myString, 1);
echo $newString;


text:
Q: Mikrotik: динамическое добавление IP адресов в список разрешенных при резолвинге DNS В целях безопасности решил изолировать Windows Server от внешнего мира (правилами файрволла в роутере Mirkotik).
Но при этом хотелось бы иметь доступ к Windows Update. На Technet говорят, что подсети постоянно меняются и советуют разрешить доступ к ресурсам, каждый раз их резолвя.
Вот их список:

*

*http://windowsupdate.microsoft.com

*http://*.windowsupdate.microsoft.com

*https://*.windowsupdate.microsoft.com

*http://*.update.microsoft.com

*https://*.update.microsoft.com

*http://*.windowsupdate.com

*http://download.windowsupdate.com

*http://download.microsoft.com

*http://*.download.windowsupdate.com

*http://wustat.windows.com

*http://ntservicepack.microsoft.com

*http://stats.microsoft.com

*https://stats.microsoft.com
Вопрос: как силами роутера разрешить к ним доступ?

A: Если немного помучать базы данных radb.net, можно получить список адресов, закрепленных за Microsoft. Из него заполняем адрес листы:
/ip firewall address-list add list=microsoft address=65.52.0.0/15
/ip firewall address-list add list=microsoft address=65.54.0.0/20
/ip firewall address-list add list=microsoft address=65.55.0.0/16
/ip firewall address-list add list=microsoft address=103.81.184.0/22
/ip firewall address-list add list=microsoft address=131.107.0.0/16
/ip firewall address-list add list=microsoft address=157.54.0.0/15
/ip firewall address-list add list=microsoft address=157.56.0.0/14
/ip firewall address-list add list=microsoft address=157.60.0.0/16
/ip firewall address-list add list=microsoft address=167.220.0.0/16
/ip firewall address-list add list=microsoft address=198.105.232.0/22
/ip firewall address-list add list=microsoft address=198.180.95.0/24
/ip firewall address-list add list=microsoft address=199.2.137.0/24
/ip firewall address-list add list=microsoft address=199.242.48.0/22
/ip firewall address-list add list=microsoft address=204.182.144.0/24
/ip firewall address-list add list=microsoft address=204.255.244.0/23
/ip firewall address-list add list=microsoft address=205.248.126.0/23
/ip firewall address-list add list=microsoft address=206.138.168.0/21

IP4 свободных осталось не много, так что врятли они поменяются ближайшие годы. По этим спискам будут доступны все сервисы Microsoft на данный момент.

A: Новые версии RouterOS поддерживают записи DNS в адрес листах:
/ip firewall address-list add list=microsoft address=windowsupdate.microsoft.com

Ресолвится всё автоматически.
Но пока не проверял работают ли звездочки (вроде нет).


text:
Q: cannot verify domain with bitly Last night I purchased a new domain with the intention of turning it into a vanity url service for my blog!
I created the a record on both cpanel and my domain registrar to point to bit.ly. This morning  however once the domain had propagated I went to verify my domain with bitly and was still getting the same message...

Short Domain verification failed for "bblg.in". Neither an A Record
  nor a CNAME record was found.

I went to to domain in chrome and I am getting a 403 forbidden page however if I goto the www. version of that domain it automatically redirects to bitly.com
Weirdly if I visit the non-www version of that domain on chrome on my android mobile device that redirects to the mobile version of bitly.com but if i visit www.bblg.in on my mobile I get a 403 forbidden page.
I assume there is some redirect issue going on which is preventing me to verify my domain with bitly and would probably need a .htaccess file on there! Also to confirm there is nothing in the bblg.in file on my server just a cgi-bin file that automatically gets placed there.
Any help in this would be greatly appreciated! Many thanks
- Phillip Dew


text:
Q: In JavaScript ES6, if console.log() doesn't invoke obj.toString(), what does it use? Some related info is in this question: Within the standard JavaScript ES6 environment, when is .toString() ever called?
By polymorphism, toString() is the standard message to send to the object (or the standard method to invoke on the object), by the interface of the Object class.
But obviously, console.log() doesn't use it:
// Inside of Node

> let aSet = new Set([1,3,5]);

> aSet.toString()
'[object Set]'

> console.log(aSet);
Set { 1, 3, 5 }

> let aMap = new Map([["foo", 1], ["bar", 2]])

> aMap.toString()
'[object Map]'

> console.log(aMap)
Map { 'foo' => 1, 'bar' => 2 }

so what does console.log() use?  It is not valueOf(), as valueOf() just returns the object itself in this case, when no primitive value is available.
It'd be quite ugly to "special case" what class it is, and perform different actions -- as polymorphism, having the standard "verb", in this case toString(), is what is supposed to be used. To find out what the class is and perform different actions (such as using a switch statement), is exactly what we don't want to do in OOP.

A: console.log(), along with other console methods, is implementation-dependent.
My answer applies only to Node.js.

After some looking into the internal source files of Node.js, it turned out that in Node (v12), console methods use a common way to display values: the util.formatWithOptions method.
Its internal source is written in JavaScript, and it calls internal formatter functions (located in internal/util/inspect.js), that formats objects based on their type, for example:

*

*Primitives are simply stringified.

*Plain objects are iterated over their properties, to show them.

*Arrays are iterated over based on their length.

*Set and Map objects' values are looked up using their iterators.

A: The console is a host-provided object, and its implementation varies from host to host. Chrome's is different from Firefox's which is different from Node.js's which is different from... :-)
Typically, they check the type of what you're logging and then show whatever the implementer thought was a reasonable representation of what you logged. For objects and arrays, that usually involves querying the object/array for its contents (rather than calling toString) and showing a representation of those contents. (They may even query the contents using an internal feature of the JavaScript engine rather than going through the object's JavaScript-accessible API.) In "live" consoles like the ones in most browsers, the console even keeps a reference to the object so you can expand it and dive into its properties (details in the answers to this question).
(At one stage, Node.js's console looked for a method on the object called inspect and used that, but that turned out to be problematic for objects where inspect wasn't meant to be used that way and was removed. As far as I know they haven't added that back using a Symbol-named method instead.)

A: There is a separate specification for console, provided by WHATWG community: Console Living Standard.
When looking for console.log in that specification you get via the section 2.1 Logger to the section 2.3 Printer, which states:

How the implementation prints args is up to the implementation, but implementations should separate the objects by a space or something similar, as that has become a developer expectation.

Typically, a console implementation will want to give a rich user interface, with expandable items, styling, allowing to drill down to the primitive values that build up the overall value. It does not have to be implemented in JavaScript, and calling toString may not be that handy any way, knowing that even ({ a: 1 }).toString() returns "[object Object]", which is not that useful.
Sometimes the given information goes beyond to what you could query synchronously in code, as is the case with promise objects. In the console the current state of such objects is output, while in code you need to at least call then (or do an await) to get that info.


text:
Q: Why is my image not matching what I expect it to look like? So, I have to create a ppm file that will give me the image of the italian flag (3 vertical bars in the order from left to right, green, white, and then red). And the image has to be 600 by 400. (columns by rows) I've tried rewriting my code multiple times, but, my image is just the three bars horizontally placed rather than vertically. Also, the lines aren't completely level. But the biggest issue is, why aren't my green, white, and red bars vertical? Any help is greatly appreciated.
Here's my code:
#include <stdio.h>

int main() {
   printf("P6\n");
   printf("%d %d\n", 600, 400);
   printf("255\n");

   int height, widthGreen, widthWhite, widthRed, i, j;
   unsigned char Rcolor, Bcolor, Gcolor;

   widthGreen = 200;
   widthWhite = 400;
   widthRed = 600;
   height = 400;

   for (j = 0; j < height; j++) {
      for (i = 0; i < widthGreen; i++) {
         Rcolor = 0;
         Gcolor = 128;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 0; j < height; j++) {
      for (i = 201; i <= widthWhite; i++) {
         Rcolor = 255;
         Gcolor = 255;
         Bcolor = 255;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 0; j < height; j++) {
      for (i = 401; i <= widthRed; i++) {
         Rcolor = 255;
         Gcolor = 0;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   return (0);
}

A: Four things: The first is to add spaces between the values. The second is to add newlines after each line. The third is to print the values as (unsigned) integers, and not as characters, neither of 255 nor 128 will print as valid characters. The fourth would be to use one loop for the height, with three loops inside it for the colors. Think of the loop counters as pixels instead, and you will understand why.

A: Why are you using printf ? You should use the i and j index to build and index into an array. In your code, the i and j variable are only used as loop counter, not as coordinate.
What you are doing :
for each line
     print some green

for each line
    print some white

for each line
    print some red

What you should be doing :
for each line
    print some green
    print some white
    print some red

You could also use more meaningful variable name, like row instead of j and col (for column) instead of i


text:
Q: How get total and name to field with query builder in formtype symfony I want to create a select field with referece of my types available.
I have 3 entity. Post, Types[typebase_id, count=0], TypesBase[name,quantity].
I want to display => Choices =>

*

*TypeA (3)

*TypeB (12)

1- I need to get TypeBase Name.
2- I need to group by Types (Typebase_id and count=0)
3- The selected value will be Typebase_id of Types entity.
I have this in my formtype.
$builder->add('types', 'entity', array(
                    'class' => 'PostBundle:Types',
                    'query_builder' => function(EntityRepository $er) use ($user) {
                        return $er->createQueryBuilder('w')
                            ->where("w.user = :user")
                            ->setParameter('user', $user)
                            ->andWhere("w.active = :active")
                            ->setParameter('active', 0);
                    },
                ));

I try __toString in Types, but i cant get TypeBase Name.
Thanks

A: Use choice_label parameter.
Docs: http://symfony.com/doc/2.7/reference/forms/types/entity.html#choice-label
$builder->add('types', 'entity', array(
    'class' => 'PostBundle:Types',
    'query_builder' => function(EntityRepository $er) use ($user) {
        return $er->createQueryBuilder('w')
            ->where("w.user = :user")
            ->setParameter('user', $user)
            ->andWhere("w.active = :active")
            ->setParameter('active', 0);
    },
    'choice_label' => function ($type) {
        return $type->getName();
    }
));

Or just: 'choice_label' => 'name'.


text:
Q: Visualising diagonal in asymmetric matrix plot I have a number of symmetric matrices of the same dimensionality, and I wish to visualise the mean and variance of the values in each cell across these matrices in an elegant way (which I will make more precise below) that makes use of the symmetric character.
Let me start by making some data to illustrate. The following creates 10 9x9 matrices, aggregates the mean and variance, and transforms to long format in preparation for plotting:
library(dplyr, warn.conflicts = FALSE)
library(tidyr)

make_matrix <- function(n) {
  m <- matrix(NA, nrow = n, ncol = n)
  m[lower.tri(m)] <- runif((n^2 - n) / 2)
  m <- pmax(m, t(m), na.rm = TRUE)
  diag(m) <- runif(n)
  rownames(m) <- colnames(m) <- letters[1:n]
  m
}

matrices <- replicate(10, make_matrix(9))
means <- apply(matrices, 1:2, mean) %>%
  as_tibble(rownames = "row") %>%
  pivot_longer(-1, names_to = "col", values_to = "mean")
vars <- apply(matrices, 1:2, var) %>%
  as_tibble(rownames = "row") %>%
  pivot_longer(-1, names_to = "col", values_to = "var")
df <- full_join(means, vars, by = c("row", "col"))

head(df)
#> # A tibble: 6 x 4
#>   row   col    mean    var
#>   <chr> <chr> <dbl>  <dbl>
#> 1 a     a     0.548 0.111
#> 2 a     b     0.507 0.0914
#> 3 a     c     0.374 0.105
#> 4 a     d     0.350 0.0976
#> 5 a     e     0.525 0.0752
#> 6 a     f     0.452 0.0887

Now, I could simply use geom_tile to make one plot of the means, and one plot of the variances. However, considering that both of these are symmetric, this wastes quite a lot of space, and also  fails to communicate the symmetric character to the audience.
To address this problem, I have been playing around with the ggasym package to create an asymmetric matrix plot. The following is a slight modification from the ggasym vignette:
library(ggasym)
library(ggplot2)

ggplot(df, aes(x = col, y = row)) +
  geom_asymmat(aes(fill_diag = mean, fill_tl = mean, fill_br = var)) +
  scale_fill_diag_gradient(limits = c(0, 1), low = "lightpink", high = "tomato") +
  scale_fill_tl_gradient(limits = c(0, 1), low = "lightpink", high = "tomato") +
  scale_fill_br_gradient(low = "lightblue1", high = "dodgerblue") +
  geom_text(data = filter(df, row == col), aes(label = signif(var, 2)))

Created on 2020-06-27 by the reprex package (v0.3.0)
What bothers me about this is the diagonal. In the above, I have mapped the fill of the diagonal to the means, and overlaid the variance by text, which works, but doesn't seem great. Specifically, I would like to map all the information here to fill, so as to get rid of the text. I see a couple of options for how to do this, but I am not sure how to implement any of them:

*

*Split the fill of the diagonal cells, so that (in the example above) the lower right of each cell on the diagonal is an appropriate shade of blue, while the upper left is some shade of red.

*Plot the upper and lower matrices separately (each with the diagonal), and then somehow "overlay" these plots so that they end up next to each other in an appropriate way. In other words, this would plot the diagonal twice.

I am open to other suggestions for how to accomplish this in a clean way. Let me emphasise that I do not require a solution building on ggasym, this was simply the closest I have been able to get so far. However, I would like some kind of ggplot-based solution.

A: So here is my take on the 'split-the-fill' strategy. You can plot most of the things you would want in ggplot if you don't mind parameterising your stuff as polygons. We let the ggnewscale package handle the double fill mapping for us.
First off, we no longer autoname the matrices, as we will not use the dimnames.
suppressPackageStartupMessages({
  library(ggplot2)
  library(tidyr)
  library(dplyr)
  library(ggnewscale)
})

make_matrix <- function(n) {
  m <- matrix(NA, nrow = n, ncol = n)
  m[lower.tri(m)] <- runif((n^2 - n) / 2)
  m <- pmax(m, t(m), na.rm = TRUE)
  diag(m) <- runif(n)
  # rownames(m) <- colnames(m) <- letters[1:n]
  m
}

Below is a function that takes a matrix, parameterises it as a polygon and cuts off one half.
halfmat <- function(mat, side) {
  side <- match.arg(side, c("upper", "lower", "both"))
  # Convert to long format
  dat <- data.frame(
    x = as.vector(row(mat)),
    y = as.vector(col(mat)),
    id = seq_along(mat),
    value = as.vector(mat)
  )
  # Parameterise as polygon
  poly <- with(dat, data.frame(
    x = c(x - 0.5, x + 0.5, x + 0.5, x - 0.5),
    y = c(y - 0.5, y - 0.5, y + 0.5, y + 0.5),
    id = rep(id, 4),
    value = rep(value, 4)
  ))
  # Slice off one of the triangles
  if (side == "upper") {
    poly <- filter(poly, y >= x)
  } else if (side == "lower") {
    poly <- filter(poly, x >= y)
  }
  poly
}

Then we generate the data, compute the means and variances and reparameterise them.
matrices <- replicate(10, make_matrix(9))
means <- apply(matrices, 1:2, mean) %>% halfmat("upper")
vars <- apply(matrices, 1:2, var) %>% halfmat("lower")

Then we put in the means and variances as two seperate polygon layers, since we need to seperate the fill mappings with new_scale_fill(). There is a bit of extra fiddling with the scales, as these are now continuous instead of discrete, but it is not that bad.
ggplot(means, aes(x, y, fill = value, group = id)) +
  geom_polygon() +
  scale_fill_distiller(palette = "Reds", name = "Mean") +
  # Be sure to call new_scale_fill() only after you've set up a fill scale
  # for the upper part
  new_scale_fill() +
  geom_polygon(data = vars, aes(fill = value)) +
  scale_fill_distiller(palette = "Blues", name = "Variance") +
  scale_x_continuous(breaks = function(x){seq(x[1] + 0.5, x[2] - 0.5, by = 1)},
                     labels = function(x){letters[x]},
                     expand = c(0,0), name = "col") +
  scale_y_continuous(breaks = function(x){seq(x[1] + 0.5, x[2] - 0.5, by = 1)},
                     labels = function(x){letters[x]},
                     expand = c(0,0), name = "row")

Created on 2020-06-27 by the reprex package (v0.3.0)


text:
Q: Merging two data together in Pandas I am trying to concatenate data  together in pandas but it doesn't appear to be working out well for me.
I have some data that I wanted to convert to a numeric and I was able to do this. I then want to have it rejoin the data set.
Here is what the original data looks like:
 CallDate            Agent          Group     Direction
0  2015-09-01         Adam          Billing    Inbound
1  2015-09-01         Nathaniel     Billing    Outbound
2  2015-09-01         Jessica       Claims     Inbound
3  2015-09-01         Tom           Billing    Outbound
4  2015-09-01         Jane          CCS        Inbound

Here is my code to convert the group to a numeric
data['Group']=data['Group'].astype(str)
data.Group=data['Group'].apply(lambda x:len(x))

This worked and gave me what I was looking for
    0     1
    1     1
    2    13
    3     1
    4     6
I then try to merge this back to the group (basically I want to know what each name/number correspond to)
y=pd.concat([data,data.Group], ignore_index=True)
y [:5]

But the results are the same as the original database
Is there something obvious I am missing or an easier work around that I am not thinking of.

A: pd.concat() is to concatenate two DataFrame. I think you are trying to concatenate two columns in a DataFrame.
data
Out[42]:
     CallDate      Agent    Group Direction
0  2015-09-01       Adam  Billing   Inbound
1  2015-09-01  Nathaniel  Billing  Outbound
2  2015-09-01    Jessica   Claims   Inbound
3  2015-09-01        Tom  Billing  Outbound
4  2015-09-01       Jane      CCS   Inbound

data.Group = data.Group + data.Group.apply(lambda x:" / "+str(len(x)))

data
Out[44]:
     CallDate      Agent        Group Direction
0  2015-09-01       Adam  Billing / 7   Inbound
1  2015-09-01  Nathaniel  Billing / 7  Outbound
2  2015-09-01    Jessica   Claims / 6   Inbound
3  2015-09-01        Tom  Billing / 7  Outbound
4  2015-09-01       Jane      CCS / 3   Inbound

You can find more details in pandas concat API documentation
Update for new column,
data['Group_1'] = data.Group + data.Group.apply(lambda x:" / "+str(len(x)))

data
Out[56]:
     CallDate      Agent    Group Direction      Group_1
0  2015-09-01       Adam  Billing   Inbound  Billing / 7
1  2015-09-01  Nathaniel  Billing  Outbound  Billing / 7
2  2015-09-01    Jessica   Claims   Inbound   Claims / 6
3  2015-09-01        Tom  Billing  Outbound  Billing / 7
4  2015-09-01       Jane      CCS   Inbound      CCS / 3

A: you can use the cat function to concatenate two series in pandas check the Documentation here for the cat function .
also you can get the number of characters in any word easily by using the len function df.Group.str.len()
df['Group'] = df.Group.str.cat(df.Group.str.len().astype(str), sep=' => ')
df
Out[42]:
CallDate    Agent          Group         Direction
2015-09-01  Adam          Billing => 7   Inbound
2015-09-01  Nathaniel     Billing => 7   Outbound
2015-09-01  Jessica       Claims => 6    Inbound
2015-09-01  Tom           Billing => 7   Outbound
2015-09-01  Jane          CCS => 3       Inbound


text:
Q: CSS style being applied several times From the chrome debugger:
element.style {
}

#title a:link,a:visited,a:hover,a:active {
    color: #FF33CC;
    text-decoration: none;
}

(Everything below this is struck through)
nav a:link,a:visited,a:hover,a:active {
    color: #000000;
    text-decoration: none;
}

nav a:link,a:visited,a:hover,a:active {
    color: #000000;
    text-decoration: none;
}

#title a:link,a:visited,a:hover,a:active {
    color: #FF33CC;
    text-decoration: none;
}

#title a:link,a:visited,a:hover,a:active {
    color: #FF33CC;
    text-decoration: none;
}

I'm trying to figure out why an element (title) is not showing up properly. This is what it looks like in the html body:

    link

I understand that when it's struck through, that style isn't being applied. What I don't understand is
a) Why is the nav style being called at all?
b) Why does the title style for links get called several times? The first time it seems to work, but the second time it's being struck through? (On the website, the element currently is only showing up in black text.)
Thanks in advance!

A: Your style is being called because the nav parent only applies to the first part of the selector. Basically you have this:
nav a:link,
a:visited,
a:hover,
a:active{

//style

}

What you really want is:
nav a:link,
nav a:visited,
nav a:hover,
nav a:active{

//Style

}

The same thing goes for the #title a:link, a:visited, a:hover, a:active

My guess on why it is trying to use the same CSS multiple times would be that you have the same CSS in multiple places. E.G. you are either

*

*Importing the CSS twice

*Importing two CSS files with a duplicate style

*Duplicating the CSS in your one CSS file

Check the associated line numbers and see if they are the same (meaning it is actually using the exact same CSS twice) or different (meaning you have the same CSS in multiple places).

A: you have:
#title a:link, a:visited, a:hover, a:active {
color: #FF33CC;
text-decoration: none;
}

but what it seems like you need is:
#title a:link, #title a:visited, #title a:hover, #title a:active {
color: #FF33CC;
text-decoration: none;
}

the id tag has to appear after each comma, otherwise you are styling ALL links, not just the ones with the #title id.
Hope that helps!


text:
Q: Div containing google maps not closing with Javascript The Javascript function close() seems not to be working;it should close/hide the div containing a google maps map. In my maps.php file I've got the following:
echo"

 <button onclick='displayMap($x,$y)'>Show Map</button>";
echo"<button onclick='close()'>Chiudi</button> ";

Then, there is the JS part:


text:
Q: USING IF WITH OUTER APPLY IN MSSQL I want to write IF conditition in OUTER APPLY. I need to return more than one column so i don't want to write subqueries
SELECT name FROM v_users
OUTER APPLY
(
    IF CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)
   SELECT gender,email,age,class FROM tb_register_old WHERE id=v_users.user_id;
ELSE
   SELECT gender,email,age,class FROM tb_register_new WHERE id=v_users.user_id;
)s

A: Maybe this?
SELECT name FROM v_users
OUTER APPLY
(
 SELECT gender,email,age,class
 FROM tb_register_old
 WHERE id=v_users.user_id and CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)

 UNION ALL

 SELECT gender,email,age,class
 FROM tb_register_new
 WHERE id=v_users.user_id and CAST(reg_date AS DATE) >= CAST('03/25/2017' AS DATE)
)s


text:
Q: PHP session side-effect warning - how to get solve? I'm fairly new to php, and am sure this is easy, but I'd like to do it the right way. I have this script:
<?php
if ($_POST["username"]=="") {
    include($_SERVER['DOCUMENT_ROOT'] ."/login.inc.php");
} else {
    $username=$_POST["username"];
    $password=$_POST["password"];
    session_start();
    if ($username=="bob" AND $password=="123"){ $permission="yes";}
    $username=$_POST["username"];
    session_register("permission");
    session_register("username");

    if ($permission=="yes"){
        // Show stuff
    }
}
?>

Excuse the funky formatting of my code - can't seem to get it to show properly.
So, I keep getting this error:

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively in Unknown on line 0

Which I'm assuming means I need to change one of my variable names so it doesn't conflict with the session variable right? That's what I read, but I'm not sure which one to change.
Can anyone help / show me please?
Thanks
osu

A: It is happening because of
session_register("username");

It is not recommended, and deprecated as of PHP 5.3.

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

Source.
As we all know, register_globals is terrible, and should always be off.
The most common way to register a session var is with the $_SESSION superglobal, i.e.
$_SESSION['username'] = $username;

A: You better start on getting rid of deprecated functions such as session_register().
Use the $_SESSION array, e.g.
$_SESSION['username'] = $_POST['username'];


text:
Q: Problems in loading ARFF bases on WEKA in a Google App Engine project I'm constructing an application in Google App Engine (using Eclipse) that uses WEKA [1]  in one of its parts. This app needs to load ARFF bases, but that's allright. The directory in which these bases are is in project's root directory. Following lines are responsible for loading bases:
1. DataSource source;
2. source = new DataSource("bases/iris.arff");
3. Instances trainInstances = source.getDataSet();
4. trainInstances.setClassIndex(trainInstances.numAttributes() - 1);

Above lines are part of the code that is called in a servlet responsible for execution of the application. Servlet runs ok, but 'source' variable doesn't get to read arff file and, so, i get the following exception at line 3:
"java.io.IOException: No source has been specified
    at weka.core.converters.ArffLoader.getDataSet(ArffLoader.java:1003)"
According to [2],

It is possible to read from a file which is uploaded as part of your application provided that it is in the following locations: war/WEB-INF // in a location matching the  pattern in appengine-web.xml (which by default includes everything)

I've followed this two points, but with no sucess. To the second one, my configuration was the following:
<resource-files>
    <include path="/bases/**.arff" />
</resource-files>

Given this long history, I ask to you: Is there anyway to put "bases" directory in some place, or configuring something on GAE xml files, or on Eclipse, that make possible ARFF bases be loaded?

References
[1] www.cs.waikato.ac.nz/ml/weka/
[2] https://developers.google.com/appengine/kb/java#readfile

A: Your problem is more about loading resources in web application environment.
Some additional resources in stackoverflow about loading resources in web application environment.
Put your arff file in your source-src directory. When you compile your application, files under this directory copied to web-inf/classes directory.
See
You can see where they are copied if you create a war file. See
After you make sure that your arff file is included in your web archive file (war file). You can use appropriate path to it. Like below. You need to use InputStream constructor not String one.
InputStream stream = getServletContext().getResourceAsStream("WEB-INF/classes/iris.arff");
DataSource source = new DataSource(stream);

I have tried this with simple web application project, it works. My code is as below.
deneme.jsp
<%
InputStream stream = getServletContext().getResourceAsStream("WEB-INF/classes/iris.arff");
String summary = LoadArffFile.loadArffFileAndFindSummary(stream );

out.println(summary);

%>

LoadArffFile.java
public static String loadArffFileAndFindSummary( InputStream stream)
{

     DataSource source = new  DataSource(stream);
     String summary = null;
    try {
        summary = source.getStructure().toSummaryString();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     return summary;
}

Output in tomcat.
Relation Name: iris Num Instances: 0 Num Attributes: 5 Name Type Nom Int Real Missing Unique Dist 1 sepallength Num 0% 0% 0% 0 / 0% 0 / 0% 0 2 sepalwidth Num 0% 0% 0% 0 / 0% 0 / 0% 0 3 petallength Num 0% 0% 0% 0 / 0% 0 / 0% 0 4 petalwidth Num 0% 0% 0% 0 / 0% 0 / 0% 0 5 class Nom 0% 0% 0% 0 / 0% 0 / 0% 0


text:
Q: What is $product in bundle id I want to submit my application to appstore.
I saw this screen shot

So what is ${PRODUCT_NAME:rfc1034identifier}
Is it the name of the executable?
Is there  a way to change it?
Should I just hardcode the ${PRODUCT_NAME:rfc1034identifier} and put actual product name?

A: I believe you're correct that "product" is the executable name, but even if it isn't you won't have any problem with hard coding your bundle ID, I always do this. (true or not) I feel like it makes the process more fool proof.
EDIT: It seems like this is automatically set to the name of the project.

A: It's not the name of the project.  A project can have multiple targets, each producing different products.
PRODUCT_NAME is a build setting.


text:
Q: How to get parent node in a tree structure like this How it would be possible to get a parent when tree structure is like this:
public class TreeModel
{
    public int ID { get; set; }
    public List<TreeModel> Children { get; set; }
}

Let's say we can't add a parent element item to this class (public TreeModel Parent { get; set; }).
Edit
How to get element m22 (ID=22) parent m2 (ID=2) from the m1? I thought we could iterate through m1 and somehow return parent when condition is right.
var m1  = new TreeModel() { ID = 1  };
var m2  = new TreeModel() { ID = 2  };
var m21 = new TreeModel() { ID = 21 };
var m22 = new TreeModel() { ID = 22 };
var m3  = new TreeModel() { ID = 3  };

m1.Children.Add(m2);
m2.Children.Add(m21);
m2.Children.Add(m22);
m1.Children.Add(m3);

var parent = m1.GetParent(p => p.ID == 22); //<-- How?

A: public IEnumerable<TreeModel> GetAllDescendants(IEnumerable<TreeModel> rootNodes)
{
    var descendants = rootNodes.SelectMany(_ => GetAllDescendants(_.Children));
    return rootNodes.Concat(descendants);
}

public static TreeModel GetParent(this TreeModel rootNode, Func<TreeModel, bool> childSelector)
{
    var allNodes = GetAllDescendants(new [] { rootNode });
    var parentsOfSelectedChildren = allNodes.Where(node => node.Children.Any(childSelector));

    return parentsOfSelectedChildren.Single();
}

m1.GetParent(_ => _.ID == 22);

*

*Obtain a flat list of all nodes

*Search this list for the node whose direct children contains m22

A: Use this code pattern. It simplifies the code because you don't have to explicitly add nodes to the children and each node knows who its parent is and who its children are. Also it is all type safe.
class Program
{
    static void Main(string[] args)
    {
        var m1=new TreeModel() { ID=1 };
        var m2=new TreeModel(m1) { ID=2 };
        var m21=new TreeModel(m2) { ID=21 };
        var m22=new TreeModel(m2) { ID=22};
        var m3=new TreeModel(m1) { ID=3 };

        var item=m1.RecursiveFind((p) => p.ID==22);
        var parent=item.Parent;
        // parent.ID == 2
        var root=item.Root;
        // root.ID == 1;
    }
}

public class TreeModel : Tree<TreeModel>
{
    public int ID { get; set; }
    public TreeModel() { }
    public TreeModel(TreeModel parent) : base(parent) { }
}

public class Tree<T> where T : Tree<T>
{
    protected Tree() : this(null) { }
    protected Tree(T parent)
    {
        Parent=parent;
        Children=new List<T>();
        if(parent!=null)
        {
            parent.Children.Add(this as T);
        }
    }
    public T Parent { get; set; }
    public List<T> Children { get; set; }
    public bool IsRoot { get { return Parent==null; } }
    public T Root { get { return IsRoot?this as T:Parent.Root; } }
    public T RecursiveFind(Predicate<T> check)
    {
        if(check(this as T)) return this as T;
        foreach(var item in Children)
        {
            var result=item.RecursiveFind(check);
            if(result!=null)
            {
                return result;
            }
        }
        return null;
    }
}

When you derive from Tree<T>, you create custom tree structures that you design what the node class is (TreeModel here) and how to handle parents, children and siblings if needed.

A: What about:
public class SaneTreeModel:  TreeModel
{
  public SaneTreeModel Parent { get; set; }
}
}

A: Absolutely not, with a child node like that you can't get its parent. Simply because there isn't any reference to it.
To get the parent of the node, you have to either add the parent field or save the reference in somewhere else (by a variable or something).
EDIT
@Zulis If you search from the root node, you can definitely find the node you want. But as I said, with just the child node you can't do that.
But I think you should avoid searching because that would be slow

A: I would approach this by first finding the first element that satisfies the condition (ID == 22 in your example) and then finding the parent of this element. Not the best solution but maybe you will need them separately for something else.
public TreeModel GetParent(Func<TreeModel, bool> function)
{
    return GetParent(Where(function));
}

private TreeModel GetParent(TreeModel treeModel)
{
    if (Children == null) return null;

    if (Children.Contains(treeModel)) return this;

    foreach (TreeModel child in Children)
    {
        TreeModel result = child.GetParent(treeModel);
        if (result != null)
            return result;
    }
    return null;
}

private TreeModel Where(Func<TreeModel, bool> function)
{
    if (Children == null) return null;

    foreach (TreeModel child in Children)
    {
        if (function(child))
            return child;

        TreeModel result = child.Where(function);
        if (result != null)
            return result;
    }

    return null;
}

If you put this code block in your TreeModel class, the example you provided will return m2


text:
Q: Computer turns off and on after start ..then goes dead I built a new PC from the following components:
- CPU: Intel Core i7 950
- MB: Gigabyte X58A-UD3R
- RAM: 2x2gb i7 Corsair memory
- VGA: Zotac AMP2 GTX260
- HDD: 1 GreenSATA HDD (Western Digital 500gb RE2)
When I turn it on, it goes for a few seconds, fans at maximum speed, then turns off.
The again, it starts by itself.. and goes with fans on max speed, nothing happens.
First I suspected my PSU. It's a Chieftec 450AA PSU.
After I borrowed a Chieftec 550AA PSU, I tried to start with that.
Exact same story.
Any idea ? Do I need a bigger PSU?
Reason why its not localized. I never seen this turn on, off, on.
If you give answer for that, it would already help people like me, with the same problem.

A: Maybe your RAM sticks are faulty. You should try unplugging them and plugging them back.
Also, I suggest you check every cable connection between the motherboard and the components.
EDIT: Does your BIOS make any beeping noise? It may be notifying you of a problem.
Here are databases for AMI Bios, Award and Phoenix

*

*http://pcsupport.about.com/od/fixtheproblem/tp/ami-beep-codes.htm

*http://pcsupport.about.com/od/fixtheproblem/tp/award-beep-codes.htm

*http://pcsupport.about.com/od/fixtheproblem/tp/phoenix-beep-codes.htm


text:
Q: Properties and methods of req and res objects in node js What are the properties and methods of response and request objects available in node js?
Like : request.url or res.end, res.write?
Where can I find all the listed properties? Thanks

A: The easiest way to find out in JavaScript which functions, properties, ... an object has is to serialize the object to a string and print that string to the console.
Basically this is a one-liner, such as:
console.log(JSON.stringify(req));

This shows you everything the req object has.

A: http://nodejs.org/api/http.html

A: To best  understand one of the modules intrinsic to nodejs, you should first read its documentation. Then, if further understanding is required, you'll want to explore the source code where it is defined. (Most of the intrinsic modules are themselves written in JavaScript.)
For example, the ServerResponse object (as typically passed into HTTP request handlers as "res") is defined on line 867 in http.js which can be found in the nodejs source code at https://github.com/joyent/node/blob/master/lib/http.js
By exploring the source, you'll be able to see what methods and properties the object supports by itself.
Then, to fully understand how a object works and discover all of its methods and properties, you'll need to follow its inheritance tree.

ServerResponse inherits from

OutgoingMessage (defined in the same file) which itself inherits from

Stream (defined in stream.js) which further inherits from

events.EventEmitter, which is of course, an

Object

So, the full list of methods and properties of ServerResponse are:
ServerResponse

  statusCode             property
  _implicitHeader()      method
  assignSocket()         method
  detachSocket()         method
  writeContinue()        method
  writeHead()            method
  writeHeader()          method

  _buffer()              (from OutputMessage) method
  _finish()              (from OutputMessage) method
  _flush()               (from OutputMessage) method
  _renderHeaders()       (from OutputMessage) method
  _send()                (from OutputMessage) method
  _storeHeader()         (from OutputMessage) method
  _writeRaw()            (from OutputMessage) method
  addTrailers()          (from OutputMessage) method
  destroy()              (from OutputMessage) method
  end                    (from OutputMessage) method
  getHeader()            (from OutputMessage) method
  removeHeader()         (from OutputMessage) method
  setHeader()            (from OutputMessage) method
  write()                (from OutputMessage) method

  pipe()                 (from Stream) method

  addListener()          (from EventEmitter) method
  emit()                 (from EventEmitter) method
  listeners()            (from EventEmitter) method
  on()                   (from EventEmitter) method
  once()                 (from EventEmitter) method
  removeAllListeners()   (from EventEmitter) method
  removeListener()       (from EventEmitter) method
  setMaxListeners()      (from EventEmitter) method

  arguments              (from Object) property
  caller                 (from Object) property
  length                 (from Object) property
  name                   (from Object) property
  prototype              (from Object) property
  super_                 (from Object) property

  __defineGetter__()     (from Object) method
  __defineSetter__()     (from Object) method
  __lookupGetter__()     (from Object) method
  __lookupSetter__()     (from Object) method
  constructor()          (from Object) method
  hasOwnProperty()       (from Object) method
  isPrototypeOf()        (from Object) method
  propertyIsEnumerable() (from Object) method
  toLocaleString()       (from Object) method
  toString()             (from Object) method
  valueOf()              (from Object) method
  apply()                (from Object) method
  bind()                 (from Object) method
  call()                 (from Object) method

By following an object's entire inheritance tree, you build an intimate understanding of how nodejs works, and appreciate what an amazing tool it is.

A: You can find a lot of the properties listed at any of the Node.js manual websites, such as http://nodemanual.org/latest/nodejs_dev_guide/creating_an_http_server.html


text:
Q: How to set data for vue variable I have 2 vue variables. I want to set data for vue1 from vue2. What is the correct way to do it.
var vue1 = new Vue({
    el: '#id1',
    data: {
        'name': 'Vue name'
    },
    methods: {

    },
    delimiters: ["[[", "]]"],
});

var vue2 = new Vue({
    el: '#id2',
    data: {

    },
    methods: {
        func1:function (name) {
            // Here i want to set vue1.name=name
            vue1.name=name;
        }
    },
    delimiters: ["[[", "]]"],
});

I have seen a function setData() but I dont know how to use it and if this is the correct scenario for that function.

A: I would add a method on the component itself for that purpose.

var vue1 = new Vue({
  el: '#id1',
  data: () => ({
    name: 'Vue name'
  }),
  methods: {
    changeName(name) {
      this.name = name;
    }
  },
  delimiters: ["[[", "]]"],
});

var vue2 = new Vue({
  el: '#id2',
  computed: {
    input: {
      get: () => vue1.name,
      set: vue1.changeName
    }
  },
  delimiters: ["[[", "]]"]
});

[[$el.id]]

    [[name]]

[[$el.id]]

    <input v-model="input" />

A: You can use a store pattern. For simple solution, you can use the following.
Store stores the shared values.
var store = {
    state: {
       name: null
    },
    setName: function(val) {
       this.state.name = val;
    },
};

How to access (or set) shared values from vue.
var vue1 = new Vue({
    el: '#id1',
    data: {
        sharedState: store.state,
        otherValue: 'some value'
    },
    methods: {
        set: function() {
            store.setName('John Doe');
            console.log(this.sharedState.name); // John Doe
        }
    },
});

A: here is that way you can use data from one VUE instance to another Vue Instance . Using instance name with $data to catch the data , like app.$data.message . where i want to use first instance data to second app instance

var app = new Vue({
  el: '#app',
  data: {
    message: 'first vue app message'
  }
})

var app2 = new Vue({
  el: '#app2',
  data: {
    message: app.$data.message
  }
})

  {{ message }}

  {{ message }}


text:
Q: Which type of caching can be used in this scenario In my ASP.net Web form Application.
my Timetable.aspx page requests data from WebMethod of Timetable.aspx.cs in JSON format on the basis of a parameter GroupId, while Timetable.aspx.cs fetch data from TimeTableBl.cs which fetch data from TimeTableDataLayer.cs and which call a stored proc usp_get_TimeTableByGroupId
Fetching timetable every time from database is a very resource eating task which should be cached at some level.
So basically I want to know just an overview of that appropriate approach.
Like Doing caching in Businesslogic Layer level by creating a Hashmap of Timetable with key as GroupId if a timetable is already requested by someone then the same JSON will be rendered corresponding to that particular timetable otherwise a new Timetable will be fetched from DB and firsted inserted into the Hashmap and then rendered as JSON string.
While this can be risky when I tried to update a particular timetable object in hashmap which is being used by another thread simultaneously.
So what can be the solution of this.
Here a Timetable is a collection of Periods.
While a period contains following properties.
List<Periods> TimeTable =  new List<Periods>();

class Period
{
    int Id;
    DateTime StartTime;
    DateTime EndTime;
    tinyint Weekday;

    int RoomId;
    string RoomNo;//alphanumeric

    int facultyId;
    string FacultyName;

    int subjectId;
    string SubjectName;
}


text:
Q: Magento 2 Uncaught TypeError: data.some is not a function I have found below error in console on backend while editing customer from customer grid.
Path: Customers-> All Customers -> Edit.

Uncaught TypeError: data.some is not a function
      at findFirst (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :5:41)
      at UiClass.clear (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :13:271)
      at UiClass.setInitialValue (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :13:406)
      at UiClass.eval [as setInitialValue] (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :5:186)
      at UiClass.initialize (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :3:1152)
      at UiClass.eval [as initialize] (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :5:186)
      at UiClass._super (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :5:147)
      at UiClass.initialize (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :8:172)
      at UiClass.eval [as initialize] (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :5:186)
      at new UiClass (eval at require.load (58d22521c2a079102fb0d912e124e25b.min.js:180), :5:16)

Thanks in advance for any help.


text:
Q: RecyclerView with background image at top What I'm trying to achieve is this:

As you can see, there is a background image that appears slightly behind the first card in the RecyclerView.
When the user scrolls, the background image, as well as the "Discover" text and icon, should also scroll off the screen.
I've looked into putting the RecyclerView into a NestedScrollView, but from what I've read, this breaks the RecyclerView and doesn't allow it to recycle views (I could be wrong).
How would I achieve something like this? Right now, my layout is very bare bones:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.v4.widget.SwipeRefreshLayout>

</android.support.design.widget.CoordinatorLayout>

Thanks.

A:
Background image that appears slightly behind the first card in the
  RecyclerView.

You can do that using CollapsingToolbarLayout, it will hide parallax the background behind. Note: using   app:behavior_overlapTop to make RecyclerView loverlap the the background.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="300dp"
            app:titleEnabled="false"
            app:expandedTitleMarginBottom="94dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?colorPrimary"
            >

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:src="@drawable/london_flat"
                android:tint="#BB3E50B4"
                android:scaleType="centerCrop"
                />

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@null"
                app:layout_collapseMode="pin"
                style="@style/ToolBarWithNavigationBack"
                />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        app:behavior_overlapTop="78dp"
        android:layout_margin="8dp"
        android:background="@color/cardview_light_background"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        >

    </android.support.v7.widget.RecyclerView>

</android.support.design.widget.CoordinatorLayout>

And the result:


text:
Q: Complexity to check two graphs are isomorphic? Compute the complexity -
(i) Given two graphs and check whether graphs are isomorphic or not?
(ii) Subgraph matching.

A: ad (i) - This is an open problem, see "Recognition of graph isomorphism" or "Graph isomorphism problem".
ad (ii) - See "Matching (graph theory)".


text:
Q: Output comes in dictionary sorted order in python I have a collection of csv files with names like 2.csv , 3.csv ...., 999.csv. Each file has 91 rows in it. I want to have a set of new files collecting a particular row from all the files. Eg. row1.csv should have first row of all the 998 files and similarly row35.csv should have 35th row of all the 998 files. Therefore I should have in total 91 files (one for each row) with each file having 998 rows (one for each original file) after my script completes the run.
I use the following code for the task
import glob
import os
for i in range(2,92):
  outfile = open("row_%i.csv" %i,'w')
  for filename in glob.glob('DataSet-MediaEval/devFeatures/*.csv'):
    with open(filename, 'r') as infile:
      lineno = 0
      for line in infile:
        lineno += 1
        if lineno == i:
          outfile.write(line)
  outfile.close()

Now in any of the outfile row_i.csv my data is arranged in dictionary sorted order. Example :
First row in row_50.csv file is the 50th row of 10.csv.
In other words in any row_i.csv the rows comes from 10.csv, 100.csv, 101.csv and so on.
I wanted to know why is that happening and is there a way in which I can ensure that my row_i.csv is ordered in the way the files are ordered i.e. 2.csv, 3.csv and so on.
Thanks for the time spent reading this.

A: Not sure if this works out or if there are more problems, but it seems like glob either returns the filenames in sorted order (sorted as strings), or in random order. In both cases, you will have to extract the number from the filenames and sort by that number.
Try something like this:
p = re.compile(r"/(\d+)\.csv")
filenames = glob.glob(...)
for filename in sorted(filenames, key=lambda s: int(re.search(p, s).group(1))):
    ...

Also, it seems like you are opening, looping and closing all those 999 files for all of the 92 outfiles again and again! It might be better to open all of the 92 outfiles at once and store them in a dictionary, mapping line numbers to files. This way, you have to loop the 999 files just once.
Something like this (totally not tested):
outfiles = {i: open("row_%i.csv" %i, 'w') for i in range(2,92)}
p = re.compile(r"/(\d+)\.csv")
filenames =  glob.glob('DataSet-MediaEval/devFeatures/*.csv'):
for filename in sorted(filenames, key=lambda s: int(re.search(p, s).group(1))):
    with open(filename, 'r') as infile:
        for lineno, line in enumerate(infile):
            outfiles[lineno].write(line)
for outfile in outfiles.values():
    outfile.close()

A: You need to sort the filename list before start iteration on it. This can help you:
import re
import glob

filename_list = glob.glob('DataSet-MediaEval/devFeatures/*.csv')

def splitByNumbers(x):
    r = re.compile('(\d+)')
    l = r.split(x)
    return [int(y) if y.isdigit() else y for y in l]

filenames = sorted(filename_list, key = splitByNumbers)

then you can use instead of
for filename in glob.glob('DataSet-MediaEval/devFeatures/*.csv'):

this
for filename in filenames:


text:
Q: Restate Theorem with given theorem setup I am given the follwoing theorem setup, which I have to use.
\numberwithin{equation}{chapter}
\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{definition}[theorem]{Definition}
\newtheorem{proposition}[theorem]{Proposition}
\theoremstyle{nonumberplain}
\theorembodyfont{\normalfont}
\theoremsymbol{\ensuremath{\square}}
\newtheorem{proof}{Proof}

How is it possible to restate a theorem with the same number as when stated first. I don't mind if I have to rewrite the theorem or even put the number in by hand, because I only need it once.

A: I solved my problem by changing the setup a bit.
\numberwithin{equation}{chapter}
\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{definition}[theorem]{Definition}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem*{thm345}{Theorem 3.45}
\theoremstyle{nonumberplain}
\theorembodyfont{\normalfont}
\theoremsymbol{\ensuremath{\square}}
\newtheorem{proof}{Proof}

Now using:
\begin{thm345}
theorem text
\end{thm345}

gives me what I want


text:
Q: Insert array into MongoDB subdocument with Node.js I currently have a schema which looks as follows:
positionsApplied:[{
        position_id:String,
        index_position: Number
}],

I also have 3 objects which I need to insert into my database:

How can I insert these into my database through an Ajax call? What Ive tried so far:
Adding the data to an array like this:
["58d6b7e11e793c9a506ffe8f", 0, "58c2871414cd3d209abf4fc1", 1, "58d6b7e11e793c9a506ffe7f", 1]

Which would then be passed through my ajax call like this?(unsure)
$.ajax({
             url: "/insertPositionIndex",
             type: "POST",
             dataType: "json",
             data: {
                 newarray
             },
             success: function (data) {
            console.log(data);
          }
        })

Inserting into the database is where I'm stuck, how do I break down the array in order to insert it?
app.post('/insertPositionIndex', function(req, res){
var object = req.body.ordered_divs;
console.log(req.body);

      User.update(
        { "_id": req.user._id},
        { "$push":
            {"positionsApplied":
                {
                // unsure what to do here?

                }
            }
        }
    ).exec(function (err, result) {
           console.log(result);
           res.send({ results: result });
      });
      });

Any help is greatly appreciated!
* Note the position_id field in the schema is the div_id in the array, also the index-position field is the index_pos in the array.
user schema:
    var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var User = new Schema({
    id: String,
    name: String,
    companyname: String,
    password: String,
    email: String,
    username: String,
    location: String,
    role:String,
    teamwork:Number,
    initiative:Number,
    technical_skills: Number,
    communication:Number,
    employees: String,
    profile_image: String,
    biodescription: String,
    twitter: String,
    facebook: String,
    instagram: String,
    linkedin: String,
    biodescription: String,
    positionsApplied:[{
                            position_id:String,
                            index_position: Number
    }],
    experience: [{
          title: String,
          location: String,
          company: String,
          start: String,
          end:String,
          description:String
  }],
    position: [{
                    _id:String,
          title: String,
          location: String,
          start: String,
          term:Number,
          description:String,
          date: {type: Date, default: Date.now},
          applied:[{
                candidate_id: String,
                profile_image: String,
                location: String,
                name: String,
                _id:String
                        }],
  }],
  education: [{
          school: String,
          location: String,
          degree: String,
          start: String,
          end:String,
          description:String,
                    _id:String
  }],

    images: [{
                    one: String,
                    two: String,
                    three: String,
                    four: String,
                    five:String,
                    six:String
    }],
});

module.exports = mongoose.model('User', User);

A: Since your Schema is an array of objects and the data that you are getting(as per console of the browser) is also an array of objects why don't you just pass that array itself(the one in the console of the browser) through ajax and use the $each of mongodb $push to save it into the database.
$.ajax({
         url: "/insertPositionIndex",
         type: "POST",
         dataType: "json",
         data: {
             arrayOfObjects
         },
         success: function (data) {
        console.log(data);
      }
    })

app.post('/insertPositionIndex', function(req, res){
var object = req.body.ordered_divs;
console.log(req.body);

      User.update(
        { "_id": req.user._id},
        {
        "$push":
            {
             "positionsApplied":{
                $each: req.body.arrayOfObjects
               }
            }
        }
    ).exec(function (err, result) {
           console.log(result);
           res.send({ results: result });
      });
});

You will have to change the arrayOfObjects keys to match that of your schema positionsApplied keys.


text:
Q: Combine $facet result with subdocument and then conditionally excluding document Suppose after the $facet stage I have a result including two arrays: roomInfo and hotelInfo.
Which looks like this:
{
  "roomInfo": [
    {
      _id: 'ab1',
      booked: 3
    },
    {
      _id: 'ab2',
      booked: 1
    }
  ],
  "hotelInfo": [
    {
      name: 'Radison Blue',
      roomDetails: [
        {
          _id: 'ab1',
          roomCount: 5
        },
        {
          _id: 'xy1',
          roomCount: 5
        }
      ]
    },
    {
      name: 'Intercontinental',
      roomDetails: [
        {
          _id: 'ab2',
          roomCount: 5
        }
      ]
    }
  ]
};

Expected Result
I want an output like this:
[
  {
    name: 'Radison Blue',
    roomDetails: [
      {
        _id: 'ab1',
        roomCount: 5,
        booked: 3
      },
      {
        _id: 'xy1',
        roomCount: 5,
        booked: 0
      }
    ]
  },
  {
    name: 'Intercontinental',
    roomDetails: [
      {
        _id: 'ab2',
        roomCount: 5,
        booked: 1
      }
    ]
  }
];

Basically, adding the booked property from roomInfo into the hotelInfo's roomDetails field after matching their ids.

*Additionally, after getting the above output result I want to exclude those hotels on which all the rooms(not for a single room) have the value of fields roomCount and booked equal. I want to do this inside the aggregation pipeline stage as I will have to deal with $skip and $limit later on.

How to achieve these use cases?
Thanks!

A: Basically the approach will be iterating over the hotels and matching each room accordingly, here is a quick working code sample:
db.collection.aggregate([
  {
    $unwind: "$hotelInfo"
  },
  {
    $project: {
      name: "$hotelInfo.name",
      "roomDetails": {
        $filter: {
          input: {
            $map: {
              input: "$hotelInfo.roomDetails",
              as: "info",
              in: {
                "$mergeObjects": [
                  "$$info",
                  {
                    "$arrayElemAt": [
                      {
                        $filter: {
                          input: "$roomInfo",
                          as: "room",
                          cond: {
                            $eq: [
                              "$$room._id",
                              "$$info._id"
                            ]
                          }
                        }
                      },
                      0
                    ]
                  }
                ]
              }
            }
          },
          as: "proccessedInfo",
          cond: {
            $ne: [
              "$$proccessedInfo.roomCount",
              "$$proccessedInfo.booked"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground
With that said you mention you'd like to paginate calls in the future. the current approach does not seem scaleable, because these are "real data points" aka hotels it's fine if your scale is somewhat capped ( no more than several thousands hotels ). but if it's not I recommend you ask another question with the entire pipeline you have so we can adjust it to work better.


text:
Q: Rust lang lifetime mismatch for HashMap with str key I'm trying to implement an existing C++ algorithm, that works, in Rust to understand how lifetimes work.. What is the pattern that we should use for the following... to give a background, this algorithm tries to find the length of the longest palindromic subsequence.
use std::cmp::{max, min};
use std::collections::HashMap;
use std::str;

fn main() {
    let mut m = HashMap::new();
    println!(
        "Longest palin size: {}",
        longest_palin_substring("abdbca".as_bytes(), &mut m)
    );
}

    pub fn longest_palin_substring(is_palin: &[u8], map: &mut HashMap<&str, usize>) -> usize {
    println!("current string : {}", str::from_utf8(is_palin).unwrap());
    if is_palin.len() == 0 || is_palin.len() == 1 {
        return is_palin.len();
    }

    if let Some(len) = map.get(str::from_utf8(is_palin).unwrap()) {
        *len
    } else {
        let c1 = if is_palin[0] == is_palin[is_palin.len() - 1] {
            let r = longest_palin_substring(&is_palin[1..is_palin.len() - 1], map);
            if r == is_palin.len() - 2 {
                2 + r
            } else {
                0
            }
        } else {
            0
        };

        let c2 = longest_palin_substring(&is_palin[1..], map);
        let c3 = longest_palin_substring(&is_palin[..is_palin.len() - 1], map);

        let c = max(c1, max(c2, c3));
        map.insert(str::from_utf8(is_palin).unwrap(), c);
        c
    }
}

error[E0623]: lifetime mismatch
  --> src/main.rs:38:20
   |
14 |     pub fn longest_palin_substring(is_palin: &[u8], map: &mut HashMap<&str, usize>) -> usize {
   |                                              -----                    ----
   |                                              |
   |                                              these two types are declared with different lifetimes...
...
38 |         map.insert(str::from_utf8(is_palin).unwrap(), c);
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...but data from `is_palin` flows into `map` here

error: aborting due to previous error; 1 warning emitted

For more information about this error, try `rustc --explain E0623`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

I tried adding &'a lifetime to all the references, but then it complains of mutable borrow happening multiple times.
 pub fn longest_palin_substring<'a>(
     is_palin: &'a [u8],
     map: &'a mut HashMap<&'a str, usize>,
 ) -> usize {

Error:
error[E0499]: cannot borrow `*map` as mutable more than once at a time

My questions are as follows:

*

*first, obviously, is how I should proceed to fix this compile error

*what is the pattern to follow for some state that will be used to memoize results in a recursive implementation of, say, dynamic programming.

Any pointers where I can learn more about patterns in rust would be greatly appreciated.
Thanks.

A: You're close. First, the lifetime of the hashmap is going to be different than the lifetime of its key type.
The compile errors can be fixed as such:
pub fn longest_palin_substring<'a>(is_palin: &'a [u8], map: &mut HashMap<&'a str, usize>) -> usize {

As a general rule, if you aren't storing a reference passed to a function, you don't want any lifetime annotations on the type, the compiler uses the function signature to determine how references are used without inspecting the function's contents.
Second, for memoizing things, I would use some interior mutability primitives. If the algorithm is single threaded then Cell or RefCell will do, if not a Mutex will allow you to mutate internal state.
If things are going to be memoized only once, you may be interested in once_cell (it's still nightly-only, but there is a crate usabe in stable).


text:
Q: AngularJS: Apply a css class when a filter return no result I've created a kind of glossary with AngularJS
When i click on an alphabet list buttons,  a function (categoryFilterFn), filter the json data by categories. I would like to apply a CSS to the button, when no results is returned by the filter.
 For example if i click on the Z button, no exist related entry in the json file, so the filter return nothing, and the Z letter button will be set with a white color with css. I don't know how to apply this using ng-clas. The code here:

    <button type="button" ng-repeat="letter in alphabet" ng-click="selectCategory(letter)">
      {{letter}}
    </button>

      {{item.categoria}}

the controller:
essaiApp.controller("EssaiCtrl", function ($scope, $filter) {
    $scope.todo = model;
    var selectedCategory = null;

    $scope.selectCategory = function (newCategory) {
        selectedCategory = newCategory;
    }

    $scope.categoryFilterFn = function (polo) {
        return selectedCategory == null ||
            polo.categoria == selectedCategory;
    }

    $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
});

A: Save the filtered result:

Move selectedCategory to $scope:
$scope.selectedCategory = null;

$scope.selectCategory = function(newCategory) {
  $scope.selectedCategory = newCategory;
}

Use ng-class on the buttons:
ng-class="{ 'no-result': selectedCategory === letter && !filteredItems.length }"

Demo: http://plnkr.co/edit/Gl1i4dLyCCwuorQHB5SS?p=preview

A: As an alternative to tasseKatt's solution, you can manage your filtered array in the controller:
$scope.selectCategory = function(newCategory) {
  $scope.filtered = [];
  $scope.selectedCategory = newCategory;
}

$scope.categoryFilterFn = function(item) {
  if (item == $scope.selectedCategory)
    $scope.filtered.push(item);

  return item == $scope.selectedCategory
}

http://plnkr.co/edit/oOSOGPjaq9g7DaWRaFks?p=preview


text:
Q: Size of objects in memory If I have a class with 100 properties that are all int32's, and I have instanced 100 of these objects then does it necessarily take up 40000 bytes (plus whatever other overhead an object takes) even before any of the properties are set or does some (or all) of that space remain unallocated until you actually assign a value to the preoperties for the first time?

A: When an object is created, the memory for all fields is allocated immediately. Note that the size of the object also includes the object header, padding, etc.

A: You use the memory as soon as you instantiate the object, because int is a value type.
Reference types work a little different. If you were to make the property strings instead of integers, you would still use the ~40,000 bytes, but no more, because at this point your strings are all null-references (null references still reserve the space for the reference). As you start setting values to the strings, then you would start using the space.

A: Int32, like all value types, has a default value. (0)
So yes; as soon as you create those Int32 variables, they are taking up memory.

A: All class-scoped fields are "assigned" following instantiation, unlike locally-scoped variables, which can remain unassigned indefinitely.  Thus, value types consume their appropriate size, and references consume the size of a moving pointer, no matter what--when they are scoped at the class level.
Note also that unless the layout is sequential (as in a struct) or explicit, most value types will be padded to at least 32 bits.
It's not always straightforward to predict how much space a null reference will consume, but were they normal pointers, they would consume 4 bytes on x86 platforms and 8 bytes on x64 platforms.


text:
Q: Log click on "go back" button in browser Can you somehow log user click on go back button? I've tried to change history.go and history.back buttons, but it doesn't work.

A: Actually you can, you can store history.length in local storage, and when user click go back you'll see that the value you store is less than the value in history.length.