text:
Q: How to round numbers to hundreds, i.e., to the nearest multiple of 100 I want to round numbers to hundreds. I note Rounding a number to its hundred. However, the question asks about rounding 2,386.0 down to 2,300.0 -- and I would want it to be rounded up to 2,400.0, and I would want 2,326.0 to be rounded down to 2,300.0.
How to do this?
According to a comment by joseph-wright, it would be easy, but after reading and trying for an hour, I decided to ask here.
MWE
\documentclass{article}
\usepackage{xparse,siunitx}
\ExplSyntaxOn
\NewDocumentCommand{\hundreds}{O{}m}
 {
  \num[#1]{\fp_eval:n { trunc(#2,-2) }}
 }
\ExplSyntaxOff
\newcommand{\myhundreds}[1]{\num[round-mode=figures,round-precision=-2]{#1}}
\begin{document}

\hundreds{2348}

\hundreds[group-four-digits,group-separator={,}]{2348}

\sisetup{group-four-digits,group-separator={,}}

\hundreds{2399}

\hundreds{2301}

\myhundreds{2300}
\end{document}

A: Use round rather than trunc. From the l3fp documentation:

\documentclass{article}
\usepackage{xparse,siunitx}

\ExplSyntaxOn
\NewDocumentCommand{\hundreds}{O{}m}
 {
  \num[#1]{\fp_eval:n { round(#2,-2) }}
 }
\ExplSyntaxOff

\begin{document}

\hundreds{2348}

\hundreds[group-four-digits,group-separator={,}]{2348}

\sisetup{group-four-digits,group-separator={,}}

\hundreds{2399}

\hundreds{2301}

\end{document}

This prints 2300 2,300 2,400 2,300.

A: Just for the sake of variety, here's LuaLaTeX-based solution. It provides a LaTeX macro called \hundreds. The input of this macro must be either a number or an expression that evaluates to a number according to Lua's syntax rules; its output is that number rounded to the nearest multiple of 100. The LaTeX macro \hundreds uses LuaTeX's tex.sprint function as well as a utility Lua function called math.round_int which rounds a number to the nearest integer.
The \hundreds macro can be placed in the argument of \num for further pretty-printing.

\documentclass{article}
\usepackage[group-four-digits,group-separator={,}]{siunitx} % for \num macro
% define a Lua function called 'math.round_int':
\directlua{%
function math.round_int ( x )
   return x>=0 and math.floor(x+0.5) or math.ceil(x-0.5)
end
}
\newcommand{\hundreds}[1]{\directlua{%
   tex.sprint(100*math.floor(math.round_int((#1)/100)))}}

\begin{document}
\hundreds{2348};
\hundreds{2399};
\hundreds{2301};
\hundreds{23*100+10}; % arg evaluates to '2310'
\num{\hundreds{2301}}
\end{document}


text:
Q: My list view is automatically populating when other users are using my application(Firebase,android) Im using custom Adapter to populate my list view dynamically.Getting data from firebase realtime database. i dont want application to populate it with users who are using my application.because when everyone is offline listview stays normal.
This is whats happening
This is how it should be
i've tried everything i could. im using myadapter in 3/4 activities
My adapter.java
public class MyAdapter extends ArrayAdapter<String> {
    ArrayList<String> name=new ArrayList<>();
    ArrayList<String> status=new ArrayList<>();
    ArrayList<String> imgs=new ArrayList<>();
    ArrayList<String> key=new ArrayList<>();
    private Context context;
    private int resource;
    private LayoutInflater layoutInflater;

    public MyAdapter(@NonNull Context context, int resource, ArrayList<String> name, ArrayList<String> status, ArrayList<String> imgs,ArrayList<String> key) {
        super(context, resource);
        this.imgs=imgs;
        this.name=name;
        this.status=status;
        this.key=key;
        this.resource=resource;
        this.context=context;
        layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return name.size();
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        //  return super.getView(position, convertView, parent);
        View v=layoutInflater.inflate(resource,parent,false);
        CircleImageView view=v.findViewById(R.id.single_user_image);
        if(imgs!=null) {
            Picasso.get().load(imgs.get(position)).placeholder(R.drawable.user).into(view);
        }else{
            Picasso.get().load(R.drawable.user).into(view);
            Toasty.error(context,"check internet connection", Toast.LENGTH_SHORT).show();
        }
        TextView tv1=v.findViewById(R.id.single_user_name);
        TextView tv2=v.findViewById(R.id.single_user_status);
        tv1.setText(name.get(position));
        tv2.setText("Connected Since:"+status.get(position));
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getContext(),SingleUserProfileActivity.class);
                intent.putExtra("key",key.get(position));
                getContext().startActivity(intent);
            }
        });
        return v;
    }
}

Myactivity.java

public class ConnectedUsersFragment extends Fragment {
    ListView connectedUsersList;
    DatabaseReference connectedUsersReference;
    DatabaseReference userInfoRefernce;
    DatabaseReference presenceReference;
    ArrayList<String> name=new ArrayList<>();
    ArrayList<String> status=new ArrayList<>();
    ArrayList<String> imgs=new ArrayList<>();
    ArrayList<String> key=new ArrayList<>();
    MyAdapter adapter;
    FirebaseUser user;

    public ConnectedUsersFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_connected_users, container, false);
        connectedUsersList=v.findViewById(R.id.connected_users_list);
        user=FirebaseAuth.getInstance().getCurrentUser();
        presenceReference=FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid());
        connectedUsersReference= FirebaseDatabase.getInstance().getReference().child("connected_users").child(user.getUid());
        userInfoRefernce=FirebaseDatabase.getInstance().getReference().child("users");
        adapter=new MyAdapter(getContext(),R.layout.single_user_layout,name,status,imgs,key);
        connectedUsersList.setAdapter(adapter);
        connectedUsersReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                String userKey=dataSnapshot.getKey();
                final String userConnectedDate=dataSnapshot.child("date").getValue(String.class);
                userInfoRefernce.child(userKey).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        String userKey=dataSnapshot.getKey();
                        String username=dataSnapshot.child("name").getValue(String.class);
                        String userstatus=dataSnapshot.child("profile_status").getValue(String.class);
                        String userimg=dataSnapshot.child("thumb_image").getValue(String.class);
                        name.add(username);
                        status.add(userConnectedDate);
                        imgs.add(userimg);
                        key.add(userKey);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        Toasty.error(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toasty.warning(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();
        if(user!=null) {
            presenceReference.child("online").setValue("true");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(user!=null) {
            presenceReference.child("online").setValue("true");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if(user!=null) {
            presenceReference.child("online").setValue(ServerValue.TIMESTAMP);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(user!=null) {
            presenceReference.child("online").setValue(ServerValue.TIMESTAMP);
        }
    }
}

A: In userInfoRefernce.child(userKey) you are setting a ValueEventListener that is triggered every time a user triggers any lifecycle event (see onStart, onResume, onPause and onStop). Try using a ChildEventListener and using a Query for filtering your data before downloading it.
Hope this helps you.

A: I replaced ValueEventListener() to ListenerForSingleValueEvent() as i wanted to show listen for event just once on these pages and thanks to @Victor Maldonado i remembered the difference :P

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using setInterval in function with internal call (js)? I have such code here. I want to display result with time interval in a few seconds. But it doesn't work.
const moveCranes = setInterval(function(plate, slot_a, slot_b, slot_c) {
    if (plate > 0) {
        moveCranes(plate - 1, slot_a, slot_c, slot_b);
        port_a.innerHTML = "Move plate " + plate + " from " + slot_a + " to " + slot_c + "
";
    moveCranes(plate - 1,slot_b, slot_a, slot_c);
    }
}, 2000);
moveCranes(input.value,"slot_a","slot_b","slot_c");

Can you explain what do I wrong and why doesn't the setInterval doesn't work?

A: You seem to be looking for
function moveCranes(plate, slot_a, slot_b, slot_c) { /*
^^^^^^^^ */
    setInterval(function() {
//              ^^^^^^^^^^ this inner function takes no parameters
        if (plate > 0) {
            moveCranes(plate - 1, slot_a, slot_c, slot_b);
            port_a.innerHTML = "Move plate " + plate + " from " + slot_a + " to " + slot_c + "
";
            moveCranes(plate - 1, slot_b, slot_a, slot_c);
        }
    }, 2000);
}

And since you are recursively calling the function again, you probably wanted to use setTimeout instead of setInterval.


text:
Q: Add scroll to a table I have a table in which i add rows dynamically and i want to add a vertically scroll to the table when its width get 300 or more. Any tips?

A: You can wrap your table in a
 with the overflow: auto style, as follows:


text:
Q: UISplitViewController with multiple detail ViewControllers in tvOS I am trying to implement a UISplitViewController on tvOSapp which has a Master ViewController with a UITableView displaying a menu. I also have an Initial Detail ViewController assigned.
What I want to achieve is that when a row in the Master ViewController menu is clicked, the initial detailViewController should be replaced by another one.

A: That's what showDetailViewController(vc: UIViewController, sender: Any?) is for.


text:
Q: Escaping special characters in a SQL LIKE statement using sql parameters I have a table containing products. I need to make a query finding all the matching results to an user-input value. I am using SqlParameter for the insertion of the inputs.
SqlCommand findProcutsByPattern = new SqlCommand(
    "SELECT *" +
    " FROM [Products]" +
    " WHERE ProductName LIKE @pattern", connection);

findProcutsByPattern.Parameters.AddWithValue("@pattern", '%' + pattern + '%');

The problem comes when the user input string contains '_' or '%' as they're being interpreted as special characters. In the other hand, considering this:

Command objects use parameters to pass values to SQL statements or
  stored procedures, providing type checking and validation. Unlike
  command text, parameter input is treated as a literal value, not as
  executable code.

I shouldn't have such problems. Do I need to replace/escape all the '_' and '%' in the input string or is there a more elegant solution. I want the input to be considered as a literal.
I have a few records in the table which include special characters in the name(N_EW, N\EW, N%EW, N"EW, N'EW). Specifying \, ", and ' as the input works fine(considers them as literals).

A: You can do it like this: specify an explicit escape character in your SQL string, and then place that escape in front of all % and _ characters inside the string the user enters:
SqlCommand findProcutsByPattern = new SqlCommand(
    @"SELECT *
    FROM [Products]
    WHERE ProductName LIKE @pattern", connection) ESCAPE '_'"

When you set the parameter, replace all instances of _ and % with __ and _%:
var escapedPattern = Regex.Replace(pattern, "[%_]", "_$0");

Demo.

A: You have two options:

*

*enclose them in [ and ].  So:
where pattern like '[%]'

Looks for the percentage character.
Full list of characters to escape -  '_', '%', '[', ']' with corresponding replacements '[_]', '[%]', '[[]', '[]]'. Sample code can be found in Escaping the escape character does not work – SQL LIKE Operator

*use an escape character that is unlikely to be in the string, such as a backtick:
where pattern like '`%' escape '`'

(See the syntax on MSDN - LIKE (Transact-SQL).)
In both cases, I would suggest that you make the substitution in the application layer, but you can also do it in SQL if you really want:
where pattern like replace(@pattern, '%', '[%]')

And, giving the end-user access to wildcards may be a good thing in terms of the user interface.

Note: there are couple more special characters '-' and '^' in the LIKE query, but they don't need to be escaped if you are already escaping '[' and ']'.

A: Generally speaking, manually escaping values in SQL is considered bad practice as using parameters is the preferred (and more secure) solution.
In your example, however, you are already using parameters and you want to use the LIKE operator, so manually escaping the characters should be fine. Don't forget escaping the escape characters, too - see https://stackoverflow.com/a/13861567/232175 for some code.

A: So, basically, I manually escaped(replaced) all the wildcard symbols, which seems to work fine now. Here is the final code.
        SqlCommand findProcutsByPattern = new SqlCommand(
            "SELECT *" +
            "FROM [Products]" +
            "WHERE ProductName LIKE @pattern", connection);

        string patternEscaped = pattern.Replace("[", "[[]");
        patternEscaped = patternEscaped.Replace("_", "[_]");
        patternEscaped = patternEscaped.Replace("%", "[%]");

        findProcutsByPattern.Parameters.AddWithValue("@pattern", '%' + patternEscaped + '%');

Thank you for the support!
UPDATE: I see...

escape_character Is a character that is put in front of a wildcard
character to indicate that the wildcard should be interpreted as a
regular character and not as a wildcard. escape_character is a
character expression that has no default and must evaluate to only one
character.

So you still have to do the escaping yourself.


text:
Q: PHP: Pass in unknown number of parameters to method from array This probably sounds like a stupid question, but hear me out...
I've got a Laravel package which provides events and notifications. The notifications are triggered by events from inside the Laravel package. Users of the package can decide to use their own notifications if they wish, they'd just specify it in the package's config file.
The events I have built in have methods like $order and $stock, in fact here's an example of one of my events:
<?php

namespace DoubleThreeDigital\SimpleCommerce\Events;

use DoubleThreeDigital\SimpleCommerce\Contracts\Order;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;

class OrderPaid
{
    use Dispatchable;
    use InteractsWithSockets;

    public Order $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }
}

In my package, there's a listener which listens for this OrderPaid event. It then figures out which of the notifications need to be sent when this event is triggered.
I don't know what the notification itself is going to be (that's configured by the user) and I also don't know which methods the notification accepts in its constructor.
Although, I've figured out how to read the notifications constructor and get the right parameters from the event, which I then turn into an array.
Now I have my array of parameters, I run into a problem. How do I pass that array into the constructor of the notification without knowing how many params it accepts?
Here's my current code:
$notification = new $notification($howDoIPassInTheArrayStuffIntoHere);

I found the call_user_func_array function but I don't think it really does what I'm looking for, maybe I'm wrong?
Anyways, hopefully that's enough information - I'm never good at explaining stuff on here but hopefully someone understands me

A: Use this method, ... denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array.
Check docs:    Variable-length argument lists
function array_of_parameters(...$parameter)
{

}

array_of_parameters('p1','p2','p3');

In your case:
public function __construct(Order ...$order)
    {
        $this->order = $order;
    }


text:
Q: Zend framework 2: Load data on scroll I would like to load data (images and some texts) on scroll at the bottom of page. I am using Zend 2 framework and jquery.
view

    <?php
    $total_groups = ceil($count / 10);
    ?>

autoload_process.php
<?php
$items_per_group = 10;
if ($_POST) {
    //sanitize post value
    $group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

    //throw HTTP error if group number is not valid
    if (!is_numeric($group_number)) {
        header('HTTP/1.1 500 Invalid number!');
        exit();
    }

    //get current starting point of records
    $position = ($group_number * $items_per_group);

    //Limit our results within a specified range.
    $results = $mysqli->query("SELECT id,name,alt as message FROM works ORDER BY id ASC LIMIT $position, $items_per_group");

    if ($results) {
        //output results from database

        while ($obj = $results->fetch_object()) {
            echo '
id . '">' . $obj->id . ' - ' . $obj->name . ' — ' . $obj->message . '
';
        }
    }
    unset($obj);
    $mysqli->close();
}
?>

I do not think invoking autoload_process.php from jquery is the best way how to load files in Zend2. I think I should somehow call my Controller or my table functions, but no luck yet.


text:
Q: How to flash Ubuntu-core Snappy on Artik-5 (v 0.5)? Artik 5 already have an OS fedora 22. I followed the link to boot from SD card, and got success:
https://developer.ubuntu.com/en/snappy/start/samsung-artik-iot-modules/
But I cannot flash Ubuntu-core to Artik 5. Instead of writing to eMMC, it boots from SD card when SW2 (1:on 2:off) or (1:on 2:on).

A: This isn't possible as of now to flash the eMMc as far as I know of. We have in the plan to have a tool to flash current Ubuntu Core image that you would start from ssd card to eMMC (but no ETA on this).


text:
Q: Swagger Param Documentation Current State:
I have two methods in my controller to get data based on what parameters are passed.  The code:
@RestController
@RequestMapping("/samples")
public class SampleController {

    @RequestMapping(value = "/{id}", params = {"cost"}, method = RequestMethod.GET)
    public String getSamplesByIdAndCost(@PathVariable String id, @RequestParam(value = "cost") String cost) {
        return "result";
    }

    @RequestMapping(value = "/{id}", params = {"cost", "size"}, method = RequestMethod.GET)
    public String getSamplesByIdCostAndSize(@PathVariable String id, @RequestParam(value = "cost") String cost,
                                        @RequestParam(value = "size") String size) {
    return "ID : " + id + " / COST : " + cost + " / SIZE : " + size;
    }
}

Everything works fine, but the swagger documentation is not what I expected.

Question
Is there a way to remove {?size,cost} from the Request URL?
Here is my Docket info:
@Bean
    public Docket myApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .directModelSubstitute(LocalDate.class,
                        String.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .alternateTypeRules(
                        newRule(typeResolver.resolve(DeferredResult.class,
                                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)))
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET,
                        newArrayList(new ResponseMessageBuilder()
                                .code(500)
                                .message("500 message")
                                .responseModel(new ModelRef("Error"))
                                .build()))
                .enableUrlTemplating(true);

    }

    @Autowired
    TypeResolver typeResolver;

    @Bean
    UiConfiguration uiConfig() {
        return new UiConfiguration(
                "validatorUrl",// url
                "none",       // docExpansion          => none | list
                "alpha",      // apiSorter             => alpha
                "schema",     // defaultModelRendering => schema
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
                false,        // enableJsonEditor      => true | false
                true);        // showRequestHeaders    => true | false
    }

A: Multiple documentations for the same path based on query strings is not something that is supported by Swagger spec and therefore not by swagger-ui.
What you have enabled by setting enableUrlTemplating(true) appears to be an incubation feature in springfox but won't work as of now with swagger-ui.
Relevant discussion can be found here:

*

*https://github.com/swagger-api/swagger-ui/issues/1665

*https://github.com/springfox/springfox/issues/866
For now it seem like you either have to live with paths looking weird in the swagger-ui, or you have to merge your documentation.

A: See Tobias Raski's answer to understand more about why this problem exists.
There is a work around for this.  You can see some details here: https://github.com/springfox/springfox/issues/1484
In summary there is an experimental UI that fixes the issue.  This may eventually be irrelevant when a future fix comes out.

A: According to this thread:

Swagger spec does not allow multiple endpoints that differ by request params. However you could use the experimental feature to get around it using docket#enableUrlTemplates(true). Keep in mind it is experimental. Also please upgrade to 2.7.0

A: Remove the 'params' attribute in your @RequestMapping annotation, your code will still work.

A: you can change maven pom
<dependency>
    <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
 <dependency>
    <groupId>io.springfox.ui</groupId>
        <artifactId>springfox-swagger-ui-rfc6570</artifactId>
        <version>1.0.0</version>
</dependency>

use springfox-swagger-ui-rfc6570 instead of springfox-swagger-ui
Click here to see more.


text:
Q: Equivalent of git log command for Heroku I am wondering if there is an equivalent of git log for Heroku that shows the push history on heroku remote.

A: Using the heroku cli running the command : heroku releases should do the trick.
Source : https://devcenter.heroku.com/articles/using-the-cli

A: I complement this question by saying that heroku releases will do that, but if you want to know more about the release you can do:
For version 1: heroku releases:info v1
For version 2: heroku releases:info v2
And so on...

You can check more info in the documentation of heroku:

https://devcenter.heroku.com/articles/releases


text:
Q: convert number with decimal places from char to int in c++ I was playing around with VS 2012 and came across a very tricky problem (for me at least). I have a simple program that does mathematical   operations on inputs from the command line. However, if you input arguments with decimal places somewhere in the program it seems to forget the numbers after the decimal place.
double add (char const *inp, char const *inp2) {        //addition function
    double val = std::strtol(inp, NULL, 0);
    double val2 = std::strtol(inp2, NULL, 0);
    return val + val2;
}

and then calling the function :
double result = add(argv[1], argv[2]);
printf("%f \n", result);

and call from command line
test 52.2 44.6

returns 96 instead of 96.8.

A: You want strtod, not strtol. strtol only parses integers.
strtod only takes two arguments, because floating point numbers are always in base 10 (as far as strtod is concerned, anyway.)

A: I think you are turning your strings into longs (I'm guessing that's what strtol() is...). I was building a calculator and I had that problem - I wrote a function to handel it:
double string_to_double(string str)
{
    int length = (int)str.length();
    double output = 0; //This holds value of output.  Will be added for each 10's digit
    int decimalPos = length - 1;
    for (int i = 0; i < length; i++)
    {
        if(str.at(i) == '.') // Find if there is a decimal point
        {
            decimalPos = i - 1; //Sets Decimal Position
            str.erase(str.begin()+i);
            length--;
        }
    }

    for (int i = 0; i < length; i++)
    {
        switch (str.at(i))
        {
            case '1':
                output += 1*pow(10, decimalPos - i);
                break;
            case '2':
                output += 2*pow(10, decimalPos - i);
                break;
            case '3':
                output += 3*pow(10, decimalPos - i);
                break;
            case '4':
                output += 4*pow(10, decimalPos - i);
                break;
            case '5':
                output += 5*pow(10, decimalPos - i);
                break;
            case '6':
                output += 6*pow(10, decimalPos - i);
                break;
            case '7':
                output += 7*pow(10, decimalPos - i);
                break;
            case '8':
                output += 8*pow(10, decimalPos - i);
                break;
            case '9':
                output += 9*pow(10, decimalPos - i);
                break;
            case '0':
                break;
        }

    }
    return output;
}

...but there is probably a better way


text:
Q: Como generar objetos con coordenadas (X, Y, Z) y ver estos objetos en vistas en 2D? La idea es crear ramas (representadas por una línea entre dos nodos) con coordenadas (x,y,z) pudiendo dibujar en 2D en cualquier vista, ya sea vista(x,y), vista(z,x) o vista(z,y) y luego poder visualizar estos objetos en una vista en 3D.
He estado intentando con Python y PyQt5.
import sys

from PyQt5 import QtCore, QtGui, QtWidgets

class CadWindowMdi(QtWidgets.QMainWindow):
    def __init__(self):
        super(CadWindowMdi, self).__init__()
        self.mdiArea = QtWidgets.QMdiArea()
        self.mdiArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.mdiArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.setCentralWidget(self.mdiArea)
        # self.setWindowState(QtCore.Qt.WindowMaximized)
        self.subwindow = CadView(CadScene())
        # self.subwindow.setWindowTitle('CAD')
        self.mdiArea.addSubWindow(self.subwindow)
        self.setWindowTitle("NT")

    @property
    def scene(self):
        if self.mdiArea.activeSubWindow():
            return self.mdiArea.activeSubWindow().scene
    @property
    def view(self):
        if self.mdiArea.activeSubWindow():
            return self.mdiArea.activeSubWindow().view

Lo anterior es la ventana principal.
Lo siguiente es la vista de la escena.
class CadView(QtWidgets.QGraphicsView):
    def __init__(self, scene, parent=None):
        super(CadView, self).__init__(scene, parent)
        self.scaleFactor=1
        self.controlPress=False
        self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
        self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.setRenderHints(QtGui.QPainter.Antialiasing)

Esta es la clase escena que alberga los elementos de dibujo.
class CadScene(QtWidgets.QGraphicsScene):
    def __init__(self, parent=None):
        super(CadScene, self).__init__(parent)
        self.setSceneRect(-10000, -10000, 20000, 20000)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(255, 255, 255), QtCore.Qt.SolidPattern))
        self._edge_item = None

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            node = Node()
            node.setPos(event.scenePos())
            self.addItem(node)

            if self._edge_item:
                self._edge_item.dst = node
                self._edge_item = None
            else:
                self._edge_item = Edge()
                self._edge_item.src = node
                self.addItem(self._edge_item)

    def mouseMoveEvent(self, event):
        if self._edge_item:
            self._edge_item.p2 = event.scenePos()
        super(CadScene, self).mouseMoveEvent(event)

Lo que sigue son las clases de nodos y ramas para dibujar.
class Node(QtWidgets.QGraphicsRectItem):
    def __init__(self, rect=QtCore.QRectF(-5, -5, 10, 10), parent=None):
        super(Node, self).__init__(rect, parent)
        self.edges = []
        self.setZValue(1)
        self.setBrush(QtCore.Qt.black)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)

    def addEdge(self, edge):
        self.edges.append(edge)

    def itemChange(self, change, value):
        if change == QtWidgets.QGraphicsItem.ItemSelectedChange:
            self.setBrush(QtCore.Qt.green if value else QtCore.Qt.darkGray)
        if change == QtWidgets.QGraphicsItem.ItemPositionHasChanged:
            for edge in self.edges:
                edge.adjust()
        return super(Node, self).itemChange(change, value)

class Edge(QtWidgets.QGraphicsLineItem):
    def __init__(self, parent=None):
        super(Edge, self).__init__(parent)
        self.setPen(QtGui.QPen(QtCore.Qt.black, 1.5))
        self._src = None
        self._dst = None

    @property
    def src(self):
        return self._src

    @src.setter
    def src(self, node):
        self._src = node
        self._src.addEdge(self)
        self.adjust()

    @property
    def dst(self):
        return self._dst

    @dst.setter
    def dst(self, node):
        self._dst = node
        self._dst.addEdge(self)
        self.adjust()

    @property
    def p1(self):
        return self.line().p1()

    @p1.setter
    def p1(self, p):
        line = self.line()
        line.setP1(p)
        self.setLine(line)

    @property
    def p2(self):
        return self.line().p2()

    @p2.setter
    def p2(self, p):
        line = self.line()
        line.setP2(p)
        self.setLine(line)

    def adjust(self):
        self.prepareGeometryChange()
        if self.src:
            self.p1 = self.src.pos()
            self.p2 = self.src.pos()
        if self.dst:
            self.p2 = self.dst.pos()

Aquí se inicia la app.
def getCAD():
    app = QtWidgets.QApplication(sys.argv)
    window = CadWindowMdi()
    window.show()
    return window, app

if __name__ == '__main__':
    window, app = getCAD()
    sys.exit(app.exec_())

Dejo un GIF para explicar de mejor manera.


text:
Q: How to display List in DataGrid horizontally? I'd like to display each element of List<int> in DataGrid horizontally.
My data looks like this:
result.Add(new CatModel(1, "AA", new List<int> { 1, 2, 3 }));
result.Add(new CatModel(2, "BB", new List<int> { 4, 5, 6 }));
result.Add(new CatModel(3, "CC", new List<int> { 7, 8, 9 }));

The elements of List<int> should be split into three parts and each element should be shown in a DataGrid cell horizontally:
1    AA    1    2    3
2    BB    4    5    6
3    CC    7    8    9

Now it shows only (Collection).
I think I need to work on the XAML, but I cannot find any example.
This question is similar to mine, but the solution is different from what I want.
I'd rather like to split the column into three parts and allocate each of them to a cell.
Incidentally, the goal of introducing List<int> is to display arbitrarily many number of elements. You can assume that all rows have exactly the same length, e.g., if the 1st row has 7 elements, all the other rows (this time, the 2nd and the 3rd) have also 7 elements.
Here is my code:
CatModel.cs
using System;
using System.Collections.Generic;

namespace WpfApp1
{
    public class CatModel
    {
        //public CatModel(int Num, String Name, int Test_0001, int Test_0002, int Test_0003)
        public CatModel(int Num, String Name, List<int> Test_List)
        {
            this.Num = Num;
            this.Name = Name;
            //this.Test_0001 = Test_0001;
            //this.Test_0002 = Test_0002;
            //this.Test_0003 = Test_0003;
            this.Test_List = Test_List;
        }
        public int Num { get; set; }
        public String Name { get; set; }
        //public int Test_0001 { get; set; }
        //public int Test_0002 { get; set; }
        //public int Test_0003 { get; set; }
        public List<int> Test_List { get; set; }
    }
}

MainWindow.xaml.cs
using System.Collections.Generic;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<CatModel> result = new List<CatModel>();

            //result.Add(new CatModel(1, "AA", 1, 2, 3));
            //result.Add(new CatModel(2, "BB", 4, 5, 6));
            //result.Add(new CatModel(3, "CC", 7, 8, 9));

            result.Add(new CatModel(1, "AA", new List<int> { 1, 2, 3 }));
            result.Add(new CatModel(2, "BB", new List<int> { 4, 5, 6 }));
            result.Add(new CatModel(3, "CC", new List<int> { 7, 8, 9 }));

            this.dataGrid.ItemsSource = result;
        }
    }
}

MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="List" Height="350" Width="750"
        BorderThickness="1">

    <Grid Width="700" Height="300">
        <DataGrid AutoGenerateColumns="False"  Name="dataGrid" HorizontalAlignment="Left" Margin="10,10,10,10">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Num}" ClipboardContentBinding="{x:Null}" Header="Num" IsReadOnly="True" Width="50"/>
                <DataGridTextColumn Binding="{Binding Name}" ClipboardContentBinding="{x:Null}" Header="Name" IsReadOnly="True" Width="100"/>
                <DataGridTextColumn Binding="{Binding Test_0001}" ClipboardContentBinding="{x:Null}" Header="Test_0001" IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Binding="{Binding Test_0002}" ClipboardContentBinding="{x:Null}" Header="Test_0002" IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Binding="{Binding Test_0003}" ClipboardContentBinding="{x:Null}" Header="Test_0003" IsReadOnly="True" Width="*"/>
                <DataGridTextColumn Binding="{Binding Test_List}" ClipboardContentBinding="{x:Null}" Header="Test_List" IsReadOnly="True" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

