text:
Q: Regex - extract word inside < > brackets I am trying to extract an email address from a string like
John Smith <jsmith@email.com>
I just need the email address in the < > brackets.
Here is what I have tried so far, but I'm not very good with regex and it doesn't seem to be working, can anyone help?
import re
sender = str(message.sender)
p = re.search(r"\<(\w+)\>", sender)
logging.info(p.group(1))

A: You can try this:
import re
s = "John Smith <jsmith@email.com>"
email = re.findall('<(.*?)>', s)[0]

Output:
'jsmith@email.com'

Or, a more email-specific solution:
email = re.findall('(?<=\<)\w+@[a-zA-Z]+\.[a-z]+(?=\>)', s)[0]

Output:
'jsmith@email.com'

A: Currently your regex is : "\<(\w+)\>"
You do not actually need to escape the <>, so it becomes: "<(\w+)>"
\w matches letters, numbers and the underschore '_'. In an e-mail address there are other characters as well.
You have two options: Either just accept anything inside the <> with a regex like "<(.*)>" or actually parse an e-mail address.
A simple regex for that would be "<\S+@\S+>" (non-whitespace characters followed by @ followed by non-whitespace characters.
Restricting ourselves to the more commonly used characters, we can write: "<[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+> This still permits certain illegal e-mail addresses because I have kept it fairly simple.

A: Use a negative character set:
import re
s = "John Smith <jsmith@email.com>"
email = re.findall('<([^>])>', s)[0]

That matches anything thats not a > character, so everything thats in the angular brackets.


text:
Q: Android project depends on java project I've been playing with a Java's Magento connector called magja (https://github.com/magja/magja) in a 'normal' Java project. And everything were working fine till this point.
After that, I started a simple Android application that would use the magja code to consume such information from Magento.
The question is: how should I configure the my Android project to deal with a 'normal' Java project (not a library)? This another project uses several xml files to configuration and Maven to deal with dependencies. How this impacts my Android App?
Thanks a lot!
EDITED
Actualy, I've already tried this approach (Android project unable to reference other project in eclipse), but always when the app tries to run the 'project B' (magja) code, it causes a
java.lang.NoClassDefFoundError: org.apache.commons.httpclient.params.HttpConnectionManagerParams
I believe it's related to some .jar files that magja uses. It looks like that I would solve the problem if I could share such library between the projects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure Data Explorer Cost Estimator giving implausible estimates I am trying to estimate Azure Data Explorer cost by using the suggested tool Azure Data Explorer Cost Estimator.
Entering the data below i get a total amount if $984 (if i add Kusto Markup fees which are only discounted until 17th May but we will on in Production beyond this date).

When i increase the value in the "Data collected (TB) per day" field to 0.02 the total price drops to $837.

I understand, that the reduced price comes from suggesting only 2 Engine-VMs instead of 3 for the first amount of data.
My assumption is, that 2 Engine VMs of Type D11 are more powerful than 3 VMs of E2A_v4 VMs.
In this case my plan would be to start with D11 Engine VMs and get more power for less money.
Is my assumption correct and does this plan make sense or is there anything i am missing?
Thanks for any suggestions.

A: The VMs in Azure Data Explorer cluster provide two essentials capabilities:

*

*CPU (used to compute the queries)

*Disk (used to hold the hot data cache)

The E2a_v4 node has ~0.25 of the disk space and roughly equivalent CPU power compared to D11 node and it cost ~20% cheaper. So by trading 3 nodes of E2 with 2 nodes of D11, you are gaining more disk space (for the cache) but you lose 2 CPU cores used for computing the queries.
You should make the decision of which SKU to choose based on your workload. Assuming fixed budget, if the perf is good and the constraining factor is the disk space choose D11, if on the other hand you have small data size and can use more CPU, choose the E2a_v4.


text:
Q: Set table's highlighted column text color I am implementing a solution to cross-highlight both table rows and columns based on CssTricks ::before & ::after + negative z-index hack.
The goal is to do it with CSS only, if possible.
I want to set all highlighted cells text to Red color.
For rows it's easy, we just set a rule like tbody tr:hover td { color: red; }
But for columns I can't figure out a way to do it...
Is there a way to achieve the same with columns?
table {
  overflow: hidden;
}

th {
  background-color: silver;
  color: white;
}

td, th {
  padding: 10px;
  position: relative;
  outline: 0;
}

body:not(.nohover) tbody tr:hover {
  background-color: #ffa;
}

/* font settings for highlighted Row */
tbody tr:hover td {
  color: red;
  font-weight: bold;
}

/* font settings for highlighted Column??????? */
/* (how to do it?) */

td:hover::after,
thead th:not(:empty):hover::after,
td:focus::after,
thead th:not(:empty):focus::after {
  content: '';
  height: 10000px;
  left: 0;
  position: absolute;
  top: -5000px;
  width: 100%;
  z-index: -1;
}

td:hover::after,
th:hover::after {
  background-color: #ffa;
}

td:focus::after,
th:focus::after {
  background-color: lightblue;
}

/* Focus stuff for mobile */
td:focus::before,
tbody th:focus::before {
  background-color: lightblue;
  content: '';
  height: 100%;
  top: 0;
  left: -5000px;
  position: absolute;
  width: 10000px;
  z-index: -1;
}

        50kg
        55kg
        60kg
        65kg
        70kg

        160cm
        20
        21
        23
        25
        27

        165cm
        18
        20
        22
        24
        26

        170cm
        17
        19
        21
        23
        25

        175cm
        16
        18
        20
        22
        24

  See the Pen
  Row and Column Highlighting with CSS Only by antonio-rodrigues (@antonio-rodrigues)
  on CodePen.

Expected results:
Set color: red for all cells of highlighted Column, keep all other table cells with default black color.
How to achieve that wit CSS only?


text:
Q: writing test for angular.js directive I am having problems with writing tests for this the angular.js directive which checks if the name from input is a full name:
here is the directive:
angular.module('app.directives').directive('fullName', [
  function() {
    return {
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
        ctrl.$parsers.unshift(function(value) {

          if (value.split(' ').length >= 2) {
            ctrl.$setValidity('fullName', true);
            return value;
          } else {
            ctrl.$setValidity('fullName', false);
            return value;
          }

        });
      }
    };
  }
]);

here is a nonworking and unfinished test:
 describe('example directive test', function() {

  beforeEach(module('app.directives'));

  beforeEach(inject(function($rootScope, $compile) {
     elm = angular.element(
       '' +
         '<input' +
           'required' +
           'ng-class="{error: showErr && signupForm.name.$invalid}"' +
           'full-name' +
           'name="name"' +
           'id="user_name"' +
           'type="text"' +
           'autocomplete="off"' +
           'ng-model="user.name"' +
           'placeholder="Full Name" />' +
         'Please enter your full name.' +
       '');

     scope = $rootScope;
     $compile(elm)(scope);
     scope.$digest();

  }));

  it('should have a working full-name directive', function() {
    var input = elm.find('input');
    scope.$apply(function() {
      scope.name = "Johnsmith"
    });
    expect(input.eq(0)).hasClass("showErr").toBeTruthy();
  });

});

right now my code is throwing error "TypeError: undefined is not a function" on last line by "hasClass("ShowError"). how can I make it work?

A: hasClass is not a property of the return value of expect(). Hence the undefined is not a function. Your code should be:
expect(input.eq(0).hasClass("showErr")).toBeTruthy();


text:
Q: How make a button invisible for 1 or 2 second on another button click In my app I want to make a button invisible for a few seconds after another button has been pressed and then it should become visible again.
How it is possible?

A: You can do somthing like this:
  firstBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                secondBtn.setVisibility(View.INVISIBLE);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        secondBtn.setVisibility(View.VISIBLE);
                    }
                }, 2000); //change it for the time you need in milliseconds
            }
        });

A: btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        btn.setVisibility(View.INVISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                btn.setVisibility(View.VISIBLE);
            }
        }, 1000); // where 1000 is equal to 1 sec (1 * 1000)
    }
});

A: must make buttonView invisible then use btnView.postDelayed
Just inside onClick of second button just do
secondButtonView.setVisibility(View.INVISIBLE);
secondButtonView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        secondButtonView.setVisibility(View.VISIBLE);
                    }
                }, 2000);

View.postDelayed() simply calls Handler.postDelayed(). It's a
  convenient method that helps avoid creating Handler instances.

This quote is from Romain Guy Android framework engineer https://groups.google.com/forum/#!topic/android-developers/IuG3HgKx89Q

A: //my button invisible
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
    // Do something after 5s = 5000ms
     //my button visible
}
}, 5000);

A: U can use handler for it
also u can use Timer and TimerTask
//First button invisible

 final Handler handler = new Handler();
 handler.postDelayed(new Runnable() {

 @Override
     public void run() {
         // Second visible
         // after some MS
  }
}, 2000);

A: Suppose you have two buttons Button button1,button2 properly inflated and displayed in view. You can change visibility of button2 on click of button1 by:
button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            button2.setVisibility(View.INVISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    button2.setVisibility(View.VISIBLE);
                }
            }, 2 * 1000);//number of seconds *1000
        }
    });

A: try this,
write following code on another button's click event.
continuebutton.setVisibility(View.INVISIBLE);

continuebutton.postDelayed(new Runnable() {
        public void run() {
            continuebutton.setVisibility(View.VISIBLE);
        }
    }, 2000);


text:
Q: AttributeRouting returns Forbidden when route mirrors directory structure I'm using MVC 5.2.2 with AttributeRouting.
Imagine the code below, for example:
public sealed class DocumentsController : Controller
{
    [Route("documents")]
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
}

This has a route of /documents.
Now, imagine my project has a directory called 'documents' at the root.
IIS will serve me with a 403.14 Forbidden because directory browsing is disabled. It is disabled by design. No, I don't want to enable it.
I assume there may be some kind of Web.config magic that needs to happen.
How can I setup MVC routing to override IIS when there is an applicable route as in this situation, yet continue to serve the IIS level Forbidden when there is not a valid route?


