Q:

Jquery Living Elements

Does anybody know how to deal with the effect at http://2crossmedia.com/liv-multicolor/
If you click into the text field, its surrounded by a color-changing line.
The code says it's jquery. But how :) ?
A lot of thanks!

A:

That's pretty cool. It uses 3 images:

http://2crossmedia.com/liv-multicolor/images/input-mask.png
http://2crossmedia.com/liv-multicolor/images/gradient.png
http://2crossmedia.com/liv-multicolor/images/input-bg.png

The mask is a semi-transparent png with transparent parts where the gradient comes through. So they just fade in the gradient behind the mask. Then they just pan it using a timeout. Something like:

#gradient starts out with opacity = 0. Then you do something like: $("#gradient").fadeIn().


Q:

Multiplier algebra of $A \otimes \mathcal{K}$

If $A$ is unital C$^*$-algebra, is it true that the multiplier algebra of $A \otimes \mathcal{K} $ is $ A \otimes \mathcal{B}(\mathcal{H})$? Where $\mathcal{K}$ is  C$^*$-algebra of compact operators on the Hilbert space $\mathcal{H}$.

A:

If $A=C_0(X)$ and $B$ is a $C^\ast$-algebra then $M(A\otimes B)$ is the set of strictly continuous functions $\beta X\to M(B)$, where $\beta$ stands for Stone-Čech compactification.
If you take $X$ to be compact and $B=\mathcal{K}$ then we are in your setting.
But $C(X)\otimes\mathcal{B(H)}$ is the set of norm-continuos functions $\beta X=X\to\mathcal{B(H)}$. The strict topology is the $\sigma$-strong-$^\ast$ topology on $\mathcal{B(H)}$, which is different form the norm topology. This should answer your question in the negative.

A:

The fact stated in the answer by vap is proven in the paper "Multipliers of C*-algebras" by Akemann, Pedersen and Tomiyama (see Theorem 3.3, I guess). Moreover, they prove in Theorem 3.8 that multiplier algebras are not very well behaved with respect to minimal tensor products:

Let $A$ and $B$ be $C^*$-algebras and assume that $B$ has a countable
  approximate unit, but no unit (think of $\mathcal{K}$ here in your
  case) and that $A$ is infinite dimensional. Then
  $$
M(A) \otimes M(B) \subsetneq M(A \otimes B)
$$
  where the tensor product is the minimal one.

So, in particular, for any infinite dimensional unital $C^*$-algebra $A$, the tensor product $A \otimes \mathcal{B}(\mathcal{H})$ is always a proper subalgebra of $M(A \otimes \mathcal{K})$.


Q:

Message type system for multiple users

I have an idea for a project that will allow users in Windows to request access to a directory using a message type system. As an example, assume that there are 30 users in a Windows Server environment. Two users have the ability to grant access to a Windows Directory. I want to create a program that allows users to request the access by selecting the directory from a drop down box. The request is then sent to both people who have the ability to grant access. I am imagining some pop-up will come up near the task bar to alert the user of this request. Once granted, the initiating user will be alerted and the request will be cleared (or logged into some file).
I have a bit of C# experience and DB experience with SQL, however I am not sure how I will go about running the back end and handling of messages. I was thinking I could store the requests in a SQL database (two fields - Directory and Requesting user ID) and make it refresh the table into the program every 5 mins but this seems a bit overkill. Is there an easier way to do this? No need to worry about security of the file or database.
Cheers in advance.

A:

Just decided to create a file for each request in a directory which is then scanned on a fixed frequency by the program. Seems easier this way given the small number of users and then I won't be wasting resources by opening database connections every 2 minutes.


Q:

How to use groupBy in Backbone.js to group collections?

An example collection (showing models only):
[
    {
        name: "Bob"
        date: "Thu Mar 29 2012"
    },
    {
        name: "James"
        date: "Fri Mar 30 2012"
    },
    {
        name: "Dylan"
        date: "Fri Mar 30 2012"
    },
    {
        name: "Stanley"
        date: "Sat Mar 31 2012"
    },
]

How can I use Underscore.js' groupBy function to group models with the same date?

A:

If you are grouping an actual backbone collection you can use the backbone method groupBy which implicitly uses underscore _.groupBy functionality.  This is a much cleaner approach in my opinion.
collection.groupBy( function(model){
  return model.get('date');
});

A:

ThiefMaster answer is perfectly valid, but it caused me some confusion because I was searching a solution for a backbone.js collection as the title indicates.
If the question object is a backbone collection we should do the following to group the models by date:
_.groupBy(collection.models, function(model){
    return model.get('date')
});

I hope it helps

A:

Use _.groupBy(data, 'date');
You could also use pass a custom function, but in this case it's not necessary as the attribute shortcut syntax above works fine.
_.groupBy(data, function(row) {
    return row.date;
});

Demo:
> _.groupBy(data, 'date')
{ 'Thu Mar 29 2012': [ { name: 'Bob', date: 'Thu Mar 29 2012' } ],
  'Fri Mar 30 2012':
   [ { name: 'James', date: 'Fri Mar 30 2012' },
     { name: 'Dylan', date: 'Fri Mar 30 2012' } ],
  'Sat Mar 31 2012': [ { name: 'Stanley', date: 'Sat Mar 31 2012' } ] }
> _.groupBy(data, function(row) { return row.date });
{ 'Thu Mar 29 2012': [ { name: 'Bob', date: 'Thu Mar 29 2012' } ],
  'Fri Mar 30 2012':
   [ { name: 'James', date: 'Fri Mar 30 2012' },
     { name: 'Dylan', date: 'Fri Mar 30 2012' } ],
  'Sat Mar 31 2012': [ { name: 'Stanley', date: 'Sat Mar 31 2012' } ] }
>


Q:

Emacs xml mode indent with tabs

i desperately try to make my emacs xml (sgml?) mode indent with tabs instead of spaces.
What i tried so far:
(defun my-xml-hook ()
  (setq c-tab-always-indent t
        tab-width 4
        indent-tabs-mode t) ; use tabs for indentation
  (setq indent-line-function 'insert-tab)
)
(add-hook 'xml-mode-hook 'my-xml-hook)
(defun local-sgml-mode-hook
  (setq fill-column 70
        indent-tabs-mode t
        next-line-add-newlines nil
        sgml-indent-data t)
  (auto-fill-mode t)
  (setq indent-line-function 'insert-tab)
  )
(add-hook 'psgml-mode-hook '(lambda () (local-psgml-mode-hook)))

Nothing works though, indentation will still happen with 2 spaces (emacs23 and emacs24) when editing *.xml files.
Note that i also have
(setq indent-tabs-mode nil)

in my .emacs file, but the hook should be called afterwards so this should be overridden.
How can i force emacs to indent with tabs in *.xml files? Why are my hooks not working?

A:

(c-)tab-always-indent controls what hitting the TAB key does, not what is inserted.
Setting indent-line-function to insert-tab will make you lose the smart indentation of the mode.
If you are using a modern emacs, chances are you are using nxml-mode instead of xml-mode.  In that case nxml-mode-hook should be the one where you should do (setq indent-tabs-mode t).
If you are using default sgml mode, sgml-mode-hook should be the one where you should do (setq indent-tabs-mode t) should be done (in your snippet you are using psgml-mode-hook)
(and tab-always-indent and indent-line-function could be leave in their default states)
EDIT
To summarize conversation below: variable nxml-child-indent should not be less than tab-width.
(and since default emacs values for those variables are 2 and 8, imho configuring emacs to indent XML using tabs in emacs is harder than it should be)

A:

It took me quite a while to get nxml-mode to use tabs.  I ended up using smart-tabs-mode, which offers a concise solution.  For what it's worth, here is the configuration that I finally settled on:
;; indentation using smart-tabs-mode
(setq-default tab-width 4)
(smart-tabs-insinuate 'c 'c++ 'java 'javascript 'cperl 'python 'ruby 'nxml)

;; nxml-mode
(setq
    nxml-child-indent 4
    nxml-attribute-indent 4
    nxml-slash-auto-complete-flag t)

You don't actually need to set nxml-slash-auto-complete-flag, but it gets you auto end-tag completion, which is really nice.


Q:

Showing symmetry involving a matrix and its transposed matrix

I'd appreciate if someone could find a better title for this question, for I'm short of ideas right now.
Given a matrix $A \in R^{n,n}$, show that
$$
\frac{1}{2}(A + A^t)
$$
is symmetric.
I see that it's symmetric and it seems obvious, but I don't really know how to show that in particular.

A:

$(B+B^t)^t=B^t+(B^t)^t=B^t+B$
So $B+B^t$ is symmetric $\forall B\in R^{n\times n}$.
Take $B=A/2$ and you get the desired result.


Q:

codeigniter auto loading the database even though i removed from autoload.php

I am developing a site in php and I am using codeigniter as framework.
I removed database in $autoload['libraries'] from autoload.php. But it is showing error when i removed database credentials from database.php.
I don't understand the problem here.I must be able to load the site without a database connection. According to the documentation I just shouldn't load any database. But it is throwing an error. How to resolve this issue?
The error is:
Unable to connect to your database server using the provided settings.
Filename: C:\wamp\www\mlp\system\database\DB_driver.php

Line Number: 124

A:

You may be calling database library by loading it somewhere in your script. by using $this->library->load('database') try removing that. ... ELSE ...Try to clear your browser cache... Refresh the project once... Restart apache(if it doesnt work even after the previous two).


Q:

[Vue warn]: Unknown custom element

I am new to vuejs, While writing one js code inside laravel framework, I am getting error :
[Vue warn]: Unknown custom element: <app> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
App.js
import Vue from 'vue'
import Vcinfo from './Vcinfo.vue'
import router from './router'

const app = new Vue({
    el: '#vcinfo',
    components: { Vcinfo },
    template: '<app></app>',
    router
})

please suggest what to do?

A:

This is for future reader.
I made the mistake I had to use it like this.
import Vue from 'vue'
import Vcinfo from './Vcinfo.vue'
import router from './router'

const app = new Vue({
    el: '#vcinfo',
    components: { Vcinfo },
    template: '<vcinfo></vcinfo>',
    router
})

as per this import import Vcinfo from './Vcinfo.vue'


Q:

Powering Arduino Uno with 9 V LiPo batteries

Would it be safe to use two 9 V LiPo batteries in parallel to power an Arduino Uno?

A:

The short answer is NO, YOU CANNOT PARALLEL THE BATTERIES
In general paralleling LiPo batteries can be done but the "batteries" you point to are NOT good candidates. They are in fact NOT 9V batteries at all, they are single cell LiPos (4.3V max) with a DC-DC convertor producing a regulated 9V output.
Paralleling DC-DC convertors is bad news unless specifically designed to do so.
If you want to use more than one battery to power your Arduino you would need either:

Some power switching design to use first one then the other battery.
Some form of linear regulation that would allow current to be draw from two batteries.

As an example of what might be possible you could simply diode OR the two 'batteries' together using Schottcky diodes . This would stop the DC-DC convertors interacting. The two batteries WILL have different output voltage even if only a few mV. The diodes would ensure that the highest voltage 'battery' supplies the load. As it discharges then eventually there would be some sharing of current from each battery, though it would not be equal balancing.
If all you are powering is the Arduino this may be fine. It is unlikely to be suitable where you may be running motors or higher load current where you'd want an even balance between the two 'batteries'.


Q:

regex for comma separated dates in php

I have a problem to set regular expression for multiple dates with comma separator.
I have dates like as :
2017-03-25, 2017-03-27, 2017-03-28

please help me guys.....
i am trying to set php validation for selecting multi dates (jquery calender).
my regex is :
$value = "2017-03-25, 2017-03-27, 2017-03-28";
preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])([0-9])*$/",$value)