A: If for some reason you cannot use the DataTable (as you wrote in your comment), then you will have to use programmatic (in code behind) creation of columns.
    public MainWindow()
    {
        InitializeComponent();

        List<CatModel> result = new List<CatModel>();
        result.Add(new CatModel(1, "AA", new List<int> { 1, 2, 3 }));
        result.Add(new CatModel(2, "BB", new List<int> { 4, 5, 6 }));
        result.Add(new CatModel(3, "CC", new List<int> { 7, 8, 9 }));

        dataGrid.Columns.Clear();
        dataGrid.AutoGenerateColumns = false;

        dataGrid.Columns.Add(new DataGridTextColumn() { Header = nameof(CatModel.Num), Binding = new Binding(nameof(CatModel.Num)) });
        dataGrid.Columns.Add(new DataGridTextColumn() { Header = nameof(CatModel.Name), Binding = new Binding(nameof(CatModel.Name)) });

        for (int i = 0; i < 3; i++)
        {
            string path = $"{nameof(CatModel.List)}[{i}]";
            dataGrid.Columns.Add(new DataGridTextColumn() { Header = path, Binding = new Binding(path) });
        }

        dataGrid.ItemsSource = result;
    }

    public class CatModel
    {
        public CatModel(int num, string name, List<int> list)
        {
            Num = num;
            Name = name;
            List = list;
        }

        public int Num { get; }
        public string Name { get; }
        public List<int> List { get; }
    }

