text:
Q: Two way data binding with EditText I am working on a simple Android App using Kotlin. I want to use databindings, but I cannot get them work with an EditText
This is my XML Layout
<?xml version="1.0" encoding="utf-8"?>
<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <import type="de.knerd.applicationmanager.models.AgencyModel"/>
        <variable name="agency" type="AgencyModel"/>
    </data>
    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            tools:showIn="@layout/activity_add_agency"
            tools:context="de.knerd.applicationmanager.activities.AddAgencyActivity"
            android:orientation="vertical"
            android:layout_margin="16dp">
        <android.support.design.widget.TextInputLayout android:layout_height="match_parent"
                                                       android:layout_width="match_parent">
            <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPersonName"
                    android:ems="10"
                    android:id="@+id/name"
                    android:labelFor="@+id/name"
                    android:hint="@string/agency_name"
                    android:text="@={agency.name}"/>
        </android.support.design.widget.TextInputLayout>
    </RelativeLayout>
</layout>

This is my Model class
package de.knerd.applicationmanager.models

import android.databinding.BaseObservable
import android.databinding.Bindable
import com.j256.ormlite.dao.ForeignCollection
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.field.ForeignCollectionField
import com.j256.ormlite.table.DatabaseTable
import de.knerd.applicationmanager.BR

@DatabaseTable(tableName = "agency")
class AgencyModel : BaseObservable() {

    @DatabaseField(unique = true, canBeNull = false)
    @get:Bindable
    @set:Bindable
    var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }
    @DatabaseField(generatedId = true)
    @get:Bindable
    var id: Int = 0
    @ForeignCollectionField(eager = false)
    @get:Bindable
    var agents: ForeignCollection<AgentModel>? = null
}

And this is the part that binds the model to the view
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView<ContentAddAgencyBinding>(this, R.layout.content_add_agency)
    binding.agency = AgencyModel()
    setContentView(R.layout.activity_add_agency)
    val toolbar = findViewById(R.id.toolbar) as Toolbar
    setSupportActionBar(toolbar)
    supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}

When I try to access the properties of model that is in the binding I get a null value. The Code I use is this
private fun save(): Boolean {
    try {
        val agency = binding.agency
        Log.d("Name", agency.name)
        return true
    } catch (ex: Exception) {
        return false
    }
}

A: I found the Problem, it was caused by me binding to the wrong layout. The correct Code is as follows.
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView<ActivityAddAgencyBinding>(this, R.layout.activity_add_agency)
    binding.agency = AgencyModel()
    val toolbar = findViewById(R.id.toolbar) as Toolbar
    setSupportActionBar(toolbar)
    supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}

In both cases I had to bind to the activity layout

A: You are not using Binding the way it was meant to be Knerd. Two-Way binding is intended so that you can access objects or fields from code without ever having to reference the UI code. By you doing the binding.agency you are no different then findViewById() and you are defeating the purpose of binding.
Fix your binding problems first. Use BaseObservable for your object model and it should stay up to date with whatever values change on the screen.
Then when you save it should be nothing more then accessing the local variable.
private fun save(): Boolean {
    try {

        Log.d("Name", localObservableAgency.name)
        return true
    } catch (ex: Exception) {
        return false
    }
}

//not sure what this method is for, guessing you were try catching null. Better way would be to just do a null check on the object as catching exception by accessing null value is heavy and doesn't add value. Also Kotlin is null safe language, so you are either losing your value on the binding maybe by setting it to null to begin with or something is coded weirdly here as you have to intentionally make an object nullable if you keep a local copy. However, you weren't keeping a local copy you were just newing one up inline and accessing via binding later as if it was your repository of variables haha.
So long story short, is use data binding the way it was intended to be used and you won't have a problem. That is probably why someone down voted you is my guess.


text:
Q: How save JavaScript and HTML in option without it being auto-escaped? And there I thought I knew Wordpress well. It now seems that update_option() auto-escapes code. If I want to save some Javascript or HTML code in an option, this behavior renders the code unusable.
I refuse to do a str_replace on the returned value to filter out every backslash. There has to be a better way.
Here's the PHP for the text box to enter some code:
$option = unserialize(get_option('option'));

<textarea name="option[box]"><?php echo $option['box']; ?></textarea>

This is what happens after submitting the form (in essence):
update_option('option', serialize($_POST));

Any ideas?
Edit: I now got it to work by using PHP's stripslashes() where the script has to be rendered, and htmlentities(stripslashes()) in the text box to display the stored code. While this does the job, I'd still like to know if there is a better solution.

A:
It now seems that update_option() auto-escapes code.

It only sanitizes the value for database entry. You'll find the real troublemaker is around line 750 in wp-settings.php, and the WP function add_magic_quotes().
Yep, you read that right, add magic quotes!
For some reason, WordPress decided to enforce magic quotes, so you'll always need to stripslashes on GET and POST when writing plugins and the like.

A: That's true @TheDeadMedic stripslashes must be used like;
echo stripslashes(get_option( 'option' ));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Standard headers not found when switching to clang 3.4 and libc++ I'm getting the following error on CircleCI after installing clang 3.4 and switching to libc++ . . .

gtest/googletest/include/gtest/gtest.h:54:10: fatal error:
      'limits' file not found
#include <limits>

The offending header file is located at /usr/lib/llvm-3.4/lib/clang/3.4/include/, but I cannot prevent the error, even when using the CMake INCLUDE_DIRECTORIES(SYSTEM path_above) or setting the isystem compiler flag.
Any idea what is wrong?

A: I remember facing the issue once. This happened for me because I because was building clang from the source and had multiple instances of the binary. If memory serves, I solved it by setting the C_INCLUDE_PATH, and CPLUS_INCLUDE_PATH flags in the ~/.bashrc file.
You can do that by adding the following lines to your ~/.bashrc file like this:
export C_INCLUDE_PATH=/usr/lib/llvm-3.4/lib/clang/3.4/include/
export CPLUS_INCLUDE_PATH=/usr/lib/llvm-3.4/lib/clang/3.4/include/

Once you have done this, you can either open a new terminal or run source ~/.bashrc (so that it reads the updated ~/.bashrc file)


text:
Q: Faster way to find corrupt files on Linux I need a rapid method to list corrupted files on my HDD.
So far I tries these commands in a 6.7GiB folder before doing this on the root of the data filesystem :
$ time $(which grep) -a -r . ./ 2>&1 >/dev/null | grep -w error
grep: ./bug_de_l_an_2000.mp4: Input/output error

real    1m40.097s
user    0m18.804s
sys 0m8.052s
$ time $(which find) . -type f -exec cat {} 2>&1 >/dev/null \; | grep -w error
cat: ./bug_de_l_an_2000.mp4: Input/output error

real    1m39.405s
user    0m0.268s
sys 0m7.396s
$ time $(which find) . -type f -exec dd if={} of=/dev/null 2>&1 \; | grep -w error
dd: error reading './bug_de_l_an_2000.mp4': Input/output error

real    1m12.183s
user    0m6.856s
sys 0m20.092s
$ time $(which find) . -type f -exec pv {} 2>&1 >/dev/null \; | grep -w error
pv: './bug_de_l_an_2000.mp4': Input/output error

real    1m39.572s
user    0m0.392s
sys 0m11.708s

Do you know faster method(s) ?


text:
Q: PHP session variables lost after redirect Session variables are lost after using the following code to redirect:
    header('Location: ./protected_page.php');
    exit; //doesn't seem to do anything

On protected page I make sure to use session_start() before referencing any session variables.
Please help!

A: *

*You redirect to the same domain.If you are redirecting from
www.thedomain.com to thedomain.com can possibly end you session

*Ensure register_globals is off, you can check this on the php.ini file and also         using phpinfo().

*The session variables aren't overwritten.

*switching between http and https can also end your session.


text:
Q: H-space and fundamental group I have a certain pointed path-connected topological space $X$, and a natural map $\mu : X \times X \to X$. I want to prove it is $H$-space. So I need to prove that maps $\mu(x_0,-)$ and $\mu(-,x_0)$ are homotopic to identity, where $x_0$ is base point of $X$.
In a reference I am reading, author says that proof follows from following fact: there is subspace $Y \subset X$ which is path-connected and contains base point $x_0$, and whose fundamental group, which is identified with commutator subgroup of $\pi_1(X)$, is trivial.
Of course, this implies that fundmanetal group of $X$ is abelian. But I don't understand why this implies $X$ is H-space. Is this clear from the given data, or maybe something specific of my space $X$?
Edit: It is obvious that not any arbitrary map $\mu$ will give an $H$-space. I guess the author means that the facts given make it somehow easier to check that $\mu$ is unital multiplication. Probably, they reduce it to some trivial verifications. But I am not sure why.


text:
Q: Excel displays dates as times only by default I use Excel a lot while analyzing data and most of that data comes from SQL Server Management Studio. So I'll execute a query and copy the result set using Copy With Headers and then paste it into Excel. Annoyingly, because SQL Server Management Studio always inserts a time of midnight, Excel insists on displaying the time only.
So the value is 2015-04-17, but SSMS copies it as 2015-04-17 00:00:00.000 and Excel displays it as 00:00.0. In most cases, our date fields don't contain times (or then the implicit midnight time) and I am not even a little bit interested in those. I want to see the dates.
I am aware that I can select the cells and then set their date format (selecting Short Date from the Ribbon does the trick) but this is something I have to do every single time. Does anyone know of a way to ensure the time is not copied by SSMS, or that the default display format in Excel includes the date?

A: It depends from cells formatting. You can change this formatting cells before pasting rows. For example, you can select the entire document, right click on cells, Click on "cells format"  (I have excel in another language, I hope I translated right) and format all cells as text.
In your specific case you can do this just on the columns you need.


text:
Q: Use aggregated data with elastic search to create a graph on grafana I just started using ElasticSearch and Grafana this week (so it might be easy question J)
I have an ES base which looks like :
{
  "title": "Adventure Book",
  "month" : 01-2019,
  "price" : 50
}

So for each book, I have the price each month
What I want to do is create a dashboard on Grafana with :

*

*compute the maximum price of each book

*create an histogram on the number of book per maximum price

I managed to do the first part an create a table with book_id / maximum price.
But then i don't know how i can use my first table "as a source" for my histogram
If you have ideas or workaround to do so it would really help J


text:
Q: Is the second-level cache support for caching the query result exclude the entity Normal query manner:
Session sess=factory.getCurrentSession();
sess.beginTran....();

String hql="from Entity en where en......";
Query q=sess.createQuery(hql).setCacheble(true);
List<Entity> list=q.list();

In this case,the object in the list are "entity"s. They will be cached.
However I wonder if cache would work if the hql is like this:
hql="select new Result(count(xx),sum(xxx)) from Entity en ....";