A:

You are matching only a single date with 0+ digits after it with your regex.
You may use the following fix:
^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$

See the regex demo
Details:

^ - start of string
([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])) - Group 1 matching and capturing a date-like substring
(?:,\s*(?1))* - zero or more sequences of:

,  - comma
\s* - 0+ whitespaces (remove * to only match one, or use ? to match 1 or 0 whitespaces)
(?1) - recurse Group 1 subpattern

$ - end of string.


Q:

PostgreSQL Select highest value within time period

Using Rails, I'm trying to perform a SQL command to return an array of rows that contain the highest value for a certain user per day.
For example:
  user_id(integer) |        created_at(datetime)    | score(integer)
-------------------+--------------------------------+---------------
              1    |      "2015-07-27 21:35:24"     |         100
              1    |      "2015-07-27 21:35:24"     |         123
              2    |      "2015-07-27 21:35:24"     |         101
              2    |      "2015-07-27 21:35:24"     |         122
              3    |      "2015-07-27 21:35:24"     |         103
              3    |      "2015-07-27 21:35:24"     |         115
              1    |      "2015-07-26 21:35:24"     |         116
              1    |      "2015-07-26 21:35:24"     |         151
              2    |      "2015-07-26 21:35:24"     |         122
              2    |      "2015-07-26 21:35:24"     |         134
              3    |      "2015-07-26 21:35:24"     |         123
              3    |      "2015-07-26 21:35:24"     |         111
              1    |      "2015-07-25 21:35:24"     |         129
              1    |      "2015-07-25 21:35:24"     |         152
              2    |      "2015-07-25 21:35:24"     |         120
              2    |      "2015-07-25 21:35:24"     |         109
              3    |      "2015-07-25 21:35:24"     |         142
              3    |      "2015-07-25 21:35:24"     |         131

Expected results:
  user_id(integer) |        created_at(datetime)    | score(integer)
-------------------+--------------------------------+---------------
              1    |      "2015-07-27 21:35:24"     |         123
              2    |      "2015-07-27 21:35:24"     |         122
              3    |      "2015-07-27 21:35:24"     |         115
              1    |      "2015-07-26 21:35:24"     |         151
              2    |      "2015-07-26 21:35:24"     |         134
              3    |      "2015-07-26 21:35:24"     |         123
              1    |      "2015-07-25 21:35:24"     |         152
              2    |      "2015-07-25 21:35:24"     |         120
              3    |      "2015-07-25 21:35:24"     |         142

I've been combining various joins, having, and other methods, but to no avail. I can't get it to filter the results. I've made a little bit of progress by selecting max values per day, but then I can't filter out the lower ones on a per user_id basis. I managed to do it using multiple group_by and map in Rails, but it's super slow since it has to re-iterate over the entire array, and since there is a lot of records, it can take some time.
EDIT:
My solution was as follows:
    all_scores_in_time_period = UserScore
      .where("EXTRACT(MONTH FROM created_at) = ?", Date::MONTHNAMES.index(params[:month_control]))
      .where("EXTRACT(YEAR FROM created_at) = ?", params[:year_control])
      .select("DISTINCT ON(DATE(created_at), user_id) *")
      .order("DATE(created_at) desc")

This first filters by month/year, and then returns a list of users by their top score per user per day.

A:

You can use distinct on () which is a Postgres extension to the distinct operator:
select distinct on (user_id, created_at) user_id, created_at, score
from the_table
order by user_id, created_at, score desc;

If you want solution using standard SQL, this can also be achieved using window functions:
select user_id, created_at, score
from (
  select user_id, created_at, score,
         row_number() over (partition by user_id, created_at order by score desc) as rn
  from the_table
) as t
order by user_id, created_at;

The solution with distinct on() is typically faster in Postgres.
With a window function you could also handle ties: when a user has the same (highest) score more than once on a day. The solution with row_number() will only return a single row per (user_id, created_at). If you want all rows with the same (highest) score, you need to use dense_rank() instead.
Edit
If you want to ignore the time part of the timestamp column, just cast it to a date:
created_at::date


Q:

How can one determine if a potato is suitable for French fries?

I often make French fries by cutting potatoes into long strips, adding a bit of oil and spices, then baking them in the oven. Sometimes, this tastes very good. Unfortunately, most of the time, it tastes terrible. After baking the potatoes, I often discover that the potatoes have a very strange flavor and texture. They are somewhat sweet and the color after baking is bright yellow. I have tried baking without spices, and have found they are not to blame for the strange flavor.

Am I encountering a different variety of potato or a different kind of vegetable that on the outside looks like a potato?
Is it possible these potatoes were harvested at the wrong time, but the outside color is nearly the same?
How can I identify which potatoes make French fries?

A:

Good Eats(Alton Brown) has some good descriptions of the various difference's between potatos. He has an episode dedicated to potatoes. Main thing is the starch content in them. He has an example of each of the three groups (High, Medium, Low), includign a brief description and sample application. He mentions mentions frying in the High Starch content group, specifically Russets. He then has another episode simply about frying, where he actually talks about French Fries and again mentions the Russet (High Starch).
While you can make fries out of different types of potatoes (some of the more "all purpose" potatoes), if you want a really good classic french fry, you're going to want to look for a Russet, with a similar starch content.
Here's a page that lists some of the more common varieties. Maybe you can look to see what you bought? The age will probably affect it. A younger potato will in fact be sweeter
So, to answer your specific questions. I'm betting you did in fact buy a potato. It's probably just a sweeter variety. If it doesn't say at the market where you bought it what kind they are, I'd ask the people who work there. Also, look at the third link I have above, it does have a few pictures as well as good descriptions on what they look like.


Q:

Multiple $_POST variable in a variable

Hey I have this code that sends an email with some data sent by a form:
<?php

  if (isset($_POST['submit'])) {

    error_reporting(E_NOTICE);

    function valid_email ($str) {
      return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
    }

    if ($_POST['name'] != '' &&  $_POST['email'] != '' && $_POST['tel'] != '' && valid_email($_POST['email']) == TRUE && strlen($_POST['comment']) > 1) {

      $to = preg_replace("([\r\n])", "", $_POST['receiver']);
      $from = preg_replace("([\r\n])", "", $_POST['name']);
      $subject = 'Online Message';
      $message = $_POST['comment'];
      $match = "/(bcc:|cc:|content\-type:)/i";
      if (preg_match($match, $to) || preg_match($match, $from) || preg_match($match, $message) || preg_match($match, $subject)) {
        die("Header injection detected.");
      }

      $headers = "From: \"".$_POST['name']."\" <".$_POST['email'].">\n";
      $headers .= "Reply-to: ".$_POST['email']."\r\n";

      if (mail($to, $subject, $message, $headers)) {
        echo 1; //SUCCESS
      } else {
        echo 2; //FAILURE - server failure
      }

    } else {
      echo 3; //FAILURE - not valid email
    }

  } else {
    die("Direct access not allowed!");
  }

I want to add the $_POST['tel'] to the $message variable so in the body of the email I can get the message plus the telephone that people type into the form. In the first part of the code I think I made the telephone input obligatory.
I tried doing $message = $_POST['comment'] && $_POST['tel']; but the only thing I recieve is a 1 in the body of the mail that is the first number of the telephone entered.

A:

$message = 'Comment: ' . $_POST['comment'] . ' Tel: ' . $_POST['tel'];


Q:

setMap() of google maps api not working

I am building a map using the Google Maps API, and when I load it I get this error:

Uncaught TypeError: Cannot read property 'setMap' of undefined

I think toggle() from vm() is causing error but I don't know how to correct it.
My aim is to simultaneously display markers based on search.
Here is the code:

var locations = [
        {"name": "Marari Beach Alappuzha" ,'location': {'lat': 9.618406, 'lng': 76.340161} },
        {"name": "Tea Mueseum" ,'location': {'lat': 10.049198, 'lng': 77.051025 }},
        {"name": "Eravikulam National Park" ,'location': {'lat': 10.116233, 'lng': 77.067791} },
        {"name": "Chimmini Wildlife Sanctuary" ,'location': {'lat': 10.428646, 'lng': 76.491031} },
        {"name": "Bekal Fort ",'location': {'lat': 12.440895, 'lng': 75.030311 }}
      ]

var markers = [];
var map;
var boolean = [];
for(i=0;i<locations.length;i++){
    boolean[i] = true;
}
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: {
            lat: 10.850516,
            lng: 76.271080
        }
    });
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for (var i = 0; i < locations.length; i++) {
        var position = locations[i].location;
        var name = locations[i].name;
        var marker = new google.maps.Marker({
            // map:map,
            position: position,
            animation: google.maps.Animation.DROP,
            id: i
        });
        markers.push(marker);
        marker.addListener('click', (function(marker, i) {
            return function() {
                if (marker.getAnimation() != null) {
                    marker.setAnimation(null);
                } else {
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                    stopAnimation(marker);
                }
            }
        })(marker, i));

        function stopAnimation(marker) {
            setTimeout(function() {
                marker.setAnimation(null);
            }, 3000);
        };
    }
    toggle();
}

function toggle(){
    for(g=0;g<locations.length;g++){
        if(boolean[g] === true){
            markers[g].setMap(map);
        }else if(boolean[g] === false){
            markers[g].setMap(null);
        }
    }
}