Also keep in mind that if you can change the "CatModel.List" collection (add/remove/insert/replace elements in it), then it should be replaced with ObservableCollection.
Otherwise, the new values of the collection items will not be displayed.


text:
Q: Force due to motion around Sun
Think of one person on earth named A . Ignoring Earth for a second, I can imagine him moving around the Sun due to which he should always feel some acceleration towards Sun (Centripetal Force) say F1. Now think of Earth. A also feels centripetal acceleration towards centre of Earth due to rotation, say F2. Well the forces F1 and F2 at some moment would be in the same direction i.e. towards sun and sometimes in the opposite direction. There is a clear variation in the net force on A. Why doesn't he feel that? Why don't we feel the variation in force?

A: Hint: The centripetal acceleration in a circular motion with radius $R$ and angular velocity $\omega$ (angular velocity is velocity divided by circumference, or $2\pi/T$ with period of rotation $T$) is given by
$$a=\omega^2 R\,.$$
Can you find the accelerations due to the motion around the sun ($T=1\text{ year}$, $R\approx150\text{ million km}$) and the earth ($T=1\text{ day}$, $R\approx6800\text{ km}$)? How do they compare with gravitational acceleration due to the mass of the earth ($g\approx9.81\text{ m/s}^2$)?

A: I would dispute your assertion (last line) that we don't feel these effects. If you mean why don't we feel it in our sense of balance or movement then the answer is as per @Toffomat - it's negligibly small. However, if you happen to be a long-range sharp-shooter or an artilleryman, you will certainly observe the effect that your rounds are landing off target due to some weird force that depends on latitude and direction of shot. This weird force is the Coriolis Force - well known to anyone involved in plotting motion over large distances and speeds.