text:
Q: ffmpeg - transpose then apply watermark I'm trying to use the -vf / -filter_complex options to chain two filters - a video rotate and then applying a watermark.
I've got an existing command for the watermark:

-vf "movie=wm.png [watermark]; [in][watermark] overlay=main_w/2-overlay_w/2:main_h-overlay_h [out]"

And I have a rotate:

-vf "transpose=1"

How can I combine the two, doing the rotate, then applying the watermark?  I can't seem to get -filter_complex to work:

-i wm.png -filter_complex "transpose=1,transpose=1,overlay=main_w/2-overlay_w/2:main_h-overlay_h"

It works but the video isn't rotated.

A: I figured this one out - you need to chain the multiples together.

-vf "movie=wm.png [wm]; [in] transpose=1 [rotate]; [rotate][wm] overlay=(main_w-overlay_w)/2:main_h-overlay_h-3 [out]"

Set the watermark file name to [wm], but use a semi-colon to separate the start from the [in].  Then add another operation under [rotate], then chain it to [wm] to perform the transform.

A: you can use -filter_complex options
example:
ffmpeg -i input.mp4 -i input.png -filter_complex "transpose=1,overlay=10:10" -y out.mp4


text:
Q: Interesting question about full rank of random matrix I have a question about rank of a random binary matrix. Assume that I have to make a random binary matrix with its size are k rows and n colmuns (k<=n). Each columns only has 1 or 0 values. Now I want to caculate the probability that the binary matrix is full rank (k). Please help me formula it. Note that 0 and 1 is created with same probability.
This maybe one solution. However, I don't know it is whether correct or not. Let us verify it

A: Your formula gives probability zero for a square matrix $k=n$:
$$1-2^{k-n}=1-2^0=0.$$
It is possible?


text:
Q: Casting generic class is warning in eclipse but error in javac I'm seeing a major difference in behavior between Eclipse and javac for the following code:
public class TestIncompatibleTypes {

    private static <V> void libraryMethod(Class<? extends List<V>> in) {}

    public static void main(String[] args) {
        // Eclipse warns about 'Unchecked cast'
        // Maven fails with 'incompatible types'
        Class<? extends List<String>> l = (Class<? extends List<String>>) ArrayList.class;
        libraryMethod(l);
    }
}

Eclipse issues an 'unchecked cast' warning for the above code, but it successfully compiles. Javac generates an error:
$ java -version
openjdk version "1.8.0_72-internal"
OpenJDK Runtime Environment (build 1.8.0_72-internal-b15)
OpenJDK 64-Bit Server VM (build 25.72-b15, mixed mode)
$ javac -version
javac 1.8.0_72-internal
$ javac -source 8 TestIncompatibleTypes.java
TestIncompatibleTypes.java:13: error: incompatible types: Class<ArrayList> cannot be converted to Class<? extends List<String>>
        Class<? extends List<String>> l = (Class<? extends List<String>>) ArrayList.class;
                                                                                ^
1 error

Can anyone explain why javac disallows the cast? My understanding is that they should be completely equivalent after type erasure.
Is there a workaround to get this to compile on both compilers?

A:
Is there a workaround to get this to compile on both compilers?

Class<? extends List<String>> clazz;
// casting to interim type
clazz = (Class<? extends List<String>>) (Class<? extends List>) ArrayList.class;
// raw types .......
clazz = (Class) ArrayList.class;

HOWEVER! This code deserves an explanation of why it works and when it might not be safe:

*

*java.util.ArrayList has no particular constraints for its type variable.

*java.lang.Class is immutable and can only be used to create new instances.

If you use different types besides ArrayList and Class, this same casting can cause heap pollution by e.g. casting away important information:
class IntegerList extends ArrayList<Integer> {}
// now we can create a new instance and put String in a List<Integer>
Class<? extends List<String>> clazz =
    (Class<? extends List<String>>) (Class<? extends List>) IntegerList.class;

(I'm also going to make the caveat that it could still be possible to cause heap pollution using ArrayList.class and I just haven't thought hard enough about it.)
In Java 8, we should prefer lambdas to reflection for instance creation, which avoids this entire problem:
static <V> void libraryMethod(Supplier<? extends List<V>> in) {}
void somewhere() {
    Supplier<? extends List<String>> supplier = ArrayList::new;
    libraryMethod(supplier);
}

Of course if you can't use this for some reason, then you are a little stuck doing the occasional kludgy thing with Class.

Can anyone explain why javac disallows the cast?

Java doesn't allow "sideways" casts, e.g.:
Number n = ...;
String s = (Number) n; // compiler error

I explained how this works for the raw type argument here and here.
The short explanation is that there is a subtyping relationship like this:
           Class<? extends List>
            ╱                 ╲
Class<? extends List<String>>  Class<ArrayList>

Both are subtypes of Class<? extends List> and neither one is a subtype nor a supertype of the other.

A: Looks like you're casting a Class<ArrayList>> to Class<? extends List<String>>, but the ArrayList class doesn't have that kind of generic. I'm not sure if you need the <String> generic for your Class<? extends List>


text:
Q: Table within table styling - blank first column CSS I've got a table with CSS styling that has a blank (e.g. white background) first column, and a second column with alternating rows. The problem, however, is that I need to insert another table into the table that doesn't apply the same logic and just acts like a normal table.
Every time I try, it gets over-ridden by the styling and the table within the table also appears white
Any ideas?
HTML:

                            1.
                            Turn alarm off - If already turned off, check to see if anyone else is in the building

CSS
.ContentTable1 td:first-child {
    text-align: left;
    background-color: #FFFFFF;
}

A: To target just the first column of the parent table, use the CSS child selector (>):
.ContentTable1 > tbody > tr > td:first-child {
  text-align: left;
  background-color: #FFFFFF;
}


text:
Q: How to change the breakpoint order of column in materializecss? How to change the breakpoint order of column in materializecss?

                        example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text

PS: The first

 just for specific space in my html.
Desktop View
to
Mobile View
How can I change the break order? I want to have the text first instead of the penguin.
Which classes do I need to add for this example?

A:

@media only screen and (max-width: 600px){
    .flex-container {
        padding: 0;
        margin: 0;
        list-style: none;

        -ms-box-orient: horizontal;
        display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -moz-flex;
        display: -webkit-flex;
        display: flex;

        -webkit-flex-flow: row wrap;
        flex-flow: row wrap;
    }
    .flex-item:nth-of-type(1) { order: 2; }
    .flex-item:nth-of-type(2) { order: 1; }

    .flex-item:nth-of-type(1){
        text-align: center;
    }
}

                        example text example text example text example text example text example text example text example texhttps://stackoverflow.com/questions/54363459/how-to-change-the-breakpoint-order-of-column-in-materializecss#t example text example text example text example text example text example text example text example text example text


text:
Q: Android NumberPicker NullPointer why? i am try to implement a numberPicker to select minute values.
But i am getting a NullPointer Exception at this line:
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
Following Code:
public class MainActivity extends Activity {

NumberPicker minutePicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Auswahl Minuten zum starten / Stoppen aller
    minutePicker = new NumberPicker(MainActivity.this);
    minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
    minutePicker.setMaxValue(30);

    minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            abschaltzeit = minutePicker.getValue();
        }
    });

    minutePicker.setValue(0);
    minutePicker.setWrapSelectorWheel(false);

}
}

XML:
<NumberPicker
    android:id="@+id/minuten_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_row="6"
    android:layout_column="0"
    android:paddingLeft="20dp" />

Log:
09-25 11:00:09.749  10687-10687/de.carsten.awesome.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: de.carsten.awesome.app, PID: 10687
    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.carsten.awesome.app/de.carsten.awesome.app.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at de.carsten.awesome.app.MainActivity.onCreate(MainActivity.java:83)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

A: minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);

You're creating a NumberPicker programmatically and then overwriting the reference with whatever findViewById() returns. It returns null if your activity_main layout does not contain a minuten_picker.

*

*Choose only the other: either create it prorgrammatically or find it from a view hierarchy you inflated.

*If you choose the programmatic way new NumberPicker(), remember to add it to some layout in your activity view hierarchy, e.g. with setContentView()

*If you choose the inflation way, make sure you have the view in your XML layout file.
I'm guessing the NPE you're seeing is actually on the following line where you're trying to invoke a method on the minutePicker and it's null.

A: I apologize.
I moved the Code from the MainActivity in the creating Fragment and it works with rootView.findView.
Sorry but i am new with the Fragement Konzept.
Thanks a lot for your help !


text:
Q: jQuery - parameter of ajax request I'm studying the following code and I'm wondering how the callback function gets its parameter:
Doing the request
getData( "hg34j3", loadData);

Callback function
function loadData(param) {
    var data = param;
    ......
 }