var z,g;
var vm = function(){
    var self = this;
    self.loc = ko.observableArray(locations);
    self.query = ko.observable('');
    self.filteredloc = ko.computed(function () {
        z=0;
    var filter = self.query().toLowerCase();
    console.log(boolean);
    toggle();
    if (!filter) {
        return self.loc();
    } else {
        return ko.utils.arrayFilter(self.loc(), function (item) {
            boolean[z] = item.name.toLowerCase().indexOf(filter) !== -1;
            // console.log(boolean[z]+'in pos'+z);
             z++;
            return item.name.toLowerCase().indexOf(filter) !== -1;
        });
    }
});

};

ko.applyBindings(new vm());
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compaitable" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Neighbourhood Map</title>
    <link rel="stylesheet" href="style.css">

                    <form action="#">
                        <input placeholder="Search…" type="search" name="q" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off">
                    </form>

Neighbourhood Map

A:

I don't have a solution for you, but I want to show you some ways you can greatly simplify your JavaScript code.
First, I got rid of the separate markers and boolean arrays. Instead, it's better to make those properties of the locations array elements. After all, locations is where you have your information about a location, so put all the information there. In the new code, each locations array element has a marker property (if a marker has been created) and a show property that corresponds to the former boolean array elements. Things get much simpler if you don't have to update separate arrays but just keep all your information in one place.
I replaced a couple of for loops with forEach(). forEach() takes a callback function, which is very nice because in this case it gives you a closure on the location argument passed to the callback. So you don't need the complicated code in marker.addListener() to create a closure - the closure already exists for you.
And I simplified the toggle() function a bit by removing and combining duplicate code.
That's all I have time for right now, but I hope it will give you some things to look at that will help you simplify your code - because simpler code is easier code to understand and debug.

var locations = [
    { "name": "Marari Beach Alappuzha" ,'location': { 'lat': 9.618406, 'lng': 76.340161 } },
    { "name": "Tea Mueseum" ,'location': { 'lat': 10.049198, 'lng': 77.051025 } },
    { "name": "Eravikulam National Park" ,'location': { 'lat': 10.116233, 'lng': 77.067791 } },
    { "name": "Chimmini Wildlife Sanctuary" ,'location': { 'lat': 10.428646, 'lng': 76.491031 } },
    { "name": "Bekal Fort ",'location': { 'lat': 12.440895, 'lng': 75.030311 } }
];

var map;

function initMap() {
    map = new google.maps.Map( document.getElementById('map'), {
        zoom: 7,
        center: {
            lat: 10.850516,
            lng: 76.271080
        }
    });
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    locations.forEach( function( location ) {
        var marker = location.marker = new google.maps.Marker({
            position: location.location,
            animation: google.maps.Animation.DROP
        });
        marker.addListener( 'click', function() {
            if( marker.getAnimation() ) {
                marker.setAnimation( null );
            } else {
                marker.setAnimation( google.maps.Animation.BOUNCE );
                stopAnimation( marker );
            }
        });

        function stopAnimation(marker) {
            setTimeout( function() {
                marker.setAnimation(null);
            }, 3000 );
        }
    });
    toggle();
}

function toggle() {
    locations.forEach( function( location ) {
        if( location.marker ) {
            location.marker.setMap( location.show ? map : null );
        }
    });
}

var vm = function() {
    var self = this;
    self.loc = ko.observableArray( locations );
    self.query = ko.observable('');
    self.filteredloc = ko.computed( function () {
        var z = 0;
        var filter = self.query().toLowerCase();
        toggle();
        if( ! filter ) {
            return self.loc();
        } else {
            return ko.utils.arrayFilter( self.loc(), function( item ) {
                boolean[z] = item.name.toLowerCase().indexOf(filter) !== -1;
                // console.log(boolean[z]+'in pos'+z);
                z++;
                return item.name.toLowerCase().indexOf(filter) !== -1;
            });
        }
    });
}

ko.applyBindings( new vm() );
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compaitable" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Neighbourhood Map</title>
    <link rel="stylesheet" href="style.css">

                    <form action="#">
                        <input placeholder="Search…" type="search" name="q" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off">
                    </form>

Neighbourhood Map


Q:

Async pipe subscription not work correctly when nested inside ngIf

I have a quick search box which I would like to have a loading animation. I used ng-template with ngIf to show/hide this animation. And I have some li's nested inside the same div which subscribed to a search result Observable using async pipe to display results. This async pipe works great when there's no *ngIf on the parent div, but seems it is not subscribing anymore when I apply ngIf. Is this an expected behavior? Or am I doing anything wrong?
My markup looks like this.
<input #searchBox type="text" (keyup)="itemLoading=true;searchTerm$.next(searchBox.value)"/>

{{item}}

<ng-template #loading>

LOADING...

</ng-template>

And I am using switchMap to run the search:
private source = of(['apple', 'pear', 'banana']).pipe(delay(500));

  searchTerm$ = new Subject<string>();
  result$: Observable<string[]>;
  itemLoading = false;

  constructor() {
    this.result$ = this.searchTerm$.pipe(
      tap(term => console.log('search term captured: ' + term)),
      debounceTime(300),
      distinctUntilChanged(),
      switchMap(() => this.source.pipe(
        tap(_ => {
            console.log('source reached');
            this.itemLoading = false;
          })
      ))
    );
  }

When ngIf is present in parent div, the 'source reached' message is never logged in console, as well as the loading template keeps hanging there.
Here is a full working example of what I am talking about: https://stackblitz.com/edit/angular-2ukcqu

A:

Rewriting the *ngIf as hidden should solve the problem.  The reason result$ isn't working is because those elements inside the *ngIf won't be added to the dom until itemLoading is false.  At that point they'll subscribe to result$, but the event will have already occurred.
Alternatively shareReplay(1) might also do the trick without you having to rewrite anything else, as the reply will run when the Observable is subscribed too.
Solution A

LOADING...

Solution B
this.result$ = this.searchTerm$.pipe(
  //...
  shareReplay(1)
);


Q:

Answering tex.stackexchange.com questions from the iPad (solved)

Edit (may 6, 2014)
This issue is now solved. From IOS6 (dec 2012), Safari has access to the camera roll, so it is possible to upload images directly from Safari without the Dropbox workaround. That is, I can follow the steps 1 and 2 of the original question, and then upload it directly to StackExchange.
I leave the original question and its edits for reference.
Original question (jul 22, 2012)
Currently I am far from my computers, and I've got a lot of spare time, so I'd like to participate in this site and answer some questions, using my iPad.
I've found that the site is very iPad friendly, and that I can navigate, read and write answers without problems (specially if I use an external bluetooth keyboard, which make more accessible the markup symbols).
However, when I want to try out the code in my answers and post an image with the resulting output, I get into trouble. These are the steps that I'm currently using:

I try the code using LaTeX previewer which is also very iPad friendly, to my delight.
If the code works, and I want to paste the resulting output, I select the image and save it in the iPad Photo Album.
Using Dropbox for iPad, I upload the photo from the iPad to some Dropbox folder.
Using Dropbox again, I get an url for the uploaded image (which is a shortened url).
Since stackexchange image upload service does not work with shortened urls, I use Safari to connect to that shortened url, download the image, and get the expanded url which points to the real png
I use stackexchange's image uploader to give the url of that image and finally get the result in the post.

This is how I answered Drawing node in tikz with both background fill and grid pattern?, for example.
I wonder if there is a shorter method, or if I am the only one trying to do such a thing from the iPad.
EDIT (jul 23, 2012)
The reason for such a convoluted process is that in iOS (iPad, iPhone and iPod operating system) the filesystem is sandboxed for each application. In other words, an application has not access to the files created in a different application. The user has no control about where the files are stored. When you "download" an image with Safari, it "sends" that image to Photo Album app, which stores it in its private filesystem. But then, when some web page offers you to "upload" a file, Safari dismisses that option, because the only part of the filesystem that Safari can read is its own private space, and this is use for caching only. This is why I have to use Dropbox as an intermediate store.
However perhaps an iPad user more skilled than me knows about some workaround. It is a pain to be unable to upload files from the browser.

A:

[Answered from my iPad]
A shorter workflow is to submit screenshots rather than the actual pictures. You take a screenshot by pressing the "home" and "power" buttons simultaneously. The screenshot automatically goes to the camera roll, which can be directly accessed from Safari--it's the only thing you can get to from a conventional "upload" menu.

The disadvantage is that you have less control over exactly what shows up in the picture.


Q:

How to make a synchronus calls in nodejs

I am trying to parse excel file data from files to mysql db but i will do it for many files but due to asynchronous property of nodejs before completing the  task for first file it interrupts for second file so is there any way to make this functionality synchronous.
My nodejs code:
while (typeof issue.fields.attachment[r] != "undefined") {
    if (typeof issue.fields.attachment[r].content != "undefined") {
        var url = issue.fields.attachment[r].content;
        console.log('url :' + url);
        request({
                method: "GET",
                "rejectUnauthorized": false,
                "url": url,
                "headers": {
                    "Content-Type": "application/json",
                    "Authorization": "Basic" +
                }
            },
            function(err, data, body) {
                //console.log(data.body);
                console.log('file downloading');
            }).pipe(fs.createWriteStream('file.xlsx'));
        console.log('file downloaded');
        parseXlsx('file.xlsx', function(err, data) {});
    }
}

A:

You can make the contents of a while call execute in series pretty easily with async's whilst method. You wrap your condition in an anonymous function and pass that as the first argument, your while's content in another anonymous function and pass that as the second argument.  You then call a callback when your while's work is done each time, and that is how it knows to loop.
var async = require('async');
async.whilst(function(){return typeof issue.fields.attachment[r] !== "undefined"},function(callback){
    if(typeof issue.fields.attachment[r].content != "undefined")
    {
        var url = issue.fields.attachment[r].content ;
        console.log('url :'+url);
        var wstream = fs.createWriteStream('file.xlsx');
        request({
            method: "GET",
            "rejectUnauthorized": false,
            "url": url,
            "headers" :{
                "Content-Type": "application/json",
                "Authorization": "Basic"+
            }
        },function(err,data,body){
            //console.log(data.body);
            console.log('file downloading');
        }).pipe(wstream);
        wstream.on('finish',function(){
            parseXlsx('file.xlsx', function(err, data){
                return callback();
            });
        });
    }
}

You will want to put in some error handling.  If you call callback() with an err, it will stop looping, so if you want it to continue despite an error, you just call callback();
Note:I also fixed up some of your writestream code.


Q:

React-Native: Unable to open device settings from my android app

I'm using React-Native (^0.35.0) for making Android application. There is scenario where I need to check whether internet connectivity is present or not. If there is no internet connectivity then I need show a button which will open device settings (through which user can enable his connectivity).
I'm Using Linking library provided by react-native.
I am trying in followin way:
componentWillMount(){
    Linking.canOpenURL('app-settings:')
      .then(supported => {
        if (!supported) {
          console.log('Can\'t handle url: ' + url);
       } else {
       return Linking.openURL('app-settings:');
      }
  }).catch(err => console.error('An error occurred', err));
}

then above code gives- console Can't handle url:app-settings:
When I tried following:
componentWillMount(){
    Linking.canOpenURL('app-settings:')
      .then(supported => {
        return Linking.openURL('app-settings:');
      }).catch(err => console.error('An error occurred', err));
    }

Above code gives- Error: Could not open URL 'app-settings:': No Activity found to handle Intent { act=android.intent.action.VIEW dat=app-settings: flg=0x10000000 }
Is there anything that I am missing here? or Is there is need to change in any other file like AndroidMainfest.xml, MainActivity.java, etc..

A:

I'm new with react-native and not having much insights of java(android). I faced similar problem but I managed to open Android settings by creating the custom react-native module.
Below are the steps which I've taken to achieve this functionality.
1 - Create a folder for module under android/app/src/main/java/com/<projectname>/. In this case I've created the opensettings folder.
2 - Under this folder create module file OpenSettingsModule.java (where we put module functionality) and package file OpenSettingsPackage.java (where we will register our module).
3 - Put following code in OpenSettingsModule.java
package com.<projectname>.opensettings;

import android.app.Activity;
import android.content.Intent;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactContextBaseJavaModule;

public class OpenSettingsModule extends ReactContextBaseJavaModule {

  @Override
  public String getName() {
    /**
     * return the string name of the NativeModule which represents this class in JavaScript
     * In JS access this module through React.NativeModules.OpenSettings
     */
    return "OpenSettings";
  }

  @ReactMethod
  public void openNetworkSettings(Callback cb) {
    Activity currentActivity = getCurrentActivity();

    if (currentActivity == null) {
      cb.invoke(false);
      return;
    }

    try {
      currentActivity.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
      cb.invoke(true);
    } catch (Exception e) {
      cb.invoke(e.getMessage());
    }
  }

  /* constructor */
  public OpenSettingsModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }
}

4 - We have done with our module which will open android settings by calling openNetworkSettings function. Now we need to register this module. Add below code in OpenSettingsPackage.java
package com.<projectname>.opensettings;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OpenSettingsPackage implements ReactPackage {
  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new OpenSettingsModule(reactContext));

    return modules;
  }

  @Override
  public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
  }

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }
}

5 - Provide this package to getPackages method of the MainApplication.java.
import com.<projectname>.opensettings.*;
...
@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
      new OpenSettingsPackage() /* <---- add here */
  );
}

6 - We are done with JAVA part, import NativeModules in your component, we can now access our module through NativeModules.OpenSettings. JSX implementation as below.
import { NativeModules } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.openSettings = this.openSettings.bind(this);
  }

  openSettings() {
    NativeModules.OpenSettings.openNetworkSettings(data => {
      console.log('call back data', data);
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress={this.openSettings}>Open Android Settings</Text>
      </View>
    );
  }
}

7 - reference
https://shift.infinite.red/native-modules-for-react-native-android-ac05dbda800d#.yj9pspfpn
http://facebook.github.io/react-native/docs/native-modules-android.html
Note: If there is any better way to achieve the same functionality then please let me know here.

A:

I have used the same steps for opening device network operator settings. The steps above are quite helpful.
Here is my code.
package com.<projectname>.opensettings;

import android.app.Activity;
import android.content.Intent;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactContextBaseJavaModule;

public class OpenSettingsModule extends ReactContextBaseJavaModule {

  @Override
  public String getName() {
    /**
     * return the string name of the NativeModule which represents this class in JavaScript
     * In JS access this module through React.NativeModules.OpenSettings
     */
    return "OpenSettings";
  }

  @ReactMethod
  public void openNetworkSettings(Callback cb) {
    Activity currentActivity = getCurrentActivity();

    if (currentActivity == null) {
      cb.invoke(false);
      return;
    }

    try {
      currentActivity.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
      cb.invoke(true);
    } catch (Exception e) {
      cb.invoke(e.getMessage());
    }
  }

  /*This is for open location Settings*/
  @ReactMethod
  public void openLocationSettings(Callback cb) {
    Activity currentActivity = getCurrentActivity();

    if (currentActivity == null) {
      cb.invoke(false);
      return;
    }

    try {
      currentActivity.startActivity(new Intent(android.provider.Settings.ACTION_NETWORK_OPERATOR_SETTINGS));
      cb.invoke(true);
    } catch (Exception e) {
      cb.invoke(e.getMessage());
    }
  }

  /* constructor */
  public OpenSettingsModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }
}

All you need to do is just put the constant(like ACTION_NETWORK_OPERATOR_SETTINGS) in above code and create your own function like one which is created above i.e. openNetworkSettings. Other steps 4, 5 and 6 are same.
Here are the list of constants:
https://developer.android.com/reference/android/provider/Settings.html


Q:

Picasso placeholder image animation

I am trying to load an image into an ImageView using picasso. The code is given below:
Picasso.with(this)
       .load(imageURL)
       .placeholder(drawable1)
       .error(drawable1)
       .into(imageview)

Now here while picasso is waiting for the download to complete, the imageview goes blank. To prevent that I want to fade out the current image to a drawable and then to load the image present in the URL. Is there any way to do this?

A:

I think Picass has done this for you, placehoder drawable is used to be shown when image is being loaded, and the error drawable will be shown when image load failed.
If you want to really to do some thing you can use Target as following:
new Target() {
  @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
    imageView2.setImageBitmap(bitmap);
   }

   @Override public void onBitmapFailed(Drawable errorDrawable) {

   }

   @Override public void onPrepareLoad(Drawable placeHolderDrawable) {

   }
}


Q:

Is there a way to get logs on how many people download from your yum repository?

So we host some yum repositories for various customers and I'm wondering if there is any way to find out how often package XYZ gets downloaded from our yum repository? Is this something that is tracked at all? Couldn't find anything via google but maybe someone has experience in this?

A:

Usually, the repo is served by a web server. Web servers keep log files about every file downloaded if you configure them accordingly.
The same is true for repos served by FTP.


Q:

Is there an "official" translation of Malcom X's You can't hate the roots of a tree and not hate the tree"?

Malcom X once said:

You can't hate the roots of a tree and not hate the tree. You can't hate Africa and not hate yourself.

It is a fairly well known quote.

Are there any “official” translations of this quote? (Not Google translate, etc.)

A:

Such sayings have their culture background and only Malcom X himself could tell whether a translation is right or not.
"背祖忘宗" or "數典忘祖" may carry a similar meaning but does not have the same context.  Not to say creative translations like "惱根怎可不惱樹, 厭鄉也該厭自己".


Q:

IvyChart object added to newly created reports and interferring with version control

I'm using a version control and update solution similar to the one described in this answer that uses SaveAsText and LoadFromText to manage incremental updates.
However, a problem arose recently when loading reports saved using LoadFromText that had been created using SaveAsText on different computers. I tracked this problem down to the following issue:
MCVE
On PC 1:

Create a new database
Create a table in that database using the ribbon Create, then Table button
Close and save that table
Create a report by selecting the table, and pressing Create, and then Report
Close and save the report
In the immediate window, execute SaveAsText acReport, "Table1", "C:\SomePath\Report.txt"

On PC 2:

Create a new database
In the immediate window, execute LoadFromText acReport, "Table1", "C:\SomePath\Report.txt"
I receive a generic error, a file called error.txt is created at the database location, and in it, it says Expected: object name. Observed: IvyChart.

Further observations:
The text file Report.txt is approximately 100 KB (previous exports of reports based on small tables were around 40 KB).
In the report.txt file, you can find the report contains:

A BoundObjectFrame
A Chart
An UnboundObjectFrame
A CustomControl
A WebBrowser
A NavigationControl
An IvyChart with the following properties:
UnknownProp = {48 ,329 ,2 ,1 ,1 } Begin
    0x00
End
UnknownProp = {49 ,11 ,2 ,1 ,1 } Begin
    0x00
End
UnknownProp = {98 ,150 ,3 ,4 ,2 } Begin
    0xb811
End
UnknownProp = {99 ,44 ,3 ,4 ,2 } Begin
    0x130b
End
UnknownProp = {260 ,462 ,4 ,4 ,4 } Begin
    0x27000080
End
UnknownProp = {295 ,616 ,4 ,0 ,4 } Begin
    0x01000000
End
UnknownProp = {300 ,756 ,10 ,4 ,22 } Begin
    0x4300680061007200740020005400690074006c006500
End

None of the other controls have these UnknownProp properties.
When I create the report on PC 2, using the same steps, all these controls don't show up.
All these controls are not visible on the report itself. The problem mainly manifests when exporting from a computer with Office 2016 (365) version 1803, and importing in an older version of Office 2016
Access is not using any add-ins, COM or otherwise. This occurs with blank databases, so only using the default references.
Has anyone got any idea what this IvyChart object is, why it's on all newly created reports based on existing objects, and why all these other seemingly random invisible controls come with it?
Can I stop Access adding these invisible controls to new reports?
Googling IvyChart or consulting other resources has brought no insight at all.
I can just open the database on PC 2 and use SaveAsText from there. However, if I do that, the weird controls aren't there but text file is full of lines like this:
Begin
End

This makes importing the text file invalid on any computer.
My workaround for now is when creating a new report based on an object, to select all controls, copy all controls (using ctrl + A) to a blank report, and then save the report. The fact that this works, and these hidden controls causing errors aren't copied, also feels a bit iffy to me.

A:

IvyChart is the internal control name for the new Chart control type that was added in O365.  Office 2016 does not support this control type, so you get an error when trying to LoadFromText a form or report that contains them.
Note that 2016 Access can still open these forms/reports, but will not display the chart.
If you want to use the new charts, you need to use Office 365, or Office 2019.


Q:

cancelAnimationFrame on button click is not working