A:
Why doesn't he feel that? Why don't we feel the variation in force?

We most certainly do, they're called "tides".
The issue is that the force in question is very small compared to the force of the gravity of the Earth. So although it is having an effect on you, it's too small to notice, and too slow changing.
The force is so small that, acting across the distance of the entire planet, it can lift water a couple of feet. So you might imagine that the same force acting across the distance of your body is a tiny amount.
Tider are very cool. If you want to see how cool, go read Neutron Star by Niven, it will explain all of this and is entertaining as well.


text:
Q: NSTimer inaccurate? I'm using an NSTimer to update a label that shows the current time each minute. I fire the timer at a full minute date (e.g. 2:23:00 instead of 2:22:17). The problem is that NSTimer seems to work inaccurately, which means it sometimes fires too early (which results in (e.g.) 2:23 PM when it is really 2:24 PM).
Is there any fix / workaround?
EDIT: Here's how I start the timer:
NSTimer *clockTimer = [[NSTimer alloc] initWithFireDate:[NSDate nextFullMinuteDate]
                                               interval:60.0
                                                 target:self
                                               selector:@selector(updateClocks:)
                                               userInfo:nil
                                                repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:clockTimer
                             forMode:NSDefaultRunLoopMode];
[clockTimer release];

Btw, I have tried adding a few milliseconds to the fire date, this seems to help but it looks like finding an appropriate interval to add is hit-and-miss.
EDIT 2: Ok, so I manually set my timer to fire 0.05 seconds after a full minute and then again after 60.0 seconds. Now here's what I logged in the called method:
0.048728
0.047153
0.046484
0.044883
0.043103

As you can see, NSTimer doesn't actually use a 60 second time interval, but a slightly shorter one.

A: From the NSTimer docs:

A timer is not a real-time mechanism; it fires only when one of the
  run loop modes to which the timer has been added is running and able
  to check if the timer's firing time has passed. Because of the various
  input sources a typical run loop manages, the effective resolution of
  the time interval for a timer is limited to on the order of 50-100
  milliseconds. If a timer's firing time occurs during a long callout or
  while the run loop is in a mode that is not monitoring the timer, the
  timer does not fire until the next time the run loop checks the timer.
  Therefore, the actual time at which the timer fires potentially can be
  a significant period of time after the scheduled firing time.

This means that an NSTimer is horribly inaccurate.
If you programming a "stopwatch," you could use the NSTimer to display the results to the user while an NIRTimer(one of my favorite classes) keeps track of time. This is outlined below:
NIRTimer *nirTimer;
NSTimer *timer;

- (void)start {
    nirTimer = [[NIRTimer alloc]init];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
    [nirTimer start];

- (void)timerFired:(NSTimer *)timer {
    [self displayTimeToUser:[nirTimer seconds]];
}

In the code above, the NSTimer may not be accurate, but the precise time is kept by the NIRTimer, which is displayed every 0.01 seconds to the user.
If you actually need specific code run at an exact time, the best solution I've found is to use an NSThread and usleep():
BOOL timerRunning;

- (void)start {
     timerRunning = YES;
     [NSThread detachNewThreadSelector:@selector(timer) toTarget:self withObject:nil]; //make a new thread
}

- (void)timer {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; //Make an autorelease pool since we're in a new thread
    NIRTimer *timer = [[NIRTimer alloc]init]; //Make an NIRTimer
    while (timerRunning) {
        [timer reset];
        [timer start];
        [self doSomething];
        usleep(10000 - [timer microseconds]); //Wait for .01 seconds which is 10000 microseconds (a microsecond is 1/1000000th of a second) - the time it took to accomplish whatever we were doing
    }
    //Clean up
    [timer release];
    [pool release];
}

In this case, set timerRunning to NO to stop the timer. You may also want to use [self performSelectorOnMainThread:@selector(doSomething) withObject:nil waitUntilDone:NO] instead of [self doSomething] if what you're trying to do isn't thread safe.
For more on the wonderful world of threading, take a look at the Threading Programming Guide.

A: I assume that you're starting with the current time, then each time your NSTimer goes off you add one minute to that original time and then display it. What you should do with your timer is: each time the timer goes off, re-read the current time and just display that.

A: You should set your timer to fire each second instead of each minute. But don't update your label each second. Just compare if the new minutes in the current time is different then the minutes in the last time you updated the label and if so update the label.

A: Well, I just wrote my own little NSTimer wrapper, called MinuteTimer to "solve" the problem. I've uploaded it on pastebin. The idea is to reset the timer whenever it has fired too quickly so often that the date risks being displayed incorrectly.
Since this is duct-tape programming, I'm still eager to hear other answers!


text:
Q: all elements within horizontal navigation on same height I got a horizontal ul-li navigation. Inside the li elements are anchor elements. Some of those anchor elements have more lines of text than others, so they have different heights which looks quite crappy. The li elements have the same height (equal to the tallest anchor element).
Setting the anchor element height to 100% didn't do anything.
Solutions I know of right now:
- giving the anchor elements a fixed height
- use JS to scale the font size to ensure that all anchor elements have only one line of text
- use JS to equalize the height of the anchor elements once everything is loaded
I want to avoid using JS for styling purposes, and I'd like to keep the height dynamic instead of fixed, so that I don't have to update the css manually each time the content of an anchor element might change.
Is there any other option?
Thanks.

A: Try CSS3 Flex property display:flex Check the DEMO.
ul{display:flex}

ul li{

 width:100px;
 display:inline-block;
 border:1px solid red;
}

a{background:gold; display:block;}

A: CSS table styles will help here
JSfiddle Demo
HTML

Short text

Word

Long long long text

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto alias.

CSS
ul {
    display: table;
}

li {
    display: table-cell;
    border:1px solid grey;
    width:25%;
    vertical-align: middle;
    text-align: center;
}

a {
    text-decoration: none;
}


text:
Q: How to turn a pandas column of seconds as float values into time? I have a df with a column like this:
df

time

0.5

30.5

60.3

90.2

120.3

and so on, with each time represented as a float of seconds - for example, 60.3 is simply 60.3 seconds. How can I turn this into data type of time? I have tried:
df['time'] = pd.to_timedelta(df['time'])

but it is returning incorrect values. For example, time of 60.3 seconds is converted into:
0 days 00:00:00.000000060

which is not only incorrect as it should be 0 days 00:00:60.3, but I would also like to only extract the minutes and seconds, leaving with me a column of data that looks like:
00:60.3

Thank you.

A: I'd use .to_datetime and set the unit to seconds ('s'). Then you can apply a format to the datetime object.
Try this out:
df['time'] = pd.to_datetime(df["time"], unit='s').apply(lambda x: x.strftime("%M:%S.%f"))

Should get:
           time
0  00:00.500000
1  00:30.500000
2  01:00.300000
3  01:30.200000
4  02:00.300000


text:
Q: When I insert value then only last value stored <?php
include("connection.php");

// Collect services.
$serviceid = "select * from service";
$servicevalue = $conn->query($serviceid) or die ($conn->error.__LINE__);
$services = [];
while ($row = $servicevalue->fetch_assoc()) {
    $services[] = $row;
}

// Collect activities.
$activityid = "select * from activity";
$activityvalue = $conn->query($activityid) or die ($conn->error.__LINE__);
$activities = [];
while ($row = $activityvalue->fetch_assoc()) {
    $activities[] = $row;
}

// Collect something else?
$perid = "select * from periodicity";
$pervalue = $conn->query($perid) or die ($conn->error.__LINE__);
$pers = [];
while ($row = $pervalue->fetch_assoc()) {
    $pers[] = $row;
}

foreach ($services as $service):

?>

    <form method="post" action="doalert.php" name="test">

                <input name='arr[1][service]' type='checkbox' data-id='Incometax'value="<?php echo $service['service_id']?>"/><?php echo $service['servicename']?>

                        <?php foreach ($activities as $activity) : ?>

                            <input type='checkbox' name='arr[1][activity][]' value="<?php echo $activity['activity_id']?>" /><?php echo $activity['nameofactivity'];?>

                    <?php endforeach;?>

<?php endforeach;?>
<input type="submit" name="submit" value="Submit"/>
</form>

The value of services and activity come from the database, I want to store all the services and related activity in DB serviceactivitymap table, here is my php code but when I store the data then last checked service value only stored with all the activity checked

*

*incometax

*

*filling

*return

*gst

*

*filling

*return

If incometax,gst,filling,return is checkboxes then when we check :

incometax->filling,return and gst->filling,return

Then the code only store

gst->filling,return and gst->filling,return

Instead of :

incometax->filling,return and gst->filling,return

A: You need to pass the service_id to the activity name like :
<input type='checkbox' name='activity[<?php echo $service['service_id']?>][]' value="<?php echo $activity['activity_id']?>" /><?php echo $activity['nameofactivity'];?>

Full form will be like :
<form method="post" action="doalert.php" name="test">
    <?php foreach ($services as $service): ?>

                <input name='service[]' type='checkbox' data-id='Incometax' value="<?php echo $service['service_id']?>"/><?php echo $service['servicename']?>

                    <?php foreach ($activities as $activity): ?>

                            <input type='checkbox' name='activity[<?php echo $service['service_id']?>][]' value="<?php echo $activity['activity_id']?>" /><?php echo $activity['nameofactivity'];?>

                    <?php endforeach;?>

    <?php endforeach;?>
    <input type="submit" name="submit" value="Submit"/>
</form>

A: In your code, the form start tag is created every time a loop runs as it is inside the service foreach. Try taking it outside the loop
Also, the name you used for service input tag as arr[1]["service"] will be overwritten everytime the loop runs. Instead I would suggest if you can use a variable increment in each loop like
$i=0;
foreach($services as $service)
{
    .....

    <input name='arr[$i][service]' ......

    $i++;
 }

This will differentiate the input tag name and saving may happen properly.


text:
Q: Customize Spring Security OAuth 2 Response In my Java app, I'm using the Spring Security OAuth 2 library to implement an OAuth provider. The response to a successful authentication (for the authorization_code grant type) is something like:
{"access_token": "d179bf70-aa40-4df9-a3e1-440e835c273a",
"expires_in": "43199",
"refresh_token": "879e7bd0-5e0f-48a9-b64d-f61d5665bf4e",
"scope": "read",
"token_type": "bearer"}

Is there a way to add additional properties to this response, e.g. the user's name or email address?

A: Spring OAuth2 allows you to put arbitrary values in the OAuth2AccessToken via its additionalInfo property. You can inject as much as you need in an AccessTokenConverter (which in turn can be added to the DefaultTokenServices easily via configuration callbacks). I'm not really sure why you need it though, and I would consider your use case carefully before sending additional values for consumption by clients (they are supposed to just use the token value, which is opaque).


text:
Q: React/Redux... Error: Actions must be plain objects. Use custom middleware for async actions I have a component that consists of photo grid where users can click on a cell to upload images from the camera roll. The component state is an object with a series of key value pairs, the key being the index and the value is itself an object with an image property. The state is being updated correctly upon photo upload and deletion, it's just when I call dispatch that I get an error.
Similar questions have involved people calling dispatch within async function or using await but I make no declaration here.
This has been irritating me for the last day and I feel like I'm missing something really obvious so I appreciate any help.
const PhotoUpload = ({ navigation }) => {

    const [photos, setPhotos] = useState(
        {'0' : {image: null},
         '1' : {image: null},
         '2' : {image: null},
         '3' : {image: null},
         '4' : {image: null},
         '5' : {image: null}}
     )

    const dispatch = useDispatch();
    dispatch(setPhotos(photos)); // Error: Actions must be plain objects. Use custom middleware for async actions.

    ...

    return (
        <>
            <SortableGrid >
            {
                Object.keys(photos).map((key) =>
                // image is not showing
                <View key={ key } fixed={photos[key].image === null ? true : false} onTap={() => this.pickSingle(true, false, key)}  style={ styles.itemContainer } >
                    <Image defaultSource={ require('./default-avatar.png') } source={ getPhoto(key) } style={ styles.itemImage }  />
                    { photos[key].image != null
                        ? <TouchableOpacity onPress={() => deletePhoto(key)} style={styles.deleteButton} >
                            <Icon name={"ios-remove"}  size={20} color="#ff0000" />
                          </TouchableOpacity>
                        : null
                    }
                </View>

                )
            }
            </SortableGrid>
        </>
    )

This is my reducer:
const INITIAL_STATE = {
  user: {
    name: "",
    gender: "",
    birthdate: "",
    photos: {},
  }
}

const userReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      case 'SETPHOTOS':
          return {
            // likely incorrect logic here
            ...state,
            user: {
              ...state.user,
              photos : state.user.photos.concat(action.payload)
            }
          }
      default:
        return state
    }
  };