class Result{
  long num;
  long sum;
  //constructor,getter and setter
}

Now,the type of the objects in the result list will be Result.
List<Result> list=q.list();

My question is if the Result Object can be saved at the second-level cache?
Also how about the ResultTransformer?
q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);

At this case,the type of the objects in the q.list() will be Map,does these maps can be cached also?

A: It certainly works for "new Result(...)" but I'm not 100% sure about the ResultTransformer. I cannot see a reason why it wouldn't, considering that the transformation is made after the query.


text:
Q: Selecting style in Google fonts how to apply two different styles(bold in one section and regular in another section) of montserrat in css using google fonts? With the link provided in google fonts i can use only one

A: I assume you already did this but, the steps are, first, embedding the fonts. You can do this either by using a link tag on the HTML, like this:
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">

Or using an import on the CSS, like this:
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap');

After that, on your CSS, you need to use the correct font-family, like this:
font-family: 'Montserrat', sans-serif;

And then specify the font-weight, like this:
font-weight: 700;


text:
Q: rest web api 2 makes a call to action method without invoked I am following a tutorial located here:     https://docs.asp.net/en/latest/tutorials/first-web-api.html
and i am running the web api in iis express and call it using postman with the following path:
http://localhost:5056/api/todo
this call hits the constructor and then somehow calls the
   GetAll function which is never called and does not even have HttpGet verb. How is it getting called?
namespace TodoApi.Controllers
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        public TodoController(ITodoRepository todoItems)
        {
            TodoItems = todoItems;
        }

        public IEnumerable<TodoItem> GetAll()
        {
            return TodoItems.GetAll();
        }

        [HttpGet("{id}", Name="GetTodo")]
        public IActionResult GetById(string id)
        {
            var item = TodoItems.Find(id);
            if (item == null)
                return HttpNotFound();
            return new ObjectResult(item);
        }

        public  ITodoRepository TodoItems { get; set; }
    }
}

A: All methods in the controller are per default HttpGet. You don't need to specify the HttpGet verb explicit.
If you are using the default route specified in the WebApiConfig and call the http://localhost:5056/api/todo it will route to the first parameterless function in the controller. In your case GetAll().
If you want to specify the routing you can use the attributes RoutePreFix and Route
namespace TodoApi.Controllers
{
[RoutePrefix("api/[controller]")]
public class TodoController : Controller
{
    public TodoController(ITodoRepository todoItems)
    {
        TodoItems = todoItems;
    }
    Route("First")]
    public IEnumerable<TodoItem> GetAll1()
    {
        return TodoItems.GetAll();
    }

    [Route("Second")]
    public IEnumerable<TodoItem> GetAll2()
    {
        return TodoItems.GetAll();
    }

    [HttpGet("{id}", Name="GetTodo")]
    public IActionResult GetById(string id)
    {
        var item = TodoItems.Find(id);
        if (item == null)
            return HttpNotFound();
        return new ObjectResult(item);
    }

    public  ITodoRepository TodoItems { get; set; }

}

And to call the methods:
http://localhost:5056/api/todo/first
http://localhost:5056/api/todo/second
You can read more about it here


text:
Q: thread 1 program received signal SIGABRT #import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}

When I run it on my device it gives me the following error:

Thread 1:Program received signal: "SIGABRT".

How do i fix this?
2011-11-10 14:59:43.487 AVMultiPlayer[13554:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
*** First throw call stack:
(0x3102a8bf 0x381cf1e5 0x3102a7b9 0x3102a7db 0x3803e06f 0x3803e00b 0x2dc9 0x2b5d 0x30f84435 0x32fdf9eb 0x32fdf9a7 0x32fdf985 0x32fdf6f5 0x32fdf321 0x32fde485 0x32fddf01 0x32fc44ed 0x32fc3d2d 0x33bafe13 0x30ffe553 0x30ffe4f5 0x30ffd343 0x30f804dd 0x30f803a5 0x33baefed 0x32ff2743 0x25b5 0x2574)
terminate called throwing an exception(gdb)

That is what the output box tells me.

A: Somewhere in your code you use
[NSURL initFileURLWithPath:]

but you pass a nil path value.
Check your string.

A: Your path is nil on the device.
First, try cleaning your project.

Then, ensure the files are being copied over in the "Copy Bundle Resources" build phase

And as Anna Karenina suggested, make sure the names are being handled in a case sensitive manner.

A: - (void)playOnce:(NSString )aSound {    // <-- Write NSString* here. Check it, it may be null

    // or "aSound".caf is not include in your project or is just not checked to be part of your project (remove it and add it again)
    NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
    AVAudioPlayer theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

   [theAudio setDelegate: self];
   [theAudio setNumberOfLoops:0];
   [theAudio setVolume:1.0];
   [theAudio play];
}

A: The important error is 'NSInvalidArgumentException', and as the error says, the problem is that one of the strings is null that shouldn't be. Depending on what you're trying to do, this post may be of help: Proper use of UIApplicationMain


text:
Q: how to disable YellowBox in react-native totally in a native way ? not in JavaScript I know console.disableYellowBox = true could be answer. But I want ban it with all my control because my App has multiple package and I do not want to use console.disableYellowBox = true in every package.
is there any way to achieve this by set a config in shaking bar ?

A: I tried with the new React version replacing the import to:
import { LogBox } from "react-native";
and adding this line inside App.js
LogBox.ignoreAllLogs();
And it's working good for me.

A: You have multiple way's in doing that, which is not recommended since you want to know what's causing these warnings and sometimes it's important informations you need to know, here is some of the ways you can do

Warnings will be displayed on screen with a yellow background. These
alerts are known as YellowBoxes. Click on the alerts to show more
information or to dismiss them.
As with a RedBox, you can use console.warn() to trigger a YellowBox.
YellowBoxes can be disabled during development by using
console.disableYellowBox = true;

*

*using ignore

console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];
ignoredYellowBox allows you to ignore certain warnings as you can see in the example above.

*using disableYellowBox
console.disableYellowBox = true;
disableYellowBox allows you to disable it completely from your app.
however both these ways you need to use inside App.js before you render you app.
example:
import React, { Component } from "react";
import { View } from "react-native";

//console.disableYellowBox = true;
//OR
//console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];

export default class App extends Component {
  render() {
    return (
      <View>
        {/*Your Code will be here*/}
      </View>
    );
  }
}

Take a look at Debugging React Native to learn more about YellowBox
// RN >= 0.52
import {YellowBox} from 'react-native';
YellowBox.ignoreWarnings(['Warning: ReactNative.createElement']);

// RN < 0.52
console.ignoredYellowBox = ['Warning: ReactNative.createElement'];


text:
Q: asp.net MVC 2.0 REST service with FormCollection Let's say the Action below is exposed via REST service and is called from a different appliation how would it handle the posted data/object?
Should I use Create(FormCollection collection) here?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Member member)
{
 ....
}

A: I'd suggest using a model, but one in which all of the parameters are nullable and use the RequiredAttribute for actual, required parameters.  This would allow your method to accept invalid requests -- with missing or extra data -- yet have valid data bound to the model. For invalid data, you can supply error returns instead of presuming default values for non-nullable properties. Using the model binding validation architecture provides a convenient way to make sure that the request is legal.  It would be up to you how you want to handle "extra" data supplied by the request -- I'd say ignore it.


text:
Q: Resolution change when switching from VGA to HDMI I have an HP Envy dv6 connected by VGA to an LG 27EA63V-P and the HP is getting flaky after updating from Win 8.1 to 10.  Found a nice Acer (Aspire V15 Nitro) that I want to get, but no VGA.  LG has HDMI port and I tested it with the HP.  Works fine, but resolution is low (1366x768) compared to the VGA (1920x1080).  I really don't want to have to buy a new monitor, but I need one in addition to the laptop display.
My question is: Will I be able to get Full HD (1920x1080) with HDMI going from the Acer to my LG?
Thanks.

A: Yes, this will work fine.
What is happening at the moment is one of 2 things -  More likely the screen built into your existing laptop is 1366x768, and the display is being mirrored onto your monitor - at a matched resolution.
The alternative is that the EDID (graphics card support reported by computer to the monitor) is being reported at 1366x768 so the monitor is obliging.
HDMI is a much newer standard then VGA, so it can trivially support 1080p.  1080p is also the native (preferred) resolution of your monitor, so it will support it over HDMI.   Any non-ancient PC will support 1080p over HDMI.


text:
Q: Compare vector with no name #include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;

int main()
{
    std::list<int> list{ 1, 2, 3, 4, 5 };
    std::vector<int> vec1{ 1, 2, 3, 4, 5 };
    std::vector<int> vec2{ 1, 2, 3, 4 };
    if(vector<int>(list.begin(), list.end()) == vec1)
    {
        cout << "haha";
    }
    return 0;
}

There is no name in vector<int>(list.begin(), list.end()).
How is it possible to compare vector<int> with no name and vec1.

A:
How is it possible to compare vector with no name and vec1.

std::vector has overloaded operator== as a non-member function.
template< class T, class Alloc >

bool operator==( const std::vector<T,Alloc>& lhs,
                 const std::vector<T,Alloc>& rhs );

This means that when you wrote:
vector<int>(list.begin(), list.end()) == vec1

a temporary std::vector<int> object is created and is passed as the first argument to the above shown overloaded operator== while vec1 is passed as the second argument to the same overloaded operator== and thus the comparison succeeds. In other words, the first parameter lhs is bound to the temporary std::vector<int> while the second parameter rhs is bound to vec1.


text:
Q: Custom DataGridView control with popout editor I've implemented custom DataGridViewColumn, DataGridViewCell, and DataGridViewEditingControl classes as demonstrated in an MSDN Sample.
The problem I have is that while the DateTimePicker in the MSDN example is able to pop it's calendar picker out and have it appear over top of the rows below, and cells adjacent to, it; my control is trapped within the space defined by the size of the DGV cell.  My control consists of a textbox and a list of auto-complete suggestions; so I need a way to get the list to appear without making the row several times as tall as normal.
Since I took the example from MSDN and only changed to to the extend of swapping out DateTimePicker for MyControl and other related changes I assume the magic is happening in the base DateTimePicker class; but don't know what I need to change in my control to have it behave the same way.

A: The DataGridViewEditingControl you implement is sized, moved into the cell area, and made visible when the cell enters edit mode. What you need is in addition to the editing control, a "popup control" which you can create when the editing control becomes active and destroy when it becomes not active.
Here's a simple WinForms popup control example: http://www.codeproject.com/Articles/17502/Simple-Popup-Control
However, if all you want is a cell with auto-completion, you can get that for free using the stock DataGridViewTextBoxColumn, or DataGridViewComboBoxColumn.
http://bytes.com/topic/c-sharp/answers/442061-autocompletestringcollection-text-box-datagridview-2-0-a