I am trying to animate a left or right rotation on button click. Unfortunately, when i click the button for left rotation, it compiles on itself, getting faster and faster. The same occurs with the right click. It takes multiple clicks of the opposing button to negate the rotation.
I would like the left button to cancel the right rotation and go straight into rotating left and vice versa. Right now, you have to click the opposing button  time for each time you've pressed the initial button.
Code below:
var initialFrame = function () {
  requestAnimationFrame(initialFrame);
  renderer.render(scene, camera);
};

var rotateLeft = function () {
  requestAnimationFrame(rotateLeft);
  wrap.rotation.y += -0.02;
  wrapBack.rotation.y += -0.02;
  renderer.render(scene, camera);
};

var rotateRight = function () {
  requestAnimationFrame(rotateRight);
  wrap.rotation.y += 0.02;
  wrapBack.rotation.y += 0.02;
  renderer.render(scene, camera);
};

initialFrame()

$("#left-button").click(function() {
  cancelAnimationFrame(rotateRight);
  rotateLeft();
});

$("#right-button").click(function() {
  cancelAnimationFrame(rotateLeft);
  rotateRight();
});

A:

I think that it's better to put all the animation login into the render loop and the controls in the button event.
var step =0;
var initialFrame = function () {
  wrap.rotation.y += step;
  wrapBack.rotation.y += step;
  requestAnimationFrame(initialFrame);
  renderer.render(scene, camera);
  step=0; // if you want to rotate one step on a click (remove this for infinite rotation)
};

var rotateLeft = function () {
  step=-0.02;
};

var rotateRight = function () {
  step=0.02;
};

$("#left-button").click(function() {
   rotateLeft();
});

$("#right-button").click(function() {
   rotateRight();
});

initialFrame();


Q:

Connecting two microcontrollers using I2C

I Have an ATmega16 mc which is master on the i2c and a ATMega8 mc which is slave on the i2c.
I have connected the two mcs' sda and scl ports to each other alongside a pullup resistor.
Now I want to read a register from the ATMega8 using the ATMega16.
The problem is that I don't want to assign all the variables manually. Is there any libs or headers that will do this thing for me?

A:

It's been a while since I've used the AVR, but there where two libraries which would do what you are looking for. Unfortunately ATMEL doesn't provide proper firmware libraries themselves (as e.g. STM does).

Procyon AVRlib is quite outdated, but also very lightweight. You can just use the parts that you are interested in.
AVR Libc is another library which is slightly more recent and in my experience quite comprehensive. I think it is actually bundled with a lot of toolchains.

A:

I've not used the ATMega family, but have lots of experience of configuring many other devices - setting up the control registers for I2C is usually pretty straight forward, with appropriate reference to the datasheet/user-manual and will help you understand what's going on.
For such tasks, a library is (a) inefficient (b) overkill and (c) doesn't help you learn.
I don't know if there is one, but wouldn't recommend you use it, if there was...


Q:

C# Generics Extension Method Issues

so I'm fairly new to writing generic transform model extensions and I was trying to go from a model to an azure service bus message which works as expected. But I'm now trying to do the reverse where it can go from a message to a specified type.
The extension method currently looks like so.
    public static class ModelExtensions
    {
        public static Message ToMessage<TModel>(this TModel model) =>
            new Message(
                Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(model)));

        public static TType FromMessage<TModel, TType>(this TModel model)
        {
            return JsonConvert.DeserializeObject<TType>(JsonConvert.SerializeObject(model));
        }
    }

Is there a way to do the reverse of what I have just done to many types depending what is specified on the other side of the extension method for example if on the outside I have done something like.
message.FromMessage()
Any help would be appreciated,
Thanks in advance,
Chris.

A:

Should be as simple as
public static TModel FromMessage<TModel>(this Message message)
  => JsonConvert.DeserializeObject<TModel>(Encoding.UTF8.GetString(message.Body));

Usage
var result = message.FromMessage<MyLovelyHorse>()


Q:

PyCrypto Cyphertext incorrect length even with a one char data

I want to encrypt/decrypt a set of data which is contained in a .csv file.
I generate my RSA public/private keys with this code :
import Crypto
from Crypto.PublicKey import RSA

key = RSA.generate(2048)

k = key.exportKey('PEM')
p = key.publickey().exportKey('PEM')

with open('private.pem', 'w') as kf:
    kf.write(k.decode())
    kf.close()

with open('public.pem', 'w') as pf:
    pf.write(p.decode())
    pf.close()

with open('private.pem','r') as fk:
    priv = fk.read()
    fk.close()

with open('public.pem','r') as fp:
    pub = fp.read()
    fp.close()

privat = RSA.importKey(priv)
public = RSA.importKey(pub)

if key == privat:
    print('Private key has been successfuly write')
if key.publickey() == public:
    print('Public key has been successfuly write')

Then I encrypt with this code without any problem:
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

with open('public.pem','r') as fp:
    pub = fp.read()
    fp.close()

public = RSA.importKey(pub)

#stockage du fichier dans une variable rep
fichier = open('test.csv', 'r')
rep = fichier.read()
fichier.close()

#eliminations des spaces
rep = rep.replace(' ', '')

#encodage pour type bytes
rep = rep.encode()

#decoupage en mot de 10 chars
rep = [rep[i:i+10] for i in range(0, len(rep), 10)]

cipher = PKCS1_OAEP.new(public)

fichier2 = open('encrypted.csv', 'a')
for i in rep:
    encrypted_line = cipher.encrypt(i)
    fichier2.write(str(encrypted_line))
    fichier2.write('\n')

fichier2.close()

I can modify how my data are separate by modifying this line :

rep = [rep[i:i+n] for i in range(0, len(rep), n)]

This line separate my data by groups of n chars
Here my code to decrypt the data, it raises:

ValueError: Ciphertext with incorrect length.

import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

with open('private.pem','r') as fk:
    priv = fk.read()
    fk.close()

private = RSA.importKey(priv)

fichier = open('encrypted.csv', 'r')
rep = fichier.read().splitlines()
fichier.close()

cipher = PKCS1_OAEP.new(private)

fichier2 = open('decrypted.csv', 'a')
for i in rep:
    decrypted_line = cipher.decrypt(i)
    decrypted_line = decrypted_line.decode('utf-8')
    fichier2.write(str(encrypted_line))

fichier2.close()

I tried to encode a sample file and it raised this ValueError . Then I try to work with a file which contain only one char directly on the Python interpreter. Encryption worked well but decryption broke with the same error as above.

A:

The main problem with the code is the use of newline characters to separate the chunks of encrypted data.  The encrypted data may already contain newline characters, so attempting to split the encrypted data into lines may produce partial chunks, which will raise the ValueError that you see when decrypted.
A second problem is that the encrypted files are being opened in text mode.  When dealing with encrypted data open files in binary mode.  Encrypted bytes are unlikely to be decodable to str, so using text mode will result in encoding or decoding errors.
This version of your code works:
import functools

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

if __name__ == '__main__':

    # Encrypt

    with open('public.pem', 'r') as fp:
        pub = fp.read()
        fp.close()

    public = RSA.importKey(pub)

    # tockage du fichier dans une variable rep
    with open('test.csv', 'r') as fichier:
        rep = fichier.read()

    # liminations des spaces
    rep = rep.replace(' ', '')

    # ncodage pour type bytes
    rep = rep.encode()

    cipher = PKCS1_OAEP.new(public)

    # decoupage en mot de 10 chars
    rep = [rep[i:i+10] for i in range(0, len(rep), 10)]

    # Open the file in binary mode so we can write bytes.
    with open('encrypted.csv', 'wb') as fichier2:
        for i in rep:
            fichier2.write(cipher.encrypt(i))

    # Decrypt
    with open('private.pem', 'r') as fk:
        priv = fk.read()

    private = RSA.importKey(priv)

    CHUNK_SIZE = 256
    # Open the file in binary mode so we can read bytes.
    with open('encrypted.csv', 'rb') as fichier:
        # Create an iterator that will return chunks of the correct size.
        chunker = iter(functools.partial(fichier.read, CHUNK_SIZE), b'')
        rep = list(chunker)

    cipher = PKCS1_OAEP.new(private)

    with open('decrypted.csv', 'w') as fichier2:
        for i in rep:
            decrypted_line = cipher.decrypt(i)
            fichier2.write(decrypted_line.decode())

Rather than splitting the encrypted data on newlines, this code reads from the file in chunks of 256 bytes, as the encryption process seems to generate 256 bytes for each chunk of input.  I'm not a cryptologist, so it's possible this isn't always true.  In that case it might be better to encrypt (or decrypt) all the data in a single step.


Q:

extracting from 7z archive failed when executed through command line

I downloaded a 7z archive which needs a password to extract the contents of the archive. I used the command
        7z -e archive.7z
It failed with the following error:
error: Incorrect command line.
Can anyone tell me command to extract the file. Thanks in advance.

A:

7z e archive.7z
Lose the dash.


Q:

Why won't an EditText wrap its lines when inside a TableLayout?

I noticed that when I put an EditText (or two) inside a single TableLayout row, the text won't wrap.
I'd like to understand what's going on here, and if there's any correct way to use a multi-line EditText (or two) inside a TableRow.
The below layout file:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TableRow>

        <EditText
            android:layout_width="match_parent"
            android:hint="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
            android:minLines="3" />
    </TableRow>

</TableLayout>

results in the following layout with no wrap (I presume the View is actually stretching beyond the right bounds of the screen.):

However, either adding android:stretchColumns="0" or omitting the TableRow tag works for one EditText but not two:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:layout_width="match_parent"
        android:hint="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
        android:minLines="3" />

</TableLayout>

A:

Try using this as an EditText attribute:
android:scrollHorizontally="false"


Q:

Closure Compiler Externs - WARNING - Property never defined on

I am preparing externs for PIXI.js library. I am getting the following warning:
js/Test.js:188: WARNING - Property position never defined on PIXI.Sprite
        button.position.y = y;

Here are the relevant extern definitions:
//UPDATE
/**
 * @constructor
 * @extends {PIXI.Container}
 * @param {PIXI.Texture} texture
 */
PIXI.Sprite = function(texture){};

/**
 * @constructor
 * @extends {PIXI.DisplayObject}
 */
PIXI.Container = function(){};

/**
 * @constructor
 * @extends {PIXI.EventEmitter}
 */
PIXI.DisplayObject = function(){};

/**
 * @type {PIXI.Point}
 */
PIXI.DisplayObject.position;

Still getting the same warning.
What am I doing wrong?
When I am replacing PIXI.DisplayObject.position; with PIXI.DisplayObject.prototype.position; that seems to clear the warning.
Does it mean that I should always define SomeObject.prototype.prop rather then SomeObject.prop ?