get data
function getData(anId, callback) {
    var request = $.ajax({
        url: url + "abc/" + anId,
        type: "GET"
      });
      request.done(callback);

A: The statement
    request.done(callback)

Doesn't exactly call the callback function. Rather it passes a reference to the callback function to the .done method of the jQuery Deferred object. Within that object is the actual call to the callback function. If you were to look at the source code for jQuery, you'd see that when the Ajax completes, it does indeed call the function with a parameter of the Ajax results.


text:
Q: Google Closure Compiler complaining about XMLHttpRequest.response type Below is a very simplified version of some code that I'm passing to Google Closure Compiler:
"use strict";

var xhr = new XMLHttpRequest();

xhr.open("GET", "somefile", true);
xhr.responseType = "arraybuffer";

xhr.addEventListener(
  'load',
  function() {
    var data = new Uint8Array(xhr.response);
    /* ... do something ... */
  }
);

This is basically an Ajax query to retrieve raw binary data and it is working as expected.
However, the compiler emits the following warning:
WARNING - actual parameter 1 of Uint8Array does not match formal parameter
found   : *
required: (Array<number>|ArrayBuffer|ArrayBufferView|null|number)
        var data = new Uint8Array(xhr.response);
                                  ^

I've spent some time trying to fix it with JSDoc directives, in order to explicitly define the type of 'xhr.response' as 'ArrayBuffer'.
For instance:
/** @property {ArrayBuffer} response */
var xhr = new XMLHttpRequest();

But nothing worked.
What DID finally work was to separate the variable declaration from its initialization, without adding any JSDoc directive:
var xhr;
xhr = new XMLHttpRequest();

No warning anymore.
The problem is that I don't get it. Why does it fix the problem? Was it really the right thing to do?

A:
Why does it fix the problem?

I think you've found a bug in the closure-compiler. You could report an issue about it.
Splitting up that line into two lines shouldn't change what the compiler is doing.  For clarity, here is the line that you split.
var xhr;
xhr = new XMLHttpRequest();

I confirmed your report using online closure compiler with optimization set to Advanced.

Was it really the right thing to do?

The definition in the html5.js extern is
/**
 * @type {*}
 * @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-responsetype-attribute
 */
XMLHttpRequest.prototype.response;

So the error you got was reasonable. Fix it with a type-cast:
var r = /** @type {!ArrayBuffer}*/(xhr.response);
var data = new Uint8Array(r);

Try the following in the online closure compiler with optimization set to Advanced.
"use strict";

var xhr = new XMLHttpRequest();

xhr.open("GET", "somefile", true);
xhr.responseType = "arraybuffer";

xhr.addEventListener(
  'load',
  function() {
    var r = /** @type {!ArrayBuffer}*/(xhr.response);
    var data = new Uint8Array(r);
    /* ... do something ... */
  }
);

It works for me there. I also get the error you reported with your original version.  Note however that with optimization set to "Simple" we don't get the error.


text:
Q: Sharing class pointers between processes I have a server library which my client executable injects into a remote process.
It is the server's responsibility to set up some sort of IPC/RPC implementation to allow the client to seamlessly communicate with the remote process.
Update
Take a look at the following server-side header:
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
using namespace boost::interprocess;

typedef allocator<int, managed_shared_memory::segment_manager> ShmIntAllocator;
typedef vector<int, ShmIntAllocator> IntVector;

class A
{
public:
    A();
    A(string str, offset_ptr<IntVector> ints)
        : m_str(string(str)), m_ints(ints) {};
    ~A();

    string m_str;
    offset_ptr<IntVector> m_ints;
};

class B
{
public:
    B();
    B(offset_ptr<A> obj) : m_obj(obj);
    ~B();
    VOID DoSomethingUseful()
    {
        MessageBoxA(NULL, m_obj->m_str.c_str(), "SomethingUseful", MB_ICONINFORMATION);
    }

    offset_ptr<A> m_obj;
};

And here's the server-side implementation:
managed_shared_memory g_shm;
offset_ptr<A> g_objA = nullptr;
PVOID g_hMem = nullptr;

BOOL StartServer()
    // Create a shared memory pool
    try {
        g_shm = managed_shared_memory(create_only, "MySharedMem", OVR_MAPSIZE);
    } catch(interprocess_exception& e) {
        std::string msg(e.what());
        MessageBoxA(NULL, msg.c_str(), "Error", MB_ICONERROR);
        return FALSE;
    }

    // Construct a local class instance
    const ShmIntAllocator alloc_intVector (g_shm.get_segment_manager());
    offset_ptr<IntVector> ints = g_shm.construct<IntVector>(unique_instance)(alloc_intVector);
    ints->push_back(10);
    ints->push_back(20);
    ints->push_back(30);
    g_objA = new A("Testing", ints);
    B objB(g_objA);

    // Copy data into shared memory
    size_t len = sizeof(objB); // <-- Doesn't seem to make a difference if I set this to be something higher
    g_hMem = g_shm.allocate(len);
    std::memcpy(g_hMem, &objB, len);
    return TRUE;
}

VOID StopServer()
{
    // Free used resources

    if(g_objA) {
        delete g_objA;
        g_objA = nullptr;
    }

    try{
        g_shm.destroy<B>(unique_instance);
        g_shm.deallocate(g_hMem);
        g_hMem = nullptr;
        shared_memory_object::remove("MySharedMem");
    } catch(interprocess_exception& e) {
        std::string msg(e.what());
        MessageBoxA(NULL, msg.c_str(), "Error", MB_ICONERROR);
    }
}

And the client implementation:
BOOL Connect()
{
    // Grab the shared memory pool and extract the class
    managed_shared_memory shm(open_only, "MySharedMem");
    std::pair<B*, std::size_t> ret = shm.find<B>(unique_instance); // <-- Always ends up being 0x00000000!
    B *objB = static_cast<B*>(ret.first);
    if(!objB) return FALSE;
    objB->DoSomethingUseful();
    return TRUE;
}

You'll notice that managed_shared_memory::find() always fails to return a valid pointer to the client. But as far as I can tell, the code is perfectly valid. There are no compiler warnings or errors, and everything appears to run smoothly up until this point.
So why is this failing?
How can I get this to work as expected?

A: Distinct address spaces for pointers
When you are sharing values, everything is clear. For example when put a float value such as 1234.5 in the shared memory, in the other side you can read it simply.
But when you are sharing complex objects (which contain pointers) there is an important problem. The address space of two processes are completely different and distinct. For example you can not put a std::vector object in the shared memory, because it has a pointer to its data in process1 e.g. 0x1ABF212 and this number is meaningless for process2.
So, you have to write down the items of std::vector one by one in the shared memory. Read about Serialization technique to share complex data.
Also, if you're insisting to share complex object as a unique object between processes, you can make those objects with specific memory allocators.
AFAIK Boost.Interprocess has that allocators. It manages shared memory and makes pointers inside the shared memory which is meaningful for both processes.
Sorry for ambiguity, My bad English

A: You are trying to find B that supposed be created by Unique instance construction. Boost documentation says

The find function obtains a pointer to the only object of type T that can be created using this "unique instance" mechanism.

but in your code you are allocating raw memory and just copy your B object. So your B was not created as Unique instance
So i would suggest change your code as following:
try use
B &objB = *g_shm.construct<B>(unique_instance) (g_objA);

instead of
B objB(g_objA);


text:
Q: Could the likelihood increase monotonically in a misspecified EM algorithm? I am dealing with the estimation of a Gaussian Hidden Markov Model with conditional distribution given the first-order Markov state $S_t = j,\ j=1,...,J$
$$
Y_t|S_t=j\sim N(0,\sigma^2_j)
$$
where the variance has the following non-standard specification
$$
\sigma^2_j = \mathbb{1}_{(S_t=1)}+\mathbb{1}_{(S_t>1)}*(S_t-1)*c
$$
with $\mathbb{1}_{(A)}$ being the indicator function of the event A.
I derived an EM algorithm to estimate, among the standard parameters of the HMM, $\sigma^2$ and $c$. The algorithm delivers a monotonic increasing likelihood but it does not seem to be able to identify the true model under simulation. I am therefore wondering, could the likelihood still increase monotonically if my algorithm was ill-derived and/or implemented?

A: You did not specify the transition probabilities $p(S_t|S_{t-1})$ in your HMM, so I will assume that your observations are i.i.d.. If that is the case, no implementation of the EM algorithm will be able to converge to the ground-truth parameters, since what we have here is a tell-tale example of non identifiability.
The distribution of $Y_t$ is a mixture of Gaussian distributions having all the same mean $\mu = 0$ but different variances $\{\sigma^2_j\}_j$: hence, $Y_t$ also follows a normal distribution with mean $\mu = 0$. Such a distribution can be perfectly and uniquely described by its mean and variance (2 free parameters). Here, you are trying to fit much more free parameters: many different combinations of parameters will equally well explain the data. The algorithm won't be able to discriminate between them, and hence to converge to the ground-truth values.
We describe a similar problem in Figures 2 and 3 of the following paper:
Gontier, C., & Pfister, J. P. (2020). Identifiability of a binomial synapse. Frontiers in computational neuroscience, 14, 558477.
The issue is thus not in your implementation of the EM, but in the model itself.


text:
Q: Model List returning as null from view to controller ASP.NET Core MVC I'm having trouble with a list within my model returning as null even tho in the view it clearly has some value.
I had trouble trying to add objects to my model's list, someone helped me and my problem was half solved. This is the code I came up with after the help
My view:
@model ActivityForm

@{
    ViewData["Title"] = "Activity Details";
}

Activity Details

Form

                <form id="form" class="row g-3 w-90" asp-action="Create">

                        @Html.DisplayNameFor(model => model.Name)
                        <input asp-for="Name" type="text" class="form-control" id="inputEmail4"
                            placeholder="@Html.DisplayNameFor(model => model.Name)">

                        @Html.DisplayNameFor(model =>
                            model.Description)
                        <textarea asp-for="Description" class="form-control" id="exampleFormControlTextarea1" rows="5"
                            placeholder="@Html.DisplayNameFor(model => model.Description)"></textarea>

                        @Html.DisplayNameFor(model =>
                            model.StartDate)
                        <input asp-for="StartDate" type="date" class="form-control"
                            placeholder="@Html.DisplayNameFor(model => model.StartDate)">

                        @Html.DisplayNameFor(model => model.EndDate)
                        <input asp-for="EndDate" type="date" class="form-control"
                            placeholder="@Html.DisplayNameFor(model => model.EndDate)">

                        @Html.DisplayNameFor(model => model.Points)
                        <input asp-for="Points" type="number" class="form-control"
                            placeholder="@Html.DisplayNameFor(model => model.Points)">

                        Add award

                                Cancel

                                Post Activity