text:
Q: how to find out method is executed? Assume that we have below method which will be called in differnt times, for example 10 times :
EventBus.getDefault().post(Id_of_Media_Group);

and receiver method in another class will be like below method in a sequentially way ( because of using ThreadNode.MAIN_ORDERED ) :
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void refreshList(ExampleClass example) {
    // doing a fairly heavy duty
}

this means that will be done using a queue(of callings), and every Queue's element(calling function) may take a few time to finish, my question is that, how Can I understand when every job or all these jobs will be finished using Listener?
my Listener must be in former method class.

A: Use a AtomicInteger in your receiver method and increment it when ever it gets called
At the end you can check that atomic to see how many times it's been called

A:
well that is so simple make Logs in every job , and see it in Logcat if your Log execute or not. here is the Example, Log.d("checking the jobs","jobs 1 is done");


text:
Q: How do multiplayer javascript games communicate with servers? how do online javascript games like agar.io, slither.io and all the other ".io" games communicate with their servers? I opened the Network tab on google chrome but no requests were there. Does google chrome hide these requests or do these websites use a different protocol?

A: Most likely WebSockets. For example, in agar.io if you go into the chrome network tab you can see a WebSocket request:

Clicking on it we see the following WebSocket packets being transmitted and receieved:

The green being transmitted packets, and the red being received packets. If you click on one of those packets you can see a hex dump of the packet. If you want to learn more about WebSockets you can go here. A good WebSocket library is socket.io which you can learn  about here.


text:
Q: Problem with BytesToRead in System.IO.Ports C# I want to Receive a string from Serial Port and Display with MessageBox in WinForm . But BytesToRead Property its not working fine and the string is corrupted . like receive half of it .
when i use for loop that condition is fixed value (i<20) , the string that is 20 char long will receive completely . but (i<BytesToRead) makes problem . here is the code :

string Data = "";

Thread.Sleep(1000);

for (int i = 0; i < com.BytesToRead; i++)
{
    Data += ((char)com.ReadByte()).ToString();
}

MessageBox.Show(Data);
///// End of Code

Example of Received Text : 12345678901234567890
Example of Displayed Text : 123456789

A: This might help:
int count = com.BytesToRead;
int intReturnASCII = 0;
while (count > 0) {
intReturnASCII = com.ReadByte();
Data += Convert.ToChar (intReturnASCII);
count--;
}


text:
Q: How to write a path with LaTeX? How can I write a path with LaTeX? I want something like this:
C:\\Program Files\\My Program\\my file.txt

I have to use double slashes, not single ones.

A: Found this:
How does one insert a backslash or a tilde into Latex

The Comprehensive LaTeX Symbol List is your friend. \textbackslash and \textasciitilde are found in Table 2 of the list

So you should try
C:\textbackslash\textbackslash Program Files\textbackslash\textbackslash My Program\textbackslash\textbackslash my file.txt


text:
Q: How can I get the right Pandas series index when plot with Matplotlib? I want to plot a Pandas series with Matplotlib, but I get the error message:

index type not supported.

Here's my code:
inputX = values_dataset[:,:-horizon]
inputX = inputX.reshape(inputX.shape[0], time_steps, dim)
yhat = model.predict(inputX)
yhat = scalery.inverse_transform(yhat)
series_actual = series.loc[Syhat.index[0]:Syhat.index[-1]]

Syhat_native = {}
if get_transform_status(target_var) == 1:
    for i in range(horizon):
        Syhat_horizoni = pd.Series(yhat[:,i], index= train_val_test_time).iloc[i:]

        series_shift = series_actual.shift(i).dropna()
        Syhat_native[i] = inv_diff(series_shift, Syhat_horizoni, 12)
else:
    for i in range(horizon):
        # The code goes here
        Syhat_horizoni = pd.Series(yhat[:,i], index= train_val_test_time)
        Syhat_native[i] = Syhat_horizoni.shift(i)

Here's the code when I want have a plot:
#now we plot the
if horizon>1:
    fig, ax = plt.subplots(1, horizon, figsize=[horizon*10,5])
    for i in range(horizon):
        Syactual_horizoni= series_actual.shift(i)
        Syactual_horizoni.plot(ax=ax[i], color='b',label = 'actual')

        # This line below where the error occured
        Syhat_native[i].plot(ax=ax[i], color='r', label = 'pred')

        ax[i].set_title('horizon-'+str(i))
        ax[i].legend()
        ax[i].axvline(train_time[-1])

#     fig.savefig("./visualization/LSTM-bidirectional-Covid-h14/LSTM-Bidirectional-Covid-Transformed-1.png")
    fig.suptitle('TRAIN+TEST SET inversed',fontsize=20 )

Is there something I missed?

A: i already got the answer, the Syhat_native series index is not in datetime format. so i did this
inputX = values_dataset[:,:-horizon]
inputX = inputX.reshape(inputX.shape[0], time_steps, dim)
yhat = model.predict(inputX)
yhat = scalery.inverse_transform(yhat)
series_actual = series.loc[Syhat.index[0]:Syhat.index[-1]]

Syhat_native = {}
if get_transform_status(target_var) == 1:
    for i in range(horizon):
        Syhat_horizoni = pd.Series(yhat[:,i], index= train_val_test_time).iloc[i:]

        series_shift = series_actual.shift(i).dropna()
        Syhat_native[i] = inv_diff(series_shift, Syhat_horizoni, 12)
else:
    for i in range(horizon):
        # The code goes here
        Syhat_horizoni = pd.Series(yhat[:,i], index= train_val_test_time)

        Syhat_native[i] = Syhat_horizoni.shift(i)
        Syhat_native[i].index = pd.to_datetime(Syhat_native[i].index)


text:
Q: Parallel.For in Java?
Possible Duplicate:
"Parallel.For" for Java?

.NET has Parallel.For which lets you run a for loop in parallel without having to play around with threads directly.
Details are here
Is there something similar in Java? I found the exact same question (Here), however it was asked before the latest version of java came out, which claims to have:
"Concurrency utilities under JSR 166"
So, did they put something in?

A: While it could be suggested that Parallel.For is simular to ExecutorService.submit, I suspect it is not.
public static void main(String... args) throws InterruptedException {
    long start1 = System.nanoTime();
    int runs1 = 1000;
    final int[] a = new int[100];
    for (int j = 0; j < runs1; j++) {
        for (int i = 0; i < 100; i++) {
            a[i] = a[i] * a[i];
        }
    }
    long time1 = System.nanoTime() - start1;
    System.out.printf("Each loop took an average of %,d micro-seconds%n", time1 / runs1 / 1000);

    int processors = Runtime.getRuntime().availableProcessors();
    long start2 = System.nanoTime();
    ExecutorService executor = Executors.newFixedThreadPool(processors);
    for (int j = 0; j < runs1; j++) {
        for (int i = 0; i < 100; i++) {
            final int i2 = i;
            executor.submit(new Runnable() {
                public void run() {
                    a[i2] = a[i2] * a[i2];
                }
            });
        }
    }
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.SECONDS);
    long time2 = System.nanoTime() - start2;
    System.out.printf("Parallel: Each loop took an average of %,d micro-seconds%n", time2 / runs1 / 1000);
}

prints
Each loop took an average of 2 micro-seconds
Parallel: Each loop took an average of 149 micro-seconds

This shows that in this example, using multiple threads is a very bad idea.  So I would hope that the loop is the slightly more efficient
    for (int j = 0; j < runs1; j++) {
        for (int i = 0; i < processors; i++) {
            final int i2 = i;
            executor.submit(new Runnable() {
                public void run() {
                    for (int i3 = i2 * 100 / processors; i3 < (i2 + 1) * 100 / processors && i3 < 100; i3++)
                        a[i2] = a[i2] * a[i2];
                }
            });
        }
    }

prints
Parallel: Each loop took an average of 28 micro-seconds

If you consider that the code in the Runnable is not thread safe, I suspect Parallel.For does something rather different or its pretty pointless.

A: Fork/Join Framework should be included with Java 8, along with lambdas/closures... Just recently there was a good speech on that subject by Angelika Langer, one of Java Champions

A: My Parallel Computing professor, Alan Kaminsky, and his herd of graduate students have written a library that has the features you need.
Javadocs, licences, downloads, and even a free book are all covered on the information page.
It's Free Software under the GNU GPL version 3.
Parallel Java 2 Library


text:
Q: EditText align digits to background image I have an EditText using the image below as the background image.

The EditText is numeric only, and is limited to 6 digits long.  On some devices, the digits line up perfectly in each slot, however I can not find a way to make it consistent across devices.  On larger screen and high density devices, the digits do not line up, and end of being in the middle of a divider.  The layout that contains the EditText is using a Weight attribute to allow it to scale correctly across devices.  Can anyone suggest a method I can use to make the digits always line up in the slots of the background image - regardless of the screen size/density?
Any suggestions/examples would be GREATLY appreciated!!!
Thank you!

A: Use 6 different EditText views with each view containing only one digit. When user input some value in first view just change the focus to the second one to make typing the values easy.
You can also handle backspace button to taking focus back to views before.
You could use TextWatcher for listen inputing events on each EditText


text:
Q: Как превратить координаты Min0, Min1, Max0, Max1 в Rectangle? Есть координаты прямоугольника на экране: Min0, Min1, Max0, Max1.
Их нужно превратить в
Rectangle(x, y, width, height)

Подскажите, пожалуйста, как это сделать?


text:
Q: Linked List code number of output does not match the number of input In this java code as I input 4 integer type numbers in linked list it shows only first 3 as output
so can you guide why is that. I when give only 1 value in linked list it doesn't appear when I give 2 values it shows the first one as output only.
here only output show 4, 34, and 5 but not 50 I don't understand what wrong with code?
enter code here
import java.lang.*;
public class Main{
    Node head;
    static class Node{
        int data;
        Node next;
        public Node(int d){
            data=d;
            next=null;
        }

    }

    public void insertFirst(int data)
    {
        Node n=new Node(data);
        n.next=head;
        head=n;

    }
    public void insertLast(int data){
        Node n=new Node(data);
        if(head==null) {
            head = n;

        }        else{
            Node t=head;
            while(t.next!=null)
            {   t=t.next;}
               t.next=n;
        }
      }
    public void display(){
            Node n=head;
            if(n==null)
                System.out.println("empty");
            else
            {
                while(n.next!=null)
                {
                    System.out.print(n.data+" ");
                    n=n.next;
                }
            }
        }
       public static void main(String [] args){
        Main m=new Main();
       m.insertFirst(34);
           m.insertFirst(4);
       m.insertLast(5);
           m.insertLast(50);
        m.display();
       }
}