And the Action:
export const setPhotos = (receivedPhotos) => {
    console.log(receivedPhotos)
    return{
        type: 'SETPHOTOS',
        payload: receivedPhotos
    };
}

A: It might be a variable name conflict? From what I can see you've used the name setPhotos for your action AND to set your local component state.
When you call dispatch(setPhotos(photos)) it is trying to dispatch the local setPhotos, not your redux action, hence the error.


text:
Q: How to create a template from existing resources? I've heard about "CloudFormer" tool, to automatically generate a base template from existing resources on the cloud.
https://medium.com/@ridmag/how-to-use-aws-cloudformer-e8d848cfafe1
I can't find this tool in aws! Perhaps this is a old tool that has been removed?
I've heard about another not-Amazon product named "terraform.io" as well. Can Terraform do this? Can it produce a template (in its proprietary format and/or in the cloudformation format) as well?

A: CoudFormer is no longer maintained and deprecated by AWS. Instead, former2 can be used which is open sourced, developed by AWS Hero and used by AWS clients as explained in AWS blog:

*

*How DNAnexus used the open source Former2 project to create infrastructure as code templates for their disaster recovery pipeline


text:
Q: Setting httpOnly false in tomcat. I have grails application, in which I need to set httpOnly to false, so that I can access the JSESSIONID from the client side.
I have used install-templates and got the web.xml in the project.
There I have added:
<session-config>
    <session-timeout>20160</session-timeout>
    <cookie-config>
        <http-only>false</http-only>
        <secure>false</secure>
    </cookie-config>
</session-config>

and started the grails server. But still from the client side, I couldn't able to get the JSESSIONID.
Where I'm making mistake?
Thanks.


text:
Q: JNI wierd error only on Samsung A6+ tablet I created an app using the JNI. At one point I need to create a Kotlin object from the C++ world, it works perfectly with the Samsung S7 and my other test phones, but an error is sometimes thrown when I am running the code on a Samsung A6+ Tablet.
I tried to simplify the code as much as possible and run it directly after loading the static library to find out where the error comes from.
//Result class :
package lib.up.com.library.calibration

class CalibrationResult(val0 : Float, val1 : Float, val2 : Float,
                              val3 : Float, val4 : Float, val5 : Float,
                              val6 : Float, val7 : Float, val8 : Float,
                              var shouldFlip : Boolean, var isReady : Boolean, var cadence : Int) {
    var rotationMatrix : ArrayList<Float> = arrayListOf(val0, val1, val2, val3, val4, val5, val6, val7, val8)
}

//Code in the native class:
jclass cls = env->FindClass("lib/up/com/library/calibration/CalibrationResult");
printf("Found class");
jmethodID methodId = env->GetMethodID(cls, "<init>", "(FFFFFFFFFZZI)V");
printf("Found init method");
//Initializing with default values
jobject obj = env->NewObject(cls, methodId,
                     0,
                     0,
                     0,
                     0,
                     0,
                     0,
                     0,
                     0,
                     0,
                     true,
                     false,
                     10);

printf("Created result object");

//Results in the logs :

D/PRINTS: Found class
D/PRINTS: Found init method
A/zygote: java_vm_ext.cc:534] JNI DETECTED ERROR IN APPLICATION: unexpected jboolean value: 140
    java_vm_ext.cc:534]     in call to NewObjectV
    java_vm_ext.cc:534]     from void lib.up.com.library.NativeClass.initCalibration(boolean)
[…]

Patterns :

*

*The unexpected jboolean value can be anything, 96, 140...

*Sometimes the JNI succeeds to create the CalibrationResult object but never more than 15 times in a row

*Out of my 4 test devices, the error appears only on the A6+ tablet

*I am creating other kotlin objects from the JNI in the app that also contain a boolean, their instantiation never crashes on all my test devices


text:
Q: Identifying and understanding algorithm of random number generation Studying different ways to generate random numbers according to a distribution and the below algorithm describes the "box method". A search on Google led to the Box-Mueller method. Are they related? Also, what would be a simple implementation of this algorithm for $f(x)=\sin{(x)}$ on $[0,\pi]$? Is it correct that $y$ should be scaled to $[0,1]$?

We generate two random numbers $x$ and $y$. We scale $x$ so that it
  gives a random point in the restricted range we want to generate random numbers in. Now we scale
  $y$ so it matches the range from 0 to the maximum value of the function $f(x)$ we want to generate.
  Now we accept $x$ if $y < f(x)$ and reject $x$ otherwise.

Implementation example:
#include <math.h>

int main(){

double x = (double)rand();
double y = (double)rand();

double xs = fmod(x,pi);
double ys = fmod(y,1);

if(ys < sin(xs)) return sin(xs);

}

A: First of all $f(x)$ needs to be a density, so $\sin(x)$ doesn't do the job. Let's sample from standard normal distribution, i.e. $$f(x)=\frac{1}{\sqrt{2\pi}}e^{-x^2/2}$$ in the range $[-3,3]$, where most of the samples reside.
A note for your C code: You shouldn't return the number from main function. Either write to a file or print out for plotting (or directly plot if you have suitable libraries). Most random samplers give you uniform RVs in $[0,1]$, so let's assume we have such $X,Y$. You can achieve that in C by dividing the generated number with INT_MAX macro.
First we scale $X$ to our new range, i.e. $X\leftarrow6X-3$. Now, our $X$ is uniform in the range $[-3,3]$. Also, $\max f(x)=1/\sqrt{2\pi}$, and therefore let $Y\leftarrow \sqrt{2\pi}Y$. Then, we compare $Y$ and $f(X)$ and accept the scaled $X$ if $Y$ is smaller. Here is an example C code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

int main()
{
    srand(time(NULL));

    int N = 100000;
    for(int i = 0; i < N; i++){
        double x = ((double) rand()) / INT_MAX;
        double y = ((double) rand()) / INT_MAX;

        x = 6 * x - 3;
        y = y / sqrt(2*M_PI);

        if( y < 1/sqrt(2*M_PI) * exp(-x*x/2) )
            printf("%f\n", x);
    }

    return 0;
}

If you redirect the standard output to a file, via > opearator while running, you'll see a histogram as follows:

Now, why does it work?
By sampling $X$ within $[a,b]$ (i.e. the interested range) and $Y$ within $[0,f_{max}]$, you create a box in the x-y plane, and sample random points on it as follows, just like you're throwing darts to a rectangular window:

Then, you accept the points which are under the curve, i.e. $y<f(x)$, which actually makes up the histogram for you, i.e. the higher $f(x)$ in the region, the higher the probability of acceptance.


text:
Q: Automatic insertion of current date and time in alphabetic form I often find myself typing the current date and time on several documents, forms, etc.
Is there any lightweight application that would allow me to automatically insert (or copy to the clipboard) the current date and time (in alphabetical form, if possible) using just a simple keyboard shortcut? I'm interested in solutions for Windows.

A: You could do it using AutoHotkey.
An example from the AutoHotkey documentation:
:*:]d::  ; This hotstring replaces "]d" with the current date and time via the commands below.
FormatTime, CurrentDateTime,, M/d/yyyy h:mm tt  ; It will look like 9/1/2005 3:53 PM
SendInput %CurrentDateTime%
return

An example from the AutoHotkey forum: Input system date and/or time, when u press a hot key:
$F12::
SetTitleMatchMode, 2
IfWinActive, Notepad
{
FormatTime, xx,, ddMMMyy ; This is one type of the date format
FormatTime, zz,, hh:mm:ss tt ; This is one type of the time format
SendInput, %xx%{Enter}
SendInput, %zz%
}
Return