Award details

                                                Name
                                                <input asp-for="Award.Name" type="text" class="form-control"
                                                    id="award-name">

                                                Description
                                                <textarea asp-for="Award.Description" class="form-control"
                                                    id="award-description" rows="5"></textarea>

                                        <button type="button" class="btn btn-outline-primary w-100"
                                            data-bs-dismiss="modal">Close</button>
                                        <input class="btn btn-primary w-100" type="submit" value="Confirm"></input>

                </form>

Awards

                            Award name
                            Description

                        @if (Model.Awards != null)
                        {
                            foreach (var item in Model.Awards)
                            {

                                    @item.Name
                                    @item.Description

                                        Edit
                                        Remove

                            }
                        }

Method in controller:
        [HttpPost]
        public async Task<IActionResult> Create(ActivityForm data)
        {
            var award = data.Award;

            if (award.Name != null && award.Description != null)
            {
                if (data.Awards == null) data.Awards = new List<AwardForm>();

                data.Awards.Add(new AwardForm { Name = award.Name, Description = award.Description });

                data.Award.Name = "";
                data.Award.Description = "";

                return View(data);
            }

            if (!ModelState.IsValid)
            {
                return View(data);
            }

            string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            await service.NewActivityAsync(data, userId);
            return RedirectToAction(nameof(Index));
        }

Model
    public class ActivityForm
    {
        public string Name { get; set; }

        public string Description { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        public int Points { get; set; }

        public AwardForm Award { get; set; }

        public List<AwardForm> Awards { get; set; }
    }

Everything was now working as intended but I had one more issue left. When I try to add another Award to the list, the list is returned to the controller method as null.
I'm not really sure if the issue is related to binding, I have noticed that every other value is bound and is returning the expected value except the list which is not bound.

A: The list binding context should include indexes to work properly.
Add to following code located below right after declaration of the  <form> tag:
<form id="form" class="row g-3 w-90" asp-action="Create">

    @if (Model.Awards != null)
    {
       for (int i=0; i < Model.Awards.Count; i++)
            {
                @Html.Hidden("Awards[" + i + "].Name", Model.Awards[i].Name)
                @Html.Hidden("Awards[" + i + "].Description", Model.Awards[i].Description)
            }
    }

    ... your markup and control that performs the submit are located here

</form>

To be a part of the binding context these hidden fields should be declared inside the <form> from that the submit is performing.

A: Change the foreach loop to:

    @if (Model.Awards != null)
    {
        @for (var i = 0; i < Model.Awards.Count; i++)
        {
            <input type="hidden" asp-for="@Model.Awards[i].Name" />
            <input type="hidden" asp-for="@Model.Awards[i].Description" />

                @Model.Awards[i].Name
                @Model.Awards[i].Description

                    Edit
                    Remove

        }
    }

This has same effect to what @Victor suggested but using input tag helper instead of html helper.
Documentation for binding model to a collection: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#collections-1
Also your form should wrap around both Form and Awards sections:
<form id="form" class="row g-3 w-90" asp-action="Create">

Form

        ...

Awards

        ...

</form>


text:
Q: how to use mat3.normalFromMat4 I'm trying to implement a moving light source in webGL.
I understand that the normalMatrix is the key to managing the lighting equation in the fragment shader but am not winning the battle to set it up correctly. The only tutorial I can find is the excellent "Introduction to Computer Graphics"
and he says:

It turns out that you need to drop the fourth row and the fourth column and then take something called the "inverse transpose" of the resulting 3-by-3 matrix. You don't need to know what that means or why it works.

I think I do need to understand this to really master this baby.
So I'm looking for guidance on how and why to use  mat3.normalFromMat4.
(PS. I have achieved the moving light source using 3Js, but its handling of texture maps degrades the images to too great an extent for my application. In webGL I can achieve the desired resolution.)

A: For me, from reading this discussion, the answer appears to be simple. mat3.normalFromMat4 is only required if you scale the object non-uniformly (i.e. more in one dimension than the others) after the normals have been computed.
Since I'm not doing that, it's a null issue.


text:
Q: unable to install mcafee-epo from azure devops When I run command 'pip install mcafee-epo' from azure devops, I get below error.
Script contents:
pip install mcafee-epo

========================== Starting Command Output ===========================
[command]Collecting mcafee-epo
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)'),)': /simple/mcafee-epo/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)'),)': /simple/mcafee-epo/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)'),)': /simple/mcafee-epo/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)'),)': /simple/mcafee-epo/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)'),)': /simple/mcafee-epo/
  Could not fetch URL https://pypi.org/simple/mcafee-epo/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/mcafee-epo/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)'),)) - skipping
  ERROR: Could not find a version that satisfies the requirement mcafee-epo (from versions: none)
ERROR: No matching distribution found for mcafee-epo
##[error]Bash exited with code '1'.


text:
Q: Error with german umlauts in R Markdown generated pdf, when a string is inserted by a function I ran into a strange problem when trying to use a selfmade function, which inserts strings from a dataframe in a specific format, based on their location in the text, in a document with several child docs. The generation of the PDF-document always stops with a LaTeX error code 1, after using the name of a german institution with umlauts in my df of strings. No encoding workaround (e.g. \"u, ü) solves the problem.
The setup: RStudio (1.1.442) with rmarkdown (1.9) and papaja (0.1.0) on Windows 10 (1803). Function is defined in the main document, but called, during the knitting, in a child document.
I've already fiddled with the LaTeX-templates encoding/language settings to no success. Umlauts in the main document work as expected, so I am pretty sure there is something wrong with the knitting of the child documents.
Note: I've already solved this for myself (see answers). However, I suppose this is a problem with functions and child documents, rather than the papaja package, so it might be helpful in similar cases. Maybe somebody else can say more about this issue or there is some more reliable way to prevent this?

A: Ultimately, I was able to solve this using BOTH methods described by Georgery and Dirk Eddelbuettel in this question.
In short:

*

*Check the encoding of all documents involved and set them to UTF-8 if necessary

*Change umlauts in strings that are printed by your function to the html ampersand notation.

I discovered that the child document had the wrong encoding, but changing it to UTF-8 only solved the issue for the document itself. When the function printed a string from the main to the child, LaTeX would still throw an error. Multiple attempts to knit also didn't work. After additionally exchanging the 'ü' for ü everything went fine.
I don't know what's going on behind the scenes, but I assume that the encoding is messed up somehow when the string is placed at the intended location in the child document.


text:
Q: ORA-00936: missing expression(UPDATED) UPDATE TBL_TRAIN_LIST SET SEAT=t.TOTAL
(SELECT ANAM.NAME,ANAM.SEAT,ANAM2.TRAIN_NAME,
 ANAM2.SEAT,  ANAM2.SEAT - ANAM.SEAT  AS TOTAL
 FROM TBL_PASSENGER ANAM, TBL_TRAIN_LIST ANAM2
WHERE ANAM.NO=ANAM2.ID ) t
where TBL_TRAIN_LIST.ID=TBL_PASSENGER.NO;

A: That syntax doesn't looks correct. Try changing your query to something like below
UPDATE
(SELECT ANAM.NAME,
ANAM.SEAT as NEWSEAT,
ANAM2.TRAIN_NAME,
ANAM2.SEAT,
ANAM2.SEAT - ANAM.SEAT  AS TOTAL
FROM TBL_PASSENGER ANAM
INNER JOIN TBL_TRAIN_LIST ANAM2
ON ANAM.NO = ANAM2.ID ) t
SET t.NEWSEAT = t.TOTAL;


text:
Q: Django Handle big files ( imageblob ) I am writing a small gallery app and after extensive testing i submitted a 3mb image.
Basically the gallery app relies on another app that creates an UploadedFile instance for every image, however i see that for this specific image it has created 4 instances ( rows in db ) that belong to the same 3mb image, each image has "blob" at the end of its name.
My question is, how can i handle an image as big as this and be able to refer to the whole image ? in a html tag or django templatetag like sorl-thumbnail's ?
Im using python 2.7.2, Django 1.3.1 and MySQL 5.1

A: It seems like the issue was the Jquery plugin that i was using to upload multiple files. The plugin was the one who split the file into chunks which were then sent individually as POST requests, and django didn't know that blob1, blob2, blob3, blob4 where the same file in chunks.


text:
Q: How to validate for either form fields with vanilla JavaScript I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form"  action="" method="POST">
    <input type=hidden name="" value="">
    <input type=hidden name="" value="">

    <input  id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
    <input  id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
    <input  id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />

    <textarea id="description" name="description" placeholder="How can we help you?"></textarea>

    <input type="submit" name="submit" value="Send message">
</form>

$(document).ready(function() {

  $overlay = $(".modal-overlay");
  $modal = $(".modal-frame");

  $modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
  if($modal.hasClass('state-leave')) {
    $modal.removeClass('state-leave');
  }
});
$('.form-close-button').on('click', function(){
     $overlay.removeClass('state-show');
     $modal.removeClass('state-appear').addClass('state-leave');
   });

   $('#contactformbtn').on('click', function(){
     $overlay.addClass('state-show');
     $modal.removeClass('state-leave').addClass('state-appear');
   });

var formHandle = document.forms[0];

formHandle.onsubmit = processForm;

function processForm(){

  var emailInput = document.getElementById('email');

  var emailValue = emailInput.value;

  var phoneInput = document.getElementById('phone');

  var phoneValue = phoneInput.value;

  var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
  var regexEmail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
    nameErr = document.getElementById("name_errormsg");
    nameErr.innerHTML = "Please enter your phone number or a valid email address.";
    nameErr.style.color = "red";
    return false;
}

}
});

If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.

A: Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
    ....

Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?


text:
Q: Automatic login via url query string token I want to log users automatically if they click a link in an email, e.g. example.com/action?_ul=blah-guid. It would detect the '_ul' and automatically login the user. The url can be one of many different ones, so I want to detect if the query string param is present and automatically log them in using this special key if it is.
I've previously done this with the old identity provider in Global.asax.cs using Application_BeginRequest, e.g.
protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request["_ul"] != null)
    {
        var userService = new UserService();
        userService.QuickLogin(Request["_ul"]);
    }
}