A:

This is highlighting the difference between static and prototype properties.
Given:
/**
  * @constructor
  * @param {number=} opt_num
  */
function foo(opt_num) {
    if (opt_num !== undefined) {
        this.bar = opt_num;
    }
}
foo.prototype.bar = 17;
foo.bar = 42;

We have both a static property and a prototype property of the same name. However they are referenced differently:
console.log((new foo()).bar); // 17
console.log((new foo(0)).bar); // 0
console.log(foo.bar); // 42

So in an extern, when you are defining properties on a type - you typically want to define them on the prototype object:
/** @param {foo} obj_foo */
function log(obj_foo) {
   // This is an instance of "foo".
   // The "bar" property references prototype or instance
   // properties - not static properties.
   console.log(obj_foo.bar);

   // Static properties can only be referenced by the full namespace
   console.log(foo.bar);
}


Q:

Shadowbox timing issue

I'm using shadowbox js for showing Flash video in lightbox style popups.
So far it's working but I have this problem:
when the page loads and the user clicks too early on the linked image which should open the
shadowbox the swf is loaded directly (and no popup appears).
Also, the script seems to stop in this case and never assigns the right clicklistener - so the shadowbox is never shown also on subsequent clicks.
Shadowbox 3.0.1
Anybody has experienced the same issue, any solutions?
Thanks.

A:

You didn't post any info on when is the shadowbox first called.
If my guess is correct, You are running shadowbox in an onload event handler.
Try calling it when DOM is ready.
jQuery:
$(document).ready(function(){
//call it here
});

[EDIT]
In response to Your comment.
If this doesn't help there is only one solution.
Add this just after the line loading jquery script in head

The above should be one line, but then it's being cut by the stackoverflow's CSS ;)
and then $('.cover').remove(); when You are sure everything is loaded.
I do that when running crazy lots of code on pageload ;)


Q:

Difference between AWS Elastic Container Service's (ECS) ExecutionRole and TaskRole

I'm using AWS's CloudFormation, and I recently spent quite a bit of time trying to figure out why the role I had created and attached policies to was not enabling my ECS task to send a message to a Simple Queue Service (SQS) queue.
I realized that I was incorrectly attaching the SQS permissions policy to the Execution Role when I should have been attaching the policy to the Task Role. I cannot find good documentation that explains the difference between the two roles. CloudFormation documentation for the two of them are here: ExecutionRole and TaskRole

A:

Referring to the documentation  you can see that the execution role is the IAM role that executes ECS actions such as pulling the image and storing the application logs in cloudwatch.
The TaskRole then, is the IAM role used by the task itself. For example, if your container wants to call other AWS services like S3, SQS, etc then those permissions would need to be covered by the TaskRole.
Using a TaskRole is functionally the same as using access keys in a config file on the container instance. Using access keys in this way is not secure and is considered very bad practice. I include this in the answer because many people reading this already understand access keys.


Q:

Check to see if element exists after DOM is ready

I'm trying to detect whether an element is visible after the DOM is ready. This element is a third party widget that loads slower than the page does.
My console.log for 'dom ready' is firing - like it should, but my check to see if the element is visible is returning false, as the element loads after the dom is ready.
Is there a way to listen for elements after the dom has loaded?
<script>
    $(function(){
        console.log('dom ready');

        if($(element).is(':visible')){
            console.log('element is visible. do stuff.');
        }

    });
</script>

A:

you can get the id from the iframe, or from the document that is being loaded and do something like this..
$('#external').load(function(){
    //lets do something when is loaded
    if($(element).is(':visible')){
       console.log('element is visible. do stuff.');
    }
});

This will trigger once that script, iframe is done loading


Q:

How would I use the cursor.map function to skip one of the the first item in a collection

I have the following template helper for outputting the first {{url}} and all the {{thumb}}
however I want to skip the first item if the {{thumb}} not sure how to do this in the map function.
Template.motionPictures.helpers({
  posts: function() {

  return  Posts.find({}, {fields: {thumb: 1, url: 1}}).map(function(post, index) {
  if (index === 0) {
    return post;
  } else {
    delete post.url;
    return post;
  }
});

}
});

When I console.log the posts array, I get the following

This is what I expected but I want the first object in the array to only show its {{url}} not is {{thumb}} so far all the suggestions just delete the object in total, or not at all.

A:

Ok so you both had good advice but I didn't realize what I had to do until I did that console .log.
The following code worked just as I wanted it to
Template.motionPictures.helpers({
  posts: function() {
   return Posts
        .find({}, {fields: {thumb: 1, url: 1}, sort: {createdAt: -1}})
        .map(function(post, index) {
          if (index === 0) {

            delete post.thumb;
            return post;

          } else {
            delete post.url;
            return post;
          }
        });
    }
});


Q:

TestAgentInstaller service is marked as an interactive service

I'm getting the following error in System Event Log on the VM when trying to Install Agents in Lab Center:

The TestAgentInstaller service is marked as an interactive service.
  However, the system is configured to not allow interactive services.
  This service may not function properly.

How can this be resolved?

A:

According to http://msdn.microsoft.com/en-gb/library/windows/desktop/ms683502%28v=vs.85%29.aspx check local registry value NoInteractiveServices under
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows
Also, check Windows service Interactive Services Detection - whether it's not Disabled.


Q:

Can not query linq to sql in the Views of asp.net MVC C#

I want to query the user that log in success in the web site :
This is what I did in my views :
var query = from i in Model.DataContext.Customers
            where i.WebAccount == User.Identity.Name
            select i;

But it show the error Object reference not set to an instance of an object, I have no idea , why it is like that.
Any one know about that? Thanks.

A:

socheata,
there's a very good chance that your User.Identity object could be null if the user has not yet signed in (thus the User.Identity.Name invocation would throw an error).
So, there are several approaches that spring to mind:

move that logic out of the view and into either your service layer or your controller action
create an html helper that provides the functionality that you
require from the view. useful if this is required across multiple views

there are of course other options, but these would be my starting point.


Q:

Why are string-related data types like account_name converted to type uint64_t?

According to the types.h all string-related data-types (or at least those where i would presume that they receive strings) like account_name, token_name and so on are declared as uint64_t and i am curious why it is so?
I stumbled upon this code from EOS-repo:
struct contract {
   contract( account_name n ):_self(n){}
   account_name _self;
};

and looked up the type account_name which is defined in types.h:
typedef uint64_t account_name;
typedef uint64_t permission_name;
typedef uint64_t token_name;
....

At a first glance i thought that strings maybe stored only once per lifetime in the blockchain database to reduce its size and that they will receive something like an ID as uint64 to reuse in further contracts. But then i found from a future related perspective that the range of an uint64 may not fit all needs over upcoming decades. Also the lookup could take some time from up to a specific size.
At a second glance i think it could simply be a hash of this string. If so, will the appropriate string stored as a full string elsewhere?
Any clarification is very appreciated.
Also, if my assumption is right, i'd like to ask how to convert a string into such an uint64-based number within code internally (or which hash-function will be used).
Thanks in advance!

A:

They are not strings, but rather base32 string representations of the uint64s. That’s why they are limited to 12 chars length and only the characters a-z, 1-5 and .
When ever you see the preprocessor function N(something) being called is actually doing the conversion https://github.com/EOSIO/eos/blob/9be89106da1d6a1543eb19dd0f3b96a53e286088/libraries/chain/include/eosio/chain/name.hpp#L21

A:

The account name is converted into an integer uint64 using the function string_to_name
defined in types.hpp file
static constexpr uint64_t string_to_name( const char* str ) {
   uint32_t len = 0;
   while( str[len] ) ++len;
   uint64_t value = 0;
   for( uint32_t i = 0; i <= 12; ++i ) {
      uint64_t c = 0;
      if( i < len && i <= 12 ) c = uint64_t(char_to_symbol( str[i] ));
      if( i < 12 ) {
         c &= 0x1f;
         c <<= 64-5*(i+1);
      }
      else {
         c &= 0x0f;
      }
      value |= c;
   }
   return value;
}

static constexpr  char char_to_symbol( char c ) {
   if( c >= 'a' && c <= 'z' )
      return (c - 'a') + 6;
   if( c >= '1' && c <= '5' )
      return (c - '1') + 1;
   return 0;
}


Q:

Selecting batches of rows

I have a table widget_events that records event_what events occurring to
widget widget_id on date event_when.  It's possible for the same event to
occur multiple times to the same widget on the same day.  For this reason,
column event_id is used as primary key to distinguish such rows.  Here is
the table declaration:
CREATE TABLE widget_events
(
event_id    int4 UNIQUE NOT NULL,
event_when  date NOT NULL,
event_what  text NOT NULL,
widget_id   int4 REFERENCES widgets (widget_id) NOT NULL,
PRIMARY KEY (event_id)
);