See FormatTime for a list of the available date formats.
To set it up:

*

*Download and install AutoHotkey_L, let it associate with .ahk files

*Copy either of the above examples, paste in into Notepad, and save somewhere with an .ahk extension, e.g. My Documents/keys.ahk

*Navigate to the file you saved and double click it

*Add the .ahk script to your Startup folder

A: Short of just copying and pasting it to your documents, there is a feature to do that on Microsoft Word.

A: Phraseexpress will do it and a lot more.
https://www.phraseexpress.com/
They have a free version which is What I  use.
Make a phrase with
{#date} {#datetime -f tt}
I use ctrl alt t for a hotkey.
Pastes it anywhere on computer.


text:
Q: How to animate the entry and deletion of characters on UITextField? I would like to animate the user entry and deletion character by character in UITextField. For example, I want each character bounce in and bounce out when user is entering or deleting them.
Is there a formal way to do that by overriding some methods in UITextField ? Or I need to do a trick by using another UILabel or somehow, do you have an idea ?
Thanks in advance.


text:
Q: How to show: $-\sum_{k=-\infty}^\infty \frac{i*k*(-1)^k}{1+k^2}e^{-i*k*x}=2\sum_{k=1}^\infty \frac{k(-1)^{k-1}}{1+k^2}sin(kx)$ I am struggling to show below in a big question:
$-\sum_{k=-\infty}^\infty \frac{i*k*(-1)^k}{1+k^2}e^{-i*k*x}=2\sum_{k=1}^\infty \frac{k(-1)^{k-1}}{1+k^2}sin(kx)$
Tried to analyse with geometric series (no use).
Any help is appreciated

A: Hint 1
$$e^{-ikx} = -i\sin(kx) + \cos(kx)$$
Hint 2
The Sine function is an odd function, whilst Cosine is even function.
Let's proceed
Once you wrote the series split into sine and cosine part, you have this
$$-\sum_{k = -\infty}^{+\infty}\frac{k(-1)^k}{1+k^2}\sin(kx)- \sum_{k = -\infty}^{+\infty}i\frac{k(-1)^k}{1+k^2}\sin(kx)$$
Now, according to the parity of those functions, you can immediately see that the first series does contain an even function, and the second one does contain an odd function (respectively $k\sin(kx)$ which is even and $k\cos(kx)$ which is odd). So the second series is zero by definition.
You remain with
$$-\sum_{k = -\infty}^{+\infty}\frac{k(-1)^k}{1+k^2}\sin(kx)$$
and since it's even, you can write
$$-2\sum_{k = 0}^{+\infty}\frac{k(-1)^k}{1+k^2}\sin(kx)$$
The minus sign can be incorporated in the $(-1)^k$ term which will become $(-1)^{k-1}$ thence the result.
$$2\sum_{k = 0}^{+\infty}\frac{k(-1)^{k-1}}{1+k^2}\sin(kx)$$


text:
Q: Is there a way to stack date and time vertically in Vaadins DateTimePicker component? For choosing some values of different data types in my UI, I use Vaadin's DateTimePicker introduced in 14.3.x.
I am wondering if I can somehow position date and time input fields vertically instead of horizontally? See the picture:

The DateTimePicker component is here simply to width horizontically. And I don't have the option to make all other inputs like the one for a string wider, too.
I have checked the API but there doesn't seem to be a stardard way of achieving the vertically stacking. Has anyone an idea how to get this done?

A: it's doable with CSS. In your Java class, add a CSS import annotation for the class something like follows:
@CssImport(value = "./styles/dtp.css", themeFor = "vaadin-date-time-picker")
public class MyView extends Div {
//...

When creating the DateTimePicker:
        DateTimePicker dateTimePicker = new DateTimePicker();
        dateTimePicker.setClassName("stacked");

and in /frontend/styles/dtp.css:
:host(.stacked) .slot-container {
    display: flex;
    flex-direction: column;
}


text:
Q: How do I do a JPA findAllBy native query for an object's property value when that object is within a List object, within an outer object? I am trying to code the matchmaking feature of my game web-app, the User entity contains a property, UserStats with a OneToMany relationship which stores a list of 2 UserStat JPA entitites, these userStat entities have 2 different sets of stats, and one of the stats I require is called victoryScore.
How can I search for Users where their UserStats.get(0).victoryScore is a specific value/range of values?
I think I need to use JOIN possibly, here is my attempt:
 @Query(
            value = "SELECT * FROM user u JOIN u.userStats us WHERE u.location = :location AND u.rating BETWEEN :lowerRatingBound AND :upperRatingBound AND us.victoryScore BETWEEN :lowerVictoryScoreBound AND :upperVictoryScoreBound",
            nativeQuery = true)
    List<User> findChallengingUsers(@Param("lowerRatingBound") Integer lowerRatingBound, @Param("upperRatingBound") Integer upperRatingBound, @Param("lowerVictoryScoreBound") Double lowerVictoryScoreBound, @Param("upperVictoryScoreBound") Double upperVictoryScoreBound, @Param("location") String location);

And the error:
No property victoryScore found for type User!

User:
@Entity(name = "User")
@Table(name = "user")

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Column(name = "username", unique = true)
private String username;

@Column(name = "password")
private String password;

private String name;
private String email;
private String location;
private String bio;
private Integer rating;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = CascadeType.PERSIST)
private List<UserStats> userStats;
}

UserStats:
    @Entity()
@Table(name = "userStats")

  @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
public class UserStats {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userStatsId;

    private Integer victories;
    private Integer draws;
    private Integer defeats;

    private Double victoryScore;

private boolean isLeagueUserStats;

@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@JoinColumn(name = "user_id")
private User user;
}

Is this even possible?
For reference, I access the victoryScore value for how I want it to search for using:
user.getUserStats(0).getVictoryScore;

The user stats class is also a domain entity so also has its own repository interface.
Any help would be greatly appreciated, thanks!

A: Try this query,
Query(value ="SELECT * FROM user u INNER JOIN userStats us ON u.id = us.user_id where (u.location = :location AND u.rating BETWEEN :lowerRatingBound AND :upperRatingBound) AND (us.victoryScore BETWEEN :lowerVictoryScoreBound AND :upperVictoryScoreBound)",nativeQuery = true)


text:
Q: Adding html between Angular Material 2 table rows I would like to add html markup between the rows of my md-table (Angular-Material 2).
The idea being that when a row is clicked additional information can slide out beneath the row within a div.
After reading the docs I can't quite work out if this is possible. Does anyone have any idea if this could be done?


text:
Q: setting cookie in a for loop I am looking since yesterday to fix this problem, I know there are plenty of similar tutorials but somehow they didnt work for my situation.
What I am trying to do is setting the cookie whenever the user click on any product(It should store product_id). So this product is going to be added to chart.
I check it on javascript console of the chrome but there is a strange error "Uncaught SyntaxError: Unexpected token }" and it says there isnt any stored cookie.
   echo "
";
    for($i=0;$i<$num;$i++)
        {
            $ftc = mysql_result($result, $i, "product_image");
            $ftc2 = mysql_result($result, $i, "product_id");
            $ftc3 = mysql_result($result, $i, "product_name");
            $ftc4 = mysql_result($result, $i, "product_preis");
            $ftc5 = mysql_result($result, $i, "product_old_preis");
echo "

".$ftc3 ."    &nbsp
        ".$ftc4."TL  &nbsp".$ftc5."TL

 ";

        }
        echo "
 ";

    ?>

And this javascript code is on the head of the page:

thanks in advance

A: The error is probably because of this function toGMTString(). If you had used script type="javascript", the toGMTString() would have worked. Since you've used script type="text/javascript", you do not need to convert to GMT format, browsers nowadays do it for you.
I suggest you just remove the conversion to GMT and give a try.
Regards

A: First of all, if your browser is telling you about a javascript error, you should be able to note what line of code it's complaining about and look there for your first error.  Sometimes, the error will point to a line of code after the error rather than the actual line causing the error, but it's usually in the general area of the first error.  So, you should be using that information to help here.
Then, I see these issues:
Issue #1: I don't know if this is your first problem or not, but this won't work because of the quoting:

You're trying to use single quotes nested inside of single quotes.  That won't work.  I don't know how your template language works so I'm not entirely sure how to fix that part of it, but from HTML/javascript's point of view, you want to use single quotes nested inside of double quotes or vice/versa perhaps like this:

A: Is the following line in GetCookie possibly causing the unexpected syntax issues?
if (i == 0) break;

All other if statements in your code wrap the affected lines in { and }, but this one does not.  If you change it to if (i == 0) { break; }, does that solve your syntax problem?


text:
Q: Distance between two zipcodes using zipcodeR package not working I am using zipcodeR package to calculate distance between two zip codes. For the most part it is working well but there are some zip codes that it is not able to return the distance for. For example, I am using the following code:
zip_distance("02118", "32610")
It appears that trying to calculate any distance from the zip code "32610" returns an NA
Has anyone else encountered this problem?
Thanks,
Siri

A: The zip code "32610" is not valid as per is_zcta  (which returns true if the given ZIP code is also a ZIP code tabulation area)
is_zcta("32610")
[1] FALSE


text:
Q: pandas preserve multi index multi columns with to and from csv How to easily recover a multi-indexed mutli-columns indexed with dump into a csv file?
MWE:
df = (
    pd.DataFrame({
        'a': list(range(10)),
        'b': list(range(10)),
        'c': list(range(10)),
        'd': list(range(10)),
        'score': pd.np.random.rand(10),
    })
    .pivot_table(
        index=['a', 'b'],
        columns=['c', 'd'],
        values='score',
    )
)

df.to_csv('pivot_table.csv')

# pd.read_csv('pivot_table.csv')

I don't know how to recover the initial df with pd.read_csv.

A: pd.read_csv("'pivot_table.csv'", header = [0,1], index_col = [0,1])

You have to specify the header and index col rows/columns. In our case it would be the 0,1 row of the csv, and the 0,1 column.


text:
Q: Emacs "start-server" does not change variable "server-mode" I'm running Emacs 23 in Debian Squeeze. ~/.emacs does not contain any server-related commands.
I launch Emacs and enter C-h v server-mode, which returns nil, as no server is running. I then enter M-x start-server, which starts an Emacs server in the running instance of Emacs.
However, the variable server-mode is still nil when I check it again. Only after running M-x server-mode, does variable server-mode get a value of t. Is this a bug or am I doing something wrong?
Server-mode works fine after entering start-server; I can use emacsclient to open a file in the Emacs server. However, I wanted to use variable server-mode in the mode-line to indicate if the server is running, but if starting the server with start-server does not change the value of server-mode, this will not work as expected.