However, in this project we're using Asp.Net Identity and it seems the OwinStartup is happening after this point and is throwing an error:

No owin.Environment item was found in the context.

This happens in the initialisation of the service:
    public UserService()
    {
        signInManager = HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
    }

I tried using an ActionFilter but this happens after authentication.
I'm unsure how to do this in Asp.Net Identity, I want to keep normal forms authentication, but also detect if there is a particular query string value, log out if they're presently logged in, then log in using the special key.
What's the correct way to do this additional login check?

A: You need to implement AuthorizeAttribute. I've done something very similar to what you are trying to do:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;

public class TokenAuthenticationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var providedToken = filterContext.Controller.ValueProvider.GetValue("_ul").AttemptedValue;

        // Here check if your provided token is correct one and indeed authenticates user

        var user = // get your ApplicationUser based on your token

        var userManager = HttpContext.Current.GetOwinContext().Get<ApplicationUserManager>();

        // this might be different in your code. Basically you need to crate ClaimsIdentity from ApplicationUser object
        var identity = user.CreateIdentity(userManager, DefaultAuthenticationTypes.ApplicationCookie);

        var claimsPrincipal = new ClaimsPrincipal(identity);

        var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

        // signs out the current user
        authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

        // you need this for the current request, otherwise user will be authenticated only for the next request.
        HttpContext.Current.User = claimsPrincipal;

        // sets the cookie for the next request
        authenticationManager.SignIn(new AuthenticationProperties(), identity);
    }
}

You need to apply this attribute to controllers/actions where you'd like to authenticate users with the token.
Give this a bash. I'm not absolutely sure it will work from the first attempt - this is adapted version of what I have.


text:
Q: Angular 4 directive not having effect on page load I've written a directive that hides an element depending on screen size.  When the page loads the element that is supposed to be hidden is being initialised.
This is my directive
mobile-only.directive.ts
@Directive({
  selector: '[appMobileOnly]'
})
export class MobileOnlyDirective {

  constructor(private el: ElementRef) {
    this.displayElement(window.innerWidth < 992);
  }

  displayElement(isMobile) {
    if (isMobile) {
      this.el.nativeElement.style.display = 'block';
    } else {
      this.el.nativeElement.style.display = 'none';
    }
  }
}

It is implemented like this
<div appMobileOnly>
  <app-brochure-mobile></app-brochure-mobile>
</div>

The directive behaves as expected in that the component isn't rendered to the screen, however the ngOnInit function in the component is being fired.  Any idea why this might be happening?

A: You are inserting your component into the DOM and only hiding it visually, so ngOnInit fires. You could work with ngIf or other structural directive but CSS media queries are the way to go in this scenario.
BTW your code doesn't account for window resizes.


text:
Q: How to compare two lists in R I have two lists that I want to compare. I want to see if the values of each element of the list are equal or not.
> m1
[[1]]
integer(0)

[[2]]
[1] 3 4

[[3]]
integer(0)

[[4]]
[1] 1

[[5]]
[1] 2 3 4

> m3
[[1]]
[1] 3

[[2]]
[1] 1 4

[[3]]
[1] 2

[[4]]
[1] 3

[[5]]
[1] 1 4

And I expect a result like this:
> Result
[[1]]
[1]
FALSE

[[2]]
[1]
FALSE TRUE

[[3]]
[1]
FALSE

[[4]]
[1]
FALSE

[[5]]
[1]
FALSE FALSE TRUE

If I try to apply m1[1]==m3[1] or similar, I get messages as Error in m1 == m3 : comparison of these types is not implemented. I don't manage to do that simple thing! Thanks for your help in advance.

A: You can try using the purrr library to get your desired output, that examines each element. I used %in% instead of == if NAs exist. Also this assumes each list has the same structure to work.
library(purrr)
purrr::map2(m1, m3, function(x, y) x %in% y)

A: You can use Map(or mapply) with %in%.
Map(`%in%`, m1, m3)

[[1]]
logical(0)

[[2]]
[1] FALSE  TRUE

[[3]]
logical(0)

[[4]]
[1] FALSE

[[5]]
[1] FALSE FALSE  TRUE

However, m1 contains integer(0), which makes %in% return logical(0) instead of FALSE. So you need to convert logical(0) to FALSE afterward.
res <- Map(`%in%`, m1, m3)
res[lengths(res) == 0] <- FALSE
res

[[1]]
[1] FALSE

[[2]]
[1] FALSE  TRUE

[[3]]
[1] FALSE

[[4]]
[1] FALSE

[[5]]
[1] FALSE FALSE  TRUE

A: Both Darren and EJJ decided to go along and use %*%
If we don't mind the default behaviour of NA in boolean comparison, we can use a simple for-loop or lapply
lapply(seq(la), function(i)a[[i]] == b[[i]])

If we want some security that the lists are 'matchable' we can compare their outer and inner lengths and wrap this in a function as below
compare_each_list_element <- function(a, b){
  la <- length(lla <- lengths(a))
  lb <- length(llb <- lengths(b))
  if(la != lb || any(lla != llb)){
    warning('Either length(a) != length(b) or some length within a is not equal to some length within b!')
    return(FALSE)
  }
  lapply(seq(la), function(i)a[[i]] == b[[i]])
}
compare_each_list_element(list(1:3, 2, c(3, 2)), list(1:3, 3, c(2, NA)))
[[1]]
[1] TRUE TRUE TRUE

[[2]]
[1] FALSE

[[3]]
[1] FALSE    NA

A: The compare() function in {waldo} makes it very easy to compare lists or data frames. In this case:
m1 = list(integer(), c(3,4), integer(), 1, c(2, 3, 4))
m3 = list(3, c(1,4), 2, 3, c(1, 4))

waldo::compare(m1, m3, x_arg = "m1", y_arg = "m3")
#> `m1[[1]]` is an integer vector ()
#> `m3[[1]]` is a double vector (3)
#>
#> `m1[[2]]`: 3 4
#> `m3[[2]]`: 1 4
#>
#> `m1[[3]]` is an integer vector ()
#> `m3[[3]]` is a double vector (2)
#>
#> `m1[[4]]`: 1
#> `m3[[4]]`: 3
#>
#> `m1[[5]]`: 2 3 4
#> `m3[[5]]`: 1   4

The console output is color coded:

Created on 2022-03-16 by the reprex package (v2.0.1)


text:
Q: What are "steps" in RegexBuddy? RegexBuddy on the tab "Debug" shows how regular expressions are executed step by step. But what exactly that steps mean? What operations are behind every step?

A: In RegexBuddy's debugger, a step is when the regex engine matches something, or fails to match something.  Steps that match a character are indicated by all the characters matched by the regex so far which will usually be one character more than the previous step.  Steps that match a position, like a word boundary, are indicated by the characters matched so far plus "ok".  Steps that failed to match something are indicated by the characters matched so far plus "backtrack".
If you click on any of the matched characters in the debugger, RegexBuddy selects the token in the regular expression that matched those characters and highlights all the characters in the debugger matched by that token.  If you click on an "ok" or "backtrack" indicator, RegexBuddy selects the token in the regex that matched or failed to match.
Moving the cursor with the keyboard has the same effect as clicking.  Pressing the End key on the keyboard moves the cursor to the end of a step.   Then pressing Arrow Up or Down moves the cursor to the previous or next step while keeping the cursor at the end of that step.  By moving the cursor this way, you can easily follow how the regex engine steps through your regular expression and which characters is matches and backtracks along the way.
For more details, see these two pages in RegexBuddy's help file:
https://www.regexbuddy.com/manual.html#debug
https://www.regexbuddy.com/manual.html#benchmark

A: The steps count is basically how many times the current position in the input was changed, which is a very good indicator of performance.
The "current position" may be at any character or between characters (including before and after the entire input).
Simplifying it, regex engines process the input by moving the current position along the input and evaluating whether the regex matches at that position. They also keep track of the position in the regex the match is up to.
I don't want to turn this answer into a regex tutorial, but... regex engines always consume as much of the input as possible while still matching. To give a simple example, given the input "12345" and the regex .*1.*, the regex engine will first apply .* consuming all input leaving the position at the end of the input, fail to match a 1, then back track by "uncomsuming" one character at a time until it finds a 1, then continue. You can see that this would take 9 steps just to process the initial .*.
By contrast, if the regex was [^1]*1.*, the regex will match the "1" in just one step.


text:
Q: IE: CSS Misalignment issue in UL/LI Im encountering a misalignment issue with IE. Below is a sample output. When IE creates a second line due to the long text, the whole paragraph gets mis aligned. Making the 2nd line pulled to the left. I want the first and second line to be aligned to the left. Just like a normal text-align: left will do.
http://img.photobucket.com/albums/v682/markeeh/alignment_tissue.jpg
Below is the code:

Modular carpet offers hospitals and care homes a calming environment to speed patient recovery

Hygienic guarding against bacteria through Intersept® antimicrobial protection

Improved patient comfort and well-being

Therapeutic surroundings with less noise and less stress

Use of colour and design for more cheerful facilities

Hope someone other there is willing to help. Thanks. :)

A: Try to reset margins for li and ul.
Like:
ul, li {margin:0;padding:0;}

and than just set them again the way you want with
ul.ul_content-l { code here }
ul.ul_content-l li { code here }

Also try to be consistent and use only px or only ems.

A: use this
.ul_content-l {
    width:330px;
    list-style:square;
    margin-left: 295px;
    padding-left:10px;
    line-height:16px;
    }