A: When you reach the last node, node.next == null, you don't print it.
You need to change the condition in your display() method.

A: Change while(n.next!=null) to while(n != null). The last node has n.next == null, but you should still print it.


text:
Q: Web API 2: Added a new controller, it won't register? Having a heck of a time here... (Web API 2.1, .NET 4.5.1)
I had one controller that worked perfectly:
[RoutePrefix("v1/members")]
public class MembersController : ApiController
{
    [Route("{id}")]
    public Member Get(string id)
    {
        DataGateway g = new DataGateway();

        return g.GetMember(id);
    }
}

Works as intended and desired like:
/v1/members/12345
But I added a new controller today and it doesn't seem to be registered or recognized at all. It doesn't get added to the Help pages and it returns a 404 Not Found when trying to access it:
[RoutePrefix("v1/test")]
public class Test : ApiController
{
    [Route("{id}")]
    public string Get(int id)
    {
        return "value";
    }
}

Like I stated, the new controller doesn't show up in the Help pages and returns a 404:
/v1/test/12345

What am I doing wrong?
EDITED TO ADD:
I installed tracing and it doesn't even seem to be hitting that.  The first controller works fine and shows a trace, the new Test controller doesn't show any trace info.
EDIT 2:
Updated example code to better match my actual code, which was the problem all along.

A: The problem was here:
[RoutePrefix("v1/test")]
public class Test : ApiController

Changed to:
[RoutePrefix("v1/test")]
public class TestController : ApiController

Seems the almighty important word "Controller" needs to be in the class name for the magic to happen.


text:
Q: Task serialization error with the third-party library I try to solve Spark 2.2 serialization problem. The error is well-known and I was normally solving it using forEachPartition or mapPartitions.
However, now this approach does not work. I have the object modCol that is of the third-party library.
val modCol = // Non-serializable object

val rdd = myRDD.mapPartitions{ iter =>
  val c = modCol
  iter.map(
    x => {
    (x.getId, x.getAttribute(c))
  })
}

val df = rdd.toDF()

However, I get Task serialization error for c:
Caused by: java.io.NotSerializableException: org.gephi.graph.impl.ColumnImpl
My final goal is to create a DataFrame df.

A:
The error is well-known and I was normally solving it using forEachPartition or mapPartitions.

Indeed, but you don't use it correctly. Don't initialize object in outer scope. Initialize it in the function call:
val rdd = myRDD.mapPartitions{ iter =>
  val modCol = ???
  iter.map(
    x => {
      (x.getId, x.getAttribute(modCol))
  })
}


text:
Q: After saving memcache data, is it immediately available on GAE? On Google App Engine (python), I need to save data with memcache and quickly read it on another page.
But before I start coding to have memcache saved, then on the next page I open up that data with the known key, I'm starting to wonder if the data will always be there on the next page? How long does it take to cache the data, and reliably be there on the next page to read? Is this an issue since it's a cloud service, or would this be an issue even if it was on one server? Or is it not an issue at all and I can count on it being there on the next page?
NOTE: This method isn't the backbone of my webapp, its just a special case I need to use for one scenario. Also, for this scenario I do not want to persist data between pages with a querystring, cookies or header values.

A: I don't believe there is anything special with the GAE implementation of memcached so cached values will be available immediately after they are set, so yes, it will be available on the next page unless it is expired because the memcached server hit it's memory limit. Google don't appear to limit how much data you can store in memcache, only the number of requests you can make so in reality I doubt that this is a problem.
It is not good practice to rely on a cached value being available, in all cases you should use a pattern like the one below.
key = generate_key()
value = memcache.get(key)
if value is None:
    value = generate_value()
    memcache.set(key, value)

A: The distributed  memcache architecture has a pool of memcache instances that serves all the Google App Engine applications; the stored data is not replicated between memcache servers.
After successfully saving data on memcache, your data will be there* for any subsequent requests because it is stored in one specific memcache instance.
* one caveat: values may be evicted from the cache in case of low memory

A: In practice, that data will probably be there most of the time, but you cannot count on it, by design -- see the docs:

However, when considering whether to
  store a value solely in the memcache
  and not backed by other persistent
  storage, be sure that your application
  behaves acceptably when the value is
  suddenly not available. Values can
  expire from the memcache at any time,
  and may be expired prior to the
  expiration deadline set for the value.
  For example, if the sudden absence of
  a user's session data would cause the
  session to malfunction, that data
  should probably be stored in the
  datastore in addition to the memcache.

(emphasis mine)


text:
Q: How to get "Library" path on actual iOS device I am using the following code to my app base directory:
// /private/var/mobile/Applications/exampleID/example.app/
FAppDataDirPath := GetHomePath + PathDelim + Application.Title + '.app' + PathDelim;
// /private/var/mobile/Applications/exampleID/example.app/Library/
FAppDataLibraryDirPath := FAppDataDirPath + 'Library' + PathDelim;

On iOS simulator both these paths exist.
However, on the iOS device only FAppDataDirPath exists. The "Library"
variation can not be created using e.g ForceDirectories
What is wrong? :(


text:
Q: Re-render component ReactJs I am new to react and creating some demo app I want to render my header component on the login user but somehow my app doesn't re-render the app.js component when I login with the user
here is my app.js
function App() {

  return (

      <Router>

        <Switch>
          <Route path="/login">
            <LoginPage />
          </Route>
       </Switch>
    </Router>

  );
}

note: I am saving my user in localStorage when I login into the app, please let me know if you need more info

A: You can maintain the user data in state of App component and pass on the function to update user as props to the login component, once the user is logged in, call the function to update the user state. This will cause App component to rerender and subsequently update Header component.
Below is a sample implementation of how you can possible structure and write your code
function App() {
  const [user, setUser] = useState(localStorage.getItem("user"));
  return (

      <Router>

        <Switch>
          <Route path="/login">
            <LoginPage setUser={setUser}/>
          </Route>
       </Switch>
    </Router>

  );
}

function Login(props) {
   ...
   onUserLogin=() => {
     // Below is a mock implementation of a API service. You can use fetch or axios
     Api.loginUser({...you params go here}).then(user => {
         props.setUser(user); // This updates the parent component with user state
     })

   }
   ....
}

A: localStorage doesn't trigger a re-render in React.
You must have a global store to save the user data.


text:
Q: Radius of Convergence for $f(z) = \dfrac{1}{1+z^2+z^4}$ at $\dfrac{1}{2}$ I am practicing some qualifying problems, and I cannot compute the following:
Find the radius of convergence $R$ of the Taylor series of $f(z) = \dfrac{1}{1+z^2+z^4}$ centered at $\dfrac{1}{2}$.
I'm thinking I am having just a technical issue by not seeing the trick for finding the Taylor series for this function.
I tried rewriting $f(z)$ and got to $f(z) = -\dfrac{4}{3} \dfrac{1}{1-\frac{4}{3}\left(\left(z-\frac{1}{2}\right)^2+z+\frac{1}{4}\right)^2}$ although I couldn't find the Taylor series from here.

A: The radius of convergence is $\sqrt3/2$.  It's just the distance from $z=1/2$ to the nearest zero(es) of $1+z^2+z^4$ (i.e., the nearest pole(s) of $1/(1+z^2+z^4)$.  If you note that $(1-z^2)(1+z^2+z^4)=1-z^6$, you see that those zeroes are sixth roots of unity, i.e., $\pm{1\over2}\pm{\sqrt3\over2}i$, so the nearest zeroes are at ${1\over2}\pm{\sqrt3\over2}i$.

A: If a function is holomorphic on a disk centered at $\frac12$, then it has a convergent power series on that disk centered at $\frac12$, and therefore the radius of convergence is at least as big as the radius of the disk.  Conversely, in the disk centered at $\frac12$ whose radius is the radius of convergence of the power series centered at $\frac12$, the function is holomorphic.
Thus the radius of convergence is the radius of the largest disk centered at $\frac12$ on which the function is holomorphic.  In this case, that means the distance from $\frac12$ to the nearest pole, a.k.a. the nearest zero of the polynomial $1+z^2+z^4$.  This polynomials is quadratic in $z^2$, so it is easy to explicitly calculate its roots and determine their distances to $\frac12$.


text:
Q: JSVC not starting and I'm not getting any error messages I'm trying to run a simple JSVC program. However it does not start when I run the script.
I'm also not getting any errors in the log files, terminal or any syslogs I can find.
It does not seem that JSVC validates the class paths because if I purposely make them invalid I
still don't get an error about it.
It DOES validate other parameters that it will complain about if wrong or missing so JSVC IS installed.
Java home should also be correct as it complained about that before.
Script:
#!/bin/sh

# Setup variables
EXEC=/usr/bin/jsvc
JAVA_HOME=/usr/lib/jvm/default-java
CLASS_PATH="/usr/share/java/commons-daemon.jar":"/home/xxxuserxxx/Desktop/Tutorials/StackOverflow_version/EchoTest.jar"
CLASS=Main
USER=xxxuserxxx
PID=/tmp/example.pid
LOG_OUT=/tmp/example.out
LOG_ERR=/tmp/example.err

do_exec()
{
    $EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 -wait 20 $CLASS
}

case "$1" in
    start)
        do_exec
            ;;
    stop)
        do_exec "-stop"
            ;;
    restart)
        if [ -f "$PID" ]; then
            do_exec "-stop"
            do_exec
        else
            echo "service not running, will do nothing"
            exit 1
        fi
            ;;
    *)
            echo "usage: daemon {start|stop|restart}" >&2
            exit 3
            ;;
esac

Code:
import java.util.Timer;
import org.apache.commons.daemon.*;

public class Main implements Daemon {

private static Timer timer = null;

public static void main(String[] args) {
    System.out.println("Hello");
    timer = new Timer();
    timer.schedule(new EchoTask(), 0, 1000);
}

@Override
public void init(DaemonContext dc) throws DaemonInitException, Exception {
    System.out.println("initializing ...");
}

@Override
public void start() throws Exception {
    System.out.println("starting ...");
    main(null);
}

@Override
public void stop() throws Exception {
    System.out.println("stopping ...");
    if (timer != null) {
        timer.cancel();
    }
}

@Override
public void destroy() {
    System.out.println("done.");
}

}

import java.util.Date;
import java.util.TimerTask;

public class EchoTask extends TimerTask {
    @Override
    public void run() {
        System.out.println(new Date() + " running ...");
    }
}

A: Ok I think I made an error setting up all the constants.
The code was based on this Q/A:
How to convert a java program to daemon with jsvc?
It started working after I removed the wait parameter and expanded the full class/package path in the class parameter.
The error and output files are working, they must have been fixed by something I did earlier.. I guess.


