text:
Q: curl stop working on my server Curl stop working on my server but it is working perfectly on the other server
Here is my script:
 <?php
    $proxy_ip = '165.139.149.169';
    $proxy_port = '3128';
    $url = 'https://www.google.com/search?q=skinny+fiber+ingredients&btnG=Search&client=ubuntu&channel=fs&num=100&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=sw9CVbCuPKaA8QfX0ICYBA&gws_rd=cr';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, 'https://www.google.com');
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0');
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // Good leeway for redirections.
    curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port);
    curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
    curl_setopt($ch, CURLOPT_PROXY, $proxy_ip);
    //curl_setopt($ch, CURLOPT_PROXYUSERPWD, $loginpassw);
    $data = curl_exec($ch);
    curl_close($ch);
    echo "abc";
    echo $data;
?>

http://serpbull.com/dev/curl.php (script not working here)
http://imarkdev.com/serp/curl.php (script working here)
Edit:
Not working script takes very long to respond (curl timeout) and prints empty response.

A: Use curl_error() function to get more information about the failure.
$data = curl_exec($ch);
if ($data === false)
{
    echo 'Curl error: ' . curl_error($ch);
} else {
    echo 'Response: ' . $data;
}


text:
Q: Alt Menu Shortcut Keys not working normally in Windows 8 Ever since I was given a Windows 8 Dell laptop at work, I've been unable to use the "Alt+underlined letter" shortcuts that I'm used to in order to open menus in windows applications.
The only way to use menus by shortcuts is to change this shortcut into 2 keystrokes.  "Alt" to open the menu, release the key and then a second keystroke to hit the underlined letter corresponding to the menu that I wish to use.
However, if I try to do it as the Alt+letter (combined, or without releasing the Alt) it ignores the letter.
I originally assumed that this was another annoying Windows 8 UI change until I used someone else's Windows 8 laptop and found that Alt+letter opened menus fine on her PC.  Obviously, this isn't universal on Windows 8.
I've tried many Google searches.  I've checked out keyboard settings and usability settings, but have come up dry.  I'm stumped!
This is clashing with decades of muscle memory...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Producing a random Wang Tile tiling image more efficiently I'm following along with this SIGGRAPH 2006 paper Recursive Wang Tiles for Real-Time Blue Noise - there's a video here too. Eventually I want to try to produce the blue noise results in the paper, and experiment with texture synthesis, but I'm just getting started using Wang Tiles at the moment.
Here I'm trying to turn the 8-tile tile set that appears in the video and produce a random valid tiling. I'm using a ResourceFunction["BacktrackSearch"] and an ArrayFilter to check all the tiles match edges, or match to a zero tile / padding that has not yet been filled in.
It's a bit slow. Is there a more efficient way to generate a tiling?
Remove["Global`*"]

(* tile num to colours 1,2,3,4 *)
tileset = <|0 -> {0, 0, 0, 0}, 1 -> {1, 2, 3, 4}, 2 -> {1, 4, 3, 2},
   3 -> {3, 4, 3, 4}, 4 -> {1, 4, 1, 4}, 5 -> {3, 4, 1, 2},
   6 -> {3, 2, 1, 4}, 7 -> {3, 2, 3, 2}, 8 -> {1, 2, 1, 2}|>;