text:
Q: How to do a "horizontal UNION" in MySQL? (concating tables) I am looking for a possibility to concat or union two (or more) tables. I cannot JOIN all tables as there is no reference an no matching columns. If I join without any "ON" I will get all data from Table 1 multiplied with all data from Table 2 (not what I want). So I tried to provide fake rownums with MySQL user defined variables but as there are different amounts of data in all tables I cannot compare those. This is a little hard to explain. So I will provide some examples.
Example 1 (Table 1 = 4 Rows, Table 2 = 3 Rows, Result = 4 Rows)
+---------+---------+---------------+
| Table 1 | Table 2 | Result        |
+---------+---------+-------+-------+
| Col 1   | Col 1   | Col 1 | Col 2 |
+---------+---------+-------+-------+
| A       | H       | A     | H     |
| B       | I       | B     | I     |
| C       | J       | C     | J     |
| D       |         | D     | NULL  |
+---------+---------+-------+-------+

Example 2 (Table 1 = 3 Rows, Table 2 = 4 Rows, Result = 4 Rows)
+---------+---------+---------------+
| Table 1 | Table 2 | Result        |
+---------+---------+-------+-------+
| Col 1   | Col 1   | Col 1 | Col 2 |
+---------+---------+-------+-------+
| A       | H       | A     | H     |
| B       | I       | B     | I     |
| C       | J       | C     | J     |
|         | K       | NULL  | K     |
+---------+---------+-------+-------+

Example 3 (Table 1 = 3 Rows, Table 2 = 4 Rows, Table 3 = 2 Rows, Result = 4 Rows)
+---------+---------+---------+-----------------------+
| Table 1 | Table 2 | Table 3 | Result                |
+---------+---------+---------+-------+-------+-------+
| Col 1   | Col 1   | Col 1   | Col 1 | Col 2 | Col 3 |
+---------+---------+---------+-------+-------+-------+
| A       | H       | O       | A     | H     | O     |
| B       | I       | P       | B     | I     | P     |
| C       | J       |         | C     | J     | NULL  |
|         | K       |         | NULL  | K     | NULL  |
+---------+---------+---------+-------+-------+-------+

Now for the real hard part. I need this as a query. I do not want to fill other temporary tables. If possible :-)

A: I take it you are joining on the dense ordinal rank of each table simply ordered by the "Col 1" value?
This is effectively a full outer join by the rank of each table.
Unfortunately MySQL doesn't support the ROW_NUMBER() analytical function, which would make this relatively simple:
SELECT *
FROM (SELECT "Col 1", ROW_NUMBER() (OVER ORDER BY "Col 1") AS RowNum FROM "Table 1") AS T1
FULL OUTER JOIN (SELECT "Col 1", ROW_NUMBER() (OVER ORDER BY "Col 1") AS RowNum FROM "Table 2") AS T2
    ON T2.RowNum = T1.RowNum
FULL OUTER JOIN (SELECT "Col 1", ROW_NUMBER() (OVER ORDER BY "Col 1") AS RowNum FROM "Table 3") AS T3
    ON T3.RowNum = T2.RowNum
ORDER BY COALESCE(T1.RowNum, T2.RowNum, T3.RowNum)

There are alternatives in MySQL, but I'm not familiar with the workarounds.
As far as the FULL OUTER JOIN workaround, it's easy for ranks since the known ranks are simply the natural numbers:
SELECT *
FROM Numbers
LEFT JOIN (SELECT "Col 1", ROW_NUMBER() (OVER ORDER BY "Col 1") AS RowNum FROM "Table 1") AS T1
    ON T1.RowNum = Numbers.Number
LEFT JOIN (SELECT "Col 1", ROW_NUMBER() (OVER ORDER BY "Col 1") AS RowNum FROM "Table 2") AS T2
    ON T2.RowNum = Numbers.Number
LEFT JOIN (SELECT "Col 1", ROW_NUMBER() (OVER ORDER BY "Col 1") AS RowNum FROM "Table 3") AS T3
    ON T2.RowNum = Numbers.Number
WHERE COALESCE(T1.RowNum, T2.RowNum, T3.RowNum) IS NOT NULL
ORDER BY Numbers.Number

A: This is a tricky method using prepared queries:
SET @r1= (SELECT COUNT(*) FROM table1);
SET @r2= (SELECT COUNT(*) FROM table2);
SET @a=-1;