text:
Q: how to change the working directory to the location of the program I want to use c++ to open a file on Mac OS.
If I run the program under Xcode, the working directory is the same with the program, which is fine. However, if I try to run the program in terminal, the working directory is alway "Users/username". Do you know how to change the working directory to the location of the program?
Here is the sample code:
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, const char * argv[])
{
    char * dir = getcwd(NULL, 0);
    cout << "Current dir: " << dir << endl;

    ifstream fin("hi.txt");
    if (fin.is_open()) cout << "File is Open" << endl;
    else cout << "File is not open" << endl;
    fin.close();
    return 0;
}

A: You can set a custom working directory for your project in Xcode. In Xcode 4 choose Edit Scheme from the Scheme menu in the project window toolbar to open the scheme editor. Select the Run step from the left side of the project editor. Click the Options button at the top of the scheme editor. Select the Use custom working directory checkbox. Click the button on the right side of the text field to choose the working directory.

A: This is a really old post - updating some info for Xcode 12 (Sept 2020)
Step 1). Xcode -> Product -> Scheme -> Edit Scheme (or create a new one)

Step 2) RUN(DEBUG), Working Directory(Checkmark) and enter $(PROJECT_DIR) as a starting point.

A: Use the value $(PROJECT_DIR) in the working directory in your scheme debug settings:

A: You could use chdir(), see here: Change the current working directory in C++.
Or if you could always just issue a system call (stdlib.h): http://www.cplusplus.com/reference/clibrary/cstdlib/system/.  This won't be portable, but it might be good enough for what you need.


text:
Q: onResume for android annotations I am using android annotations and have some code that I need to execute in the onResume() function in my activity.
Is it safe to just override the onResume function from the android annotation activity (ie with @EActivity)?

A: Yeah, you should use these lifecycle methods just like with plain Android activities. There is one thing though: injected Views  are not yet available in your onCreate method, this is why @AfterViews exist:
@EActivity(R.layout.views_injected)
public class ViewsInjectedActivity extends Activity {

    @ViewById
    Button myButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // myButton is not yet available here
    }

    @AfterViews
    void setupViews() {
        // myButton is first available here
        myButton.setText("Hello");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // just as usual
    }
}

A: Yeah.  Just call super.onResume() and then add your code.
I'd do it just like their on create example here: https://github.com/excilys/androidannotations/wiki/Enhance-activities

A: You can bind your custom class with lifecycle component of android. It holds life cycle information of android component so that your custom class observe lifecycle changes.
public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
}

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());


text:
Q: Finding X and Y to solve var(X) and var (Y) in probability Suppose you toss a coin four times.
The sample space
Ω = {HHHH, HHHT, HHT H, . . . , T T T T }

contains 16 outcomes and you should assume each outcome is equally likely.
Let $X$ be the Binomial random
variable that corresponds to the number of heads in an outcome,
e.g., X(HT HT) = 2.
Let $Y$ be the Bernoulli
random variable that evaluates to 1 if there is an even number of heads in the outcome,
e.g., Y (HHHT) = 0
and Y (HT HT) = 1.
What is the value of E(X), E(Y) and var(X), var(Y)?
I got that:$$E(X) = np$$
$$E(Y) = p$$
$$ therefore, E(X) = (4)(\frac {1}{2})$$
$$E(Y) = \frac 12$$
Assuming these are correct
I believe that Var's formula is: $$E[(X - E[X])^2]$$
What would be X and Y in this case? I'm confused...


text:
Q: Do not submit whole form on ajax action Is it possible in Richfaces 4 not to submit the whole form to server on an ajax action? Does such an attribute or tag exist?
If I have a large form, it makes sense to submit to server only what is needed.

A: Well normally the execute attribute (of a4j:commandButton for example) is for that purpose. You can also define sections with a4j:region to use as a part you want to execute.
More info

*

*a4j:commandButton

*a4j:region


text:
Q: Mass Item-level Update for SQL Server 2005 Reporting Services Portal I have a SQL Server Reporting Services site that I can get to by https://localserver/reports Now when for setting permissions on each folder and report item or datasource item in that folder I have to click on the "properties" then "security" of the item, and then assign the appropriate permissions. It's just that there are hundreds of items I need to modify the security to pretty much the same thing. Is there a way I can do a mass update of the Item-level security roles?

A: You might want to look this up.
Raj


text:
Q: How to get access to ioctl() I'm trying to get access to the ioctl() function from within Swift. It doesn't seem to be exported via the Darwin package.
I tried importing  in the Swift -Cocoa-Bridging-Header.h, but that doesn't seem to make it available either.
Any ideas? ;-)

A: ioctl()/fcntl() are not automagically mapped to Swift because they use varargs. The fix is to write small wrapper functions, like:
int my_ioctlVip(int fildes, unsigned long request, int *val) {
  return ioctl(fildes, request, val);
}


text:
Q: How to link a *lib I am trying to create an executable that links to a static library (on Windows), called mkl.lib in the CMakeLists below.
I had a look at this question and tried the suggestions in this one  but for me they didn't work.
I have tried two different approaches to get the *.exe to link against the *.lib I have but every time I run it, I get the error message requiring the mkl.dll file (which I don't have).
My CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.15)

project(MKLLink)

add_executable(MKL main.cpp)
find_library(MKLLIB NAMES mkl.lib HINTS "${CMAKE_CURRENT_SOURCE_DIR}/external/lib/")
target_link_libraries(MKL PUBLIC ${MKLLIB})
target_include_directories(MKL PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/external/include")

and my main.cpp looks like:
#include "mkl/mkl_service.h"
#include <iostream>

int main( int argc, char** argv)
{
  // Correct version is
  MKLVersion pVersion;
  mkl_get_version(&pVersion);
  std::cout << "Major:  " << pVersion.MajorVersion << std::endl;
  std::cout << "Minor:  "  << pVersion.MinorVersion << std::endl;
  std::cout << "Update: " << pVersion.UpdateVersion << std::endl;

  return 0;
}

Using CMake I can create the project files for VSStudio and open the solution there. The Properties look correct and he solution compiles fine and does not complain about linking. When I run the executable, I see the error requiring mkl.dll.
Independently, I have tried starting from scratch and created a VS Project but I get exactly the same issue. Compilation and Linkage are good but running crashes asking for *.dll. Generally, it seems to me that I should just be able to link against a *.lib file but maybe I am missing some flags.
Thank you


text:
Q: I can't stop writing the body of email when I connect smtp by using openssl -starttls command. (centos 7) [root@ip-xxx-xxx-xxx-xxx xxxx]# openssl s_client -starttls smtp -connect smtp.gmail.com:587
CONNECTED(00000003)
~~~SKIP~~~
250 SMTPUTF8
AUTH PLAIN ~~~SKIP~~~
235 2.7.0 Accepted
MAIL FROM: <~~~SKIP~~~>
250 2.1.0 OK t2sm4646317pgh.89 - gsmtp
rcpt to: <~~~SKIP~~~>
250 2.1.5 OK t2sm4646317pgh.89 - gsmtp
DATA
354  Go ahead t2sm4646317pgh.89 - gsmtp
Test email!
.

Here is my command list.
In normal cases, it will finish writing the email body at the timing that the dot(.) is typed.
But I can't stop writing...
How can I solve this problem?

A: The dot needs to be alone on a new line, and you need to type this explicitly. You can type a new line character (◙) by using ALT+10 (type 10 on the numpad).
If you use this command to finalize your message, it will send:
◙.◙

Alternatively, you could copy/paste the above in your session and confirm.

A: You should use the -crlf option of OpenSSL (i.e. openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf) to make sure you send a carriage return (CR) followed by a line feed (LF).
And in order to have a dot on a line of its own, you have to enter another new line after the dot.
On a different note, I'm note sure whether Gmail allows you to skip mandatory header fields and the empty line between the header and the body.
If you still struggle with this, here's a tool that I wrote.

A: Run the QUIT command after dot.


text:
Q: Statistical Tests Would Reject Existence of Rare Diseases? Why? I was wondering the other day. Given a rare disease that occurs 1 in every thousand. That would infect 7 million people in the world. Yet, most statistical tests, testing for the existence of this disease at even a 1% level would be rejected. How does statistical theory resolve this issue?

A: You wouldn't do a statistical test for whether or not the disease existed.  Rather, you would do a statistical test to test a hypothesis about the prevalence of the disease.  Using a large enough sample size, you could determine whether or not the hypothesis was likely to be accurate (the "% level" of the test refers to the probability that the observed prevalence of the disease closely matches the actual prevalence).
Statistical theory resolves this by dealing with intervals, and probabilities.  You can never be 100% sure of something without looking at every member of the population.  Testing a sample, you can say something like "we are 99% sure that less than .0001% of the population has this disease".  This uses an assumption about the percentage of the population, using this you obtain a range of values that would be likely to occur from a random sample from the population, and you compare this to the data you obtain from an actual sample.  But you are working with statistics, so you are not dealing with absolutes.


text:
Q: Xpath ID created dynamically in each bootstrapping, hence won't be targeted easily Say I desire to change an element with no direct identifiers, but with a similar Xpath:
#js_n6 > div > ul > li:nth-child(4) > a > span > span

I would gladly use it Inside a document.querySelector('') but there is problem:
The #js_n6 ID is created dynamically in each bootstrapping (in each time the webpage is formed or refreshed):
In each bootstrapping you get a different Id like #js-x1, #js_v9, #js z4, #js k1 and so forth, while the rest of the Xpath stays the same.
I tried using a CSS wildcard like [id^="js"] for the ID, but it seems to be ineffective because it targets other, earlier elements with the similar ID's found by the wildcard.

A direct code example is Facebook.com's conversations page. Go to the page with all conversations and run in console:
document.querySelector('.5blh.4-0h').click();

Then, inspect the "Delete" button on the modal menu, and view Xpath. Then, refresh and view again and you'll see what I mean to.
I just give this as an example; I ask no one to do any scraping and I don't ask this specifically about Facebook, but rather to get a general principle.

I wonder what can be done in that case, to select such an object with no direct identifiers, and with an Xpath with a dynamic ID.
Notes:

*

*In any such case I don't own the site and can't add identifiers from server side.

A: Combining selection of a parent element with a CSS ID wildcard helped.
Here's basically what I did:
1) I selected an element that parents the element with the ID (.idElementParent).
2) I selected the element with dynamic ID with a CSS ID wildcard.
3) I than used the relevant portion of the Xpath.
document.querySelector('.idElementParent > [id^="js"] > div > ul > li:nth-child(4)').someMethod();


text:
Q: list OutputCache entry in my asp.net mvc application i'm using the OutputCache attribute on different action method.
Is possible to view the current entries on the cache related to OutputCache attribute?
If i cicle on System.Web.HttpContext.Current.Cache i don't find this type of entry.
Thanks in advance F.