The client application processes events in batches, where each batch consists
of all events for one widget on one date.  However, the application has no
previous knowledge of which widgets and dates are stored in widget_events.
One possible solution is to start by selecting one random row from
widget_events (using SQL's LIMIT), and then do another query for all
rows with the same widget_id and widget_when.  After this batch is
processed, those rows can be deleted from widget_events, and we go back
to the first step.  The algorithm stops when the first step reports that
there is no more random row to return.
My question is whether there is a faster, more elegant way to do this.
Is it possible in SQL (in particular the SQL understood by PostgreSQL)
to return each distinct batch in a single query?

A:

To select distinct batches:
select  distinct event_when
,       event_what
from    widget_events

Or you could pick up a single batch in one query, like:
select  batch.*
from    widget_events batch
join    (
        select  event_when
        ,       event_what
        from    widget_events
        limit   1
        ) filter
on      filter.event_when = batch.event_when
        and filter.event_what = batch.event_what


Q:

how to generate wsdl client in intelij idea

this is the most simplified version of my problem I could generate.
I got a web service :
@WebService()
public class Service {
  @WebMethod
  public IsLoggedInResponse IsLoggedIn() {
    return new IsLoggedInResponse();
  }
}

this is the class I return:
@XmlRootElement
public class IsLoggedInResponse {
    private boolean isLoggedIn;

    public IsLoggedInResponse(boolean isLoggedIn) {
        this.isLoggedIn = isLoggedIn;
    }

    public IsLoggedInResponse() {
        // TODO Auto-generated constructor stub
    }

    @XmlElement
    public boolean isLoggedIn() {
        return isLoggedIn;
    }

    public void setLoggedIn(boolean isLoggedIn) {
        this.isLoggedIn = isLoggedIn;
    }
}

this is the xsd generated when pressing right click on the webserivce and generate wsdl code from java:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://webservice.pubsale.com/" xmlns:tns="http://webservice.pubsale.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="IsLoggedIn" type="tns:IsLoggedIn"/>

  <xs:element name="IsLoggedInResponse" type="tns:IsLoggedInResponse"/>

  <xs:element name="IsLoggedInResponse" type="tns:IsLoggedInResponse"/>

  <xs:complexType name="IsLoggedIn">
    <xs:sequence/>
  </xs:complexType>

  <xs:complexType name="IsLoggedInResponse">
    <xs:sequence>
      <xs:element name="return" type="tns:isLoggedInResponse" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="isLoggedInResponse">
    <xs:sequence>
      <xs:element name="loggedIn" type="xs:boolean"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

notice isLoggedInResponse is created twice. why? how do I stop it?

A:

alright found the problem seems for each webmethod  'METHODNAME' JAXB creates in the schema a complex type named METHODNAMEResponse
my solution was to to add "DTO" to all my requests/responses.
could also change my method name
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://webservice.pubsale.com/" xmlns:tns="http://webservice.pubsale.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="IsLoggedIn" type="tns:IsLoggedIn"/>

  <xs:element name="IsLoggedInResponse" type="tns:IsLoggedInResponse"/>

  <xs:element name="isLoggedInResponseDTO" type="tns:isLoggedInResponseDTO"/>

  <xs:complexType name="IsLoggedIn">
    <xs:sequence/>
  </xs:complexType>

  <xs:complexType name="IsLoggedInResponse">
    <xs:sequence>
      <xs:element name="return" type="tns:isLoggedInResponse" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>


Q:

How do I "install" specific web files on a proxy server?

This is for a in house system, that is required to be set-up this way.
I need specific web files, for example, all images to be manually pre-installed on a proxy server and never downloaded from the web server.
When the browser request the page, the only thing sent from the web server to the proxy should be the plain html page.
I would then like the images the html page uses, to be grabbed from the the proxy every time, for the complete render to the browser.
Is there a name for this set up? I have seen about caching but I do not even want the images downladed once. In addition, how would the html page know to use the images from the proxy?
How would I set up such a thing? I do not have a proxy server set-up yet so I do not know what platform I will be using, but suggestions are appreciated.
Thank You.

A:

Well, I think that you could, for example, use Privoxy and tell it to redirect some queries for images to a local server or even let it replace the img src=" attribute inline using regexes.


Q:

Can you change the camera angle?

Is there any way to change the default camera angle in LoL? I've seen some videos where the camera angle looks different, but I can't seem to do it the game.

A:

No, You can zoom the camera in and out but the angles are always fixed while the game is being played. When you are seeing the different camera angle it is generally on a replay video, where the camera's movement is a bit more free.


Q:

How to close fancybox at facebook canvas application?

I have a facebook application and i use fancybox. I want to close fancybox with following code but when user clicks the Close link, fancybox opens again. This code works at a non-facebook page.
Close

Does anyone have idea how can i close the fancybox at a facebook canvas application?

A:

I am guessing fancybox is tied to anchor tags, so your code closes it, but the event listener attached picks up the click and fires the open. Try using another tag to fire your close script:
Close

If that works you can add styles to your span to give it the pointer cursor and otherwise make it look like a link if you want to.


Q:

Editing "testproject.zip" to stop "UnitTest1.cs" being created

I've been modifying the VS2010 item and project templates so each time we do a "new project" or "new item" we get it created in a format that works for us.  This is all working fine; if we create a new class library we get it with the references we've set up and it doesn't create the "class1.cs" file - that all works.  We've made a similar change to the TestProject.zip file that lives in:

C:\Program Files (x86)\Microsoft Visual Studio
  10.0\Common7\IDE\ProjectTemplates\CSharp\Test\1033

Gone through the same process of zipping it back up, copying it over top of the original and refreshing the cache.  However for the test project we can't stop it creating the default "unittest1.cs" file.  All of our other changes to the test project are working fine but we just can't stop it creating the "unittest1.cs" file.  It was never in the template or csproj file originally so I'm not sure what is creating it.
Can anyone help?  What creates the default test file for the test project - I'm wondering if it's a reference to the wizard that is in the template file but have no idea what changes would be needed.

A:

Close Visual Studio
Extract BasicUnitTest.zip from:

C:\Program Files (x86)\Microsoft Visual Studio
  10.0\Common7\IDE\ItemTemplates\CSharp\1033

Open BasicUnitTest.vstemplate
Remove <ProjectItem ReplaceParameters="true">UnitTest.cs</ProjectItem>
Zip BasicUnitTest.vstemplate into BasicUnitTest.zip (excluding UnitTest.cs)
Go to:

C:\Program Files (x86)\Microsoft Visual Studio
  10.0\Common7\IDE\ItemTemplatesCache\CSharp\1033

Delete UnitTest.cs and replace BasicUnitTest.vstemplate with your modified copy
On the next run of Visual Studio you should see the modified UnitTest

Though you can do this for every default template, I recommend creating a new template based on the BasicUnitTest.zip instead of overriding the ones shipped with Visual Studio. It's easier, safer and won't be overwritten by future service packs.


Q:

Can I ask this question differently without it getting closed?

The question What is the best Canon lens (around $500) for taking pictures of my newborn?
The answers fulfill the posters original question OK I think. But for example the top answer recommends the 28mm f/2.8 lens, which in my opinion is not even close to a wide enough aperture for newborn photography.
Maybe the entire difference between how I want to ask this question and how this was previously asked is price. $500 is not even a ballpark figure for what I will spend on a lens. I want to get the best, ignoring price.
Can I ask the exact same question and remove the price barrier?
As a side note, the thread doesn't mention the 35mm f/1.4 L or 24 f/1.4 L, which are two HUGE reasons to even select full frame, and in my opinion may be the BEST newborn lenses available(I could be wrong, that is why I want to ask).

A:

Since the original question has an explicit budgetary requirement, asking something similar but with a higher or unlimited budgetary limit would be acceptable. However, to be honest, I think you particularly are probably quite capable of deciding for yourself, dpollitt. ;) You've already narrowed it down to two key options...the 35/1.4 and 24/1.4. You are skilled enough to know why those lenses could fit your need, and only you are capable of deciding what you really want to spend on such a lens. I'm not really sure asking a question here will give you any other insight you can't garner for yourself.


Q:

Beresheit 3:21: What was the material Hashem used to cover Adam and Chava?

I'm seeking a general consensus on what material Hashem used to clothe Adam and Chava. I realize there are various translations stating they were leather or animal skins. Commentaries range from materials like that of fingernails or wool or linen. The Hebrew word used is kotnot but that means gown or garment but does not describe the actual material it was made of.

A:

Midrash Rabbah - Genesis XX:12
Skin was a smooth and shiny surface that was fingernail-like. Machlokes in the Gemara if they were clothed in a type of animal's hide and which type of animal.


Q:

How to include urls with app_name without having to use reverse with app name in Django?

I have a custom directory for allauth templates. I need some custom urlpatterns as well as I don't want some default views. I wanted to start with glueing in the entire allauth and change things that I need later on.
My main app config/urls.py file
from django.urls import include, path

urlpatterns = [
    path("account/", include("users.urls")),
]

Users app:
users/urls.py
app_name = "users"

urlpatterns = [
    path("login/", allauth_views.login, name="account_login"),
    path("logout/", allauth_views.logout, name="account_logout"),
    path("signup/", allauth_views.signup, name="account_signup"),
]

With this basic setup, if I go to /account/login it routes correctly to the desired view, but it is defined in users app with the app_name = "users", therefore, I have to access it in other views with reverse(users:account_login). The problem is that allauth LoginView has this method
    def get_context_data(self, **kwargs):
        ret = super(LoginView, self).get_context_data(**kwargs)
        signup_url = passthrough_next_redirect_url(self.request,
                                                   reverse("account_signup"),
                                                   self.redirect_field_name)
        redirect_field_value = get_request_param(self.request,
                                                 self.redirect_field_name)
        site = get_current_site(self.request)

        ret.update({"signup_url": signup_url,
                    "site": site,
                    "redirect_field_name": self.redirect_field_name,
                    "redirect_field_value": redirect_field_value})
        return ret

which does the lookup on reverse("account_signup") but Django gets lost and throws django.urls.exceptions.NoReverseMatch.
Two solutions:

If I set those allauth urlpatterns in my main urls file it works correctly but I want to keep this file small and define allauth urls in my users app.
If I don't define app_name in my users/urls.py it works properly but I want it for other routes. I consider adding app_name to be a good practice. I could have created another app for allauth without an app name but then I'd have users stuff in two apps.

None of these satisfy me.
What I want:
Can I somehow include them without a namespace? I tried path("account/", include("users.urls", namespace=None)) without any luck.

A:

I wasn't thinking... I can keep my custom users urls in users/urls.py with an app name and create another urls file like users/allauth_urls.py in users app and things work correctly.
Then, with
    path("account/", include("users.allauth_urls")),

Things work as exepcted.


Q:

D3 directed graph nodes as rectangle

I'm very new to D3, I'm trying to draw an directed graph, but I want the nodes to be an rectangle instead of circle. Here is the code that I have tried:
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>Testing</title>
    <style>

.node {
    fill: #ccc;
    stroke: #fff;
    stroke-width: 2px;
}

.link {
    stroke: #777;
    stroke-width: 2px;
}

    </style>
</head>
<body>
    <script src='http://d3js.org/d3.v3.min.js'></script>
    <script>

var width = 640,
    height = 480;

var nodes = [
    { x:   width/3, y: height/2 , width:50,height:50 },
    { x: 2*width/3, y: height/2 ,width:50,height:50 },
    { x: 3*width/4, y: height/2 ,width:50,height:50 },
    { x: 6*width/5, y: height/2 ,width:50,height:50 }
];

var links = [
    { source: 0, target: 1 }
];

var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height);

var force = d3.layout.force()
    .size([width, height])
    .nodes(nodes)
    .links(links);

force.linkDistance(width/2);

var link = svg.selectAll('.link')
    .data(links)
    .enter().append('line')
    .attr('class', 'link');

var node = svg.selectAll('.node')
    .data(nodes)
    .enter().append('rect')
    .attr('class', 'node');

force.on('end', function() {

    node.attr('r', width/25)
        .attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; });

    link.attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

});

force.start();

    </script>
</body>
</html>

but the above code only displays the line, not rectangle, however if I change:
.enter().append('rect')