SET @query= IF (@r1 > @r2,
    (
        SELECT GROUP_CONCAT(CONCAT(
        'SELECT (SELECT col1 FROM table1 LIMIT ', @a:=@a+1, ', 1) AS col1,
        (SELECT col1 FROM table2 LIMIT ', @a, ', 1) AS col2 FROM table1')
        SEPARATOR ' union ') FROM table1
    ),
    (
        SELECT GROUP_CONCAT(CONCAT(
        'SELECT (select col1 from table1 limit ', @a:=@a+1,', 1) as col1,
        (SELECT col1 FROM table2 LIMIT ', @a, ', 1) AS col2 FROM table2')
        SEPARATOR ' union ') FROM table2
    )
);
PREPARE my_query FROM @query;
EXECUTE my_query;

Mind it's not an effective method at all, it just solves your problem.


text:
Q: How to use onMove to reorder horizontal lists in SwiftUI? I have a list where I can currently reorder elements using drag and drop.
@State private var contacts = [
        "John",
        "Alice",
        "Bob",
        "Foo",
        "Bar"
    ]

var body: some View {
    List {
        ForEach(contacts, id: \.self) { contact in
            Text(contact)
        }.onMove { from, to in
            contacts.move(fromOffsets: from, toOffset: to)
        }
    }
}

I want to change this list so that the elements are aligned horizontally, rather than vertically as they are now, while still maintaining the ability to drag and drop elements to reorder them. How can I achieve this?
Thank you in advance.


text:
Q: How can I write my own plugin loader in java? How can I implement a plugin facility in my java program?
I am working with Java. My current project is something related to a general purpose electronics hardware, which have a custom command set.
Now there is a general GUI through which one can access the hardware. The hardware behaves in different ways in different environment, i.e. for different clients. Now the problem is that the GUI must be capable of adding plugins. Plugin means, it must be capable of giving a particular facility to a customer who has the privilege. From the customer side, the addition of plugin is to be simple, like just click on a button to add a particular facility.
The reason why I think about plugins is that more and more facility will be introduced only after delivering the core product.

A: You need to provide following things:

*

*create an API which your plug-ins can use to change/extend the behavior of your program (IMHO this is the trickiest part)

*define a common entry to the plug-ins, e.g., a plug-in-specific properties file defining the entry point or extension points of your plug-in (class name of a plug-in class implementing an interface)

*dynamically load the plug-ins from a location of your choice, e.g., all *.jar files from a specific directory (take a look at URLClassLoader)

API suggestions:

*

*prefer interfaces over (abstract) classes

*it might be useful to help the user to quickly see which interfaces she could implement (e.g. IAction, notice the leading I) and which are provided by your application for plug-in usage (e.g. WindowManager)

A: The main idea behind implementing plugins in any object oriented language, is to define a set of common interfaces that the plugin and related classes must implement, and then load and instantiate them via reflection...
You can use abstract factory pattern so that any objects needed by the plugin can be instantiated...
Let's say that your plugin architecture has only 3 interfaces and each plugin must provide classes that implement those interfaces, then your plugin architecture could be like this:
public interface PluginInterfaceA {
//Define API here
};

public interface PluginInterfaceB {
// Define API here
};

public interface PluginInterfaceC {
// Define API here
};

public interface PluginFactory {
/**
 * Creates plugin A object.
 */
PluginInterfaceA createPluginA();
/**
 * Creates plugin B object.
 */
PluginInterfaceB createPluginB();
/**
 * Creates plugin C object.
 */
PluginInterfaceC createPluginC();
};

And then let the plugins to define in an XML file or properties file the class name of the plugin factory for the plugin:
For instance let's say your plugin defines:
package com.my.plugin;

public class PluginAImpl implements PluginInterfaceA {
// Code for the class
};

public class PluginBImpl implements PluginInterfaceB {
// Code for the class
};

public class PluginCImpl implements PluginInterfaceC {
// Code for the class
};

public class PluginFactoryImpl implements PluginFactory {
public PluginInterfaceA createPluginA() {
  return new PluginAImpl();
}
public PluginInterfaceB createPluginB() {
  return new PluginAImpl();
}
public PluginInterfaceC createPluginC() {
  return new PluginAImpl();
}
};

And then define in the properties file
// File plugin.properties provided in the plugin.jar of the plugin
plugin.factory.class = com.my.plugin.PluginFactoryImpl;
In your application can do
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("plugin.properties"));

String factoryClass = properties.get("plugin.factory.class");

PluginFactory factory = Class.forName(factoryClass);

PluginInterfaceA interfaceA = factory.createPluginA();
PluginInterfaceB interfaceB = factory.createPluginB();
PluginInterfaceC interfaceC = factory.createPluginC();

// Here invoke created classes as you like.
Thanks
Pablo

A: You can add a jar or plugin to an application at anytime. You don't have to do anything special to achieve this.
If you use OGSi you can manage this easier, support multiple version of the same jar and remove them while the application is running.  I suggest looking at Apache Karaf + iPOJO

A: The JAR file format has its own little system for managing plugins, which is used for several parts of Java SE, including JDBC driver management.  Just define a service interface, put JAR files with implementations on the classpath and load the implementations with ServiceLoader.load.


text:
Q: Turn off framebuffer console in Ubuntu Minimal I'm trying to set up a VM based on Ubuntu Minimal to test out working with the framebuffer/DirectFB. I want the VM to only display what I put on the framebuffer, while I'm controlling the VM over SSH. So ideally, it boots to a blank screen without a console.
I enabled the framebuffer device by adding video=vesafb and vga=0x305 to the kernel parameters. The framebuffer is working, because "cat /dev/urandom > /dev/fb0" (over ssh) fills the screen with noise.
However, the VM still shows console 1/tty1, and even after I fill the framebuffer with data, there is still a blinking cursor.
How do I turn off the framebuffer console?

A: Try to add console=/dev/null as a kernel parameter, it should help.


text:
Q: MongoDB MMS API 404 I'm trying to find the endpoint for MMS per MongoDB's documentation on the MMS API, but when I try a variety of endpoints, such as :
* https://myhost:8080/api/public/v1.0/
* http://myhost:8080/api/public/v1.0/
* http://myhost/api/public/v1.0/
* https://myhost:8080/api/
* http://myhost:8080/api/
* etc...

I only see:
Yikes! The resource you requested was not found.

This is really frustrating and MongoDB's documentation on the MMS API is pretty badly designed.
Anyone ever worked with it before?

A: Funny that the documentation doesn't mention it, but did you try https://mms.mongodb.com/api/public/v1.0/ ?
The example sections of the API documentation gives you all the information you need, including the correct endpoint, see the sub-pages of https://docs.mms.mongodb.com/reference/api/


text:
Q: How many Spyder Consoles can I open simulatenously So I am running a process that takes approximately 20 hours to run. For my final analysis I will have to run approximately 96 of these processes. If I make the math this is 80 straight day of running code which is a little unrealistic. I've tried making the code efficient, and I believe to be maxed out (at least for my capacities).
I've tried running multiple spyder consoles, this make me get the job done way quicker. Although the overall process slows down from 20hr to around 30-35 hr, depending on how many consoles I have open. I can run 4-8 of them simultaneously in 4-8 different consoles. Is there a limit on the number of consoles that I can open? If so how does opening an extra console affect the performance of the other consoles? Is this affected by the cored and threads of my CPU? I see that memory is at approximately 38% so RAM doesn't seem to be the bottleneck.
thank you very much!


text:
Q: How to get content-transfer [size] information like in devtools network tab? I want to get the content-transfer size like in chrome devtool network tab through chrome extension API but it doesn't have events for this.

Also checked webRequest API.

A: Low-level precise approach
DevTools itself uses CDP (Chrome DevTools Protocol) events like Network.responseReceived and its encodedDataLength field (source).
It can be used in an extension via chrome.debugger API:

*

*attach the debugger to the tab

*navigate it to the URL or call chrome.tabs.reload()

*send debugger command Network.enable

*register an event listener for Network.responseReceived

*detect the moment the page is loaded by using a sliding timeout aka debounce
An annoying side-effect is that Chrome shows a warning in all tabs when the debugger is used by an extension. If you need more info, search for chrome.debugger examples yourself (here's a few official ones) and inspect the source code of devtools.
Content-Length approach
Another approach is to use Content-Length HTTP header but it's not guaranteed to be present on all responses: here's an example that you can further enhance with a check for fromCache field that's provided in a separate onCompleted event.


text:
Q: Rails: RSpec - undefined method `cookie_jar' for nil:NilClass Rails newbie. Trying to follow Michael Hartl's tutorial.
Stuck trying to add a helper method to simulate log in an RSpec test:
describe "when the a user has logged in and attempts to visit the page" do
    let(:user) { FactoryGirl.create :user }
    before do
      log_in user
    end
    it "should redirect the user to next page" do
      specify { response.should redirect_to loggedin_path }
    end
  end

In my spec/support/utilities.rb:
def log_in user
    visit root_path
    fill_in "Email", with: user.email
    fill_in "Password", with: user.password
    click_button "Log in"
    cookies[:remember_token] = user.remember_token
end

Error:
Failure/Error: log_in user
     NoMethodError:
       undefined method `cookie_jar' for nil:NilClass

What gives?
Edit, full stack trace:
Index page when the a user has logged in and attempts to visit the page should redirect the user to next page
     Failure/Error: log_in user
     NoMethodError:
       undefined method `cookie_jar' for nil:NilClass
     # ./spec/support/utilities.rb:8:in `log_in'
     # ./spec/features/pages/index_spec.rb:20:in `block (3 levels) in <top (required)>'

A: RSpec is very particular about the directory that you place your tests. If you put the test in the wrong directory, it won't automagically mix-in the various test helpers that setup different types of tests. It seems your setup is using spec/features which is not an approved default directory (spec/requests, spec/integration, or spec/api).
Based on the tutorial page, I'm not sure how they have the spec_helper.rb file setup. Though the examples so they are using spec/requests to hold the tests.
You can force RSpec to recognize another directory for request specs by using on of the following:
Manually add the proper module to the test file:
# spec/features/pages/index_spec.rb
require 'spec_helper'

describe "Visiting the index page" do

  include RSpec::Rails::RequestExampleGroup

  # Rest of your test code
  context "when the a user has logged in and attempts to visit the page" do
    let(:user) { FactoryGirl.create :user }

    before do
      log_in user
    end

    specify { response.should redirect_to loggedin_path }
  end

end

Include this in your spec/spec_helper.rb file:
RSpec::configure do |c|
  c.include RSpec::Rails::RequestExampleGroup, type: :request, example_group: {
    file_path: c.escaped_path(%w[spec (features)])
  }
end

Since this is a tutorial I'd recommend following the standard of including require 'spec_helper' at the top of the spec file and that your actual spec/spec_helper.rb file has require 'rspec/rails'
A minor note, you don't need to put a specify inside of an it block. They are aliases of each other, so just use one.
context "when the a user has logged in and attempts to visit the page" do
  let(:user) { FactoryGirl.create :user }

  before do
    log_in user
  end

  # All of the following are the same

  it "redirects the user to next page" do
    response.should redirect_to loggedin_path
  end

  it { response.should redirect_to loggedin_path }

  specify "redirects the user to next page" do
    response.should redirect_to loggedin_path
  end

  specify { response.should redirect_to loggedin_path }
end

Note, according to the documentation for capybara, you should be able to put your capybara tests into spec/features. To make this work, ensure you are loading require 'capybara/rspec' in your spec_helper or test spec file directly.
However, looking at the source, I didn't see where they are automatically including that directory. You can also try adding the tag type: :feature to the outer describe block in your test file. Though the more likely solution is to use spec/requests.

A: Shouldn't you have the "user" argument of the method enclosed in parenthesis?
def log_in(user)
    visit root_path
    fill_in "Email", with: user.email
    fill_in "Password", with: user.password
    click_button "Log in"
    cookies[:remember_token] = user.remember_token
end

A: To have a mock cookie jar, you must have either rack-test or rspec-rails gem included in your Gemfile. I think maybe you have included just rspec and maybe missed out rspec-rails.
You also need to ensure you've configured the session store as follows:
config.session_store = :cookie_store
This must have been done in either config/application.rb or some file under config/initializers. If you have configured this in config/environments/development.rb or somewhere else, the Test environment will not be able to pick it up.


text:
Q: find new coordinates after joining the images I have 25 images with the coordinates (x,y) and images are of size 128*128 . SO I am joining the images and new the image size would be 640 * 640.
I want to find out the new coordinates of (x,y)
I tried something like
#w,h of the new image i.e 640 , 640
#imw,imh of the old image i.e 128*128
#x,y old coordinates

newx = int(( w * x )/ imw)
newy = int(( h * y )/ imh)

A: Small image (i, j) to large image:
X = 128 i + x,
Y = 128 j + y

Large image to small:
i = X / 128,
j = Y / 128,
x = X mod 128,
y = Y mod 128

(with integer division).


text:
Q: CSS Animation not showing all content So I found nice CSS-only news ticker here, I have also implemented it:
http://jsbin.com/xitazujuko/edit?html,css,output
My problem is that it only shows 4 news lines instead of 6 even though it in HTML I have input 6:

News line 1

News line 2

News line 3

News line 4

News line 5

News line 6

Can anybody tell what I am missing here?

A: Change this bit of code, you've only divided the height into 4;
@keyframes  ticker {
    0% {
        margin-top: 0
    }
    16.66666% {
        margin-top: -30px
    }
    33.33333% {
        margin-top: -60px
    }
    50% {
        margin-top: -90px
    }
    66.66666% {
        margin-top: -120px
    }
    83.33333% {
        margin-top: -150px
    }
    100% {
        margin-top: 0px
    }
}

A: In this section of the code:
@keyframes ticker {
    0%   {margin-top: 0}
    25%  {margin-top: -30px}
    50%  {margin-top: -60px}
    75%  {margin-top: -90px}
    100% {margin-top: 0}
}

change it to 20% points and add one more:
@keyframes ticker {
    0%   {margin-top: 0}
    20%  {margin-top: -30px}
    40%  {margin-top: -60px}
    60%  {margin-top: -90px}
    80%  {margin-top: -120px}
    100% {margin-top: 0}
}

A: you can change your key frames as below to show last 5 news( and change for other number you want ) :
    @keyframes  ticker {
    0% {
        margin-top: 0
    }
    20% {
        margin-top: -30px
    }
    40% {
        margin-top: -60px
    }
    60% {
        margin-top: -90px
    }
    80% {
        margin-top: -120px/* this */
    }
    100% {
        margin-top: 0
    }
}

also you can change timing as you want!
    .news ul {
    float: left;
    padding-left: 10px;
    animation: ticker 25s cubic-bezier(1, 0, .5, 0) infinite;/* now set to 25s */
    -webkit-user-select: none
}

sorry for my poor English :)


text:
Q: Form $setValidity back to true not working I set up a form to validate on the server side OnBlur event. The server-side validation is working fine and returning errors as expected. However, once I set validity to false for a field, setting it back to true is not removing the $error messages. Isn't $setValidity true supposed to remove errors from form?
This is the controller:
angular.module('artists').controller('ArtistsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Artists',
  function($scope, $stateParams, $location, Authentication, Artists) {
    $scope.authentication = Authentication;

    $scope.processForm = function(val){

        var artist = new Artists({
            name: $scope.artistForm.name.$viewValue,
            quote: $scope.artistForm.quote.$viewValue
        });
        artist.$save(function(response) {
          $scope.artistForm.$setValidity(val,true);
        }, function(errorResponse) {
          if(val in errorResponse.data){
            $scope.artistForm.$setValidity(val,false,errorResponse.data[val].message);
          }else{
            $scope.artistForm.$setValidity(val,true);
          }
        });

    };
 }]);