A: Output Cache is not publicly-accessible so you will not find it in System.Web.HttpContext.Current.Cache . In ASP.NET 2 it is contained in the CacheInternal's _caches member, which you can guess by the name is a private member of an internal abstract class.
It is possible to retrieve it with reflection, though it is not an easy task.
Also if you retrieve it you'll see that it contains all kinds of internal cache entries like configuration files path cache, dynamically generated classes cache, mobile capabilities, raw response cache (this one is the type of the output cache items).
Let's say that you can filter the items related to output cache. The problem is that they don't contain much human readable information apart from the key and raw response (as byte array). The key generally consists of information if GET (a1) or POST (a2) method i used, the site name, root relative url and hash of the dependent parameters.
I guess it was a common pain-point so in ASP.NET 4 a new concept of custom output cache providers was introduced. You can implement your own output cache provider inheriting from OutputCacheProvider and provide a method that returns all entries. You can check out this article - http://weblogs.asp.net/gunnarpeipman/archive/2009/11/19/asp-net-4-0-writing-custom-output-cache-providers.aspx. I personally haven't looked in the new OutputCache infrastructure, so if you find anything it will be interesting to write about it.
This is the code to retrieve the internal cache entries. You can browse their values while debugging in Visual Studio:
Type runtimeType = typeof(HttpRuntime);

PropertyInfo ci = runtimeType.GetProperty(
   "CacheInternal",
   BindingFlags.NonPublic | BindingFlags.Static);

Object cache = ci.GetValue(ci, new object[0]);

FieldInfo cachesInfo = cache.GetType().GetField(
    "_caches",
    BindingFlags.NonPublic | BindingFlags.Instance);
object cacheEntries = cachesInfo.GetValue(cache);

List<object> outputCacheEntries = new List<object>();

foreach (Object singleCache in cacheEntries as Array)
{
   FieldInfo singleCacheInfo =
   singleCache.GetType().GetField("_entries",
      BindingFlags.NonPublic | BindingFlags.Instance);
   object entries = singleCacheInfo.GetValue(singleCache);

   foreach (DictionaryEntry cacheEntry in entries as Hashtable)
   {
      FieldInfo cacheEntryInfo = cacheEntry.Value.GetType().GetField("_value",
         BindingFlags.NonPublic | BindingFlags.Instance);
      object value = cacheEntryInfo.GetValue(cacheEntry.Value);
      if (value.GetType().Name == "CachedRawResponse")
      {
         outputCacheEntries.Add(value);
      }
   }
}


text:
Q: Как выполнять одинаковые действия перед каждым тестом  import unittest
 from selenium import webdriver
 from selenium.webdriver.common.keys import Keys
 from selenium.webdriver.common.by import By
 import time

 class TestSelenium(unittest.TestCase):

     def test_authorization(self):
        driver = webdriver.Chrome(executable_path="C:\chromedriver\chromedriver.exe")
        driver.get('https://iacn2uksisa1iris1str1.z33.web.core.windows.net/')
        time.sleep(3)
        log = driver.find_element(By.XPATH, '//*[@id="root"]/div[1]/div/div/div/div/a')
        log.click()
        time.sleep(2)

        login_input = driver.find_element(By.NAME, 'Username')
        login_input.send_keys('111111111')
        login_password = driver.find_element(By.NAME, 'Password')
        login_password.send_keys('111111111')
        log_button = driver.find_element(By.XPATH, '/html/body/div[2]/div/div[2]/div/div/div[2]/form/button[1]')
        log_button.click()
        time.sleep(1)
        self.assertTrue('Press to start' in driver.page_source)
        driver.close()

У меня есть тест автоматизации, суть теста проверить автризацию, я хочу ещё создавать другие функции которые будут выполныять иные тесты, но вот проблема, каждый раз мне необходимо в каждый тест добавлять ещё и авторизацию, код просто не читабелен, можно ли до прогона любого другога теста, запускать сразу самый первый ?? Если да, то как, может будут советы по автоматизации, фреймворкам, методам и подходам приветствуются

A: Имплементировать функцию setUp().
И почитать что-нибудь про организацию тестов. Ту же документацию к unittest, например.


text:
Q: How to activate Angular component only one time? I have main application component that contains tabs:
    <tabs>
       <tab><app-layers *ngIf="tab === 'layers'"></app-layers></tab>
    </tabs>

The problem is when I switch between tabs it destroy and initialize the component again, how to initialize the component only one time then don't?
I know it can be solved using routing, but I have another structure of components.

A: You can hide your component and show it instead of destroying it and initializing it each time with *ngIf
<tabs>
   <tab><app-layers [class.is-hidden]="tab !== 'layers'"></app-layers></tab>
</tabs>

.is-hidden {
      display: none;
 }

EDIT:
you can use  a combination of *ngIf and [class.is-hidden] to achieve what you mentioned in the comments:
how it works:
First, you want to keep track of the tabs that are loaded, that why we use a Dictionnary (key value) where key is the name of the tab, and the value is a boolean that indicates wether this tab is loaded or not.
Next in the condition we have 2 clauses:
*ngIf: load the component if it's selected ond NOT loaded before
but the second clause in the *ngIf condition will leave the component visible once it's loaded, so we need to hide it using the [class.is-hidden] class binding
component.ts
  tabs : { [name: string] : boolean } = {"layers": false, "other-tab":false};
  currentTab : string |undefined = undefined;

  selectTab(name:string) {
  this.tabs[name] = true;
  this.currentTab = name;
}
}

component.html
<tabs>
   <tab (click)="selectTab('layers')">
     <app-layers
           *ngIf="currentTab === 'layers' || tabs['layers']"
           [class.is-hidden]="currentTab!== 'layers'">
     </app-layers>
   </tab>
   <tab click)="selectTab('other-tab')">
     <app-other-tab
        *ngIf="currentTab=== 'other-tab' || tabs['other-tab']"
         [class.is-hidden]="currentTab!== 'other-tab'">
     </app-other-tab>
   </tab>
</tabs>

component.css
.is-hidden {
      display: none;
 }

As you can see, I kept navigating between the tabs but this will load the component only one time and only when the user clicks the tab.

Demo here -used li instead of tabs for simplicity-