(* given a tile id, produce an image *)
tileToImage[num_] :=
 With[{ts = tileset[num],
   cols = {
     RGBColor[0.9999785876752382, 0.475513385976072, 0.6629426677719442],
     RGBColor[0.9999991551385031, 0.6620017739781776, 0.9994575868819303],
     RGBColor[0.7921405246863186, 0.9455041087128487, 0.3831022964631722],
     RGBColor[0.5908239188023992, 0.7286211433501548, 0.0005627139280530491]}
   },
  Rasterize[
   Graphics[
    MapIndexed[{#1,
       Rotate[Triangle[],
        45° - 90° *(#2[[1]] - 1), {0, 0}]} &,
     cols[[ts]]], ImageMargins -> 0, ImageSize -> Full,
    PlotRange -> {{-1, 1}, {-1, 1}}/Sqrt[2]], RasterSize -> {32, 32}]]

(* match a piece with center or zero - zero is just padding and always matches *)
moz[x_, a_] := x == a || x == 0 || a == 0;
(* take the 3x3 block b and match the n,s,e,w quadrants with corresponding opposite sides on neighbours *)
matching[b_] := With[{c = tileset[b[[2, 2]]]
   , top = tileset[b[[1, 2]]]
   , right = tileset[b[[2, 3]]]
   , bottom = tileset[b[[3, 2]]]
   , left = tileset[b[[2, 1]]]},
  moz[c[[1]], top[[3]]] &&
   moz[c[[2]], right[[4]]] &&
   moz[c[[3]], bottom[[1]]] &&
   moz[c[[4]], left[[2]]]
  ]

(* Reshape the tile list into a grid. A choice of tiles is valid if for every element its immediate neighbours all match or match with zero *)
valid[tiles_, dimensions_] :=
 With[{grid = ArrayReshape[tiles, dimensions]},
  Count[ArrayFilter[matching, grid, 1, Padding -> 0], False, 2] == 0]

result = Module[{dimensions = {8, 8}, problemsize},
   problemsize = Times @@ dimensions;
   ArrayReshape[
    (* find a list of tiles we can organize into a dim x dim array *)

    ResourceFunction["BacktrackSearch"][
     Table[RandomSample@DeleteCases[Keys[tileset], 0], problemsize],
     valid[#, dimensions] &,
     valid[#, dimensions] && Length[#] == problemsize &
     ], dimensions]
   ];

ImageAssemble[Map[tileToImage, result, {2}]]

Update:
This works a bit better by precomputing all the tile images and not doing the ArrayFilter on the whole array, but instead only matching up the last tile added with the tile above and the tile to the left. I can now get 16x16 tilings in a more reasonable time frame, though it's still a bit slow for some reason:
(** ^^^ tileset and tileToImage ^^^ **)

(* match a piece with center or zero - zero is just padding and always matches *)
moz[x_, a_] := x == a || x == 0 || a == 0;

(* match the top and left edges up *)
matching[thisone_, above_, left_] :=
 With[{t = tileset[thisone], a = tileset[above], l = tileset[left]},
  moz[t[[1]], a[[3]]] && moz[t[[4]], l[[2]]]]

lastValid[tiles_, dims_] := With[{
   width = Last@dims,
   offset = Length@tiles},
   matching[tiles[[-1]],
   If[offset > width, tiles[[offset - width]], 0],
   If[Mod[offset, width] == 1, 0, tiles[[offset - 1]]]
   ]]

result = Module[{dimensions = {16, 16}, problemsize},
   problemsize = Times @@ dimensions;
   ArrayReshape[
    (* find a list of tiles we can organize into a dim x dim array *)

    ResourceFunction["BacktrackSearch"][
     Table[RandomSample@DeleteCases[Keys[tileset], 0], problemsize],
     lastValid[#, dimensions] &,
     Length[#] == problemsize &
     ], dimensions]
   ];

tileImages = AssociationMap[tileToImage, Keys@tileset];
ImageAssemble[Map[tileImages[#] &, result, {2}]]

A: Haven't looked much to check what ResourceFunction["BacktrackSearch"] does, but this appears similar in spirit to OP's edit (i.e. using horizontal/vertical topology constraints to select the next tile). This is inspired by this excellent community post on tiling constraints and my comment there.
Pre-define the topology constraints (manually in this case, since it was easy - I suppose it can be automated fairly easily during the tileset information):
topologyConstraints["right"]=<|1->{2,5,7,8},2->{1,3,4,6},3->{1,3,4,6},4->{1,3,4,6},5->{1,3,4,6},6->{2,5,7,8},7->{2,5,7,8},8->{2,5,7,8}|>;
topologyConstraints["bottom"]=<|1->{3,5,6,7},2->{3,5,6,7},3->{3,5,6,7},4->{1,2,4,8},5->{1,2,4,8},6->{1,2,4,8},7->{3,5,6,7},8->{1,2,4,8}|>;

We then start by randomly selecting a starting tile on the top-left, and construct the first row and column from that:
{dimx, dimy} = {16, 16};
topLeft = RandomInteger[{1, 8}];
left = NestList[RandomChoice@*topologyConstraints["bottom"], topLeft,dimy - 1];
solution = Transpose[
 ReplacePart[Transpose[
  Prepend[ConstantArray[0, {dimy - 1, dimx}],
   NestList[RandomChoice@*topologyConstraints["right"], topLeft,
    dimx - 1]]], 1 -> left]];

Finally, we start from the (2,2) tile and make our way down by randomly selecting a tile at the intersection of the available horizontal/vertical topological constraints:
Do[solution[[i, j]] =
   RandomChoice[
    Intersection[topologyConstraints["bottom"][solution[[i - 1, j]]],
     topologyConstraints["right"][solution[[i, j - 1]]]]], {i, 2,dimy}, {j, 2, dimx}];

ImageAssemble[Map[tileToImage, solution, {2}]]

Note: to speed-up the visualization, it suffices to memoize the rastering function, i.e. add tileToImage[num_] := tileToImage[num] = ... to the definition.


text:
Q: Active Directory TLS I want to secure my Active Directory 2012R2 environment with TLS.
Can I use a wildcard commercial SSL certificate and can the secure version of AD (port 636) coexist with the default one (port 389)?

A: The certificate will enable LDAPS on port 636. Active directory uses sign and seal and is already secure when using port 389. Yes they can coexist at the same time
This article should help explain LDAPS. http://social.technet.microsoft.com/wiki/contents/articles/2980.ldap-over-ssl-ldaps-certificate.aspx
This article explains how to use a third party certificate to enable LDAPS
https://support.microsoft.com/en-us/kb/321051
According to this article the certificate must be issued to the FQDN of the server. So a wildcard certificate might not work
https://technet.microsoft.com/en-us/library/cc725767(WS.10).aspx

A: You don't need a commercial certificate to secure LDAP in Active Directory; all computers accessing it will by definition be domain members (*), thus you can use Windows' own Certificate Services to build an AD-integrated certification authority, which will be automatically trusted by all users and computers in the domain.
(*) Should you need to perform LDAP queries from a non-domain-joined device, you'll simply need to import the root certificate of your CA into its store of trusted certificates.


text:
Q: group by value but only for continue value OK, the title is far from obvious, I could not explain it better.
Let's consider the table with columns (date, xvalue, some other columns), what I need is to group them by xvalue but only when they are not interrupted considering time (column date), so for example, for:
      Date |xvalue      |yvalue|
    1 Mar  |10          |1     |
    2 Mar  |10          |2     |
    3 Mar  |20          |6     |
    4 Mar  |20          |1     |
    5 Mar  |10          |4     |
    6 Mar  |10          |2     |

From the above data, I would like to get three rows, for the first xvalue==10, for xvalue==20 and again for xvalue==10 and for each group aggregate of the other values, for example for sum:
1 Mar, 10, 3
3 Mar, 20, 7
5 Mar, 10, 6

It's like query:
select min(date), xvalue, sum(yvalue) from t group by xvalue

Except above will merge 1,2,5 and 6th of March and I want them separately

A: This is an example of a gaps-and-islands problem.  But you need an ordering column.  With such a column, you can use the difference of row numbers:
select min(date), xvalue, sum(yvalue)
from (select t.*,
             row_number() over (partition by xvalue order by date) as seqnum_d,
             row_number() over (order by date) as seqnum
      from t
     ) t
group by xvalue, (seqnum - seqnum_d)
order by min(date)

Here is a db<>fiddle.

A: Datas in a database are logically stored in mathematicl sets inside which there is absolutly no order and no way to have a default ordering. they are comparable to bags in which objects can move during their use.
So there is no solution to answer your query until you add a specific column to give the requested sort order that the user need to have...


text:
Q: How do I use Wagtail App Pages to create dynamic pages from django model? I have a django model of data for several locations that I need to generate pages from in wagtail. Like a blog, I need a listing page and detail pages.
I followed this documentation: https://wagtail-app-pages.readthedocs.io/en/latest/index.html
models.py
from django.db import models

from wagtail.core.models import Page
from wagtail_app_pages.models import AppPageMixin

from . import misc_options

class Feature(models.Model):
    feature = models.CharField(max_length=50)
    description = models.CharField(max_length=300)

    class Meta:
        ordering = ['feature']
        verbose_name = "Feature"
        verbose_name_plural = "Features"

    def __str__(self):
        return self.feature

class Location(models.Model):

    template = 'locations/locations_list.html'

    name = models.CharField(max_length=30, null=True, blank=False)
    address = models.CharField(max_length=60, null=True, blank=False)
    city = models.CharField(max_length=25)
    state = models.CharField(
        max_length=2, choices=misc_options.STATES, null=True, blank=False)
    zipcode = models.CharField(max_length=5, null=True, blank=False)
    lat = models.CharField(max_length=50, null=True, blank=False)
    lon = models.CharField(max_length=50, null=True, blank=False)
    phone = models.CharField(max_length=10, null=True, blank=False)
    email = models.CharField(max_length=40, null=True, blank=False)
    places_id = models.CharField(max_length=100, null=True, blank=True)
    facebook_url = models.CharField(max_length=100, null=True, blank=True)
    google_url = models.CharField(max_length=100, null=True, blank=True)
    entity = models.CharField(max_length=10, null=True, blank=True)
    truck_url = models.CharField(max_length=100, null=True, blank=True)
    trailer_url = models.CharField(max_length=100, null=True, blank=True)
    supplies_url = models.CharField(max_length=100, null=True, blank=True)
    features = models.ManyToManyField(Feature)

    class Meta:  # noqa
        ordering = ['name']
        verbose_name = "Location"
        verbose_name_plural = "Locations"

    def __str__(self):
        return self.name

class LocationPage(AppPageMixin, Page):
    template = 'locations/locations_list.html'
    url_config = 'location.urls'

    class Meta:  # noqa
        verbose_name = "Locations List"
        verbose_name_plural = "Locations Lists"

urls.py
from django.urls import path

from .views import LocationDetailView, LocationListView

urlpatterns = [
    path(r"^locations/?$", LocationListView.as_view(), name="location_list"),
    path(r"^location/<int:pk>/?$",
         LocationDetailView.as_view(), name="location"),
]

views.py
from django.shortcuts import render
from django.views.generic import DetailView, ListView
from .models import Location
from .google import getGoogleReviews
from .wss import getWSSUnits

class LocationDetailView(DetailView):

    model = Location

    context_object_name = "location"
    queryset = Location.objects.all()
    template_name = "locations/location_details.html"

    def get(self, request, **kwargs):
        self.object = self.get_object()
        places_id = self.object.places_id
        entity = self.object.entity

        reviews = getGoogleReviews(places_id)
        units = getWSSUnits(entity)
        context = self.get_context_data(
            object=self.object, reviews=reviews, units=units)

        return self.render_to_response(context)

class LocationListView(ListView):

    model = Location

locations/locations_list.html
{% extends 'base.html' %}
{% load app_pages_tags %}

{% block content %}
{% for item in location_list %}
{{item.name}}
{% endfor %}
{{ location_list }}
This is the locations list
{% endblock %}

I have the option to select a 'Locations List' page in wagtail. I create the page, the only field available is the internal name field, which is correct.
When I go to the URL though, The content block is blank. When I try to go to a location, i.e. 'location/1', I get a 404.
I think what is happening is that my model is being ignored, wagtail page apps is being ignored, and Locations List is being treated as a blank wagtail page model. I don't understand what I am doing wrong. There are no errors in the console.

A: I'm sorry I found this a bit late, but I'll try to weigh in as the author.
I just tried to reproduce the issue locally. I had to make a few tweaks to the code, and I'm not sure what versions of django and wagtail you're using, but I managed to get a basic setup working based on your code.
It's hacked together very quickly, but feel free to take a look at this, it's a repo including an sqlite database with content, you can log in with admin/admin.
To be honest, I'm a little confused about what was unclear about the way the URL config works, as it follows the principles of django url configs pretty closely. Your example does seem to use a strange mix of syntaxes, mixing regex and non-regex based syntax. I changed that a bit in my example, showing both a regex and non-regex pattern (django 3.0).
Please let me know if this clears things up, and I'm happy for any suggestions as to how I can improve the documentation.

A: The examples in the docs do not properly demonstrate the way URLs work with this library.
Wagtail sets the URL for the listing page. I created a page using the LocationPage template, named it 'Locations', and it is accessible at '/locations'. My url.conf was wrong. I had the listing page set to r'^locations/?$'.

*

*wagtail app pages does not like regex for some reason. I'm to green to understand why, but it is a no no.

*what I choose as my LocationListView slug has to be added to the path of the wagtail page URL. removing the regex, if I use 'locations/' in my URL conf, then my page is accessible at 'locations/locations/'.
I think the documentation assumes that your wagtail page URL will be root (which wouldn't make sense) so the blog listing page would be accessible at root/articles. but, as far as I know, that would cause your root URL to be claimed but unused, so you wouldn't have a home page. Very confusing.


text:
Q: AssertionError: Some objects had attributes which were not restored I was training a basic LSTM on text prediction by following the official TensorFlow site here. I had managed to train my model up to 40 epochs on a GTX 1050ti and had saved the checkPoint file in a separate folder. However, when I now try to restore the model, I get this long error:-
StreamExecutor device (0): GeForce GTX 1050 Ti, Compute Capability 6.1
WARNING:tensorflow:Entity <function standard_gru at 0x7f9e121324d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <function standard_gru at 0x7f9e121324d0>: AttributeError: module 'gast' has no attribute 'Num'
WARNING:tensorflow:Entity <function cudnn_gru at 0x7f9e120c1d40> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <function cudnn_gru at 0x7f9e120c1d40>: AttributeError: module 'gast' has no attribute 'Num'
WARNING:tensorflow:Entity <function standard_gru at 0x7f9e121324d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <function standard_gru at 0x7f9e121324d0>: AttributeError: module 'gast' has no attribute 'Num'
WARNING:tensorflow:Entity <function cudnn_gru at 0x7f9e120c1d40> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <function cudnn_gru at 0x7f9e120c1d40>: AttributeError: module 'gast' has no attribute 'Num'
WARNING:tensorflow:From /home/awesome_ruler/.local/lib/python3.7/site-packages/tensorflow/python/training/tracking/util.py:1200: NameBasedSaverStatus.__init__ (from tensorflow.python.training.tracking.util) is deprecated and will be removed in a future version.
Instructions for updating:
Restoring a name-based tf.train.Saver checkpoint using the object-based restore API. This mode uses global names to match variables, and so is somewhat fragile. It also adds new restore ops to the graph each time it is called when graph building. Prefer re-encoding training checkpoints in the object-based format: run save() on the object-based saver (the same one this message is coming from) and use that checkpoint in the future.
Traceback (most recent call last):
  File "main.py", line 95, in <module>
    model.load_weights(checkpoint_dir)
  File "/home/awesome_ruler/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 162, in load_weights
    return super(Model, self).load_weights(filepath, by_name)
  File "/home/awesome_ruler/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py", line 1398, in load_weights
    status.assert_nontrivial_match()
  File "/home/awesome_ruler/.local/lib/python3.7/site-packages/tensorflow/python/training/tracking/util.py", line 917, in assert_nontrivial_match
    return self.assert_consumed()
  File "/home/awesome_ruler/.local/lib/python3.7/site-packages/tensorflow/python/training/tracking/util.py", line 894, in assert_consumed
    (unused_attributes,))
AssertionError: Some objects had attributes which were not restored: {<tf.Variable 'embedding_1/embeddings:0' shape=(65, 256) dtype=float32, numpy=
array([[-0.00044268, -0.02351714, -0.01139065, ..., -0.00327835,
         0.00074228, -0.00383734],
       [-0.02313181,  0.04697707, -0.02350216, ...,  0.040385  ,
         0.03087702,  0.02765551],
       [ 0.0410727 ,  0.00130001,  0.0051438 , ...,  0.02899202,
         0.04258115, -0.03773504],
       ...,
       [-0.03134514,  0.01370119,  0.00993627, ..., -0.02257681,
         0.02617678,  0.03761976],
       [-0.02954974,  0.02407967,  0.02768463, ..., -0.0056519 ,
        -0.01507735,  0.04617763],
       [-0.04113789, -0.03544737,  0.01056757, ...,  0.01236727,
        -0.01791535, -0.01635399]], dtype=float32)>: ['embedding_1/embeddings'], <tf.Variable 'dense_1/kernel:0' shape=(1024, 65) dtype=float32, numpy=
array([[-6.7811467e-02, -2.5536597e-02,  5.1763237e-02, ...,
        -6.9665730e-02,  3.9457709e-02, -5.3290475e-02],
       [ 1.5835620e-02, -3.0763537e-02, -7.4058644e-02, ...,
         3.8087368e-05, -9.1508478e-03,  5.5485427e-02],
       [ 3.8143486e-02,  8.8131428e-04, -2.3478847e-02, ...,
        -1.5135627e-02, -5.2146181e-02,  7.1185097e-02],
       ...,
       [-6.6591002e-02,  4.7627889e-02,  5.7474524e-02, ...,
         4.1528463e-02,  4.6467118e-02, -3.0670539e-02],
       [-5.0804108e-02,  5.4505378e-02, -1.5776977e-03, ...,
         2.1875933e-02, -2.9637258e-02,  2.0201296e-02],
       [-4.7325939e-02, -8.0013275e-03, -3.6348965e-02, ...,
        -7.0560835e-02, -4.9752403e-02,  1.0509960e-02]], dtype=float32)>: ['dense_1/kernel'], <tf.Variable 'dense_1/bias:0' shape=(65,) dtype=float32, numpy=
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
      dtype=float32)>: ['dense_1/bias'], <tf.Variable 'gru_1/kernel:0' shape=(256, 3072) dtype=float32, numpy=
array([[ 0.00432818,  0.03131782,  0.00038544, ..., -0.00559966,
         0.03458985, -0.03219106],
       [-0.00865119,  0.01648769, -0.00768028, ...,  0.01366192,
        -0.03043955, -0.01382086],
       [-0.01379537,  0.00547716, -0.00385967, ..., -0.00027269,
        -0.01285852,  0.0377048 ],
       ...,
       [-0.01940641,  0.01454895,  0.03349226, ..., -0.04234404,
        -0.02699661,  0.0376601 ],
       [ 0.00186675, -0.00547577, -0.02205843, ..., -0.01287581,
        -0.02314153,  0.04158166],
       [ 0.00954719, -0.02883693, -0.03259185, ..., -0.02587803,
         0.02906795, -0.00559821]], dtype=float32)>: ['gru_1/kernel'], <tf.Variable 'gru_1/recurrent_kernel:0' shape=(1024, 3072) dtype=float32, numpy=
array([[ 9.11542401e-03,  1.50135346e-02,  2.96630897e-02, ...,
         2.25223936e-02,  2.31253020e-02, -2.96920985e-02],
       [-2.21075956e-02, -8.46013427e-06, -2.16848943e-02, ...,
        -1.26914177e-02, -3.49153839e-02, -3.01396102e-02],
       [-3.59148793e-02,  9.98445973e-03,  2.60963626e-02, ...,
         3.15430500e-02,  1.28889643e-02,  3.37569825e-02],
       ...,
       [ 3.39106433e-02,  6.54980540e-03, -1.27352085e-02, ...,
        -4.14674729e-03,  3.53236459e-02, -1.36333425e-02],
       [-3.50691415e-02, -1.76392253e-02,  1.67468414e-02, ...,
        -2.06982102e-02, -1.06042419e-02,  2.26641595e-02],
       [-1.14825107e-02, -3.46554294e-02, -1.83847174e-03, ...,
         2.25809850e-02,  2.45791934e-02, -2.70933360e-02]], dtype=float32)>: ['gru_1/recurrent_kernel'], <tf.Variable 'gru_1/bias:0' shape=(2, 3072) dtype=float32, numpy=
array([[0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]], dtype=float32)>: ['gru_1/bias']}

I am trying to load the file ckpt_40.index which, as you can see is the latest checkpoint. However I am not able to. I am using this code to load my model ==>
checkpoint_dir = 'CheckPoints/ckpt_40.index'

model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)

model.load_weights(checkpoint_dir)

model.summary()

And am using the generate_text function from the website to predict something.

I think a similar issue was posted on Stack overflow here, but it wasn't answered. I am using Tf[GPU] 2.0- beta1 which was the latest tf version for GPU...

A: A really idiotic mistake I made, which was so minor that I doubt anyone could have picked it up. In this line :-
checkpoint_dir = 'CheckPoints/ckpt_40.index'

Though the file is named to have the '.index' prefix, For some reason attaching that extension to the variable/call function has caused it to panic for some reason(Maybe a bug). What would have been more helpful was an error to point out the incorrect extension.
So for anyone else having this problem, just change your checkpoint directory to this ===>
checkpoint_dir = 'CheckPoints/ckpt_40  # .index has been removed'


text:
Q: opencv - Ошибка TypeError: only size-1 arrays can be converted to Python scalars Есть такой код:
import cv2
import random
import numpy as np
t=int(input())
r=int(input())
g=int(input())
b=int(input())
r=0
g=0
b=0
img = cv2.imread("color.bmp")
r=cv2.imread("color.bmp")
for i in range(1,480,t):
    for j in range(1,720,t):
        img[i:i+t, j:j+t]= ( b/((480+720)/t-2)*(((i-1)/t)+((j-1)/t)), g/((480+720)/t-2)*(((i-1)/t)+((j-1)/t)), r/((480+720)/t-2)*(((i-1)/t)+((j-1)/t)))
        cv2.imshow('hello',img)
        cv2.waitKey(1)
cv2.imwrite("color.jpg", img)

Выводит ошибку
Traceback (most recent call last):
  File "cv.py", line 19, in <module>
    img[i:i+t, j:j+t]= (int( b/ int((480+720)/t-2) * int(((i-1)/t)+((j-1)/t))) , int( g/ int((480+720)/t-2) * int(((i-1)/t)+((j-1)/t))), int( r/ int((480+720)/t-2) * int(((i-1)/t)+((j-1)/t))))
TypeError: only size-1 arrays can be converted to Python scalars

Подскажите, пожалуйста, как исправить.


text:
Q: I want to create a multi nested json from my pandas dataframe I have a pandas data frame in the following format :-
    EMPCODE|Indicator|CustNAME
    1        CASA       Raja
    1        CASA       lala
    1        CASA       dada
    1        TL         Nan
    1        l          Nan
    1        p          Nan
    1        q          Nan
    2        CASA       Crick
    2        CASA       Flick
    2        TL         Nan
    2        l          Nan
    2        p          Nan
    2        q          Nan

I want to convert this into a nested json .
Ive tried various different methods including groupby(),apply() but I Cant get a the output in the required json format.From the code mentioned below I am getting duplicate custNAme values for both employees .
  group = merge_hr_anr.groupby('EMPCODE_y').groups
  group1 = merge_hr_anr.groupby("EMPNAME").groups
    for variable in range(a):
            d = {'EMPCODE_y': list(group.keys())[variable],'EMPNAME':
            list(group1.keys())[variable] ,'Indicators': [{'IndicatorName':
            merge_hr_anr.loc[i, 'IndicatorName']} for i in list(group.values())
            [variable].unique()]}
            d['Indicators'] = list(map(dict,sorted(set(map(lambda x:
            tuple(x.items()),d['Indicators'])), key=list(map(lambda x:
            tuple(x.items()),d['Indicators'])).index)))
            d['Performance'] = [{i['IndicatorName']:
(merge_hr_anr.loc[merge_hr_anr['IndicatorName'].eq(i['IndicatorName']),"CUSTNAME"]).dropna().tolist()} for i in d['Indicators']]

    My output is
{
    "EMPCODE": "1",
    "Indicators": [
      {
        "IndicatorName": "CASA"
      },
      {
        "IndicatorName": "TL"
      },
      {
        "IndicatorName": "l"
      },
      {
        "IndicatorName": "p"
      },
      {
        "IndicatorName": "q"
      }
    ]
  "Performance":[
     {
         "CASA":[{"Custname":"Raja"},{"Custname":"lala"},{"Custname":"dada"}]
     },
     {
         "TL":[]
     }
     {
         "l":[]
     }
     {
         "p":[]
     }
     {
         "q":[]
     }

  ]
}
{
    "EMPCODE": "2",
    "Indicators": [
      {
        "IndicatorName": "CASA"
      },
      {
        "IndicatorName": "TL"
      },
      {
        "IndicatorName": "l"
      },
      {
        "IndicatorName": "p"
      },
      {
        "IndicatorName": "q"
      }
    ]
  "Performance":[
     {
         "CASA":[{"Custname":"Raja"},{"Custname":"lala"},{"CustName":"dada"}]
     },
     {
         "TL":[]
     }
     {
         "l":[]
     }
     {
         "p":[]
     }
     {
         "q":[]
     }

  ]
}

i want the output to be
{
    "EMPCODE": "1",
    "Indicators": [
      {
        "IndicatorName": "CASA"
      },
      {
        "IndicatorName": "TL"
      },
      {
        "IndicatorName": "l"
      },
      {
        "IndicatorName": "p"
      },
      {
        "IndicatorName": "q"
      }
    ]
  "Performance":[
     {
         "CASA":[{"Custname":"Raja"},{"Custname":"lala"},{"Custname":"dada"}]
     },
     {
         "TL":[]
     }
     {
         "l":[]
     }
     {
         "p":[]
     }
     {
         "q":[]
     }

  ]
}
{
    "EMPCODE": "2",
    "Indicators": [
      {
        "IndicatorName": "CASA"
      },
      {
        "IndicatorName": "TL"
      },
      {
        "IndicatorName": "l"
      },
      {
        "IndicatorName": "p"
      },
      {
        "IndicatorName": "q"
      }
    ]
  "Performance":[
     {
         "CASA":[{"Custname":"Crick"},{"Custname":"Flick"}]
     },
     {
         "TL":[]
     }
     {
         "l":[]
     }
     {
         "p":[]
     }
     {
         "q":[]
     }

  ]
}

A: Try the below code with constructing a dictionary:
group = merge_hr_anr.groupby('EMPCODE').groups
d = {'EMPCODE': list(group.keys())[0], 'Indicators': [{'IndicatorName': merge_hr_anr.loc[i, 'Indicator']} for i in list(group.values())[0].unique()]}
d['Indicators'] = list(map(dict,sorted(set(map(lambda x: tuple(x.items()),d['Indicators'])), key=list(map(lambda x: tuple(x.items()),d['Indicators'])).index)))
d['Performance'] = [{i['IndicatorName']: merge_hr_anr.loc[merge_hr_anr['Indicator'].eq(i['IndicatorName']), 'CustNAME'].dropna().tolist()} for i in d['Indicators']]
print(d)

Output:
{'EMPCODE': 1, 'Indicators': [{'IndicatorName': 'CASA'}, {'IndicatorName': 'TL'}, {'IndicatorName': 'l'}, {'IndicatorName': 'p'}, {'IndicatorName': 'q'}], 'Performance': [{'CASA': ['Raja', 'lala', 'dada']}, {'TL': []}, {'l': []}, {'p': []}, {'q': []}]}

To write a .json file:
with open('outvalue7.json', 'w') as f:
    f.write(str(d))


text:
Q: How do I set a limit on how many images can be shown in an image carousel? (PHP) Here is my code ( I have an external JS and jQuery file linked, and my folder for images is called uploads/):
So, currently this shows all images I upload. What I want is to have a limit on how many images it shows.
I want to limit this to allow only to show the last 4 images. Is there a way? Thanks!
<?php include("header.inc"); ?>

<?php include("nav.inc"); ?>

<?php
    $files = scandir("uploads/");
?>

          <?php
              $i = 0;
              for($a = 2; $a < count($files); $a++):
          ?>

        <li data-target="#myCarousel" data-slide-to="<?php echo $i; ?>" class="<?php echo $i == 0 ? 'active': ''; ?>">

          <?php
              $i++;
              endfor;
          ?>

          <?php
              $i = 0;
              for($a = 2; $a < count($files); $a++):
          ?>

        <div class="item <?php echo $i == 0 ? 'active': ''; ?>" align="center">
          <img src="uploads/<?php echo $files[$a]; ?>" style="width: 640px; height: 640px;">

          <?php
              $i++;
              endfor;
          ?>

        Previous

        Next

<?php include("footer.inc"); ?>

A: Replace:
$files = scandir("uploads/");

with:
const CAROUSEL_LENGTH = 4;   // Should be on top of script or in a config file
$files = array_slice(scandir('uploads/', SCANDIR_SORT_DESCENDING), 0, CAROUSEL_LENGTH);

The SCANDIR_SORT_DESCENDING flag will sort files by timestamp (see this post for a more in-depth explanation) and array_slice will take the first four.


text:
Q: Need Help C# Error: Object reference not set to an instance of an object Can you help me solve following Error Message:

"Object reference not set to an instance of an object."

I marked the areas I get the error with comments and **
Please see below.
private static void _GenerateWord(string fname, string reportStartDate, string reportEndDate)
        {
            var word = new Microsoft.Office.Interop.Word.Application();
            var doc = new Microsoft.Office.Interop.Word.Document();
            word.Visible = false;
            object missing = Type.Missing;

            object fileName = (@LetterTemplateLocation + LetterName);

            doc = word.Documents.Open(ref fileName);

            doc.Activate();//**Error message here "Object reference not set to an instance of an object."**

            string dateWithFormat = DateTime.Now.ToString("MMMM d, yyyy");

            //**Error message here "Object reference not set to an instance of an object."**
            foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
            {
                _FindAndReplace("<date>", dateWithFormat, tmpRange, missing);

                _FindAndReplace("<filename>", fname, tmpRange, missing);

                _FindAndReplace("<startdate>", reportStartDate, tmpRange, missing);

                _FindAndReplace("<enddate>", reportEndDate, tmpRange, missing);
            }

            if (doc != null)
            {
                doc.Close(ref missing, ref missing, ref missing);
                word.Application.Quit(ref missing, ref missing, ref missing);
            }
        }

Thank you.

A: As a practice need to check doc for null.

If(doc !=null){...}

Also need to evaluate valid file, as others suggested.


text:
Q: How do I get the Maui ListView ContextMenu to bind to my viewmodel command I have the following XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="MyApp.Pages.Locations.LocationsList"
             xmlns:mvvm="clr-namespace:MvvmHelpers;assembly=MvvmHelpers"
             xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Add" Command="{Binding AddCommand}" />
    </ContentPage.ToolbarItems>
    <ContentPage.Behaviors>
        <toolkit:EventToCommandBehavior EventName="Appearing" Command="{Binding LoadCommand}" />
    </ContentPage.Behaviors>
    <ContentPage.Resources>
        <ResourceDictionary>
            <toolkit:SelectedItemEventArgsConverter x:Key="SelectedItemEventArgsConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ListView BackgroundColor="Transparent"
              CachingStrategy="RecycleElement"
              ItemsSource="{Binding Locations}"
              SelectedItem="{Binding SelectedLocation, Mode=TwoWay}"
              SeparatorVisibility="None"
              HasUnevenRows="True">
        <ListView.Behaviors>
            <toolkit:EventToCommandBehavior
                        EventName="ItemSelected"
                        EventArgsConverter="{StaticResource SelectedItemEventArgsConverter}"
                        Command="{Binding SelectCommand}"/>
        </ListView.Behaviors>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.ContextActions>
                        <MenuItem Text="Delete" IsDestructive="True"
                                          Command="{Binding DeleteCommand}"
                                          CommandParameter="{Binding .}" />
                        <MenuItem Text="Edit"  Command="{Binding EditCommand}"
                                    CommandParameter="{Binding .}" />
                    </ViewCell.ContextActions>
                    <Grid Padding="10">
                        <Frame>
                            <StackLayout Orientation="Horizontal">
                                <Image Source="map.png" WidthRequest="40" />
                                <StackLayout Orientation="Vertical" Padding="10,0,0,0">
                                    <Label VerticalOptions="Center"
                                       FontSize="Medium"
                                       Text="{Binding Name}" />
                                    <Label VerticalOptions="Center"
                                       FontSize="Micro"
                                       Text="This is where the address will go." />
                                </StackLayout>
                            </StackLayout>
                        </Frame>
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

My ViewModel uses the Maui Community Toolkit and has 4 AsyncCommands defined

*

*LoadCommand

*SaveCommand

*DeleteCommand

*EditCommand

The LoadCommand and SaveCommand work perfectly but the DeleteCommand and EditCommand do not fire.  I assume it's something to do with the commands being on the viewmodel and NOT on the item source model.  How do I get it to trigger the AsyncCommands on the viewmodel?
Thanks

A: For this, you can check document Define MenuItem behavior with MVVM.
The MenuItem class supports the Model-View-ViewModel (MVVM) pattern through BindableProperty objects and the ICommand interface. The following XAML shows MenuItem instances bound to commands defined on a viewmodel:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:viewmodels="clr-namespace:MenuItemDemos.ViewModels"
             mc:Ignorable="d"
             x:Class="MenuItemDemos.MenuItemXamlMvvmPage"
             x:Name="myContentpage"
             Padding="10"
             Title="MenuItem XAML MVVM Demo"
             >

    <ContentPage.BindingContext>
        <viewmodels:ListPageViewModel />
    </ContentPage.BindingContext>

    <StackLayout>
        <Label Text="Reveal the context menu by right-clicking (UWP), long-pressing (Android), or swiping (iOS) an item in the following list." />
        <Label Text="{Binding Message}"
               TextColor="Red"
               HorizontalOptions="CenterAndExpand"
               VerticalOptions="Start" />
        <ListView ItemsSource="{Binding Items}"
                  HorizontalOptions="CenterAndExpand"
                  VerticalOptions="CenterAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.ContextActions>
                            <MenuItem Text="Edit"
                                      IconImageSource="icon.png"
                                      Command="{Binding Source={x:Reference myContentpage}, Path=BindingContext.EditCommand}"
                                      CommandParameter="{Binding .}"/>
                            <MenuItem Text="Delete"
                                      Command="{Binding Source={x:Reference myContentpage}, Path=BindingContext.DeleteCommand}"
                                      CommandParameter="{Binding .}"/>
                        </ViewCell.ContextActions>
                        <Label Text="{Binding .}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

The viewmodel(ListPageViewModel.cs) contains the commands referenced in the XAML:
public class ListPageViewModel : INotifyPropertyChanged
{
    ...

    public ICommand EditCommand => new Command<string>((string item) =>
    {
        Message = $"Edit command was called on: {item}";
    });

    public ICommand DeleteCommand => new Command<string>((string item) =>
    {
        Message = $"Delete command was called on: {item}";
    });
}


text:
Q: Number of elements of a set via action Let $G$ be a finite group, acting on a finite set $X$. Burnside's lemma says that the following holds
$$|X/G| = \frac{1}{|G|}\sum_{g\in G}|St(g)|$$
I'm wondering does it mean that $|X| = |X/G|\cdot|G|$ as in Lagrange's theorem for groups. Or maybe there's a classification of actions for which this is true.

A: Edit: I am assuming that $X$ and $G$ are finite for everything to make sense.
Note that precisely by Burnside's lemma, your question translates to asking wether
$$
|X| = \sum_{g \in G}|X^g|
$$
where $X^g := \{x \in X : g \cdot x = x\}$.
However, when $g = 1$ we have
$$
X^1 = \{x \in X : 1 \cdot x = x\} = X
$$
so in turn this would mean that
$$
0 = \sum_{g \neq 1}|X^g|,
$$
or equivalently, that $|X^g| = 0$ for all $g \neq 1$.
Thus equality holds when $g \cdot x \neq x $ for all $x \in X, g \neq 1$. If I recall correctly, this is the definition of a free action.


text:
Q: SharpDX Bitmaps I've been looking around the internet for a while, and I can't seem to find the answer I've been looking for. So what I intend to do with bitmaps is I want to draw them onto the window, and be able properly resize them whenever. Any help would be appreciated!

A: For those of you who do not know, you can use matrices to translate, resize, and rotate. Here's how to do it. Also be sure to change the Matrix for the RenderTarget before you draw the actual object.
Vector2
RenderTarget.Transform
RenderTarget.DrawBitmap
Matrix.Transformation2D
Vector2 center = new Vector2(bitmap.Size.Width / 2, bitmap.Size.Height / 2);
renderTarget.Transform = Matrix.Transformation2D(center, 0f, new Vector2(width / bitmap.Size.Width, height / bitmap.Size.Height), center, MathHelper.ToRads(rotation), new Vector2(x - center.X, y - center.Y));
renderTarget.DrawBitmap(bitmap, 1f, BitmapInterpolationMode.NearestNeighbor);
renderTarget.Transform = Matrix.Transformation2D(Vector2.Zero, 0f, new Vector2(1f, 1f), Vector2.Zero, MathHelper.ToRads(0), Vector2.Zero);


text:
Q: Should I incorporate sex as a control variable or use multi-level modelling? I'm doing a linear regression model to look at how socio-economic status impacts children's height. My dataset will be survey data for both males and females.
To me, it makes sense to control for sex, as boys and girls obviously have different growth patterns. However, I've been told that with regression models you should only control for confounding variables - those that are associated with both the independent and dependent variables and could therefore create a spurious relationship.
So, should I instead be controlling for confounders, then using multi-level modelling to look at the relationship on both a male and female level? Or would I just collect info about sex in the survey and filter the dataframe by sex to run models for each?  Or should I approach it a different way? OR should I in fact be including sex as a control variable?
Any help would be very very much appreciated!
Thank you!

A: My two cents:  Adjust your estimate for sex by adding it into the model.  Justification is below...

you should only control for confounding variables

This is not completely accurate.
If your goal is to estimate causal relationships, then adjusting for confounders is a good thing -- indeed its a must!  However, the estimate can actually be improved by conditioning on a variable which is associated with the outcome but does not lay on the causal pathway between the exposure and the outcome.  By adjusting for these related covariates, the residual variance is decreased thereby increasing the efficiency of the causal estimate.
Its simple to demonstrate via simulation.  I'm going to simulate data from this causal graph.  Note that $w$ is not a confounder of the causal effect of $x$ on $y$.  However $z$ is.  We will repeatedly simulate data, fit two models -- one with $w$ and one without it -- and compare the disrtribution of estimated effects.  The result is shown below.

Note that the distribution of effects for $x$ when not conditioning on $w$ is much wider.  This results in lower statistical power.  Since $w$ effects $y$ and does not lay on the causal pathway, it is a good idea to adjust for it.

As to if you should or should not adjust for sex, it really depends on your causal graph.  I agree that a child's sex partly causes their height, and I see no way in which a child's sex could cause SES so I don't see it as a confounder.  I'm open to different interpretations should there be any.


text:
Q: consistency of MLE estimator example Given the density function $f(x;\theta)=\theta x^{\theta -1}$ with $\theta \gt 0$ and $x \in (0,1)$, once found the MLE estimator $\hat{\theta}=\frac{-n}{\sum{\log{X_i}}}$ i want to show the consistency of such an estimator. I was suggested to apply the strong law of large numbers, although i am not sure how. Should I first obtain the expected value of the random variable $\log(X_i)$ and then apply the SLLN on them or is there another way?

A: You can show that $Y = -\ln X \sim Exp(\theta)$, hence $\mathbb{E}[Y]=1/\theta$, thus by the SLLN and the continuous mapping theorem
$$
\hat{\theta}_n \xrightarrow{a.s.} (1/\theta)^{-1} = \theta,
$$
as $n \to \infty$.

A: If you are not familiar with SLLN, there are several other ways to approach the  problem,

*

*The simplest: a property of ML Estimators is that they are consistent.

*Consistency you have to prove is $\hat{\theta}\xrightarrow{\mathcal{P}}\theta$
So first let's calculate the density of the estimator.
Observe that (it is very easy to prove this with the fundamental transformation theorem)
$$Y=-logX\sim Exp(\theta)$$
Thus $W=\Sigma_iY_i\sim Gamma(n;\theta)$ and $\frac{1}{W}\sim \text{Inverse Gamma}$ and consequently
$$\mathbb{E}[\hat{\theta}]=\frac{n}{n-1}\theta$$
$$\mathbb{V}[\hat{\theta}]=\frac{n^2}{(n-1)^2(n-2)}\theta$$
This grant the following are both true
$$\lim\limits_{n\to \infty}\mathbb{E}[\hat{\theta}]=\theta$$
$$\lim\limits_{n\to \infty}\mathbb{V}[\hat{\theta}]=0$$
This is an IFF condition for the convergence in $L^2$ which implies also the convergence in probability (the consistency of your estimator)

*Calculate the convergence in probability by the definition

Using 2 is a better way because you proved also the convergence in quadratic mean, that it is stronger

Trying all the method we showed is an useful exercise (IMHO)


text:
Q: Keyword not supported exception when attempting to use a connection string that points to a ODBC DSN I created an ODBC DSN for my Asp.Net MVC application's database access.  One of the main reasons is it makes it easy to keep database credentials (such as server address, port, username, and password) out of source control without hindering my publishing abilities.
So I changed my connection to be DSN=MyDSN.
Unfortunately, when I run my Entity Framework queries I get Exception Details: System.ArgumentException: Keyword not supported: 'dsn'.
Does anyone know what I am doing wrong?

A: If you want to use ODBC DSN your connection string must use System.Data.Odbc native provider instead of managed SQL client.
Edit:
So now from theory to practice. It doesn't work because of internal EF implementation. EF internally calls some method which tries to get DbProviderFactory from the created connection. The problem is that this property is defined in DbConnection and it returns null. Only SqlConnection overrides property and returns correct factory. So EF doesn't work with default ODBC provider and here is very clearly described why.


text:
Q: MQTT malformed packet Running mosquito broker in docker, broker ip address is 172.18.5.10, docker network gateway is 172.18.5.1. There are also some other dockers attached to that network, also I do have several MQTT devices / programs subscribed and publishing to Mosquito broker and working just fine.
The issues is I am getting following error every ~ 40 seconds.
2023/02/22T14:20:09: New connection from 172.18.5.1:47008 on port 1883.
2023/02/22T14:20:09: Client <unknown> disconnected due to malformed packet.
2023/02/22T14:20:37: New connection from 172.18.5.1:47162 on port 1883.
2023/02/22T14:20:37: Client <unknown> disconnected due to malformed packet.
2023/02/22T14:21:05: New connection from 172.18.5.1:47270 on port 1883.
2023/02/22T14:21:05: Client <unknown> disconnected due to malformed packet.
2023/02/22T14:21:33: New connection from 172.18.5.1:47418 on port 1883.
2023/02/22T14:21:33: Client <unknown> disconnected due to malformed packet.
2023/02/22T14:22:01: New connection from 172.18.5.1:47538 on port 1883.
2023/02/22T14:22:01: Client <unknown> disconnected due to malformed packet.
2023/02/22T14:22:29: New connection from 172.18.5.1:47674 on port 1883.
2023/02/22T14:22:29: Client <unknown> disconnected due to malformed packet.
2023/02/22T14:22:57: New connection from 172.18.5.1:47782 on port 1883.

Here is result from wireshark for
2023/02/22T14:21:05: New connection from 172.18.5.1:47270 on port 1883.
2023/02/22T14:21:05: Client <unknown> disconnected due to malformed packet.

More detailed error image for different src port

Here is an example of good and bad connections, good connection are from local IP address range but this malformed is always from network gateway:
2023/02/21T22:38:03: New client connected from 192.168.3.8:52207 as sw-tasmota-hall (p2, c1, k30, u'data').
2023/02/21T22:38:04: New connection from 192.168.3.1:57113 on port 1883.
2023/02/21T22:38:04: New client connected from 192.168.3.1:57113 as switch-tasmota-bath (p2, c1, k30, u'data').
2023/02/21T22:38:04: New connection from 192.168.2.4:58631 on port 1883.
2023/02/21T22:38:04: New client connected from 192.168.2.4:58631 as node-tasmota-garage (p2, c1, k30, u'data').
2023/02/21T22:38:06: New connection from 172.18.5.1:48908 on port 1883.
2023/02/21T22:38:06: Client <unknown> disconnected due to malformed packet.
2023/02/21T22:38:28: New connection from 172.18.5.1:49018 on port 1883.
2023/02/21T22:38:28: Client <unknown> disconnected due to malformed packet.
2023/02/21T22:38:50: New connection from 172.18.5.1:49160 on port 1883.
2023/02/21T22:38:50: Client <unknown> disconnected due to malformed packet.

Docker-compose:
version: '3'

services:
  mosquitto:
    image: eclipse-mosquitto:2.0.15
    container_name: mosquitto
    restart: unless-stopped
    environment:
      - TZ=Europe/Prague
    ports:
      - "1883:1883"
    volumes:
      - /share/Container/mosquitto/data:/mosquitto/data
      - /share/Container/mosquitto/config:/mosquitto/config
      - /share/Container/mosquitto/log:/mosquitto/log
      - /etc/localtime:/etc/localtime:ro
    logging:
      driver: "syslog"
      options:
        syslog-address: "tcp://192.168.1.106:514"
        tag: "{{.Name}}/{{.ImageName}}"
    networks:
      ha_net:
         ipv4_address: 172.18.5.10
networks:
  ha_net:
    external: true

mosquitto.conf
persistence true
persistence_location /mosquitto/data/
persistence_file mosquitto.db

listener 1883

allow_anonymous true

log_type error
log_type warning
log_type notice
log_type information
log_dest stdout
log_timestamp true
log_timestamp_format %Y/%m/%dT%H:%M:%S

password_file /mosquitto/config/pwfile

I am looking for help how to detect ip address of the device/host/program that is causing this issue.
Thanks,
salvq

A: I was able to fix the issue (disconnects due to malformed packet) by running mosquito docker in HOST network mode rather than custom bridge network mode.
However, I have not been able to determine the root cause of the disconnects due to malformed packet on the docker custom bridge network, but not in host network mode.
Working docker-compose
version: '3'

services:
  mosquitto:
    image: eclipse-mosquitto:2.0.15
    container_name: mosquitto
    restart: unless-stopped
    network_mode: host
    environment:
      - TZ=Europe/Prague
    volumes:
      - /share/Container/mosquitto/data:/mosquitto/data
      - /share/Container/mosquitto/config:/mosquitto/config
      - /share/Container/mosquitto/log:/mosquitto/log
      - /etc/localtime:/etc/localtime:ro
    logging:
      driver: "syslog"
      options:
        syslog-address: "tcp://192.168.1.106:514"
        tag: "{{.Name}}/{{.ImageName}}"


text:
Q: Reject IP that is already in white list Time ago I set
firewall-cmd --permanent --zone=public --add-source=170.8.0.0/18

Today I ran
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='170.8.1.1' reject";

*

*Which of both prevails?

*What if the order is reversed? First reject an IP and then add it to a whitelisted range.

A: The command which is executed later will override policy. Later command will override previous command.


text:
Q: Set default application by extension not mimetype Is it possible to set the default application to open a file by extension rather than mimetype?
MuseScore saves its files as .mscz files, which are actually just zip-archives containing the data of the MuseScore file. Since Ubuntu recognizes it as a zip-archive, it opens them with the archive manager. So I always have to right-click and say Open with MuseScore, which is annoying.
If I set MuseScore as default for the .mscz files, it becomes the default for all zip-archives, which is obviously not what I want. So it would be useful if I could set MuseScore as default for all files with the .mscz extension.
As far as I know, I don't have any .mscz archives that are not MuseScore files, so that wouldn't be a problem. And if I ever do encounter some, I don't mind dealing with that.

A: Try the following:

*

*Use nano to create the /usr/share/mime/packages/musescore3.xml file:
sudo nano /usr/share/mime/packages/musescore3.xml

*Copy and paste (with Ctrl+Shift+V) the following:
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
  <mime-type type="application/x-musescore3">
    <comment>MuseScore file</comment>
    <sub-class-of type="application/zip"/>
    <glob pattern="*.mscz"/>
  </mime-type>
  <mime-type type="application/x-musescore3+xml">
    <comment>uncompressed MuseScore file</comment>
    <sub-class-of type="application/xml"/>
    <glob pattern="*.mscx" />
  </mime-type>
  <mime-type type="application/vnd.recordare.musicxml3">
    <!-- http://www.musicxml.com/for-developers/musicxml-dtd/ -->
    <_comment>compressed MusicXML file</_comment>
    <sub-class-of type="application/zip"/>
<!-- Note: a custom icon is used for MusicXML files. You can change this below -->
<!--  <icon name="application-x-musescore"/> Uncomment to use MuseScore file icon -->
<!--  <generic-icon name="audio-x-generic"/> Uncomment to use generic audio file icon -->
    <glob pattern="*.mxl"/>
  </mime-type>
  <mime-type type="application/vnd.recordare.musicxml3+xml">
    <!-- http://www.musicxml.com/for-developers/musicxml-dtd/ -->
    <_comment>uncompressed MusicXML file</_comment>
    <sub-class-of type="application/xml"/>
<!--  <icon name="application-x-musescore"/> Uncomment to use MuseScore file icon -->
<!--  <generic-icon name="audio-x-generic"/> Uncomment to use generic audio file icon -->
    <magic>
      <match type="string" value="<?xml" offset="0">
        <match type="string" value="score-partwise" offset="0:128"/>
        <match type="string" value="score-timewise" offset="0:128"/>
      </match>
      <match type="string" value="<!--" offset="0">
        <match type="string" value="score-partwise" offset="0:128"/>
        <match type="string" value="score-timewise" offset="0:128"/>
      </match>
    </magic>
    <glob pattern="*.xml" weight="40"/>
  </mime-type>
  <mime-type type="application/vnd.recordare.musicxml3+xml">
        <!-- http://www.musicxml.com/for-developers/musicxml-dtd/ -->
        <_comment>uncompressed MusicXML file</_comment>
        <sub-class-of type="application/xml"/>
        <!--  <icon name="application-x-musescore"/> Uncomment to use MuseScore file icon -->
        <!--  <generic-icon name="audio-x-generic"/> Uncomment to use generic audio file icon -->
        <magic>
              <match type="string" value="<?xml" offset="0">
                    <match type="string" value="score-partwise" offset="0:128"/>
                    <match type="string" value="score-timewise" offset="0:128"/>
              </match>
              <match type="string" value="<!--" offset="0">
                    <match type="string" value="score-partwise" offset="0:128"/>
                    <match type="string" value="score-timewise" offset="0:128"/>
              </match>
        </magic>
        <glob pattern="*.musicxml" weight="40"/>
  </mime-type>
</mime-info>

*Save and close nano using Ctrl+O and Ctrl+X.

*Run:
sudo update-mime-database /usr/share/mime

*Then right-click a .mscz file and then go to Properties → Open With → select MuseScore from the list → Set as default.

*If that doesn't work immediately, repeat step 5 to set the default program (Archive Manager) for a zip file and then repeat for Musescore.
The following screenshot is an example of the Properties window.


text:
Q: How to Sort an Javascript Array with IndexString eg: a['String'] i Have a JS array Like this
CDate['1997-02-11']={dc: 3, da: 1, dm: 4};
CDate['1998-03-18']={dc: 6, da: 1, dm: 1};
CDate['1999-02-1']={dc: 4, da: 1, dm: 0};
CDate['2001-02-11']={dc: 1, da: 1, dm: 4};
CDate['2000-02-11']={dc: 3, da: 1, dm: 4};
CDate['1985-03-18']={dc: 6, da: 1, dm: 1};
CDate['1999-02-1']={dc: 4, da: 1, dm: 0};

and im using this CDates for a function to split the data into 4 arrays for a graph
for(var Dt in cDate)
{    console.log(Dt);
     chDate.push(Dt);
     chDa.push(cDate[Dt].da);
     chDm.push(cDate[Dt].dm);
     chDc.push(cDate[Dt].dc);
};

and in console i can see Dates printed bt not as sorted. so my graph doesnt looked in chronological order. wen i searched there are lot functions to sort array on key or property value bt not to sort "KEY" or "INDEX"..
Is there any way for this ?

A: A couple of observations:

*

*CDate is not an array, it's an object. Object properties are unsorted in JavaScript and you cannot have repeated keys in an object (as you have for key 1999-02-1).

*You can get the object's keys using Object.keys().

*The keys can then be sorted using the Array.prototype.sort() method, but because of how your dates are formatted, the natural (lexical) sort order is not suitable (e.g. 2017-01-10 will end up before 2017-02-2).
In the code below I corrected the date format. If you're unable to correct the date formats, you will have to write your own sort logic.

let CDate = {};
CDate['1997-02-11']={dc: 3, da: 1, dm: 4};
CDate['1998-03-18']={dc: 6, da: 1, dm: 1};
CDate['1999-02-01']={dc: 4, da: 1, dm: 0};
CDate['2001-02-11']={dc: 1, da: 1, dm: 4};
CDate['2000-02-11']={dc: 3, da: 1, dm: 4};
CDate['1985-03-18']={dc: 6, da: 1, dm: 1};

let chDate = [];
let chDa = [];
let chDm = [];
let chDc = [];

let keys = Object.keys(CDate).sort();

keys.forEach(key => {
  chDate.push(key);
  chDa.push(CDate[key].da);
  chDm.push(CDate[key].dm);
  chDc.push(CDate[key].dc);
});

console.log(chDate);
console.log(chDa);
console.log(chDm);
console.log(chDc);

A: var CDate = [];
var chDate = [];
var chDa = [];
var chDm = [];
var chDc = [];

CDate['1997-02-11']={dc: 3, da: 1, dm: 4};
CDate['1998-03-18']={dc: 6, da: 1, dm: 1};
CDate['1999-02-1']={dc: 4, da: 1, dm: 0};
CDate['2001-02-11']={dc: 1, da: 1, dm: 4};
CDate['2000-02-11']={dc: 3, da: 1, dm: 4};
CDate['1985-03-18']={dc: 6, da: 1, dm: 1};
CDate['1999-02-1']={dc: 4, da: 1, dm: 0};

var sortedData = Object.keys(CDate).sort();

for (var index = 0; index < sortedData.length; index++) {
    var data = CDate[sortedData[index]];
    console.log(data);
    chDate.push(data);
    chDa.push(data.da);
    chDm.push(data.dm);
    chDc.push(data.dc);
}

console.log(chDate);
console.log(chDa);
console.log(chDm);
console.log(chDc);


text:
Q: creating a menu with CSS and overflow: auto The main structure of the page is like this:

Menu

Submenu 1

Submenu 2

Submenu 3

I use JQuery to make the H1 elements in #Menu clickable so that all the other UL's are rolled up and the UL after the H1 is rolled down. I would like to scroll #Main indepently of the #Menu and I would like scrollbars, if needed, in each UL in #Menu. Here is the relevant CSS:

    html { height: 100%; overflow: hidden; font-size: .8em; }
    body { height: 100%; overflow: hidden; }
    div#Main { position: absolute; right: 0px; top: 0px; bottom: 0px; width: 79.9%; }
    div#Menu { position: absolute; left: 0px; top: 0px; bottom: 0px; width: 20%; }

    div#Main { overflow: auto; }
    div#Menu h1 { font-size: 1.5em; }
    div#Menu ul { max-height: 87%; overflow: auto; }

This works exactly the way I want it to. The #Main area is scrollable and each UL, when expanded, gets a scroll bar if there is more content than the containing #Menu DIV can contain.
The only problem is that I have to specify a height of 87% of the containing #Menu DIV, which only works for my combination of screen size, window size and font size. Is there a way to achieve the same effect without hard-coding the height of each UL?
If you like, you can see the page. I would post links to the CSS (/musicdb.css) and the JS code (/musicdb.js), but I'm not allowed. If you want to view source, you can switch content types by adding ?mode=xml or ?mode=html to the URL and view it in IE or Firefox.

A: I was playing around your site page with Firebug. Can't really have a really elagant a quick solution for you except for this one:
Setting the "div#Menu" to 100% and "div#Menu H1" to a height in percentage say 5%.
You have "menu", "artists", "labels" and "formats" = 4 h1 items. That's 5 X 4 = 20%.
Set "div#Menu ul" to 100-20 = 80%.
Play around with the numbers and also adjust the vertical alignment, you should be good to go. The downside is, you will not have nice view in extremely small or large screens.
My 2 cents.


text:
Q: Django: Return 'None' from OneToOneField if related object doesn't exist? I've got a Django class like this:
class Breakfast(m.Model):
    # egg = m.OneToOneField(Egg)
    ...

class Egg(m.Model):
    breakfast = m.OneToOneField(Breakfast, related_name="egg")

Is it possible to have breakfast.egg == None if there is no Egg related to the Breakfast?
Edit: Forgot to mention: I'd rather not change the related_name to something like related_name="_egg", then have something like:
@property
def egg(self):
    try:
        return self.egg
    except ...:
        return None

Because I use the name egg in queries, and I'd rather not have to change the queries to using _egg.

A: I just ran into this problem, and found an odd solution to it: if you select_related(), then the attribute will be None if no related row exists, instead of raising an error.
>>> print Breakfast.objects.get(pk=1).egg
Traceback (most recent call last):
...
DoesNotExist: Egg matching query does not exist

>>> print Breakfast.objects.select_related("egg").get(pk=1).egg
None

I have no idea if this can be considered a stable feature though.

A: I know that on ForeignKey you can have null=True when you want to allow the model not to point to any other model. OneToOne is only a special case of a ForeignKey:
class Place(models.Model)
    address = models.CharField(max_length=80)
class Shop(models.Model)
    place = models.OneToOneField(Place, null=True)
    name = models.CharField(max_length=50)
    website = models.URLField()

>>>s1 = Shop.objects.create(name='Shop', website='shop.com')
>>>print s1.place
None

A: Django 1.10 solution as by Fedor at accepted answer:
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import OneToOneField
from django.db.models.fields.related_descriptors import ReverseOneToOneDescriptor

class ReverseOneToOneOrNoneDescriptor(ReverseOneToOneDescriptor):
    def __get__(self, instance, cls=None):
        try:
            return super(ReverseOneToOneOrNoneDescriptor, self).__get__(instance=instance, cls=cls)
        except ObjectDoesNotExist:
            return None

class OneToOneOrNoneField(models.OneToOneField):
    """A OneToOneField that returns None if the related object doesn't exist"""
    related_accessor_class = ReverseOneToOneOrNoneDescriptor

A: This custom django field will do exactly what you want:
class SingleRelatedObjectDescriptorReturnsNone(SingleRelatedObjectDescriptor):
    def __get__(self, *args, **kwargs):
        try:
            return super(SingleRelatedObjectDescriptorReturnsNone, self).__get__(*args, **kwargs)
        except ObjectDoesNotExist:
            return None

class OneToOneOrNoneField(models.OneToOneField):
    """A OneToOneField that returns None if the related object doesn't exist"""
    related_accessor_class = SingleRelatedObjectDescriptorReturnsNone

To use it:
class Breakfast(models.Model):
    pass
    # other fields

class Egg(m.Model):
    breakfast = OneToOneOrNoneField(Breakfast, related_name="egg")

breakfast = Breakfast()
assert breakfast.egg == None

A: OmerGertel did already point out the null option. However, if I understand your logical model right, then what you actually need is a unique and nullable foreign key from Breakfast to Egg. So a breakfast may or may not have an egg, and a particular egg can only be associated with one breakfast.
I used this model:
class Egg(models.Model):
    quality = models.CharField(max_length=50)
    def __unicode__(self):
        return self.quality

class Breakfast(models.Model):
    dish = models.TextField()
    egg = models.ForeignKey(Egg, unique=True, null=True, blank=True)
    def __unicode__(self):
        return self.dish[:30]

and this admin definition:
class EggAdmin(admin.ModelAdmin):
    pass

class BreakfastAdmin(admin.ModelAdmin):
    pass

admin.site.register(Egg, EggAdmin)
admin.site.register(Breakfast, BreakfastAdmin)

Then I could create and assign an egg in the edit page for a breakfast, or just do not assign one. In the latter case, the egg property of the breakfast was None. A particular egg already assigned to some breakfast could not be selected for another one.
EDIT:
As OmerGertel already said in his comment, you could alternatively write this:
    egg = models.OneToOneField(Egg, null=True, blank=True)

A: I would recommend using try / except Egg.DoesNotExist whenever you need to access Breakfast.egg; doing so makes it very clear what's going on for people reading your code, and this is the canonical way of handling nonexistent records in Django.
If you really want to avoid cluttering your code with try / excepts, you could define a get_egg method on Breakfast like so:
def get_egg(self):
    """ Fetches the egg associated with this `Breakfast`.

    Returns `None` if no egg is found.
    """
    try:
        return self.egg
    except Egg.DoesNotExist:
        return None

This will make it clearer to people reading your code that eggs are derived, and it may hint at the fact that a lookup gets performed when one calls Breakfast.get_egg().
Personally, I'd go for the former approach in order to keep things as clear as possible, but I could see why one may be inclined to use the latter approach instead.


text:
Q: kivy VirtualMachine for python for android gives (initramfs) udev97 : timeout killing '/sbin/blkid -o udev -p /dev/sda1' [188] I am new to kivy module and learnt that to compile a Kivy app for android on a virtual box is provided with all requisite software installed.
I have done the following:

*

*Downloaded the Kivy_Python_for_android.7z from https://docs.google.com/uc?export=download&confirm=no_antivirus&id=0B1WO07-OL50_bTR0SElrLTZGWEU

*Extracted the file Kivy_Python_for_android.vdi

*Downloaded a Oracle VM VirtualBox v3.2.6

*Created a virtual machine pointing it to Kivy_Python_for_android.vdi image and started machine

However when machine starts it gives following error again and again :
(initramfs) udev97 : timeout killing '/sbin/blkid -o udev -p /dev/sda1' [188]

As per documentation on http://kivy.org/docs/guide/packaging-android.html there should be a directory named, distribution on the virtual image but I can't find any. Also Python was not installed on it. Please advice.


text:
Q: Creating list of times from 7:30 to 22:30 I'm trying to create list of dateTimes from  2015-04-18 to 2015-11-13 (Saturdays and Sundays only), with the times of 7:00 to 22:30 . The code I have so far is:
dates <- seq(as.Date("2015-04-18"),as.Date("2015-11-13"),1)
weekdays<- weekdays(dates)
times<-format(seq(as.POSIXct("2015-04-18 7:30:00"),as.POSIXct("2015-04-18 22:30:00"),by="30 min"),format="%H:%M")
res <- data.frame(dates,weekdays)
res<-res[res$weekdays=="Sunday" | res$weekdays=="Saturday",]

The paste() function won't work because it 'recycles' the values. So, basically I want a set of values that looks like this:
"2015-10-03 7:30 PDT"
"2015-10-03 8:00 PDT"
"2015-10-03 8:30 PDT"
"2015-10-03 9:00 PDT"
etc

For each day in the sequence. I have a feeling it is an apply() function that will accomplish this but I'm not proficient with them.

A: You can use expand.grid to find all combinations:
combo <- with(expand.grid(as.character(times), as.character(res$dates)), paste(Var2, Var1))
head(combo)
# [1] "2015-04-18 07:30" "2015-04-18 08:00" "2015-04-18 08:30" "2015-04-18 09:00" "2015-04-18 09:30"
# [6] "2015-04-18 10:00"


text:
Q: Eclipse.ini file not present in windows 7 In my eclipse am getting this error An internal error occurred during: "Building workspace". Java heap space

For that i surfed online. they told to edit the eclipse.ini file. The eclipse.ini file is located in the eclipse home directory. When i searched into my eclipse home directory. eclipse.ini file is not present.


text:
Q: Setting up authorization requestfilter on JAX-RS backend with Firebase I am following this (pretty great) guide to trying to implement an Authorization filter for my REST backend. However, I'd like to use the authorization module from Firebase, so my 'verify token' should verify tokens with firebase.
I've tried to implement it like this:
private void validateToken(String token, final ContainerRequestContext requestContext) throws Exception {
    FirebaseAuth.getInstance().verifyIdToken(token)
            .addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {

                @Override
                public void onSuccess(FirebaseToken decodedToken) {
                    System.out.println("success");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    System.out.println("fail" + e);
                    requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
                }

            }).addOnCompleteListener(new OnCompleteListener<FirebaseToken>() {
                @Override
                public void onComplete(@NonNull Task<FirebaseToken> task) {

                }
    });
}

But the problem is the listeners are of course running in a different thread, so as it looks now, the request will go through and the onFailure listener won't be able to abort it.
I've made it work just by adding a sleep timer in the bottom, however I'd like a better solution. I've tried to lock the main thread using synchronized, trying to unlock it in the onCompleteListener, but haven't been able to make it work.
Is there any nice way to work around this?
Thanks in advance!

A: I managed to make it work using the CountDownLatch. Big thanks too peeskillet!
For anyone interested, my solution looks like this:
    private void validateToken(String token, final ContainerRequestContext requestContext) throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);

    FirebaseAuth.getInstance().verifyIdToken(token)
            .addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {
                @Override
                public void onSuccess(FirebaseToken decodedToken) {
                    System.out.println("on success");
                    latch.countDown();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    System.out.println("on fail " + e);
                    requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
                    latch.countDown();
            }
        });
    latch.await();
}


text:
Q: Marginal Effects of GLMM in R I am trying to calculate the marginal effects of covariates estimated using "glmer" from package lme4.I am using the code provided in http://researchrepository.ucd.ie/bitstream/handle/10197/3404/WP11_22.pdf?sequence=1. The code does not give standard errors for specific variable. What might be the reason for this and how can i fix it.Here is the code used;
glm3 <-glmer(Distance~Weather+Gender+Time+`(1|Population),data = pr,family = binomial('logit'),control = glmerControl(optimizer = "bobyqa"),nAGQ = 1)`
glmermfx<-function(x,nsims = 1000){
set.seed(70)
pdf<-mean(dlogis(-log((1-fitted(x))/fitted(x))))
pdfsd<-sd(dlogis(-log((1-fitted(x))/fitted(x))))
marginal.effects<-pdf*fixef(x)
  sim<-matrix(rep(NA,nsims*length(fixef(x))),nrow=nsims)
  for(i in 1:length(fixef(x))){
    sim[,i]<-rnorm(nsims,fixef(x)[i],diag(vcov(x)^0.5)[i])
  }
  pdfsim<-rnorm(nsims,pdf,pdfsd)
  sim.se<-pdfsim*sim
  res<-cbind(marginal.effects,sd(sim.se))
  colnames(res)[2]<-"standard.error"
  ifelse(names(fixef(x))[1]=="(Intercept)",
         return(res[2:nrow(res),]),return(res))
}

glmermfx(glm3)

And the output looks like this
    marginal.effects standard.error
Weather                 0.03913997      0.1085925
Gender                  0.05745454      0.1085925
Time                   -0.05135142      0.1085925


text: Q: Sudo su is not picking up the password When I type command like sudo su,su or sudo -i, I get the space to enter the password. But the problem is when I type the password it is not entered in the terminal. I tried pressing Enter then typing the password but no help. In GUI based password dialogs (like unlocking Ubuntu while booting) it is working fine. Is there any alternative for a root access terminal in Ubuntu LTS 18.04.3?


text:
Q: Python 3.4 code to load a csv file into MySql I am new to Python and I am using python 3.4 and would like to write a script to load data from a csv file(with just 2 cols- emp_id, emp_name) into a MySQL DB table. Anybody have sample code? Please help.

A: You don't need Python for that. You don't even need a program for that. MySQL has a statement for reading CSV files.
See: https://dev.mysql.com/doc/refman/5.1/en/load-data.html , from the documentation:
LOAD DATA INFILE can be used to read files obtained from external sources. For
example, many programs can export data in comma-separated values (CSV) format,
such that lines have fields separated by commas and enclosed within double
quotation marks, with an initial line of column names. If the lines in such a
file are terminated by carriage return/newline pairs, the statement shown here
illustrates the field- and line-handling options you would use to load the file:

LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;

If the input values are not necessarily enclosed within quotation marks, use
OPTIONALLY before the ENCLOSED BY keywords.

Apart from that, MySQL also comes with a program called mysqlimport which can do that too.


text:
Q: mailto link not working in Visualforce page In my Visualforce page i have give the following line to open email to support group.
<apex:outputLink value="mailto:supportgroup@abccorp.com">

When i click the link nothing is happening. Need help in fixing this.
Thanks,
IRaj


text:
Q: Python type hint for variable of a specific type, from a specific class/enum Let's say I have a class with this two variables:
class MyClass:
    FOO: str = "simple string 1"
    BAR: str = "simple string 2"

def myFunc(data: MyClass) -> MyClass:
    ...

I want to write a function myFunc() that accept one of the variables from MyClass (example: FOO) and return one of the variables of MyClass (example: BAR). I know what I want to be passed to this func - I know the types of these variables - so this function type hints could be also written as:
def myFunc(data: str) -> str:
    ...

The problem here is that - although type checker is happy with it - user lost the important info of what are the possible values. What I want is that user know in this function can be passed only string, but must be from a specific class - in this case, I want user to pass a str value from class MyClass.
def myFunc(data: SomeTypeHintSyntax[str, MyClass]) -> SomeTypeHintSyntax[str, MyClass]:
    ...

Q: Is there a simple way to tell user where data of type str should come from?
If type hint would suggest that data should come from Myclass, user can than use IDE to pass possible values by:


text:
Q: How to fix "Unable to start an example program using cgal and boost library in VS 16 2019. Cannot create the ALL_BUILD file."? I'm having trouble in running a program with CGAL and Boost library on Visual Studio 16. It shows a message saying the 'ALL_BUILD' path is not available, hence it is unable to start the program. What should I do?

A: ALL_BUILD is a convenience target that builds all targets. It is not an executable. Select another target in the solution, like a test or an example,  to run.


text:
Q: CSV manipulation using php Hey everyone I am learning some php and manipulating some csv files here. I'm creating a random key generator for some courses. Basically I am adding a new column with the keys for a course.
I have managed to do this. However when I run my script I get an extra row being read and a key generated for that. Example if I have 3 courses A,B,C then 4 keys would be generated and added to the csv.
Can I have some help or tips on reading and writing to a csv?
<?php
$file= fopen("input.csv","r");
$output=fopen("output.csv","w");
function gen_keys($length=10)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

//echo gen_keys();
$list=array();
while(!feof($file))
{

    //print_r(fgetcsv($file));
    $list=fgetcsv($file);
    //$list=array_filter($list);
    $list[]=gen_keys();
    echo "
";
    print_r($list);
    fputcsv($output, $list);
    //print_r(fgetcsv($output));

}
fclose($file);
fclose($output);?>

Input :
comp1400
comp2000
info2425
eng1234

A: Here is updated and working version:
$list=fgetcsv($file);
if (!empty($list)) {
    //$list=array_filter($list);
    $list[]=gen_keys();
    echo "
";
    print_r($list);
    fputcsv($output, $list);
}

Please note line with if (!empty($list)) { it checks if we have any imput.
More information about empty() in documentation.

A: <?php
$infp = fopen("in.csv", "r");
$outfp = fopen("out.csv", "w");

while(!feof($infp)) {
  $list = fgetcsv($infp);
  // change $list and write to output
  fputcsv($outfp, $list);
}


text:
Q: Can I use ng-repeat within one object? I'm trying to display pictures saved in my factory.
This is my factory:
[
    {
        id: 01,
        title: 'Kabinet in hoger beroep tegen klimaatvonnis',
        text: '...',
        date: '31 oktober, 2015',
        image: 'post1.jpg',
        introtext: '...'
    },
    {
        id: 02,
        title: 'Leraren kritisch over passend onderwijs',
        text: '...',
        date: '05 mei, 2014',
        image: 'post2.jpg',
        image: 'post6.jpg',
        introtext: '...'
    },
    {
        id: 03,
        title: 'Premier Curaçao dient ontslag in',
        text: '...',
        date: '14 april, 2015',
        image: 'post3.jpg',
        image: 'post8.jpg',
        introtext: '...'
    },
    {
        id: 04,
        title: 'Asscher heeft nog geen akkoord met Marokko over uitkeringen',
        text: '...',
        date: '25 januari, 2015',
        image: 'post4.jpg',
        introtext: '...'
    }

]
here I want to display it:

{{ currentNieuwsbericht.title }}

        {{ currentNieuwsbericht.date }}

                {{ currentNieuwsbericht.introtext }}

{{ currentNieuwsbericht.text }}

I know the ng-repeat that you see now in my code doesn't work but I want something like that, because not every post has more picture.
I hope you understand my problem if you don't just ask what you need to know I'm already struggling with this a whole day.

A: What you are doing will just override the attribute image value.
Make image an array
{
    id: 02,
    title: 'Leraren kritisch over passend onderwijs',
    text: '...',
    date: '05 mei, 2014',
    image: ['post2.jpg','post6.jpg'],
    introtext: '...'
}

So in your JS you can easily iterate image

PS: Please use proper naming convention. ng-repeat should be like:
ng-repeat="currentImage in images"

A: You will not receive an error when you have JSON with duplicate key names. However, when you try getting the value, you will get the value of the last property. You should change your data structure to something like images: ['img1.jpg', 'img2.jpg'] ant let ngRepeat iterate that.


text:
Q: How disable JFrame Background I've made a JFrame with the next Properties:
setLayout(null)
setUndecorated(true)
setResizable(false)

within i've put a JLabel with one Icon(PNG image) in netbeans, and im looking for some soluction that disable the backgroud(full Transparent, and unactive) when the mouse moves THROUGH JFrame's Image(or someother component) BUT the mouse works different outside of the JLabel because JLabel Icon avoid any mouse action over the JLabel. But there's a default Gray background that doesnt exactly what i want.
We can see that mouse doesnt do anything on the JLabel(unless there were some component in the Frame)

Green = JFrame size.
And here the mouse change when moves through of the web page

A:
im looking for some soluction that disable the backgroud(full Transparent, and unactive) when the mouse moves

Don't use full transparency.
If the pixels are not 100% transparent, then the MouseEvents will be handled by the frame.


text:
Q: AWS Lambda : CodePipeline job never ends, even after retuning sucess I am working on executing an AWS Lambda code from Code-pipeline. I have given the lambda role full access to EC2 and code-deploy. The commands generally work when I am not triggering them from code-pipeline. When Triggered from code-pipeline, they just keep on running, even though success is sent. What am i doing wrong?
Code :
import boto3
import json

def lambda_handler(event, context):
    reservations = boto3.client('ec2').describe_instances()['Reservations']
    instances_list = []
    process_instance_list = []
    command = 'COMMAND TO EXECUTE ON SERVER'
    ssm = boto3.client('ssm')
    for res in reservations:
      instances = res['Instances']
      for inst in res['Instances']:
        for tag in inst['Tags']:
            #print("Tag value is {}".format(tag['Value']))
            if tag['Value']=='Ubuntu_Magento':
               print("{} {} {}".format(tag['Value'], inst['InstanceId'], inst['LaunchTime']))
               instances_list.append(inst)

    instances_list.sort(key=lambda x: x['LaunchTime'])
    instance_id = instances_list[0]['InstanceId']
    ssmresponse = ssm.send_command(InstanceIds=[instance_id], DocumentName='AWS-RunShellScript', Parameters= { 'commands': [command]})
    code_pipeline = boto3.client('codepipeline')
    job_id = event['CodePipeline.job']['id']
    code_pipeline.put_job_success_result(jobId=job_Id)

A: Any lambda by default has lifespan of 15 mins only, after that it exits no matter what. I think it has something to do with the way you are trigger it.


text:
Q: Algorithm to Find the Aggregate Mass of "Granola Bar"-Like Structures? I'm a planetary science researcher and one project I'm working on is N-body simulations of Saturn's rings.  The goal of this particular study is to watch as particles clump together under their own self-gravity and measure the aggregate mass of the clumps versus the mean velocity of all particles in the cell.  We're trying to figure out if this can explain some observations made by the Cassini spacecraft during the Saturnian summer solstice when large structures were seen casting shadows on the nearly edge-on rings.  Below is a screenshot of what any given timestep looks like.  (Each particle is 2 m in diameter and the simulation cell itself is around 700 m across.)

The code I'm using already spits out the mean velocity at every timestep.  What I need to do is figure out a way to determine the mass of particles in the clumps and NOT the stray particles between them.  I know every particle's position, mass, size, etc., but I don't know easily that, say, particles 30,000-40,000 along with 102,000-105,000 make up one strand that to the human eye is obvious.
So, the algorithm I need to write would need to be a code with as few user-entered parameters as possible (for replicability and objectivity) that would go through all the particle positions, figure out what particles belong to clumps, and then calculate the mass.  It would be great if it could do it for "each" clump/strand as opposed to everything over the cell, but I don't think I actually need it to separate them out.
The only thing I was thinking of was doing some sort of N2 distance calculation where I'd calculate the distance between every particle and if, say, the closest 100 particles were within a certain distance, then that particle would be considered part of a cluster.  But that seems pretty sloppy and I was hoping that you CS folks and programmers might know of a more elegant solution?

Edited with My Solution:  What I did was to take a sort of nearest-neighbor / cluster approach and do the quick-n-dirty N2 implementation first.  So, take every particle, calculate distance to all other particles, and the threshold for in a cluster or not was whether there were N particles within d distance (two parameters that have to be set a priori, unfortunately, but as was said by some responses/comments, I wasn't going to get away with not having some of those).
I then sped it up by not sorting distances but simply doing an order N search and increment a counter for the particles within d, and that sped stuff up by a factor of 6.  Then I added a "stupid programmer's tree" (because I know next to nothing about tree codes).  I divide up the simulation cell into a set number of grids (best results when grid size ≈7 d) where the main grid lines up with the cell, one grid is offset by half in x and y, and the other two are offset by 1/4 in ±x and ±y.  The code then divides particles into the grids, then each particle N only has to have distances calculated to the other particles in that cell.
Theoretically, if this were a real tree, I should get order N*log(N) as opposed to N2 speeds.  I got somewhere between the two, where for a 50,000-particle sub-set I got a 17x increase in speed, and for a 150,000-particle cell, I got a 38x increase in speed.  12 seconds for the first, 53 seconds for the second, 460 seconds for a 500,000-particle cell.  Those are comparable speeds to how long the code takes to run the simulation 1 timestep forward, so that's reasonable at this point.  Oh -- and it's fully threaded, so it'll take as many processors as I can throw at it.

A: My first suggestion is to cut up your problem into two problems: first, figure out what you want and then figure out how to efficiently get what you want. You can't efficiently get something you haven't defined yet. I'll put some ideas in this answer that may help you find this definition. I suggest you make an inefficient implementation of the ideas you like first, apply it to a few not-too-large datasets, evaluate the results by hand, adapt your definition and repeat (possibly asking another question here), until you are happy with your definition. After that, I suggest you ask another question on how to efficiently compute the result of your definition (if you still need help).
So, let's see what would correspond with our intuitive idea of a 'strand'. Your strands seem to consist of roughly uniformly distributed points, though you should check this by making a zoomed-in picture (of the original dataset) - the resolution of your picture is too low to say with certainty that the points really are roughly uniformly distributed. I'll assume they are for this answer.
An initial idea may be to look at the nearest neighbor of every point. Let's pick a point X, call its nearest neighbor Y and set D as the distance between X and Y. We then look at the circle C around X with radius D*A, where A is a tuning parameter, say A=3. If X is part of a strand, we expect that for every point Z in C, the distance from Z to its nearest neighbor W is about the same as D. If it is significantly shorter, say more than A (or maybe some other parameter B) then X is apparently near to points that are much nearer to each other than to X, so X is probably not part of a strand.
This criterion is not complete however. It only gives a criterion to detect a 'border' between between areas dense with points and areas less dense with points. We still have to cluster points together into strands.
There is a feature in your picture that shows that this is not simple. In the lower-right corner of your picture, there is a relatively large area with a lot of stray points. These stray points are themselves roughly uniformly distributed, so if we were to remove all points in the strand around it (and all other points), then we would expect any strand-detecting algorithm to mark this set of stray points as a strand! We therefore need to be careful when making our clusters.
An idea may be to do the following. We are going to make a graph on these points, where the vertices are the points and edges signify that two points have similar density. For every point, we check the criterion above. If it checks out, we connect X with an edge to all points in C. If it does not check out, we do not add any edge, and mark X as 'stray'. After doing this for every point, we consider the set of connected components. These should consist of a single (in the case of your picture, but other datasets may have multiple) connected component consisting of all points in strands, plus (potentially a lot) more components consisting of single stray points and these 'stray strands'. However, these stray strands have points in them that have been marked as 'stray', so you can simply ignore any component containing a point that has been marked as 'stray'.
A danger of this idea is that you may have a feature where the density of a strand progressively lowers as you move along the strand, until the density is so low that it is just a set of stray points. As our criterion is 'local', it may not detect this and mark these stray points as part of the strand. I'm not sure if this will be a problem: I'd guess most stray points should be caught by the criterion, as changes in density seem quite abrupt in your picture.
If this problem does occur, you could try an alternative to just taking the connected components. For every point X, we calculate the distance to its nearest neighbor D(X). We start at the point with minimal D(X) and perform a BFS (or DFS, the order doesn't matter). We add any point Y whose D(Y) is not much larger than the D(X) (by a tunable factor) we started with. If we do encounter a point Y that has too large D(Y), we remove the edge (X, Y), mark Y as 'stray' and act as if we never visited Y in our BFS. If tuned right, this should prevent the problem I describe above.
An alternative idea to fix this problem acts a bit more local: you could do a BFS and keep track of the lowest D(X) (I use D(X) as a measure of the density around a point) encountered at most say 10 BFS-steps before, and if we encounter a Y that has D(Y) that is much larger than this D(X), we do the same as the other (potential) solution I offered.
As a disclaimer: all the ideas above I thought up on the spot just now, I don't really know if this particular problem has been studied before, so I may just be sprouting nonsense. Just try out the ideas (whether my ideas or your own) that sound sensible to you and find out if they really work, and only then focus on implementing them efficiently.

A: Using modular decomposition you can create a tree that will contain all particles as leafs and upper nodes will cluster these. Based on that tree you can define measures that are applied to every node of it from the root to the leafs downwards. You stop this downwards traversal when the measurements reach user defined thresholds. One such measurement may be the density of the convex hull of all particles in a cluster.

A: I think you're after a machine learning clustering algorithm.
This page from the Python SciKit Learn toolkit has pictures that suggest the DBSCAN algorithm (Wikipedia) could be what you're looking for.  It seems ideal as it's input parameter is the neighbourhood size, while most other clustering algorithms want the number of clusters, which you would not know in advance.
"A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise" Ester, M., H. P. Kriegel, J. Sander, and X. Xu, In Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996

A: I have been thinking about this problem. I am not a physics expert, so bear with me.
It seems that it is not the distance between the particles that counts to determine the clumps. It is whether or not the gravity fields overlap.
Take a particle P, and determine what other particles have overlapping gravity fields.
Then take one of those and do the same thing. Your goal is not to find all the particles in the clump but to find its boundaries.
Repeat this until all the clumps are found.
Now go back and determine the mass of the clumps. You will have eliminated stray particles, and you can use the clump boundaries to find the mass.
I am not sure if this helps, but it is all I could think of.

A: You could, at the end of each timestep, convert the data into a graph, compute the minimum spanning tree, and then begin to remove edges that exceed a certain threshold. That should give you clumps and an easy way to enumerate through the particles in each clump.


text:
Q: ContextMenu position is unpredictable when I'm trying to show same instance of menu more than once I need to show ContextMenu at specific location and it works just fine the first time. If I move mouse cursor and try to show the same ContextMenu, then it may show up at different location, even if HorizontalOffset and VerticalOffset is hardcoded.
How can I open ContextMenu at specific location without reinitializing it each time?
System.Windows.Controls.Input.Toolkit version: 5.0.5.0
XAML
<Grid x:Name="LayoutRoot" Background="White"
      MouseRightButtonUp="LayoutRoot_MouseRightButtonUp"
      MouseRightButtonDown="LayoutRoot_MouseRightButtonDown"/>

Code
private ContextMenu menu;

private void LayoutRoot_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    if (menu == null)
    {
        menu = new ContextMenu();
        menu.Items.Add("test");
    }

    menu.HorizontalOffset = 100;
    menu.VerticalOffset = 100;

    menu.IsOpen = true;
}

private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
}

A: There appears to be a bug in the ContextMenu. It's not picking up the mouse pointer position on the first click.
Here's a workaround:
private void LayoutRoot_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    if (menu == null)
    {
        menu = new ContextMenu();
        menu.Items.Add("test");
        menu.HorizontalOffset = 100;
        menu.VerticalOffset = 100;
    }
    else
    {
        menu.HorizontalOffset = 100 - e.GetPosition(null).X;
        menu.VerticalOffset = 100 - e.GetPosition(null).Y;
    }

    menu.IsOpen = true;
}

Update:
I had a closer look at the disassembled sources, and it appears that once a ContextMenu is shown, MouseTracking is enabled, which is why we need to adjust the offset to cancel out the effect of ContextMenu trying to adjust it's position based on the last mousemove event, not the last MouseRightButtonUp position. Here's a revised code sample to account for it:
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        LayoutRoot.MouseRightButtonDown += LayoutRoot_MouseRightButtonDown;
        LayoutRoot.MouseRightButtonUp += LayoutRoot_MouseRightButtonUp;
        LayoutRoot.MouseMove += LayoutRoot_MouseMove;
        SetupContextMenu();
    }

    private void SetupContextMenu()
    {
        if (menu == null)
        {
            menu = new ContextMenu();
            menu.Items.Add("test");
            ContextMenuService.SetContextMenu(this, menu);
        }

    }

    private ContextMenu menu;

    private void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
    {
        var mousePosition = e.GetPosition(this);
        menu.HorizontalOffset = 100 - mousePosition.X;
        menu.VerticalOffset = 100 - mousePosition.Y;
    }

    private void LayoutRoot_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        menu.IsOpen = true;
    }

    private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        e.Handled = true;
    }
}