A: In my case the field is set back to normal, but when I edit it. That happens because the $scope is loaded from different controller and is not applied. Therefore, you need to use $apply
$scope.$apply(function(){
     $scope.artistForm.$setValidity(val,true);
})

Here's the docs:
https://docs.angularjs.org/api/ng/type/$rootScope.Scope


text:
Q: Why is "Star Wars" crossed out on Steve's list? In Captain America: The Winter Soldier, Steve has a list of things people have recommended he catch up on.

On the American, and presumably most canon, version, "Star Wars" appears to be crossed out. It also appears to be the only thing crossed out on the list. It isn't crossed out on any of the other international versions.
Has anyone associated with the movie commented on why this is?

*

*Did Steve decide Star Wars wasn't worth watching?

*Has Steve already watched Star Wars and thus checked it off?

*Is it just a random, unintentional pen mark?

*Is it something else?

Additionally, do we by any chance know why it wasn't crossed out on the other versions of the list?

A: There appears to be no official sources, but it's likely a nod to the fact that Disney owns Marvel and Star Wars. It would make sense to have it be the only thing crossed off the list as presumably having been done.
The fact that it's one of the few things that's in all the international lists would support this.

A: I saw an article that Cap was a Star Wars fan and didnt like Star Trek, besides the obvious that Marvel is owned by the mouse it would be logical for him to watch Star Wars first because at the time there were only 7 movies compaired to the 10 Trek movies and all the series he would have to watch to catch up.


text:
Q: $F_{n}=\frac{1}{4}(F_{n-2}+F_{n}+F_{n+2})$ Let $F_i$ be in the ith Fibonacci number, and let n be any positive integer $≥3$.
show that $F_{n}=\frac{1}{4}(F_{n-2}+F_{n}+F_{n+2})$
Not sure how to approach this.

A: $$F_{n+2}=F_{n+1}+F_{n}$$
$$F_{n+1}=F_{n}+F_{n-1}$$
$$\Longrightarrow F_{n+2}=F_{n-1}+2F_{n} $$
$$F_{n}=F_{n-1}+F_{n-2}$$
$$\Longrightarrow F_{n+2}=3F_{n}-F_{n-2} $$
Rearranging gives the required result:
$$F_{n}=\frac{1}{4}(F_{n-2}+F_{n}+F_{n+2})$$

A: Well
$$F_n=F_{n-1}+F_{n-2},$$
$$F_{n+1}=F_n+F_{n-1}=2F_{n-1}+F_{n-2}$$
and
$$F_{n+2}=F_{n+1}+F_n=(2F_{n-1}+F_{n-2})+(F_{n-1}+F_{n-2})$$
etc. These might be helpful...

A: Hint: the characteristic polynomial of a sequence fulfilling $A_{n+2}=A_{n+1}+A_n$ is $p(x)=x^2-x-1$. The characteristic polynomial of a sequence fulfilling $B_n=\frac{1}{4}\left(B_{n-2}+B_n+B_{n+2}\right)$ is  $q(x)=x^4-3x^2+1$ and $p(x)$ is a divisor of $q(x)$.

A: There are three ways to write the Fibonacci recursion that combines $F_{n}$, $F_{n+1}$ and $F_{n+2}$, having each one as a function of the other two.
$$F_{n+2}=F_{n+1}+F_{n}$$
$$F_{n+1}=F_{n+2}-F_{n}$$
$$F_{n}=F_{n+2}-F_{n+1}$$
Now shift them conveniently in such a way that we obtain three different expressions for $F_n$:
$$F_{n}=F_{n-1}+F_{n-2}$$
$$F_{n}=F_{n+1}-F_{n-1}$$
$$F_{n}=F_{n+2}-F_{n+1}$$
Sum them up so terms $F_{n\pm1}$ cancel, and we are almost done
$$3F_{n}=F_{n-2}+F_{n+2}$$
Finally, add $F_{n}$ at both sides and divide by $4$ to obtain the result.


text:
Q: Difference between thread's context class loader and normal classloader What is the difference between a thread's context class loader and a normal class loader?
That is, if Thread.currentThread().getContextClassLoader() and getClass().getClassLoader() return different class loader objects, which one will be used?

A: There is an article on infoworld.com that explains the difference
=> Which ClassLoader should you use
(1)

Thread context classloaders provide a
back door around the classloading
delegation scheme.
Take JNDI for instance: its guts are
implemented by bootstrap classes in
rt.jar (starting with J2SE 1.3), but
these core JNDI classes may load JNDI
providers implemented by independent
vendors and potentially deployed in
the application's -classpath. This
scenario calls for a parent
classloader (the primordial one in
this case) to load a class visible to
one of its child classloaders (the
system one, for example). Normal J2SE
delegation does not work, and the
workaround is to make the core JNDI
classes use thread context loaders,
thus effectively "tunneling" through
the classloader hierarchy in the
direction opposite to the proper
delegation.

(2) from the same source:

This confusion will probably stay with
Java for some time. Take any J2SE API
with dynamic resource loading of any
kind and try to guess which loading
strategy it uses. Here is a sampling:

*

*JNDI uses context classloaders

*Class.getResource() and Class.forName() use the current classloader

*JAXP uses context classloaders (as of J2SE 1.4)

*java.util.ResourceBundle uses the caller's current classloader

*URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only

*Java Serialization API uses the caller's current classloader by default

A: Adding to @David Roussel answer, classes may be loaded by multiple class loaders.
Lets understand how class loader works.
From javin paul blog in javarevisited :

ClassLoader follows three principles.
Delegation principle

A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader

*

*Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.

*Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property

*System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.

*Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class.
NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C,  all  Java class loaders are implemented using java.lang.ClassLoader.
Visibility Principle

According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.

Uniqueness Principle

According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again

A: This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader() when you have to call a method that is missing a ClassLoader parameter.
When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.
When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader().
Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader(), sun.misc.VM.latestUserDefinedLoader(), or sun.reflect.Reflection.getCallerClass() it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader() exists only because whoever designed  the ObjectInputStream API forgot to accept the ClassLoader as a parameter, and this mistake has haunted the Java community to this day.
That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader (which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.
When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader before the API call (and resetting it afterwards):
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // call some API that uses reflection without taking ClassLoader param
} finally {
    Thread.currentThread().setContextClassLoader(originalClassLoader);
}

A: Each class will use its own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or its parents.
The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD.  In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.


text:
Q: Blender to Unity rotations screwed up I managed to get rotations on the console in blender, but when I try to apply it in Unity, it is just very wrong. I am using Quaternion.Set
to set the desired rotation. I know that blender uses (WXYZ) quaternion, but when I got these values and set properly it in to Unity3D (XYZW), it gives me nonsense rotations.
http://pastebin.com/bKzUVCih
here is the link to my script. Please help me point out what is wrong there.
P.S.: Euler rotations are not an option, because they're lossy as far as I know...

A: I have solved this problem to my satisfaction. The problem is that the XYZ rotations of Unity are different from those of Blender. If you wish to convert positioning and rotation of an object perfectly from Blender to Unity, use the following steps:

*

*Rotate the object -90 degrees on the X axis.

*Calculate the Blender quaternion. Remember that the Blender quaternion is going to come out in a WXYZ matrix, and a Unity quaternion is going to use a XYZW order.

*Rotate your object back 90 degrees on the X axis, export to FBX using the experimental, "apply transform," check box.

*Translate your object in Unity using the translation in Blender, BUT use the equivalent of (-X, Z, -Y) for your translation.

If you're looking for a Python script to get the quaternion out of Blender, I've put together one and put most of it here
I might as well put a YouTube clip together on this, it's simplistic but ridiculously hard to figure out.


text:
Q: Is there a way to clear graphql-rate-limit default in-memory stored contexts? I am writing a GraphQL API using apollo-server-express.
I implemented a rate limit for a login query using graphql-rate-limit directive approach. I use client IP to identify the context, using default InMemoryStore provided by package. window value is 60s and max value is 10. The rate limit implementation is working as expected.
But I wrote security e2e tests using Mocha, Chai, and graphql-request, and rate limit (as expected) always make it go wrong. It happens because I need to execute login queries to get token before every set of tests. But even if I just set a valid token without request to API, it probably will return an error.
In other tests, I just disable rate-limit. But in the case of security it does not makes sense.
Is there a way to clear stored contexts, in order to avoid the issue? For example, create a mutation for this purpose, or pass a value in headers (both just enabled in development/test environment).


text:
Q: delete all associated child rows when delete the parent row in cakephp 3 I'm new at cake php framework , and i want to delete the row from database and it's associated rows from the child table too .
Now , I can only delete the parent row but without it's child rows ,
How can i delete all the rows associated .
and here's my function for the parent :
    public function delete($id = null) {
    $contractor = $this->Contractors->get($id);
        if ($this->Contractors->delete($contractor)) {

        $this->Flash->success(__('The contractor has been deleted.'));
    }
    else {
        $this->Flash->error(__('The contractor could not be deleted. Please, try again.'));
    }

    return $this->redirect(['action' => 'index']);
}

and here's the function for the child
 public function deleteSub($id = null) {
    // $this->request->allowMethod(['post', 'delete']);

    $contractorAttachments = $this->Contractors->ContractorsAttachments->get($id);
       if($contractorAttachments->Contractors->ContractorsAttachments->delete($contractorAttachments))
    {
          $this->Flash->success(__('The contractor Attacments has been deleted.'));
    }
    else {
        $this->Flash->error(__('The contractor Attacments could not be deleted. Please, try again.'));
    }

    return $this->redirect(['action' => 'index']);
}

But i need to delete the child rows indidiual or delete all the parent row and all the associated child rows .
Can anyone help me with that ?