text:
Q: Error in log(n) : non-numeric argument to mathematical function I am trying to estimate the parameters of Burr distribution. The procedure is supposed to be pretty easy. I derived and coded a log likelihood function and I'm using a "maxLik" function for estimation.
From the error message I understand that log(n) probably gets char or NaN value and that's why return an error back, but it doesn't really help. I checked the code several times. It should work. If I change the loglik function (say, I'm using loglik from Laplace distribution with one parameter), then the code works. So, I assume it's something wrong with the way I defined the loglik function.
Here is the code I'm using:
y = c(rep(Mean.Income,Number))
N=length(y)
logLik = function(m,n,k)
{
    ll = N*(log(m)+log(n)+log(k)) - (k+1)*sum(log(1+m*y^n)) + (n-1)*sum(y)
    return (ll)
}

estimate = maxLik(logLik,start=c(0.1, 0.1, 0.1), print.level=2, method="NR", grad=NULL, hess=NULL)

y - income data. It consists of the income and the number of households, who get this income. Can it be the problem of big numbers? I have about 3000 observations, income varies 5,000-400,000 and number of occurrence (Number variable) varies from 4 to 8530.
Also, I feel like there can be a problem with this part log(1+m*y^n), because y is a vector and m, n are numbers.
When I check the function by itself, it works. For example:
> logLik(1,5,0.1)
[1] 2560797466

I will highly appreciate any hints on what I am doing wrong.

A: Function like this do not pass function parameters for each value you are estimating, instead they pass one vector with all the values and you must choose the element you want. If you pass a named vector as your start value, it will be easier to track your estimates. For example
y <- c(rep(rpois(20,500),sample(2:7, 20, replace=T)))
N <- length(y)

logLik = function(x) {
    m <- x["m"]; n <- x["n"]; k <- x["k"]
    ll = N*(log(m)+log(n)+log(k)) - (k+1)*sum(log(1+m*y^n)) + (n-1)*sum(y)
    return (ll)
}

library(maxLik)
estimate = maxLik(logLik,start=c(m=0.1, n=0.1, k=0.1), print.level=2,
    method="NR", grad=NULL, hess=NULL)

This will at least fix the error you were getting. It was caused because the parameters n and k were never set and were missing


text:
Q: Arithmetic sequence modulo a prime number I am not a mathematician or a math student, but an electrical engineer. I have noticed that an arithmetic sequence modulo a prime number p contains every integer between zero and that prime number if the arithmetic sequence has at least p elements and the arithmetic sequence has a common difference less than p.
A couple questions:

*

*Does this have a name?

*What reference would help me understand this, or can you help me understand this?
An example in Python is shown below.
import numpy as np

# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n?page=1&tab=scoredesc#tab-top
def primes(n):
    """ Returns  a list of primes < n """
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

# Common differences for arithmetic sequences
d_list = np.arange(2,20)
# Prime numbers
p_list = primes(50)
for p in p_list:
    # Common difference must be less than prime number
    sub_d = d_list[d_list < p]
    for d in sub_d:
        all_ints = set(np.arange(p))
        seq = np.arange(0, d*p, d)
        mod_set = set(seq % p)
        if not mod_set == all_ints:
            print(f'Broken at {d},{p}!')

Thank you

A: This is a result of elementary number theory. We can restate it as the combination of the following results:
Prop 1$\,\,\,\,$Let $p$ be a prime and $a$ an integer not divisible by $p$. Then as $k$ ranges from $0$ to $p-1$, $ak$ also takes on all values from $0$ to $p-1$, modulo $p$.
Another, more concise, way to say this is that multiplication by $a$ induces a bijection from $\mathbb Z/p$ to itself. (Here $\mathbb Z/p = \{0, 1, \ldots, p-1\}$ is the set of residues of the integers modulo $p$.) For a proof of this fact, consult any book on elementary number theory, for instance Elementary Number Theory by Rosen.
Prop 2$\,\,\,\,$Let $n$ be any positive integer, and $b$ any integer. Then as $k$ ranges from $0$ to $n-1$, $b+k$ also takes on all values from $0$ to $n-1$, modulo $n$.
This is easier to see. First, reduce $b$ modulo $p$ if necessary so that $0 \leq b < p$. Then, allowing $k$ to vary, the numbers $b+k$, modulo $n$, take on the values
$$
b, b+1, b+2, \ldots, n-1, 0, 1, \ldots, b-1
$$
Combining these results, we get your observation: If $p$ is a prime, $a, b$ are integers with $p$ not dividing $a$, and $k$ varies from $0$ to $p-1$, then $ak + b$ also takes on all values from $0$ to $p-1$, modulo $p$. Obviously if $k$ is allowed to continue past $p-1$, then $ak+b$ will begin to repeat values modulo $p$.


text:
Q: Node / MySQL: Insert only works first time I'm having an issue with node (currently v6) and mysql.
Node Code is being run server side and not getting any errors.  The code works the first time; however, subsequent times the name and description values are entered as an empty string, and the quantity column as 0 (default value).
created,pid, and id (auto-incremented) columns' values are inserted correctly.  I'm not sure why this is working fine the first time, and not working afterwards.
edit:  When I take the outputted query from addMany and input it directly into mysql, it works every time.
How do I get this working correctly every time? Any help is sincerely appreciated!
Table Schema:
CREATE TABLE `some_table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `pid` int(11) unsigned NOT NULL,
  `qty` int(11) unsigned NOT NULL DEFAULT '0',
  `name` varchar(128) NOT NULL,
  `description` text NOT NULL,
  `created` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `k_pid` (`pid`),
  CONSTRAINT `fk_some_table_p_pid` FOREIGN KEY (`pid`) REFERENCES `p` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1337 DEFAULT CHARSET=utf8;

Node Code:
function addMany(items, callback) {
    const itemsArray = Array.isArray(items) ? items : [items];
    const params = itemsArray.map((item) => {
        return [
            item.pid,
            item.quantity,
            item.name,
            item.description,
            Math.floor(new Date() / 1000),
        ];
    });

    const queryStr = 'INSERT INTO some_table (`pid`, `quantity`, `name`, `description`, `created`)  VALUES ?;';
    db.executeQuery(queryStr, [params], callback);
}

First Run:
const items1 = [
    { name: 'name__1', description: 'some desc 1', quantity: 1, pid: '17771' },
    { name: 'name__2', description: 'some desc 2', quantity: 1, pid: '17771' }
];
addMany(items1, () => {});

addMany creates and runs this query:
INSERT INTO some_table
    (`pid`, `quantity`, `name`, `description`, `created`)
VALUES
    ('17771', 1, 'name__1', 'some desc 1', 1502913412),
    ('17771', 1, 'name__2', 'some desc 2', 1502913412);

MYSQL show this data:
id      pid             quantity        name        description     created
6423    17771           1               name__1     some desc 1     1502913412
6424    17771           1               name__2     some desc 2     1502913412

Second Run:
const items2 = [
    { name: 'name__3', description: 'some desc 3', quantity: 1, pid: '17771' },
    { name: 'name__4', description: 'some desc 4', quantity: 1, pid: '17771' }
];
addMany(items2, () => {});

addMany creates and runs this query:
INSERT INTO some_table
    (`pid`, `quantity`, `name`, `description`, `created`)
VALUES
    ('17771', 1, 'name__3', 'some desc 3', 1502913412),
    ('17771', 1, 'name__4', 'some desc 4', 1502913412);

MYSQL show this data:
id      pid             quantity        name        description     created
6423    17771           1               name__1     some desc 1     1502913412
6424    17771           1               name__2     some desc 2     1502913412
6425    17771           0                                           1502913412
6426    17771           0                                           1502913412


text:
Q: How to access nested Unity Dependency Injection created objects? This is a beginner question for Unity so forgive me.
In my Unity Config I have the following that creates my database context (Entity Framework), Unit of Work, and a Repository pattern object (from reverse pocos and generic repo/uow):
container
.RegisterType<IDataContextAsync, myDbContext>(
    new PerRequestLifetimeManager(),
    new InjectionConstructor(new object[] { connString }))
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<Contact>, Repository<Contact>>()

In Microsoft MVC, my controllers are injected with services:
public myController(IContactService contactService) {
    _contactService = contactService;
}

My services are injected with repositories:
public class ContactService : Service<Contact>, IContactService
{
    public ContactService( IRepositoryAsync<Contact> repository) {...}
}

Everything works well but I'm not sure how to access the Unity created Unit of Work object in the Controller to save changes: UnitOfWork.SaveChangesAsync()
Without DI, here's how to create the objects:
IRepositoryProvider repoProvider = new RepositoryProvider( new RepositoryFactories());
IDataContextAsync context = new MyDbContext();
IUnitOfWorkAsync uow = new UnitOfWork(context, repoProvider);
IRepositoryAsync contactRepo = new Repository<Contact>(context, uow);

...  // database changes

uow.SaveChangesAsync(); // In the Controller

The obvious thing to do is reference a UOW in the Controller constructor function, but how would Unity use that same object for the Service, and how would the Service use it for the Repositories?

A: You have already solved your own problem...
Your UnitOfWork class is registered with the PerRequestLifetimeManager.  This lifetime will ensure that anytime a UOW is resolved within the same MVC request you will receive the same instance.  So you will automatically get the same instance of your UOW passed to your controller constructor as you will get passed to your repository constructor.


text:
Q: What does the TargetWrite/IorD Control Line do on a multicycle MIPS processer We learned all the main details about control lines and the general functionality of the MIPS chip in single cycle and also with pipelining.
But, in multicycle the control lines aren't identical in addition to other changes.
Specifically what does the TargetWrite (ALUout) and IorD control lines actually modify?
Based on my analysis, TW seems to modify where the PC points to depending on the bits it receives (for Jump, Branch, or standard moving to the next line)... Am I missing something?
Also what exactly does the IorD line do?
I looked at both course textbooks: See Mips Run and the Computer Architecture: A Quantitative Approach by Patterson and Hennessy which don't seem to mention these lines...

A: First, let's note that this block diagram does not have separate instruction memory and data memory.  That means that it either has a unified cache or goes directly to memory.  Most other block diagrams for MIPS will have separate dedicated Instruction Memory (cache) and Data memory (cache).  The advantage of this is that the processor can read instructions and read/write data in parallel.  In the a simple version of a multicycle processor, there is likely no need to read instructions and data in parallel, so a unified cache simplifies the hardware.
So, what IorD is doing is selecting the source for the address provided to the Memory — as to whether it is doing a fetch cycle for an instruction, or a read/write from/to data.
When IorD=0 then the PC provides the address from which to read (i.e. instruction fetch), and, when IorD=1 then the ALU provides the address to read/write data from.  For data operations, the ALU is computing a base + displacement addressing mode: Reg[rs] + SignExt32(imm16) as the effective address to use for the data read or write operation.
Further, let's note that this block diagram does not contain a separate adder for incrementing the PC by 4, whereas most other block diagrams do.  Lookup any of the first few MIPS single cycle datapath images, and you'll see the dedicated adder for that PC increment.  Using a dedicated adder allows the PC to be incremented in parallel with operations done by the ALU,   whereas omitting that dedicated adder means that the main ALU must perform the increment of the PC.  However, this probably saves transistors in a simple version of a multicycle implementation where the ALU is not in use every cycle, and so can be used otherwise.
Since Target has a control TargetWrite, we might presume this is an internal register that might be useful in buffering the intended branch target address, for example, if the branch target is computed in one cycle, and finally used in another.
(I thought this could be about buffering for branch delay slot implementation (since those branches are delayed one instruction), but were that the case, the J-Type instructions would have also gone through Target, and they don't.)
So, it looks to me like the machinery there for this multicycle processor is to handle the branch instructions, say beq, which has to:

*

*compute the next sequential PC address from PC + 4

*compute the branch target address from (PC+4) + SignExt32(imm32)

*compute the branch condition (does Reg[rs] == Reg[rt] ?)

But what order would they be computed?  It is clear from control signals in state 0 is that: PC+4 is computed first, and written back to the PC, for all instructions (i.e. for branches, whether the branch is taken or not).
It seems to me that in a next cycle, (PC+4) + SignExt32(imm16) is computed (by reusing the prior PC+4 which is now in the PC register — this result is stored in Target to buffer that value since it doesn't yet know if the branch is taken or not.  In a next cycle, contents of rs and rt are compared for equality and if equal, the branch should be taken, so PCSource=1, PCWrite=1 selects the Target from the buffer to update the PC, and if not taken, since the PC already has been updated to PC+4, that PC+4 stands (PCWrite=0, PCSource=don't care) for the start of the next instruction.  In either case the next instruction runs with what address the PC holds.
Alternately, since the processor is multicycle, the order of computation could be: compute PC+4 and store into the PC.  Compute the branch condition, and decide what kind of cycle to run next, namely, for the not-taken condition, go right to the next instruction fetch cycle (with PC+4 in the PC), or, for taken branch condition, compute (PC+4) + SignExt32(imm16) and put that into the PC, and then go on to the next instruction fetch cycle.
This alternative approach would require dynamic alteration of the cycles/state for branches, so would complicate the multicycle state machine somewhat and would also not require buffering of a branch Target — so I think it is more likely the former rather than this alternative.


text:
Q: Extract proper username from a string with regex in js I want to extract a username from a string that user has typed into input. The thing is that I don't want just simply validate username, but I want to show for user what will be the final username even if user types any non-allowed characters.
So for example if user types in something like &%$User)(Nam-e it will show usernam-e
there is similar question with answer Regular expression to validate username, but somehow it gives me an error of Invalid group on  node.js when I try to use it with a match or exec functions.
Anyway, most of the examples online only validates the username against regex, but not actually provides the outcome of the appropriate username.
Rules are following:

*

*Only contains alphanumeric characters, underscore, dash and dot.

*Underscore, dash and dot can't be at the end or start of a username
(e.g _username / username_).

*Underscore, dash and dot can't be next to each other (e.g
user_-.name).

*Underscore, dash or dot can't be used multiple times in a row (e.g
user__name).

So far I was only capable to do something similar with using replace function number of times
value.replace(/[^\w-]*/g,'').replace(/^[^a-z]*/,'').replace(/-{2,}/g,'-').replace(/_{2,}/g,'_');

But this doesn't look like an efficient code, especially that I would actually need to add even more replace functions to extract appropriate username.
Any ideas how to achieve that?

A: Assumes that you want the name displayed in lower-case, as in your example:
function user( n ) {
    var name = n.replace( /^[^a-z]+|[^a-z\d_\-.]|[_\-.](?![a-z\d])/gi, '' );
    if ( n != name ) {
        console.log( 'Username invalid' );
    }
    return name.toLowerCase();
}

user('&%$User)(Nam-e');    // Username invalid, usernam-e
user('_Giedrius_one_');    // Username invalid, giedrius_one
user('Giedrius--one');     // Username invalid, giedrius-one
user('Giedrius-one');      // giedrius-one
user('/.bob_/');           // Username invalid, bob


text:
Q: PHP PDO MYSQL - Easiest way to compare array to query and return an array with results not in result of query? In PHP I have a simple array called $allFiles like:
Array
(
    [0] => test1.csv
    [1] => test2.csv
    [2] => test3.csv
)

In MySQL I have a table that has values like:
| ID | PROCESSED |
| 0  | test2.csv |

What is the easiest way (Using PDO as a connection method) to compare $allFiles to the table and return a new array $newFiles that contains:
Array
(
    [0] => test1.csv
    [1] => test3.csv
)

(these are the files that are not represented in the table in MySQL)
I've been through the manual but cannot seem to find anything that would relate exactly to this, I might have missed something though. Any input would be greatly appreciated, thanks!

A: PDO returns an array of values from your table. You can check if your results are already in the db array. You can check on array key, if your results are already in the PDO array, skip this result. If your result isn't in the PDO array build a new array with that value or values.
Note: PDO returns an nummeric and text key for one record. When you check if key exist you have to check if your key is a nummeric key. If nummeric, skip that one.

A: Just like the guys in the comments has said, there is no PDO function that does this outright. You'll have to gather your results first, put them in an array and use array_diff().
Rough example:
$allFiles = ['test1.csv', 'test2.csv', 'test3.csv'];

$con = new PDO('mysql:host=localhost;dbname=DATABASE', 'username', 'password');
$query = $con->query('SELECT PROCESSED FROM table_name');
$db_results = [];
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $db_results[] = $row['PROCESSED'];
}

$results = array_diff($allFiles, $db_results);

A: There is no ready-made function to do this. Most of the time, you'll find that there is no out-of-the-box solution to your problem. You'll have to write the code yourself, which isn't too hard: query the DB getting all of the file names, create an array with the results, then get the diff between the array you have, and the query results.
A basic example would be:
$stmt = $pdo->prepare('SELECT PROCESSED FROM db.table WHERE PROCESSED IN (?,?,?)');
$stmt->execute($allFiles);
$existing = array();
while($row = $stmt->fetch(PDO::FETCH_OBJ))
    $existing[] = $row->PROCESSED;//construct array containing existing values
$notFound = array_diff($allFiles, $existing);
var_dump($notFound);

You could make the query a tad more dynamic, by using the length of the $allFiles array, and add ? placeholders accordingly:
$allFiles = array_filter(array_unique($allFiles));//clean array
$placeholders = array_fill(0, count($allFiles), '?');
$stmt = $pdo->prepare(
    'SELECT PROCESSED FROM db.table WHERE PROCESSED IN ('.implode(',', $placeholders).')'
);
//alternative:
$stmt = $pdo->prepare(
    'SELECT PROCESSED FROM db.table WHERE PROCESSED IN ('.
    substr(
        str_repeat('?,',count($allFiles)),//repeat ?, as many times as there are values
        0,-1//remove trailing ","
    ).')'
);
$stmt->execute(array_values($allFiles));//better safe than sorry
//rest is the same as before

That allows you to process any length of array.


text:
Q: How do I remove a Facebook "Insights For My Domain" Reference I have Facebook "Insights For My Domain" added to my Facebook Insights account.  I have an old domain that is no longer in use and would like to remove the domain from my Facebook Insights account.  Can you please direct me to some directions regarding if and how this can be done?

A: Delete the application in developers.facebook.com/apps corresponding to the old domain.Then the Insights for that will be deleted


text:
Q: Display Empty Data if all data values are zero in piechart Chartjs While displaying pie chart, I encounter scenarios when all the values for the data sets will be zero. Right now, when this occurs the piechart is not manifested. Instead I want to display a text as Empty Data for such case. My backbone code is as follows. Ay help would be appreciated!
ctx = $(@el).find('#active-goals-status canvas#pie-chartcanvas')[0]
ctx.height = 100%
labels = []
values = []

$.each @status_model.get('goal_status'),(status, value)->
  labels.push(status)
  values.push(value)

myPieChart = new ChartNew ctx,
  type: 'pie',
  data:
    labels: labels
    datasets: [
      backgroundColor: ['#DCDCDC','#FF0000','#00FF00','#FFFF00']
      data: values
    ]
  options:
    responsive: true
    title:
      display: true,
      text: ECL.t('goals_status_upcase', {default_value: 'GOAL
            STATUS'})
      position: 'bottom'
      fontSize: 12
      fontColor: '#999'
      fontStyle: 'normal'
    legend:
      display: false
    layout:
      padding:
        left: 0
        right: 0
      margin:
        left: 0
        right: 0


text:
Q: How to change the code on runtime after refresh the page I am trying to change code of Java script on the fly.
I am using chrome. My problem is how do I keep the changes after I do refresh because for now  I am setting break point before the change and change the code and save it and run it. But when refreshing the page it it return to the original one.
How can I load it with me changes?
Thanks!

A: Don't make changes within the debugger console, instead change your code in your underlaying *.js-file and hit refresh.


text:
Q: Can't add bootstrap classes to javascript innerHTML var result = document.getElementById("result")

//can't add bootstrap classes to
 and

result.innerHTML = "

Column A

A: First of all in your code the outer div doesn't seem to have an id attached to it, call the div like:

To add bootstrap to your html you have to first import the css file  and put it in the head element of your html like:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Then add the javascript, jquery, and popper.js file to the end of the body of the html:

Also make sure to add your javascript to the html using the script tag as seen above or put it b/w the script tags


text:
Q: ACID Transactions at the File System Background:
I am getting a temperature float from an arduino via a serial connection. I need to be able to cache this temperature data every 30 seconds for other applications (e.g. web, thermostat controller) to access and not overload the serial connection.
Currently I cache this data to RAM as a file in /run (I'm trying to follow Linux convention). Then, other applications can poll the file for the temperature as they want it all day long with i/o now the only bottle neck (using an rpi, so not a lot of enterprise-level need here).
Problem:
I think when an app reads these files, it risks reading corrupt data. Should a writer update the file, and a reader try to read the file at the same time, can corrupt data be read, causing the thermostat to behave erratically?
Should I just use sqlite3 as an overkill solution, or use file locks (and does that risk something else not working perfectly)?
This is all taking place in multiple python processes. Is Linux able to handle this situation natively or do I need to apply somehow the principles mentioned here?

A: Calls to write(2) ought to be atomic under Linux.
Which means as long you are writing a single buffer, you can be certain that readers won't read an incomplete record. You might want to use os.write to make sure that no buffering/chunking happens you are not aware of.

if a read is happening and a file is updated, will the read use the new data while in the middle of a file, or does it somehow know how to get data from the old file (how)?

If there is exactly one read(2) and one write(2), you are guaranteed to see a consistent result. If you split your write into two, it might happen that you write the first part, read and then write the second part which would be an atomicity violation. In case you need to write multiple buffers, either combine them yourself or use writev(2).


text:
Q: javascript: completely remove top.location.hash? If I have already a hash in my addressbar like e.g. domain.com#whatever and I call:
top.location.hash = "";
the #wathever is transformed into domain.com# without anything.
Is it possible to completely remove the hash? So there is no # left.
Because if I call top.location.hash = ""; the page jumps to it's top, because a # is passed to the url. I want to prevent that.

A: it's possible with history.pushState, e.g.:
history.pushState({}, '', './');

Of course it's IE<10 incompatible, but works for me :-)

A: top.location = ''

should do that, but it will cause a page reload.  I don't think there's any way to remove it programmatically.

A: window.location = window.location.href.replace( /#.*/, "");

A: Unfortunately there is no way to reliably do so without causing the page to refresh, in which case you could use the location.href property.


text:
Q: Support for SAML within .Net Framework Are there any inbuilt .Net libraries which Microsoft ship within .Net framework to build SP-Initiated Authentication.
If yes please let me know the reference.

A: Here is a list:

*

*ComponentSpace (commercial)

*OIOSAML (open source)

*ITfoxtec (open source)

*Kentor (open source)

*Owin.Security.Saml (open source)


text:
Q: no matching function for call to 'regex_search(...)' Given an old-style const char * pointer and a length, is there a way to call std::regex_search() on it without first copying the contents of the buffer into a std::string?  Here is a simple example of the problem I have:
#include <regex>

int main()
{
    const char *text = "123 foobar 456";
    const size_t len = strlen(text);

    const std::regex rx(" (.+)bar");

    std::smatch what;
    std::regex_search( text, text+len, what, rx); // <- problematic line

    return 0;
}

I thought the 5th std::regex_search() that takes two iterators is what I need, but I'm not fully understanding how to convert pointers to iterators.  When I try to compile the code above, I get this:
g++ -std=c++11 test.cpp
test.cpp:11:45: error: no matching function for call to 'regex_search(const char*&, const char*, std::smatch&, const regex&)'
/usr/include/c++/4.9/bits/regex.h:2131:5: note: template<class _Bi_iter, class _Alloc, class _Ch_type, class _Rx_traits> bool std::regex_search(_Bi_iter, _Bi_iter, std::match_results<_BiIter, _Alloc>&, const std::basic_regex<_CharT, _TraitsT>&, std::regex_constants::match_flag_type)
 regex_search(_Bi_iter __s, _Bi_iter __e,

...and a lot more errors!
Can const char * be converted to the necessary iterator?  Did I do it wrong?  Am I misunderstanding how this works?

A: The error in your code is that you're using the wrong match_results type. smatch is supposed to be used when you have an std::string object and you're passing std::string::iterators to the regex function. When you have raw char const *s use cmatch instead.
Change
std::smatch what;

to
std::cmatch what;

Live demo


text:
Q: How to hide mouse over multiple frames? I'm an actionscript n00b, please excuse my ignorance.
currently trying to make my first person shooter game and have picked up great tips from Lynda(.com) but im having difficulty changing my mouse into a crosshair cursor and having that crosshair not show up permanently in subsequent frames as I create this game.
so i have this code on an action layer but on other layers when I create another key frame to change what I shoot at on other layers, my cursor stamps a permanent image of itself onto the screen.  I definitely need to understand this language more if Im going to become good at it but for now i'f like to be able to make a few games to entertain myself, any suggestions? are appreciated
var cursor:MovieClip;

function initializeGame():void
{
cursor = new Cursor();
addChild(cursor);
cursor.enabled = false;
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
}

function dragCursor(event:MouseEvent):void
{
cursor.x = this.mouseX;
cursor.y = this.mouseY;
}

initializeGame();

A: In AS3, items will remain on the display list (on screen) until explicitly removed (or their parent is removed).
So to keep your cursor from staying on screen, you need to remove it:
removeChild(cursor);

Doing Mouse.show() doesn't affect any display objects on the screen.
If you assign a new value to the var cursor, it doesn't automatically remove the previous object - as variables are just references to objects.  So if in your subsequent frames you are making a new cursor, you want to remove the existing one prior to assigning a new one to the variable:
if(cursor.parent)  removeChild(cursor); //if there is an object assigned to cursor, and it has a parent (which means it's on screen), then remove it before doing the below code
cursor = new Cursor();
addChild(cursor);