to
.enter().append('circle')

things are working as expected. Where I'm making the mistake?
And also how can I make the arrow as directed one?
Thanks in advance.

A:

Your doing it in-correctly, you should be doing this:
node.attr('x', function(d) { return d.x; })
    .attr('y', function(d) { return d.y; })
    .attr('width', function(d) { return d.width; })
    .attr('height', function(d) { return d.height; })

instead of circle properties.


Q:

segfault on second calling of opendir

Some background:
I am writing a module for nginx (web server) that allows for on-the-fly setting of root directories in a shared environment. I have a directory that contains other directories, one for each hosting user; given a directory path relating to a requested domain I need to determine which user it belongs to.
--public_dir
---user_1
---user_2
----com/example/www/_public/
---user_3

www.example.com is converted to com/example/www and the function should return "user_2"
The problem:
I successfully do this by opening public_dir, traversing it, and checking each 1st level directory (users) for the existence of com/example/www/_public/ and caching the result. All runs as expected the first time the function is called. The second time segfaults when attempting to open public_dir again (it has been successfully closed in the previous function call):
#define NGX_SHARED_ENV_SHARED_DIR "/var/www/public/"
#define NGX_SHARED_ENV_PUBLIC_DIR "_public"

char* ownerFromDir(char *dir){
    char *owner;
    char fullPath[strlen(NGX_SHARED_ENV_SHARED_DIR)+strlen(dir)+128];
    struct dirent *e;
    struct stat sb;

// ------------ERROR IN HERE----------------------------

    fprintf(stderr, "Before opendir\n");
    DIR *sharedDir = opendir(NGX_SHARED_ENV_SHARED_DIR);
    fprintf(stderr, "After opendir\n");

// -----------------------------------------------------

    if(sharedDir){
        while((e=readdir(sharedDir))!=NULL){
            //is the entry a directory?
            if(e->d_type!=DT_DIR){
                continue;
            }
            if(strcmp(e->d_name, ".")==0 || strcmp(e->d_name, "..")==0){
                continue;
            }
            // build a path to check for /var/www/public/userX/com/example/www/_public
            snprintf(fullPath, sizeof(fullPath), "%s%s/%s/%s", NGX_SHARED_ENV_SHARED_DIR, e->d_name, dir, NGX_SHARED_ENV_PUBLIC_DIR);
            stat(fullPath, &sb);
            //if a matching directory is found then copy the entry name into owner
            if(S_ISDIR(sb.st_mode)){
                int len = 1 + (int) strlen(e->d_name);
                owner = (char*) malloc(sizeof(char)*len);
                free(owner);
                memcpy(owner, &(e->d_name), len);
                break;
            }
        }
        closedir(sharedDir);
    }
    return owner;
}

gdb isn't very helpful even when compiling with gcc -g for debug flags
Breakpoint 1, ownerFromDir (dir=0x603450 "com/example") at ngx_module.h:43
43  char* ownerFromDir(char *dir){
(gdb) step
45      char fullPath[strlen(NGX_SHARED_ENV_SHARED_DIR)+strlen(dir)+128];
(gdb) step
48      fprintf(stderr, "Before opendir\n");
(gdb) step
Before opendir
49      DIR *sharedDir = opendir(NGX_SHARED_ENV_SHARED_DIR);
(gdb) step
50      fprintf(stderr, "After opendir\n");
(gdb) step
After opendir
51      if(sharedDir){
(gdb) continue
Continuing.

Breakpoint 1, ownerFromDir (dir=0x60b4a0 "com/example2") at ngx_module.h:43
43  char* ownerFromDir(char *dir){
(gdb) step
45      char fullPath[strlen(NGX_SHARED_ENV_SHARED_DIR)+strlen(dir)+128];
(gdb) step
48      fprintf(stderr, "Before opendir\n");
(gdb) step
Before opendir
49      DIR *sharedDir = opendir(NGX_SHARED_ENV_SHARED_DIR);
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a99df2 in ?? () from /lib/x86_64-linux-gnu/libc.so.6

EDIT: backtrace
(gdb) backtrace
#0  0x00007ffff7a99df2 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007ffff7a9b446 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#2  0x00007ffff7a9dfc5 in malloc () from /lib/x86_64-linux-gnu/libc.so.6
#3  0x00007ffff7ad651b in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#4  0x0000000000400aea in ownerFromDir (dir=0x60b4a0 "com/example2") at ./ngx_module.h:48
#5  0x0000000000400cb2 in ownerFromDom (domain=0x40116c "example2.com") at ./ngx_module.h:82
#6  0x0000000000400f3f in testOwner (domain=0x40116c "example2.com", expect=0x401150 "user2") at ./ngx_module.c:45
#7  0x0000000000400e27 in runTests () at ./ngx_module.c:29
#8  0x0000000000400d0b in main (argc=1, argv=0x7fffffffe708) at ./ngx_module.c:10

Can anyone please point me in the right direction?

A:

Your code does:
        if(S_ISDIR(sb.st_mode)){
            int len = 1 + (int) strlen(e->d_name);
            owner = (char*) malloc(sizeof(char)*len);
            free(owner);
            memcpy(owner, &(e->d_name), len);
            break;
        }

and that leads to:
return owner;

You've freed the memory so the memcpy() is invalid (accessing memory that you have no right to access) and the return is at the very least dangerous and arguably invalid (you're passing back a pointer to freed memory).
Remove the free() in this code.  Who knows what's going wrong in the calling code, but a moderately plausible guess is 'you free() the returned value', which is a double free, which is also a serious no-no.
As written, the memcpy() could easily corrupt your heap; a double free could corrupt your heap.  So, with two sources of heap corruption, you're very likely to get a crash somewhere as a result, and opendir() does memory allocation, so it is a plausible victim.  If you did a memory allocation before that, it would probably crash instead.


Q:

Does (or did) any monarchy have a limited length of tenure?

Wikipedia's page about monarchies states that they might have "predetermined limits on the length of their tenure". However reading the page there is no mention about any current monarchy who does that.
So, do any current monarchy have such a system, either a simple "time limit" or something more complex? Voluntary abdication doesn't count, obviously.
If not, are there any (recent or ancient) notable examples of monarchies with such a rule?

A:

I'll look at non hereditary absolute rulers first, which are similar to monarchies. If you look up Dictator, you'll find examples of absolute rulers who had set terms. Roman Dicatators being the original example as well as Giuseppe Garibaldi.
Many states have or have had emergency power laws that effectively result in a dictator for the duration of an emergency (although sometimes this doesn't go so well, Article 48)
Protectors spring to mind as well.  So do puppet rulers, colonial governors, Proconsuls and others who ruled like kings but bowed a knee to an external authority.
As for monarchies, recently with Queen Beatrice's abdication we've been reminded of Dutch tradition, where an aged monarch is expected to abdicate. But did you know it was also expected in Medieval Japan, where it was practice for emperors to step aside so the heir could ascend relatively young. In addition, before Meiji Restoration it was common for empresses (women) to rule for the minimum time until a male descendant was old enough to rule. Women leaders acting as a temporary "stop-gap".
None of these aren't hard and fast term limits, but they are clearly informal limits on length of rule.

A:

The only modern day examples of monarchies with limited tenure are Malaysia and the United Arab Emirates.
"There are two elective monarchies, Malaysia and the United Arab Emirates, where the constituent states of each federation are hereditary monarchies but those rulers form an electoral college which assigns the federal position of head of state to one of their number for a term (of five years)."
source: Wiki page on Hereditary Titles
There are some other examples in there as well of some more ancient monarchies.

A:

Roman king (rex) had a limited term of 8 years, but this was never observed. The kings manipulated the law to extend their term.
Under Diocletian the Dominate system was established in Roman Empire where an emperor's term was limited to 10 years. But only a few emperors followed this limitation, which soon became obsolete. But it is not certain whether Dominate should be considered a monarchy.


Q:

Finite Non Commutative Rings of Cardinality n

For any given $n\in N$, Can we find a non-commutative ring of $n$ elements (with or without identity)?
If not, can we find some condition on $n$ such that a non-commutative ring of $n$ elements exists?
I found some examples here https://ringtheory.herokuapp.com/search/results/?H=43&L=1 but I want the examples for any $n$.

A:

TL;DR
There are rngs that aren't commutative of every finite order that is not squarefree.
There are rings that aren't commutative of every finite order that is not cubefree.

The smallest a noncommutative ring without identity can be is $4$ elements: see this post for an explanation.
It is obvious how to repeat this feat for any prime $p$ so that you have a noncommutative rng of order $p^2$ for any prime.
Then you have a noncommutative rng for any nonsquarefree number, because you just do the product of you noncommutative rng times $\mathbb Z_n$ for some strategically chosen $n$.
If the order is squarefree, then its underlying abelian group is necessarily cyclic. This implies the ring is commutative since you are just multiplying things of the form $m\cdot c$ where $m$ is a natural number and $c$ is the generator.
Trying to do the same thing for rings with identity, it’s immediately clear that you have noncommutative rings of order $p^3$ for any prime(namely the upper triangular 2 by 2 matrices over finite fields), and so all noncubefree orders are covered.
It is also known that all rings of order $p^2$ (with identity obviously) are commutative.
A la this answer, you can argue that the subgroup of elements of additive order divisible by $p$ is an ideal and that the subgroup of elements of additive not divisible by $p$ is another ideal. Furthermore, they have intersection $\{0\}$ and their sum generates the whole ring, so in fact the representation is a direct sum of ideals.  Repeating this, you can eventually decompose the ring into a product of rings of order $p^2$ or $p$ for distinct primes $p$.  Since these are all necessarily commutative, the whole ring is commutative.
PS: thanks for using my site.


Q:

Running Jupyter notebook from ubuntu server I'm ssh'ed into

I'm trying to set up Spark on an ubuntu server. My preferred way to use spark is through a Jupyter notebook (pyspark).
When I run
$ jupyter notebook

It starts it within the terminal. Ideally I'd like it to feed me a host address where I can access the Jupyter notebook from another computer (on the same network). Any ideas?

A:

You could start the notebook server with
jupyter notebook --ip='*' --no-browser

which would allow access to the notebook server by visiting http://10.0.0.10:8888 in your browser, assuming that 10.0.0.10 is the IP address of the machine running the server.
The --no-browser option will prevent the text browser from opening. Instead you should see the exact address you need to visit printed to the console.
Be careful with that though, because this will allow access from all machines on your local network. So people on the same network may run arbitrary Python code on your host.