A: A better way is to use (server-running-p) from server package. For example
(require 'server)
(unless (server-running-p)
    (server-start))

A: To get the functionality I need/expect (from a freshly-started Emacs), I run M-x server-mode to start the server, rather than server-start. Starting the server this way changes the value of variable server-mode to t.
I do not understand why starting the server with the documented server-start does not set the variable server-mode to t.


text:
Q: rsync --compare-dest arg does not exist no matter what I have these folders:
.
├── result
├── test
│   ├── file1
│   ├── file2
│   ├── file3
│   └── file4
└── test2
    ├── file1
    ├── file2
    ├── file3
    └── file5

*

*test is the original folder.

*In test2 some files are different, others are identical and others only exist in there.

I want to user rsync to copy in result only those files in test2 that are newer that those on test or that doesn't exist on test.
I run any os the following, varying whether or not there's a = between --compare-dest and the name of the folder, whether or not the folder name has a trailing slash, or even inverting the parameters, just in case I'm missunderstanding what folder is compare-dest :
rsync -av --dry-run --itemize-changes --compare-dest=test2 test/ result/
rsync -av --dry-run --itemize-changes --compare-dest=test2/ test/ result/
rsync -arv --dry-run --itemize-changes --compare-dest test test2/ result/
rsync -arv --dry-run --itemize-changes --compare-dest test/ test2/ result/

All of them tell me:
--compare-dest arg does not exist: NAME_OF_EXISTING_FOLDER

*

*What am I doing wrong?

*What's the correct command I have ro issue to satisfy the requirement I explain at the beginning of this question?

A: man rsync:

If DIR is a relative path, it is relative to the destination directory.

You need:
rsync -av --dry-run --itemize-changes --compare-dest="$PWD"/test test2/ result/


text:
Q: How to install the Red Hat Container Development Kit when behind a corporate webproxy? When attempting to set up the Red Hat Container Development Kit on Windows behind a corporate web proxy the installer seems to fail to recognise the proxy settings that are configured.
Installer file: devsuite-1.3.0-GA-installer.exe
At the point where you enter your developer.redhat.com credentials it fails with the message "Cannot access developers.redhat.com, please check your internet connection.".
This despite the correct settings in Internet Options and system environment variables for HTTP_PROXY and HTTPS_PROXY.
The installer page mentioned appears to be a embedded browser window.  I suspect that the underlying platform (node, electron?) is not using the proxy settings that have been configured.
I have not found any log files that are related to this.
Any suggestions on how to proceed?
Many thanks.
[Edit 5 Jun 2017]
Just tried to install the latest, 1.4.0-GA-2017-05-19-231, version of the Development Suite but suffered the same issue. Also it doesn't look like there is a 'manual install' alternative available on the web site.  Unfortunately the 'Non-Online' (Offline?) version of the installer still requires you to log in to developer.redhat.com which I'd think rather loses the point of being offline.


text:
Q: What is the Best way to convert List to List Which is the best method to convert Currently I am using something like below
List<Byte> bytes = new ArrayList<Byte>();
List<Object> integers = Arrays.asList(bytes.toArray());

Then each object inside integers needs to be typecast to Integer. Is there any other way in which I can achieve this?

A: With the standard JDK, here's how to do it
List<Byte> bytes = new ArrayList<Byte>();
// [...] Fill the bytes list somehow

List<Integer> integers = new ArrayList<Integer>();
for (Byte b : bytes) {
  integers.add(b == null ? null : b.intValue());
}

If you're sure, you don't have any null values in bytes:
for (byte b : bytes) {
  integers.add((int) b);
}

A: If Google's Guava available in your project:
// assume listofBytes is of type List<Byte>
List<Integer> listOfIntegers = Ints.asList(Ints.toArray(listOfBytes));


text:
Q: How to implement observability (as described by Charity Majors) in an Asp.Net Core application? In https://charity.wtf/tag/observability/ in the section HOW TO GATHER AND STRUCTURE YOUR DATA Charity Majors presents the following scheme:

*

*Early in the pipeline initialize a "blob" accessible everywhere in code with every request having its own copy (in effect tied to the HttpContext)

*Any code that wishes to record some information adds key-value pairs to this "blob"

*When the request exits the "blob" is delivered to the observability server as a structured event.

This scheme makes a lot of sense and is quite elegant. It avoids verbal diarrhea of the regular logs. However, it is also oversimplified, because it ignores the batch processing requests, where a request has to process N records which is likely to produce N sets of similar structured events nested within the parent structured event corresponding to the request itself. In this case we have a choice of either sending the batch record event as soon as a record is processed or accumulate the nested events within the "blob" to be sent when the request is over. In any case this complication is not discussed in the post.
Before potentially inventing the wheel I am trying to figure out whether we have something ready to use this observability scheme. Here is what I have so far:

*

*We are using Azure and its Application Insights TrackEvent API seems to be perfect as the low level API. It supports events of the form <Event Name, string-to-string map, string-to-float map> which seems to be rich enough. The collected events can be then queried across all the dimensions anyway we like it. So, the observability server is not a problem for me.

*The "blob" implementation is a problem. I was looking for Honeycomb implementation for .Net Core and came across this page - https://docs.honeycomb.io/getting-data-in/dotnet/. However the 2 options presented there do not seem mature enough:

*

*HoneyComb .NET leaves it up to us to figure out how to deal with nested events.

*OpenTelemetry .NET does not seem to be about observability at all, but about the "3 pillars of observability" - logging, metrics and tracing. Which do not give observability according to https://www.infoq.com/news/2019/02/rethinking-observability/

*The Microsoft.Extensions.Logging.ILogger interface seems to present an adequate interface. It looks like the BeginScope method exists explicitly to delimit the different batches. But it is just an interface.

So, my question is there an implementation for Asp.Net Core for observability as structured events that also takes into account the nested events in one way or another and that can be customized to deliver to the Application Insights bucket?
I could elaborate on the challenges of the batch processing, but this question is already too long, so I stop here.


text:
Q: Is my MySQL being monitored by monit using nginx? I'm unsure if my mysql is actually being monitor by monit. See screenshot.

As you can see under processes the mysqld process is not being monitored (it failed a sew times first) but under files there is mysql_bin and mysql_rc both of which are OK.
Is it safe to remove the mysql monitoring symbolic link or do i need this anyway?
thanks

A: Short answer is no. Some more info:
That both of the entries in the File section are OK does not relate to any kind of working or running application. The File section of monit simply checks file state information, such as, but not limited to, last modification time, size, file hashes, etc.
So basically the two OKs in File section just tell you that the mysql files are present and have not been changed.
The entry inside Process section is what you want to focus an. It checks the presence of a running mysqld process on your system. You need to check if the configuration of that entry inside monitrc (or included files) is looking for the right parameters. It should watch out for a process using a pidfile and could potentially check if a connection could be established.
See monit docs on MySQL and/or paste your monit config for any in-depth help regarding monit.
PS: @Shadow: The question (more likely: the resulting problem) has nothing to do with a DB, but is a question about monitoring.


text:
Q: Is there any guarantee that multiple type_index instances for a type will compare equal? I have some code which expects type_index instances for a particular type created in a shared library and instances created in an executable (for the same particular type) to compare equal.
However, I have encountered a case where this does not work on QNX 7:
// idxlib.h

#include <typeindex>
#include <string>
#include <iostream>

#ifdef BUILD_LIB
#define LIB_EXPORT __attribute__((visibility("default")))
#else
#define LIB_EXPORT
#endif

template <typename T>
class Templ
{
};

class LIB_EXPORT LibType
{
public:
    LibType();

    template <typename T=int>
    void templateMethod(int arg = 0) const
    {

#ifndef REMOVE_INSTANTIATION
        if (arg == 42)
        {
            // arg is never 42. This code path is not taken, but it instantiates the template
            templateMethod();
        }
#endif

        if (mti == std::type_index(typeid(Templ<int>)))
            std::cout << "Type indexes the same" << std::endl;
        else
            std::cout << "Type indexes NOT the same" << std::endl;
    }

    void normalMethod();

protected:
    std::type_index mti;
};

// idxlib.cpp

#include "idxlib.h"

LibType::LibType() : mti(std::type_index(typeid(Templ<int>))) {}

void LibType::normalMethod()
{
    templateMethod();
}

// sharedidx.cpp

#include "idxlib.h"

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

    if (argc == 65)
        // argc is not 65, so don't call it, just instantiate it
        lt.templateMethod();
    lt.normalMethod();
    return 0;
}

Build, scp and run:
QCC -Vgcc_ntox86_64 -g -fPIC -o idxlib.cpp.o -c idxlib.cpp -DBUILD_LIB -fvisibility=hidden -fvisibility-inlines-hidden
QCC -Vgcc_ntox86_64 -g -shared  -o libidx.so idxlib.cpp.o
QCC -Vgcc_ntox86_64 -g -o sharedidx libidx.so  sharedidx.cpp

scp -i ~/qnxinstall/id_rsa_qnx sharedidx libidx.so qnxuser@${QNXBOX}:/home/qnxuser/test

echo
echo "comparison fails:"
ssh -i ~/qnxinstall/id_rsa_qnx -t qnxuser@${QNXBOX} "cd /home/qnxuser/test && LD_LIBRARY_PATH=/home/qnxuser/test ./sharedidx"

QCC -Vgcc_ntox86_64 -g -shared -fPIC -o idxlib.cpp.o -c idxlib.cpp -DREMOVE_INSTANTIATION -DBUILD_LIB -fvisibility=hidden -fvisibility-inlines-hidden
QCC -Vgcc_ntox86_64 -g -shared  -o libidx.so idxlib.cpp.o
QCC -Vgcc_ntox86_64 -g -o sharedidx libidx.so -DREMOVE_INSTANTIATION sharedidx.cpp -fvisibility=hidden  -fvisibility-inlines-hidden

scp -i ~/qnxinstall/id_rsa_qnx sharedidx libidx.so qnxuser@${QNXBOX}:/home/qnxuser/test

echo
echo "comparison works:"
ssh -i ~/qnxinstall/id_rsa_qnx -t qnxuser@${QNXBOX} "cd /home/qnxuser/test && LD_LIBRARY_PATH=/home/qnxuser/test ./sharedidx"

Output:
Type indexes NOT the same
Type indexes the same

So, the type_index comparison fails when there is a template instantiation which contains a template instantiation of itself.
Is it a bug in QNX 7, or is my expectation (that it should ever work) wrong?
Is this code relying on implementation-defined behavior? Or undefined behavior?
QNX 7 QCC compiler is based on GCC 5.4 and uses a standard library based on libc++ from the same era. I have tested GCC 5.4 (and clang with libc++ and libstdc++) on Linux and I do not get the same behavior. I have also tried with and without _LIBCPP_NONUNIQUE_RTTI_BIT defined.
So, I'm assuming this is a result of the linker rather than the compiler. Could that be true?
Are the GCC compilers just "too helpful" in making this work on Linux across shared library boundaries?

A: I would never assume that RTTI works correctly on an embedded systems targeting toolchain. It might be supposed to work correctly, but almost nobody enables RTTI nor exceptions for embedded systems, so it'll get zero testing nor attention from support.
I'd suggest that you use a library based RTTI emulation, such as https://www.boost.org/doc/libs/1_74_0/doc/html/boost_typeindex.html which works on systems without RTTI, and is also fully deterministic and bounded in space and time unlike language RTTI.


text:
Q: android: How to pick contacts phone num I need to pick contact phone num, and I used to do it like this...

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, GET_CONTACT_FROM_RESULT);

But, when a contact has multiple numbers, the pick activity only list one contact, and can only select one phone.
What can I do to display contacts' every phone num?

A: You can ask contact picker to show one contact per phone, so contact with multiple phones will appear several times:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, PICK_CONTACT);

A:  public Map<String, String> lookupPhoneNoAndContactId(){
    Map<String, String> phonenumbers = new HashMap<String, String>();
    Cursor cursor = null;
    try {
        cursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                null, null, null);
        while (cursor.moveToNext()) {
            phonenumbers
                    .put(cursor
                            .getString(cursor
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)),
                            cursor.getString(cursor
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
        }
        return phonenumbers;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

}


text:
Q: Opening files in Xcode editing pane When I first started to work with Xcode, single clicking on a file name in the Groups&Files pane would open that file up for editing in the embedded editing pane. Double clicking the file would open it up in a new window for editing.
Now, single clicking the file does nothing. Double clicking the file will open it up in a new window as before.
How can I set xcode to open up the file in the embedded editing pane by single clicking the file name in the Groups&Files pane?

A: In Xcode 3.x, make sure you're using the Default or All-in-one layout--not Condensed.  If the editor pane is not visible, it might be shrunk down to the bottom of the window.  Look for a small gray dot at the bottom and double-click it.  The editor pane should then expand up.


text:
Q: Pygame scrolling background bug I'm trying to make a background scrolling effect in pygame when keys are pressed.
import pygame
from pygame import *
import os

pygame.init()

WIDTH, HEIGHT = 472, 708

WIN = pygame.display.set_mode((WIDTH, HEIGHT))

FPS = 60

BG = pygame.image.load(os.path.join('images', 'BG.jpg'))
BG = pygame.transform.scale(BG, (WIDTH, HEIGHT))

class Background(object):
    def __init__(self, win, image):
        self.win = win
        self.image = image
        self.bgY = 0
        self.bgY2 = BG.get_height()
        self.bgY3 = BG.get_height() * -1

    def draw(self):
        self.win.blit(self.image, (0, self.bgY))
        self.win.blit(self.image, (0, self.bgY2))
        self.win.blit(self.image, (0, self.bgY3))
        pygame.display.update()

    def bg_movement(self):
        keys = pygame.key.get_pressed()
        if keys[K_w]:
            self.bgY += 2
            self.bgY2 += 2
            self.bgY3 += 2
        if keys[K_s]:
            self.bgY -= 2
            self.bgY2 -= 2
            self.bgY3 -= 2
        if self.bgY < self.image.get_height() * -1:
            self.bgY = self.image.get_height()
        if self.bgY2 < self.image.get_height() * -1:
            self.bgY2 = self.image.get_height()
        if self.bgY3 < self.image.get_height() * -1:
            self.bgY3 = (self.image.get_height() * -1)

player = Background(WIN, BG)

def main():
    clock = pygame.time.Clock()
    running = True
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        player.draw()
        player.bg_movement()

    pygame.quit()

if __name__ == '__main__':
    main()

When I press the S key, the background scrolls normally. But when I press the W key for a while, the background starts to leave a trail.
This is the actual image used in the game.
This is the screenshot showing the bug in the game. The image leaves a trail.

A: Use the modulo (%) operator to calculate the position of the background. The % operator calculates the reminder of a division:
class Background(object):
    def __init__(self, win, image):
        self.win = win
        self.image = image
        self.bgY = 0

    def draw(self):
        self.win.blit(self.image, (0, self.bgY - self.image.get_height()))
        self.win.blit(self.image, (0, self.bgY))
        self.win.blit(self.image, (0, self.bgY + self.image.get_height()))
        pygame.display.update()

    def bg_movement(self):
        keys = pygame.key.get_pressed()
        if keys[K_w]:
            self.bgY = (self.bgY + 2) % self.image.get_height()
        if keys[K_s]:
            self.bgY = (self.bgY - 2) % self.image.get_height()


text:
Q: Python: Script prints out dictionary value letter by letter instead of full word? I have a class:
class Bike(object):
    """Parent class for bikes"""

    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

    def model(self):
        for trait in self.name:
            print trait

    def pounds(self):
        for trait in self.weight:
            print trait

    def money(self):
        for trait in self.cost:
            print trait

I created a dictionary with several key/value associations:
bikes = {}

# Bike designed for children"
bikes['bike1'] = Bike("Trike", "20", "100")

6 bikes like above,
and when I try to run them:
bikes['bike1'].model()
bikes['bike1'].pounds()
bikes['bike1'].money()

I do in fact get a print of the name, weight, and cost,
but it prints out letter by letter:
T
r
i
k
e
2
0
1
0
0
What am I missing?

A: These lines:
        for trait in self.name:
            print trait

self.name is a string.  If you loop over a string, you get the individual characters one by one.  Your print statement thus prints each character, one-by-one.  If you want to print the name of the model, just:
print self.name

You don't need a loop here at all.

A: for trait in self.name:
        print trait

handles trait as every character in the string self.name and the loop-body gets executed for every charecter in the string. So every character gets printed on a seperate line. What you want to use to print out the name in one word and one line is this. The same goes for your other methods and attributes:
def model(self):
    print self.name

A: it's because type of self.name, self.cost is string.
You won't face that issue if you will wrap that values to list
for exmple

Bike(["Trike"], ["20"], ["100"])

Other option is simply print them in .model(), .pounds(), .money() without
for loop


text:
Q: Confused on Patching in Python I've read through the docs but am still pretty confused on patching in Python.  I have a Contact class and I've written the following functions:
def update_contact(name, phone, address, company, title, contact_id):
    contact = Contact(contact_id)
    set_contact_fields(contact, name, phone, address, company, title)
    return contact.update()

def set_contact_fields(contact, name, phone, address, company, title):
    contact.name(name)
    contact.phone(phone)
    contact.address(address)
    contact.company(company)
    contact.title(title)

So Contact(contact_id) grabs the Contact object with contact_id.  Then set_contact_fields sets the appropriate fields.  Finally, contact.update saves these changes (it's an API call).
I now want to unit-test update_contact to ensure that it's changing the old field values to the new ones, but I'm a bit unsure how to go about this.
From the patch docs, it looks like I might do something like:
@patch.object(Contact, 'update')
@patch.object(Contact, 'name')
@patch.object(Contact, 'phone')
@patch.object(Contact, 'address')
@patch.object(Contact, 'company')
@patch.object(Contact, 'title')

def test_update_contact(self, update, name, phone, address, company, title):
    contact = Contact()
    update_contact('name', 'phone', 'address', 'company', 'title', contact)
    # check that update was called with...
    name.assert_called_once_with('name')
    phone.assert_called_once_with('phone')
    address.assert_called_once_with('address')
    company.assert_called_once_with('company')
    title.assert_called_once_with('title')
    update.assert_called_once_with()

Unfortunately, this test fails.  I'm not sure where I'm going wrong; help?
Thanks!


text:
Q: Regex not separating n't (not) I am trying to write a complex regex for a large corpus. However, due to many ORs, I am not able to capture the "not" in weren't don't wasn't didn't shouln't doesn't
I would like it to match base verb and n't separately: E.g. were and n't
I have added it in the first line on: https://www.regexpal.com/?fam=106183 with the regex.
Any clue why it is not picking despite it being present in the expression on first order: [a-z]{1}'\w
Edit:
The regex is long because it is part of a large corpus. My problem is that the n't is not getting separated out, even though I placed in first order of preference for OR.
Thanks in advance

A: Trying to parse natural language perfectly with a regular expression is never going to be "perfect". Language contains too many quirks and exceptions.
However, with that said, trying to cover all scenarios explicitly like you have done ("a 2 letter lower case word", "a 4 letter capitalised word", "a word with a multiple of 3 letters" (??!), ... is a doomed approach.
Keep the pattern as simple as you possibly can, and only add exceptions if you really need to.
Here's a basic approach:
/n't|\b\w+(?!'t)/

This is matching "n't", or 'any word, excluding the last letter if it's proceeded by "'t"'.
You may wish to build upon that slightly, but it solved the use case you've provided:
Demo

In order to understand why your original pattern doesn't work, let's consider a Minimal, Complete, Verifiable Example:
Cutting your pattern down to:
/[a-z]?'[a-z]{1,}|[\w-]+/

Consider how it matches the string:
"weren't"

*

*First, the characters weren are matched by the [\w-]+ portion of the pattern.

*Then, the 't characters are matched by the [a-z]?'[a-z]{1,} portion of the pattern.

Fundamentally, having the greedy [\w-]+ section in this pattern will mean it cannot work. This will always match up-to-and-including the "n" in "n't", which means the overall match fails for non-3-letter words.


text:
Q: Python simple ProcessPoolExecutor example wont work I'm trying out multithreading in Python 3, but I can't figure out why my example won't work. It should just print the numbers and as confirmation print the number again.
But it runs into many errors.
from concurrent import futures

def print_me(num):
    print('Zahl: ' + str(num))
    return num

def say_bye(job):
    num = job.result()
    print(str(num) + ' is out!')

def test_multi():
    num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    with futures.ProcessPoolExecutor(max_workers=4) as executor:
        for num in num_list:
            job = executor.submit(print_me, num)
            job.add_done_callback(say_bye(job))

test_multi()

Theoretically, instead of:
for num in num_list:
    job = executor.submit(print_me, num)
    job.add_done_callback(say_bye(job))`

I could use this, or?
executor.map(print_me, num_list)

A: To get the code running i just need to add:
if __name__ == "__main__":
    test_multi()