text:
Q: Connection to container of DataStax Distribution of Apache Cassandra I created Docker container of DataStax Distribution of Apache Cassandra (DDAC):
docker pull datastax/ddac
docker run -e DS_LICENSE=accept --name ddac -d datastax/ddac

docker ps

I got the error while connecting to the node via Datastax DevCenter:

The same error occurred during try connect via 7000 and 7199 ports.

How to connect to DDAC node deployed in a docker container?

UPDATE
I disabled Windows Firewall just in case.
Use docker run -e DS_LICENSE=accept --name ddac -p 9042:9042 -d datastax/ddac and got same error:

The specified host(s) could not be reached. All host(s) tried for
  query failed (tried: localhost/0:0:0:0:0:0:0:1:9042
  (com.datastax.driver.core.exceptions.TransportException:
  [localhost/0:0:0:0:0:0:0:1] Channel has been closed),
  localhost/127.0.0.1:9042
  (com.datastax.driver.core.exceptions.TransportException:
  [localhost/127.0.0.1] Channel has been closed))
  [localhost/0:0:0:0:0:0:0:1] Channel has been closed
  [localhost/127.0.0.1] Channel has been closed

A: That happens because container has it's own IP, and you need to either connect to it - you can get the IP of container with
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ddac

or expose Cassandra ports on the host, so you can connect via localhost - this is done via -p flag of docker run:
docker run -e DS_LICENSE=accept --name ddac --rm -p 9042:9042 -d datastax/ddac


text:
Q: How to avoid Immutable.JS functions/accessors inside React components I'm coding an application using React for UI, Redux to manage the state and Immutable.js to mutate the state, however, I'd like to know how to avoid the use of Immutable.JS accessors in my React components, like get() or getIn().
I believe that using that Immutable.JS accessors will infect my React components. How to avoid that?

A: I don't think you're going to have much in the way of an option here if you want to keep it immutable. You could convert it toJS, but then you'd be losing the benefits of object identity comparison for re-rendering pure components. Your best bet is probably to hold your nose and pretend it's basically a JavaScript Map.
Aside from that, if you're not attached to Immutable.js, you might consider using something like seamless immutable which behaves a lot more like native JavaScript arrays and objects. Or you could go old-fashioned and just Object.freeze() things yourself.

A: The way to avoid Immutable.JS accessors and use the dot-notation is using the Record structure from Immutable.JS.
First we must create a template:
const MyTemplate = Record({
  id: 0,
  name: ''
})

...
case ContentFilterTypes.ADD_ITEM:
    return {
        listObjects : state.listObjects.push(new MyTemplate({
            id: action.item.id,
            name: action.item.description,
        }))
    }

To access it in the presentional, we need only to set the prop that we want to get information, like:
<ContentFilterAvatar id={value.id} name={value.name} />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lighttpd Execute ./cgi-bin/index.cgi if exists in the folder BusyBox httpd executes the ./cgi-bin/index.cgi if it exists. This is similar to index.php but with the /cgi-bin/ folder.
So for example I have the structure:
/api/
  cgi-bin/index.cgi
/blog/
  cgi-bin/index.cgi
  /rss/
    cgi-bin/index.cgi

So when request are going to http://example.com/api/ they are actually handled by the /www/api/cgi-bin/index.cgi script.
When requested http://example.com/blog/ it's processed by /www/blog/cgi-bin/index.cgi but the /blog/rss/ path is processed by /www/blog/rss/cgi-bin/index.cgi.
But now I also want to support the Lighttpd webserver.
How can I achieve that?
This seems similar to Making lighttpd redirect from www.example.com to www.example.com/cgi-bin/index.pl but much more complicated.

A: The simplest solution is to use lighttpd mod_indexfile:
index-file.names = ( "cgi-bin/index.pl" )
An alternative if you want to internally rewrite the target, try lighttpd mod_rewrite:
Generically:
url.rewrite-once = ( ".*/(?:\?|$)" => "${url.path}cgi-bin/index.pl${qsa}" )
More precisely for only the paths in your example:
url.rewrite-once =
  ( "^/(?:api|blog(?:/rss)?)/(?:\?|$)" => "${url.path}cgi-bin/index.pl${qsa}" )


text:
Q: Docker Swarm mesh ports limit only to worker nodes? I am trying out current release of Docker Swarm as a solution for easy deployment of our application. One concern we have is manager nodes security, so we try to separate them as much as possible. And from what it looks is that ALL nodes participate in routing mesh by default. So that once an app publishes port (say 8080) ALL nodes no matter worker or manager will have that port exposed and route traffic on it t application (as seen using netstat -lnptu).
My question is -- is there any way in Swarm to restrict that say appA port 8080 only exposed on workers?


text:
Q: What is your favorite HexEditor? What are the most available open source GUI hex-editor for the Ubuntu LTS 14.04 Desktop? I have HexEdit running on OS X, and am looking for something similar. A bit more modern perhaps, with good functionality, stability, easily installed and integrated. This is a system for a novice programming student learning Linux and examining code. how would you compare: Ghex, Bless, and wxHex? Any suggestion appreciated.

A: Bless is a high quality full featured hex editor.
Bless currently provides the following features:

*

*Efficient editing of large data files and block devices.

*Multilevel undo - redo operations.

*Customizable data views.

*Fast data rendering on screen.

*Multiple tabs.

*Fast find and replace operations.

*Advanced copy/paste capabilities.

*Highlighting of selection pattern matches in the file.

*Export to text and html (others with plugins).

*Extensibility with Plugins.

You can compare hex editors here.
Installation:
Press Ctrl+Alt+T to open a terminal and run:
sudo apt-get install bless
Alternatively
click this link.

A: I have been using wxHexEditor - full featured / stable + source !
Handles HUGE files with ease (only limited by your RAM)
sudo apt-get install wxhexeditor  #  then launch using  wxHexEditor

___ OR ___
git clone https://github.com/EUA/wxHexEditor.git
cd wxHexEditor
make -j$(nproc)
sudo make install
wxHexEditor

Before compiling wxHexeditor you need wxWidgets and autoreconf on your system ... just install those libraries :
sudo apt-get build-dep  wxhexeditor

if make gives you this error
make: *** No rule to make target '-lgomp', needed by 'src/HexEditorGui.o'.  Stop.

then edit file Makefile and remove this line
LIBS += -lgomp

for details see https://github.com/EUA/wxHexEditor/issues/150
I then do
sudo ln -s /usr/local/bin/wxHexEditor /usr/local/bin/wxhexeditor

so I can launch it using lowercase  wxhexeditor


text:
Q: Is it possible to ignore GitHub files for sync only? I'm pretty new to GitHub, but I'm using it for some time now for local version tracking of small web development projects. Suppose I have a project that contains a bunch of HTML, CSS and JS files but also a PHP file to access a MySQL database. The PHP file contains my MySQL credentials including password, so obviously I don't want to make this file public. I want to keep track of all changes to my project locally, including the PHP file, but in case I wanted to put the project online, I needed some way to exclude this file from syncing.
So my question is: Can I ignore a file from syncing with my GitHub account while still being tracked in my local repo? And in case I'm totally on the wrong track, I'll be happy to hear more solid solutions to this problem. Thanks!

A: There are many solutions to omit parts of files, but those are too complex for when you are just beginning using git. Most tricks evolve around so called filters, commands that parse and create files on checkout on your production site. But you don't need these.
The easiest trick gives you the additional benefits of making the application a bit more secure and more portable.
It is safer because all the secret data is kept in one file that can get really strict permissions (so that people who have access to e.g. FTP onto the codebase, cannot see the creds).
It is better portable, because it allows your team to run their own credentials on their own development machines the way they want them. e.g. someone using XAMP may have different database-names then someone using virtual machines or homebrewn scripts to manage their project.
On the server, create a file /path/only/www-data/has/read-access/secret.inc
<?php
/** Hashing **/
define("SECRET_HASH", "hogwards");

/** Database **/
define("DB_USER", "harry");
define("DB_PASS", "alora");
?>

Then, in your settings.php, or where you store these creds now,:
<?php
require("/path/only/www-data/has/read-access/secret.inc");
// Or slightly more portable
// require("../etc/secret.inc");
?>

You can also check in an example secret.inc for new collaborators, secret.inc.example, having the defines, but with empty strings as values.
Now you can simply push settings.php along with all other commits. And it will pick up the "secrets.inc" as found on production; using the proudction-server login details for e.g. your database.

A: It isn't possible to push commits while omitting some of the content.  Doing so would cause the SHA1 identifier to change, resulting in a different commit.
You could do the public development on one branch, and then merge those changes into another branch where you track the configuration information which needs to be kept private. Since you can switch branches while carrying uncommitted changes, you could even do most of the development and testing with the private branch checked out only switching to the public branch to do the commit then switching back and merging those changes in.
But, you would need to be careful when pushing to only push your public branch and not the private branch.  In general it is a much better idea to keep the information that you don't want to push in a small separate file which can safely be ignored from tracking altogether.

A: You can ignore files being tracked on your git repository. That very common for similar cases.
There is a file called .gitignore on the root of you project. In this file you put the path of the files you don't want to track in the git repository.
Please, find a complete explanation on how to use at: https://help.github.com/articles/ignoring-files
In your case, you will have to manually send this "database configuration" files to your server.

A: No, this is not possible, but I do think you're not doing it correctly. It is a bad practice to store credentials in a PHP file. You should have a different file with settings, but then again, depending on where you put that settings file and how important it is to have a stub settings file in your repository, you might be back to the same problem, but in a different file.


text:
Q: Is there a better way to create asynchronous updates without using setInterval? I have multiple parts of my site which check for updates every half a second, so it can alert you of messages, etc. However I feel that using $.post with a setInterval could be a bit heavy on the site. Is there an alternative method that is better recommended for these tasks?

A: Yes, although it's not trivial.
The better approach
You can use long polling (or "comet"), which opens a connection, keeps it open for 20s or so, and the immediately re-opens it. The server can send something at any time.
Newer browsers provide websockets, which provides persistent connections.
Both are relatively complex to code so you need some kind of framework to handle things for you. Also, a connection needs to be kept open for each user, so it only really works with something lightweight like NodeJS.
The easier approach
If you want something easier to implement, I would recommend checking for updates as you suggested (it's called short polling to contrast it with long polling/websockets). You can do a simple polling solution like so:
window.setInterval(function () {
  // More lightweight than $.post
  $.get('/datasource', function () {
    /* do something */
  });
}, 3000);

3 seconds intervals have been used in used before by high profile people.
If things get slow, try profiling database queries in /datasource

A: socket.io would be the way to go if you're using nodeJS. Otherwise, checkout this jQuery plugin, it has graceful degradation implemented even though not as comprehensive as socket.io.


text:
Q: How to make a directive for adding sections in angular at runtime based on attribute value I have many sections like

And Accordingly i have different code  maintained in their html files like home.html and about.html and want to make a angular custom directive to render at runtime
And i had tried for making a directive but it works only first time not when i am using multiple times . so need help for making this directive
app.directive('mysection', function() {
return {
   restrict: 'E',
   transclude:true,
   templateUrl: function(elem,attrs) {
       return "sections/"+attrs.templateUrl +".html"
   }
}
});

And in html i am writing
<mysection template-url="headerSection"><mysection>
<mysection template-url="headerSection"><mysection>

A: try this markup
<mysection template-url="headerSection"></mysection>
<mysection template-url="headerSection"></mysection>

Note the close tag

A: Thanks Alex referring to your code i had reached to the solution
app.directive('mysection', function() {
return {
   restrict: 'E',
   templateUrl: function(elem,attrs) {
       return attrs.folderName+"/"+attrs.templateUrl +".html"
   }
 }
});

And following is the html code:
<mysection folder-name="sections" template-url="headerSection"></mysection>


text:
Q: read values in a table with submit button i have three columns in a html table whose rows r filled from json array values
 $.each(responseJson, function(key,value) {
                      if(responseJson!=null){
                                            var rowNew = $("

");
                                            rowNew.children().eq(0).text(value['attr']);
                                            rowNew.children().eq(1).html(value['ranking']);
                                            rowNew.children().eq(2).html(value['type']);
                                            rowNew.appendTo(table1);
                                        }
                                    });

Col1,col2,col3
a,drop1,drop2
b,drop3,drop4
column 3 and 4 are dropdown menus. when i select dropdown values for all the rows and submit it . i need to get the values in servlet something like this.
a - 1- int
b - 2 - string
how do i do this

A: Assuming the
 is inside a <form>, if you give the form elements a name attribute, you can get their value in servlet like
request.getParameter("name-of-form-element"); as a string,
for eg
String name = request.getParameter("name");

which you can cast into different types.


text:
Q: combine fade and slide ( left/top/bottom/right ) with AngularJS I see a lot of single page app(s) that uses fade-in and slide-up during scrolling etc ..
But I can't seem to find anything that I can integrate only with Angular's ngAnimate, in all websites it's either install their new code with new lib and I want to stop myself from keep installing 1000 modules that at some point I can't scale ( because I don't know how to combine two animation at once )
I've seen this code example: http://codepen.io/astrotim/pen/KDBbe
And I was trying to import it and adjust it to be used with AngularJS but w/o any luck :/
HTML
<div ng-if="front_wallpaper" class="animated fade-and-slide"> MyText </div>

Angular's app JS
angular.module('app', ['ngAnimate'])
.controller('SomeCtrl', function ($scope, $timeout) {
    $scope.front_wallpaper = false;
    $timeout(function () {
        $scope.front_wallpaper = true;
    },1000);

});

CSS
div {
            font-size: 48pt;
            color: white;
            position: relative;
            left: -60%; top: 20%;
            opacity: 0;
            transition: all .75s ease;
            transition-duration: 5s;
        }

.fade-and-slide.ng-enter {
  top: 21%;
  opacity: 1;
}

Animation example: http://shapebootstrap.net/item/1524946-lucid-html5-and-bootstrap-responsive-template/live-demo
Or the white buttons here: http://wrapbootstrap.com/preview/WB0F82581
Thanks in advance

A: Just found the answer, if we're using animation ( not transition ) we can define several animations with a comma delimiter, i.e: openSpace & moveIn
  -webkit-animation:
    openSpace 2s ease forwards,
    moveIn 0.3s 0.2s ease forwards;

Full example
.list-item.ng-enter {
  max-height: 0;
  opacity: 0;
  transform: translateX(100%);

  -webkit-animation:
    openSpace 2s ease forwards,
    moveIn 0.3s 0.2s ease forwards;
}

@-webkit-keyframes openSpace {
  to {
    max-height: 300px;
  }
}

@-webkit-keyframes moveIn {
  to {
    opacity: 1;
    transform: translateX(0);
  }
}


text:
Q: elem.innerHTML is only usable after a set timeout I am currently working on an Angular1 app. I am getting data from an API and in the promise resolve (success) I first assign different values (some of them will be used in the view) and after that, I call a function to manipulate a specific text (add a border and background-color to a party of the sentence). I get the label with document.getElementById and afterwards use label.innerHTML.replace(..).
However, the replace function does not do anything. And the view does not show a value for {{text}}. It only works if I use a timeout of 1 sec: the replace function works and the view text is updated (with a border and background-color).
Controller code with hacky setTimeout():
$scope.getTextAnalysis = function () {
    IntentRequestService.analyzeText($scope.intentApp.id, $scope.intentvalue)
      .success(function (response) {
        $scope.results = response;
        $scope.text = $scope.results.text;
        highlightEntities($scope.results);
      })
      .error(function (e) {
        ErrorHandlingService.logErrors(e);
      })
  };

  function highlightEntities(results) {
    var text = results.text;
    var entities = results.entities;
    _.forEach(entities, function (entity, i) {
      var entity_value = text.substring(entity.start, entity.end);
      var color = randomColor({
        luminosity: 'light'
      });
      var borderColor = ColorLuminance(color, -0.3);
      $scope.entities[i].backgroundColor = borderColor;
      $scope.entities[i].color = color;
      var label = document.getElementById('match-text');
      setTimeout(function(){ label.innerHTML = label.innerHTML.replace(entity_value, ''+ entity_value + ''); }, 1);
    });
  }

View:

Sentence:

{{text}}

Does anyone know how to do it without the timeout as I think it is a very hacky and ugly way to do it?

A: Pass your label element to the function called by setTimeout:
setTimeout(function(label) {
  label.innerHTML = label.innerHTML.replace(entity_value, '' + entity_value + '');
}, 1, label);


text:
Q: I have a html page with form.I want to write it to a file and then use the file content for my app I have a html page and an android app both are separate, but on the same server.So I want to get the input field values from the form and put it in a text file.And use these value from text file for processing.
For example :
in form, input would be 6(any number). So I want to create 6 different buttons and some text inputs which will be the name of buttons.
How should I go about this using php ?Thanks

[0307/175819.921:ERROR:file_io_win.cc(163)] CreateFile C:\Program Files (x86)\settings.dat: Access is denied. (0x5)
  [0307/175819.924:ERROR:registration_protocol_win.cc(84)] TransactNamedPipe: The pipe has been ended. (0x6D)
  [0307/175819.927:ERROR:file_io_win.cc(163)] CreateFile C:\Program Files (x86)\settings.dat: Access is denied. (0x5)
  [0307/175820.050:ERROR:crashpad_client_win.cc(660)] crash server failed to launch, no dump captured

A: I received the same error while using latest AngularJS version. But, When I tried with little older version, the issue has been resolved.
Below does not work for me.
<script    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

But, this worked.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><script>


text:
Q: Modify background of all TreeView items in PyGObject I want to have a (from default) different color my items in a Gtk.TreeView. The example code below has no effect. The background keeps white.
#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk

class MyTree(Gtk.TreeView):
    def __init__(self):
        Gtk.TreeView.__init__(self)

        # color
        color = Gdk.RGBA(221, 29, 157, 1)

        # model
        model = Gtk.TreeStore(int)
        for i in range(4):
            model.append(None, [i])
        self.set_model(model)

        # column
        ren = Gtk.CellRendererText(background_set=True,
                                   background_rgba=color)
        col = Gtk.TreeViewColumn('int', ren)
        col.add_attribute(ren, 'text', 0)
        self.append_column(col)

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        tree = MyTree()
        self.add(tree)
        self.connect('destroy', Gtk.main_quit)

if __name__ == '__main__':
    win = MyWindow()
    win.show_all()
    Gtk.main()

A: It was just a "bug". I used the Gdk.RGBA() the wrong way. It's parameter are valid only between 0.0 and 1.0.
color = Gdk.RGBA(.2, .9, .15, 1)


text:
Q: Tool for automatically check docstring style according to PEP257 Tools like pep8 can check source code style, but they don't check if docstrings are fromatted according to pep257, pep287. Are there such tools?
Update
I decided to implement such a static analysis tool on my own, see:
https://github.com/GreenSteam/pep257
Right now, most of pep257 is covered.
Design was heavily influenced by mentioned pep8 tool.

A: I don't know of any static analysis tool for python doc strings. I actually started building one shortly after getting started with PyLint but quickly gave up.
PyLint has a plugin system and a doc string plugin is doable if you wanted to put the work in to make the PEPs executable.
PyLint "plugins" are called checkers and come in two forms: those working with the source file as a raw text document and those working with it as an AST. I made my attempt starting from the AST. This may have been a mistake in retrospect.
Here's what I had:
class DocStringChecker(BaseChecker):
    """
    PyLint AST based checker to eval compliance with PEP 257-ish conventions.
    """
    __implements__ = IASTNGChecker

    name = 'doc_string_checker'
    priority = -1
    msgs = {'W9001': ('One line doc string on >1 lines',
                     ('Used when a short doc string is on multiple lines')),
            'W9002': ('Doc string does not end with "." period',
                     ('Used when a doc string does not end with a period')),
            'W9003': ('Not all args mentioned in doc string',
                     ('Used when not all arguments are in the doc string ')),
            'W9004': ('triple quotes',
                     ('Used when doc string does not use """')),
           }
    options = ()

    def visit_function(self, node):
        if node.doc: self._check_doc_string(node)

    def visit_module(self, node):
        if node.doc: self._check_doc_string(node)

    def visit_class(self, node):
        if node.doc: self._check_doc_string(node)

    def _check_doc_string(self, node):
        self.one_line_one_one_line(node)
        self.has_period(node)
        self.all_args_in_doc(node)

    def one_line_one_one_line(self,node):
        """One line docs (len < 80) are on one line"""
        doc = node.doc
        if len(doc) > 80: return True
        elif sum(doc.find(nl) for nl in ('\n', '\r', '\n\r')) == -3: return True
        else:
            self.add_message('W9001', node=node, line=node.tolineno)

    def has_period(self,node):
        """Doc ends in a period"""
        if not node.doc.strip().endswith('.'):
            self.add_message('W9002', node=node, line=node.tolineno)

    def all_args_in_doc(self,node):
        """All function arguments are mentioned in doc"""
        if not hasattr(node, 'argnames'): return True
        for arg in node.argnames:
            if arg != 'self' and arg in node.doc: continue
            else: break
        else: return True
        self.add_message('W9003', node=node, line=node.tolineno)

    def triple_quotes(self,node): #This would need a raw checker to work b/c the AST doesn't use """
        """Doc string uses tripple quotes"""
        doc = node.doc.strip()
        if doc.endswith('"""') and doc.startswith('"""'): return True
        else: self.add_message('W9004', node=node, line=node.tolineno)

def register(linter):
    """required method to auto register this checker"""
    linter.register_checker(DocStringChecker(linter))

As I recall this system doesn't have great docs (that may have changed in the past year). This at least gives you something to start hacking on / really simple code in place of docs.

A: I don't think it's validating against any PEPs, but Epydoc will check that all of the referenced parameters and objects in docstrmap to valid parameters and objects.


text:
Q: How to create timestamp in seconds I have this task to populate this field:

x_fp_timestamp is the timestamp created when the form is generated. It
  is equal to the number of seconds since January 1, 1970 in UTC
  (Coordinated Universal Time).

So what I do in C# is
 long ts =  DateTime.Now.Ticks / TimeSpan.TicksPerSecond;

But in that case I am getting this error:

*

*x_fp_timestamp : x_fp_timestamp invalid. Not within 15 minutes of
  present time: Thu Jan 10 21:30:25 GMT 2013. Expected 1357853425
  plus/minus 900, but received 63493442997.

So my question is how to generate current timestamp in seconds?

A: I found DateTimeOffset.ToUnixTimeSeconds to work best for my specific situation (Unity 3D [.NET standard 2.1])
    long timeNow = DateTimeOffset.Now.ToUnixTimeSeconds();
    string timeStamp = timeNow.ToString();

A: DateTime.Now.Ticks does not start at 1970; try something like this instead:
 (DateTime.Now.ToUniversalTime() - new DateTime (1970, 1, 1)).TotalSeconds


text:
Q: Most Resource-Efficient Way to Deploy Multiple Rails Apps on a Single Server I have a Virtual Dedicated Server that I use to host small websites that aren't large enough to justify their own dedicated slice.  I am a Rails developer and am currently using an Ubuntu/Nginx/Mongrel Cluster/SQLite stack to deploy these applications.
I feel that the memory being consumed by each Mongrel instance is too high.  I am wondering what the recommended way to serve these applications is to keep resource usage to a minimum.  I have heard that Mongrel is no longer recommended in favor of Passenger.  I have continued using Mongrel, though, because I feel that it is more lightweight.  This may be a complete misperception on my part, though.
Any ideas?

A: Having Passenger + Enterprise RoR may help with the memory footprint (and probably performance).


text:
Q: Python, script to input a string and get the output I'm building a script to input a taiwanese address ('928屏東縣東港鎮嘉新路160、162號') into this website URL = "https://www.latlong.net/convert-address-to-lat-long.html" and get the latitude and logitude as output.
I tried some htlm readers like beautiful soap or selenium but without success, probably I am missing something. Can anybody suggest me what I need to fix to print the output in python?
import urllib, os, urllib.request, time,  requests, re
from bs4 import BeautifulSoup
import pandas as pd
import requests
from selenium import webdriver
import re

URL = "https://www.latlong.net/convert-address-to-lat-long.html"
PropertyAddress_CN = "928屏東縣東港鎮嘉新路160、162號"

input_address = {"Type address here to get lat long":PropertyAddress_CN}

r = requests.post(URL, data = input_address)

soup = BeautifulSoup(r.content, 'lxml')

result = soup.find_all()

print(soup)

A: The website uses an API end, to which you can post directly:
import requests

url = "https://www.latlong.net/_spm4.php"
r = requests.post(
    url,
    data={"c1": "928屏東縣東港鎮嘉新路160、162號", "action": "gpcm", "cp": ""},
    headers={"x-requested-with": "XMLHttpRequest"},
)
if r.status_code == 200:
    lat, long = r.text.split(",")
    print("Latitude {}, Longitude {}".format(lat, long))

Please make sure you comply with the terms and conditions of the webservice.


text:
Q: Why is my secondary featured image not showing in using Wordpress? I am using wordpress and am using featured images(they used to be called post thumbnails). I wanted to use multiple featured images, so I chose to use the Multiple Post Thumbnails Plugin.
I can get the Secondary Image Upload box to show up in the admin area, but I can't manage to get the image to display on the page.
This is the code I am using to try and make it display (From: http://wordpress.org/extend/plugins/multiple-post-thumbnails/installation/):
<?php if (class_exists('MultiPostThumbnails')
    && MultiPostThumbnails::has_post_thumbnail('post', 'secondary-image')) :
        MultiPostThumbnails::the_post_thumbnail('post', 'secondary-image'); endif; ?>

I tried adding a random echo inside the if statement to see if it gets hit, but it doesn't echo out, so i'm guessing somehow the condition is not being met?
What am I missing?

A: First of all, I guess it is necessary to enable thumbnails, too:
// This theme uses post thumbnails
add_theme_support( 'post-thumbnails' );

Then you have to add something like
if (class_exists('MultiPostThumbnails')) {
    $types = array('post', 'page', 'my_post_type');
    foreach($types as $type) {
        $thumb = new MultiPostThumbnails(array(
            'label' => 'Secondary Image',
            'id' => 'secondary-image',
            'post_type' => $type
            )
        );
    }
}

in your themes functions.php file within the theme_setup() {...} function.
HTH, mtness.


text:
Q: Closure relative to addition and scalar multiplication I'm working with an old Introduction to Linear Algebra book by Gillet, and in the book he claims that a subset of a vector space is guaranteed to be a subspace if it satisfies closure relative to addition and scalar multiplication. I've also heard my teacher mention something similar to this effect when we were working one-on-one. I'm not entirely following how all of the other vector space axioms (additive identity, scalar multiplicative identity, etc.) arise from just closure. Could someone please elaborate on this for me? I've seen related questions, but all of them seem to be about proving a subset is a subspace for a specific problem, rather than the general logic involved.

A: Assume that $U \subset V$, where $V$ is a $K$-vector space, is closed under addition and scalar multiplication (here K is the underlying scalar field, which "usually" is $\mathbb{R}$).
Now, if $U$ is empty, there is nothing to prove. So let $x \in U$. We have that $-1 \in K$. Thus $(-1).x=-x \in U$, by multiplicative closure. Also, $x+(-x)=x-x=0 \in U$, by additive closure. Thus we have shown that additive identity is contained in $U$.
It is clear that distributivity of addition over scalar multiplication, associativity and commutativity, are induced by the same properties which hold in $V$ - they hold for all elements of $V$, thus for all elements of $U$.
Similarly, the multiplicative axioms follow immediately by the fact that they hold for all $v \in V$ and thus for all $u \in U$.


text:
Q: Sentence case for titles in biblatex I'd like to have the titles of articles in Biblatex in sentence case (first word capitialized, the rest lowercase, override with {}) as is the default in Bibtex.
I tried:
\DeclareFieldFormat{titlecase}{\MakeSentenceCase{#1}}

However it also makes converts other fields into sentence case, such as the booktile:
[Pai99] P Paillier. " Public-key cryptosystems based on composite degree residuosity classes". Eurocrypt. 1999

I'd like:
[Pai99] P Paillier. " Public-key cryptosystems based on composite degree residuosity classes". EUROCRYPT. 1999

(This assumes that booktitle is EUROCRYPT in the .bib file)
Is there anyway to do this, short of adding {} to each booktitle entry?

A: biblatex-ext introduces new field formats for a finer control over title casing. Where standard biblatex has the format titlecase that applies to all title-like fields alike, biblatex-ext has

*

*titlecase:title

*titlecase:booktitle

*titlecase:maintitle

*titlecase:maintitle

*titlecase:journaltitle

*titlecase:issuetitle
which apply only to the specific field in their name. As usual, these field formats can be defined per type. See pp. 21-22 of the biblatex-ext documentation. (Of course biblatex-ext still supports the standard titlecase format.)
If you only want the titles of entries whose titles are in quotation marks in sentence case, then use
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}

\usepackage[style=ext-authoryear, backend=biber]{biblatex}

\DeclareFieldFormat
  [article,inbook,incollection,inproceedings,patent,thesis,unpublished]
  {titlecase:title}{\MakeSentenceCase*{#1}}

\addbibresource{biblatex-examples.bib}

\begin{document}
\nocite{springer,weinberg,doody,maron,pines}
\printbibliography
\end{document}

A: The format definition
\DeclareFieldFormat{titlecase}{\MakeSentenceCase{#1}}

makes all titles in sentence case, which isn't what you want. Titles need to be printed according to both the entry and field types. For example, with the title field we need to handle @article and @book entries differently. With @inproceedings entries we need to handle the title and booktitle fields differently.
To do this we can redefine the title bibmacro to print the title field of @article and any @in* entry type in sentence case. Taking the original definition found in biblatex.def:
\DeclareFieldFormat{sentencecase}{\MakeSentenceCase{#1}}

\renewbibmacro*{title}{%
  \ifthenelse{\iffieldundef{title}\AND\iffieldundef{subtitle}}
    {}
    {\ifthenelse{\ifentrytype{article}\OR\ifentrytype{inbook}%
      \OR\ifentrytype{incollection}\OR\ifentrytype{inproceedings}%
      \OR\ifentrytype{inreference}}
      {\printtext[title]{%
        \printfield[sentencecase]{title}%
        \setunit{\subtitlepunct}%
        \printfield[sentencecase]{subtitle}}}%
      {\printtext[title]{%
        \printfield[titlecase]{title}%
        \setunit{\subtitlepunct}%
        \printfield[titlecase]{subtitle}}}%
     \newunit}%
  \printfield{titleaddon}}

Alternatively we can identify book-like entries directly and apply sentence casing to everything else. This is trickier because many more types qualify as book-like references and titles for these sources are printed by more than just one macro. In biblatex.def these include: title, booktitle, maintitle, journal, periodical and issue. To avoid redefining all of these, you can redefine the titlecase format instead.
\DeclareFieldFormat{titlecase}{\MakeTitleCase{#1}}

\newrobustcmd{\MakeTitleCase}[1]{%
  \ifthenelse{\ifcurrentfield{booktitle}\OR\ifcurrentfield{booksubtitle}%
    \OR\ifcurrentfield{maintitle}\OR\ifcurrentfield{mainsubtitle}%
    \OR\ifcurrentfield{journaltitle}\OR\ifcurrentfield{journalsubtitle}%
    \OR\ifcurrentfield{issuetitle}\OR\ifcurrentfield{issuesubtitle}%
    \OR\ifentrytype{book}\OR\ifentrytype{mvbook}\OR\ifentrytype{bookinbook}%
    \OR\ifentrytype{booklet}\OR\ifentrytype{suppbook}%
    \OR\ifentrytype{collection}\OR\ifentrytype{mvcollection}%
    \OR\ifentrytype{suppcollection}\OR\ifentrytype{manual}%
    \OR\ifentrytype{periodical}\OR\ifentrytype{suppperiodical}%
    \OR\ifentrytype{proceedings}\OR\ifentrytype{mvproceedings}%
    \OR\ifentrytype{reference}\OR\ifentrytype{mvreference}%
    \OR\ifentrytype{report}\OR\ifentrytype{thesis}}
    {#1}
    {\MakeSentenceCase{#1}}}

edit by @moewe: Note that the biblatex documentation recommends to use the starred form \MakeSentenceCase* instead of \MakeSentenceCase. The starred macro considers the language of the entry (as given in the langid field, or failing that assuming the current language) and only applies sentence case where it is appropriate (by default only for English-language publications).


text:
Q: Curie temperature and magnetization? If an ferromagnetic object is heated and reaches Tc the magnetization gradually drops as we get closer to Tc or it's a instant drop?
Can I assume as I heat the object, the magnetization is weakening gradually? Likewas as it cools?

A: Gradual drop. And its zero above the curie-temperature.

A: Answer by Allah Abdulala Gustavo ElFakir is mostly correct although steep jump can be also observed. Here is an example. As this is first order transition there is some thermal hysteresis. On heating temperature of transition is slightly higher than on cooling. Gradual drop is dramatically more common though. And in this case it occurs at the same temperature for cooling and heating.

A: For the simplest systems exhibiting continuous phase transitions, the magnetization is saturated at zero-temperature and drops continuously until it reaches a vanishing value. This is point is called the critical temperature. Roughly, the Curie temperature (or more precisely, the Curie-Weiss temperature) is an estimate of the critical temperature at which the magnetization vanishes. Intuitively, the magnetization at very high temperatures is zero since the spins, that are the elementary sources of magnetic dipolar fields which gives finite macroscopic magnetization in a given material, fluctuate strongly and on average, do not point in any specific direction, thus giving an overall zero magnetization. Conversely, at zero-temperature (again in the simplest systems), spins that are subject to ferromagnetic interactions want to align to minimize the overall energy of the system and on average give an overall finite magnetization.


text:
Q: nginx autoindex receiving 403 Forbidden I'm having trouble with nginx and autoindex.
Even though I've put it in the site-host, it's still throwing "403 -Forbidden at me"
     location /pics {
             autoindex on;
     }

is what I have as an config
        server {

        listen   80;
        server_name www.domain.com;

        access_log /home/www/log/access.log;
        error_log /home/www/log/error.log;

        location / {

                    root   /home/www/public/;
                    index  index.html index.php;
                    }

        location    /pics {
                    autoindex on;
                     }
              }

I've checked nginx -v and has been built with the autoindex module.
Just getting clueless here.

A: The root set in location / does not apply to location /pics, so if you check your error log, you'll see that nginx is looking in the default root for requests to /pics.  Just remove the location / and set the root and index directives in the server context:
server {
  root /home/www/public;
  index index.html index.php;

  location /pics {
    autoindex on;
  }
}


text:
Q: How to send text to a particular whatsapp user from my app? I want to send a text message ("e.g. Hello World") to a particular whatsapp user from my app.
Base on this whatsapp FAQ link, I can just use the custom URL scheme to launch whatsapp to a particular contact number with a predefine text:
Question:
1) But where to get the contact ID, abid?:
2) How do I know if the contact number has whatsapp in the first place [for iOS we can't access it because of sandbox limitation right?] ?
3) How to insert the contact ID into the URL:
NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"];

if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
}

A: You can UIactivityViewController instead, so apps that support your text will appear:
NSString * text = @"Hello World!!";
NSArray * itemsArray = @[text];
NSArray * applicationActivities = nil;

UIActivityViewController * activityViewController = [[UIActivityViewController alloc] initWithActivityItems:itemsArray applicationActivities:applicationActivities];

activityViewController.excludedActivityTypes = @[
                                                 UIActivityTypePostToWeibo,
                                                 UIActivityTypeAssignToContact,
                                                 UIActivityTypeAirDrop,
                                                 UIActivityTypeAddToReadingList,
                                                 // Whatever you want prevent to appear...
                                                 ];

activityViewController.popoverPresentationController.sourceView = self.view;

[self presentViewController:activityViewController animated:YES completion:nil];

You are also able to add images, etc.


text:
Q: How to extract text from a RDD? I am trying to extract text from a book. Sample line from the book.txt:

Author:  However, Mary warns her mother that she hasn't changed since
  she has worked last summer.
  It was warm summer and the city was
  filled with tourists that….

Here is the code that I have:
val bookRDD = sc.textFile("file://test/book.txt");
val sentenceRDD = bookRDD.filter(line => line.contains("Author:"))

The code grabs all of the first line that contains  Author:

"Author:  However, Mary warns her mother that she hasn't changed since she has worked last summer."

This is good, but I need to grab the text that follows Author: and exclude Author:, so I have:

However, Mary warns her mother that she hasn't changed since she has
  worked last summer.

Can you help me write the code the grabs the text after the "Author:"?   I am trying to do this within a RDD.

A: After filter you can map the rdd to replace the String Author: to blank.
e.g
val bookRDD = sc.textFile("file://test/book.txt");
val sentenceRDD = bookRDD.filter(line => line.contains("Author:")).map(line => line.replaceFirst("Author: ", ""))

A: There are multiple String manipulation techniques that you can use here. You can go with substring, replaceAll, split(probably)
Here's one with replaceAll
rdd.filter( _.startsWith("Author:") )
   .map(_.replaceAll("Author:" , "").trim )
   .first

// String = However, Mary warns her mother that she hasn't changed since she has worked last summer.


text:
Q: Force directory hosting as a Client with index.htm present? I'm asking about the client side.
Is it possible to get a directory listing from an apache if I know listings are allowed but there's a index.htm in this directory?

A: You can remove index.htm from the DirectoryIndex directive.


text:
Q: How to remove resize option present at the right bottom-corner of the textarea? I'm trying to remove dots in a textarea which are present at the bottom-right corner.
Here's an example of what I mean (from Chrome):

How to remove those diagonal lines?

A: It is as simple as the following code. Just give the textarea the style resize: none

<textarea style="resize: none"></textarea>

A: Just add in your CSS file
textarea { resize: none; }

Later (2019) edit:
Related to this answer of mine and the rising number of GitHub code search results on resize: none declarations applied to textarea elements, I wrote some lines on why I think CSS resize none on textarea is bad for UX:

Very often, the textarea is limited to a number of rows and columns or it has fixed width and height defined via CSS. Based solely on my own experience, while answering to forums, writing contact forms on websites, filling live chat popups or even private messaging on Twitter this is very frustrating.
Sometimes you need to type a long reply that consists of many paragraphs and wrapping that text within a tiny textarea box makes it hard to understand and to follow as you type. There were many times when I had to write that text within Notepad++ for example and then just paste the whole reply in that small textarea. I admit I also opened the DevTools to override the resize: none declaration but that's not really a productive way to do things.
from https://catalin.red/css-resize-none-is-bad-for-ux/

So you might want to check this out before adding the above to your stylesheets.

A: html
sass
textarea {
  position: relative;
  z-index: 1;
  min-width: 1141px;
  min-height: 58px;
}

.resizer {
  position: relative;
  display: inline-block;
  &:after {
    content: "";
    border-top: 8px solid #1c87c7;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    -webkit-transform: rotate(-45deg);
    z-index: 1;
    opacity: 0.5;
    position: absolute;
    bottom: 1px;
    right: -3px;
    pointer-events: none;
  }
}
.arrow-resizer-textarea {
  height: 0;
  width: 0;
  border-top: 8px solid #1c87c7;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  -webkit-transform: rotate(-45deg);
  position: absolute;
  bottom: 1px;
  right: -3px;
  pointer-events: none;
  z-index: 2;
}


text:
Q: How to solve this system of linear equations $$M = \left(\begin{smallmatrix} a_1 & a_2 & a_3 & a_4\\ b_1 & b_2 & b_3 & b_4\\ a_1 & c_2 & b_2 & c_4\\ a_4 & d_2 & b_3 & c_4\\ b_1 & c_2 & a_2 & e_4\\ b_4 & d_2 & a_3 & e_4\end{smallmatrix}\right)$$ All of the equations equal to 26; augmented, the matrix would then have have "26" to the right of each row.
This is basically the "Star of David" that another user posted:
http://i.stack.imgur.com/mVHwZ.jpg
but I don't think anyone has solved it like this.

A: You have forgotten the very important condition that all integers between 1 and 12 must be used exactly once.
Though the equations themselves are linear and contain only 0 and 1 as coefficients, the constraint is very tough. I don't think you could find an easy solution without integer programming, which is, like you may have known, NP-Hard and thus we have by now only exponential solutions, which are not better than brute force for such a small problem.

A: As I see, there are $960$ solutions ($80$ different solutions, ignoring rotation and mirror-transformation).
For example, $2$ of them:

Way of solving: "try-and-check".

A).
Consider any values $a,h$.
For example, $a=5,h=6$.
Then possible values for $i,c$ are:
 - $3,12$;
 - $4,11$;
 - $7,8$;
 - $8,7$;
 - $11,4$;
 - $12,3$.
For these values you'll get system of $5$ equations for $8$ variables. Reduction of system.
Sometimes such system will have no solutions.
B).
Consider $3$ any values for cells $a,c,e$.
Choose values for $b,d,f$, such that $a+c+e=b+d+f$.
When we'll have values for $a,b,c,d,e,f$, we'll get system of $6$ equations for $6$ variables ($g,h,i,j,k,l$).
But such system can have no solutions.

If you'll use brute computer search, then there is not so much permutations of $12$ numbers: $12! = 479~001~600$ (a few seconds of computer work).


text:
Q: How to use MarkLogic xquery to tell if a document is 'in-memory' I want to tell if an XML document has been constructed (e.g. using xdmp:unquote) or has been retrieved from a database. One method I have tried is to check the document-uri property
declare variable $doc as document-node() external;

if (fn:exists(fn:document-uri($doc))) then
  'on database'
else
  'in memory'

This seems to work well enough but I can't see anything in the MarkLogic documentation that guarantees this. Is this method reliable? Is there some other technique I should be using?

A: I think that behavior has been stable for a while. You could always check for the URI too, as long as you expect it to be from the current database:
xdmp:exists(fn:doc(fn:document-uri($doc)))

Or if you are in an update context and need ACID guarantees, use fn:exists.
The real test would be to try to call xdmp:node-replace or similar, and catch the expected error. Those node-level update functions do not work on constructed nodes. But that requires an update context, and might be tricky to implement in a robust way.

A: If your XML document is in-memeory, you can use in-mem-update API
import module namespace mem        = "http://xqdev.com/in-mem-update"     at  "/MarkLogic/appservices/utils/in-mem-update.xqy";
If your XML document exists in your database you can use fn:exists() or fn:doc-available()

A: The real test of In-memory or In-Db is xdmp:node-replace .
If you are able to replace , update , delete a node then it is in database else if it throws exception then it's not in database.
Now there are two situation
1. your document is not created at all:
   you can use fn:empty() to check if it is created or not.
2. Your document is created and it's in memory:
   if fn:empty() returns false and xdmp:node-replace throws exception then it's in-memory


text:
Q: Tweepy - Error while getting access token : "argument 2 to map() must support iteration" I am using tweepy (a python lib for twitter api) to create a twitter app. Below is the django view code where I am creating an OAuthHandler with consumer key,secret and getting request token and saving it in django.messages and redirecting it to the authorization url.
Later during the callback view I am retrieving the request token and creating an OAUthHandler, but I getting this below error on 'auth.get_access_token(v)'
TweepError at /twitter/return/

argument 2 to map() must support iteration

Traceback :
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
111.                         response = callback(request, *callback_args, **callback_kwargs)

File "/home/nzee/Downloads/uday/homepage/../homepage/users/views.py" in tw_return
80.   auth.get_access_token(v)

File "/usr/local/lib/python2.6/dist-packages/tweepy-1.9-py2.6.egg/tweepy/auth.py" in get_access_token
126.             raise TweepError(e)

Exception Type: TweepError at /twitter/return/ Exception Value:
argument 2 to map() must support iteration

Views.py code below
def tw_return(request):
  v = request.GET.get('oauth_verifier')

  key = settings.TWITTER_KEY
  secret = settings.TWITTER_SECRET
  auth = tweepy.OAuthHandler(key, secret)

  mess = get_messages(request)

  a=[]
  for m in mess:
    a.append(m)

  auth.set_request_token(a[0],a[1])

  auth.get_access_token(v)

  api = tweepy.API(auth)
  api.update_status('tweepy + oauth1!')
  return HttpResponseRedirect('/')

def twitter(request):
  key = settings.TWITTER_KEY
  secret = settings.TWITTER_SECRET
  auth = tweepy.OAuthHandler(key, secret)
  try:
    redirect_url = auth.get_authorization_url()
  except tweepy.TweepError:
    raise Http404

  messages.add_message(request, messages.INFO, auth.request_token.key)
  messages.add_message(request, messages.INFO, auth.request_token.secret)
  return HttpResponseRedirect(redirect_url)

A: wrong: I suspect that you are not receiving an oauth_verifier, so it's value is None (i.e., not an iterable)
this question may help: Tweepy twitter oauth authentication not returning oauth_verifier

Here's an example of an appEngine handler that uses tweepy, maybe it'll help?
https://github.com/sclm/tweepy-examples/blob/master/appengine/oauth_example/handlers.py
Final Answer:
I think you are not getting the correct request token from get_messages()... the error you are getting occurs if you call auth.set_request_token() with None. Found this in the issues on github for tweepy https://github.com/tweepy/tweepy/issues/25
# WRONG CODE
auth.set_request_token(None, None)


text:
Q: Merge objects based on certain attributes and combine(sum) certain other attributes Let's say I have MyObject with attributes attr_a, attr_b and attr_c and quantity.
I'd like to combine their quantities if they have the same attr_a, attr_b and attr_c
Here's an example and my approach. Is there a better way to do this? For instance; what if I wanted to retain the ordering of my lists after combining them?
class MyObject:
    def __init__(self, attr_a, attr_b, attr_c, quantity):
        self.attr_a = attr_a
        self.attr_b = attr_b
        self.attr_c = attr_c
        self.quantity = quantity

    def __eq__(self, rhs):
        if type(rhs) is type(self):
            return self.attr_a == rhs.attr_a and self.attr_b == rhs.attr_b and self.attr_c == rhs.attr_c
        else:
            return False

    def __hash__(self):
        return hash((self.attr_a, self.attr_b, self.attr_c))

    def __repr__(self):
        return "<{}, {}, {}, {}>".format(self.attr_a, self.attr_b, self.attr_c, self.quantity)

from collections import defaultdict

pos1 = [MyObject("AAA", "BBB", "A123", 1000), MyObject("AAA", "CCC", "A123", 2000)]
pos2 = [MyObject("AAA", "BBB", "A123", 2000), MyObject("AAA", "CCC", "A123", -2000), MyObject("AAA", "DDD", "A999", 200)]

merge = defaultdict(int)

for p in pos1 + pos2:
    merge[p] += p.quantity

res = []
for k, v in merge.items():
    k.quantity = v
    res.append(k)

print(res)

"""
Expected output: [<AAA, BBB, A123, 3000>, <AAA, CCC, A123, 0>, <AAA, DDD, A999, 200>]
"""

A: Well I think it is not a good idea to "tailor" the __eq__, etc. functions towards a specific use case: right now it means that MyObject("AAA", "BBB", "A123", 1000) is considered equal to MyObject("AAA", "BBB", "A123", 1425). For the usecase of "merging" such objects together, that might work, but that implies other (straightforward) usecases might result in a lot of extra logic.
Another thing I would avoid is changing the quantity of an existing MyObject in general: you do not know what variables are pointing to that object. As a result this can mean that a list containing MyObjects all of a sudden has a list where the quantities are different.
It might be better to implement a function like get_key:
class MyObject:
    def __init__(self, attr_a, attr_b, attr_c, quantity):
        self.attr_a = attr_a
        self.attr_b = attr_b
        self.attr_c = attr_c
        self.quantity = quantity

    def get_key(self):
        return (self.attr_a, self.attr_b, self.attr_c)

    def __repr__(self):
        return "<{}, {}, {}, {}>".format(self.attr_a, self.attr_b, self.attr_c, self.quantity)
Then we perform a more or less similar algorithm, but we construct new MyObjects:
from collections import defaultdict
res = defaultdict(int)

for obj in objs:
    res[obj.get_key()] += obj.quantity

result = [MyObject(*k, v) for k, v in res.items()]

Making some sort of clone function to copy the MyObject together with a new quantity might also improve code design.


text:
Q: jQuery: How to animate (fade) change of image source using img.attr('src', 'img.png')? So using jQuery I change the source of an image using img.attr('src', 'img.png').
This just change the source and updates the image in a very static way, without doing any animation like fading.
How would I animate this change of image?

A: Hope this will help.
Saw this solution somewhere when I faced this issue.

$("#link").click(function() {
    $("#image").fadeOut(1000, function() {
        $("#image").attr("src",$("#link").attr("href"));
    }).fadeIn(1000);
    return false;
});

Change picture

A: Fade out the imgage and, while image is invisible, change it's source:
$('#myImg').fadeOut().queue(function() {
   var img = $(this);
   img.attr('src', newSrc);
   img.fadeIn();
   img.dequeue();
});


text:
Q: AttributeError: 'History' object has no attribute 'evaluate' from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
import numpy as np

frames=[singleteamone_tweets,singleteamtwo_tweets,twoteam_tweets]
All_data = pd.concat(frames)

#creating a bag of words model
from sklearn.feature_extraction.text import CountVectorizer
cv= CountVectorizer()
X=cv.fit_transform(All_data.iloc[:,0]).toarray()  #.iloc[:,0]
Y=All_data.iloc[:,1].values

#training and test dataset

from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.25,random_state=0)

#Reshape
#X_train = np.random.rand(3, 4)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

classifier=Sequential()
#LSTM layers and Dropout regularization
classifier.add(LSTM(units=30,return_sequences=True,input_shape=(X_train.shape[1],1)))
classifier.add(Dropout(0.2))

classifier.add(LSTM(units=30,return_sequences=True))
classifier.add(Dropout(0.2))

classifier.add(LSTM(units=30,return_sequences=True))
classifier.add(Dropout(0.2))

classifier.add(LSTM(units=30))
classifier.add(Dropout(0.2))

#output layer
classifier.add(Dense(units=1, init='uniform', activation='sigmoid'))

I am getting an error while checking the accuracy its showing attribute error :- history object has no attribute ' evaluate'. i tried to fix this nothing it working.AttributeError: 'History' object has no attribute 'evaluate'
#compiling the RNN
classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model=classifier.fit(X_train,Y_train,epochs=30,batch_size=15)

# Final evaluation of the model

test_loss, test_acc = model.evaluate(X_test)

A: You should instead do something like this-
history = model.fit(...)

According to Keras documentation, the model.fit method returns a History callback, which has a history attribute containing the lists of successive losses and other metrics.
history has no attribute called 'evaluate' you should instead do this to get the validation accuracies. evaluate is an attribute of the model object.
history.history['accuracy']

This returns you a list of the epoch wise training accuracy.
To find your final test accuracy you should use the evaluate attribute on the model object-

You also need to give it y_test as you are trying to calculate the
accuracy.

model.evaluate(X_test, y_test)

# This could also be a generator instead
# model.evaluate(test_generator)

The above piece of code
Quoted from evaluate() method documentation:

Returns
Scalar test loss (if the model has a single output and no metrics) or
list of scalars (if the model has multiple outputs and/or metrics).
The attribute model.metrics_names will give you the display labels for
the scalar outputs.

Therefore, you can use metrics_names property of your model to find out what each of those values corresponds to. For example, if you write:
print(model.metrics_names)

This gives you the names of all the metrics. Since you need accuracy if you compile the model with-
metrics=["accuracy"]

You would also receive the accuracy in the model.evaluate() output.

A: It should work
history=classifier.fit(X_train,Y_train,epochs=30,batch_size=15)
test_loss, test_acc = model.evaluate(X_test)


text:
Q: Digitizing parcel data and adding attributes to create interactive map I am quite new to mapping and am attempting to learn by taking on an arbitrary little project (I also don't know how to code hope that's not going to be a problem). I want to create an interactive map that shows the residential parking permit zone along with relevant info such as time limit and enforcement details. Currently everything is static.
Data I have obtained:

*

*City-wide RPP zone map in pdf (http://www.ci.berkeley.ca.us/uploadedFiles/Public_Works/Level_3_-_Transportation/RPP_R(1).pdf)

*Parcels by RPP Area in gif (http://www.ci.berkeley.ca.us/Public_Works/Transportation/Residential_Parking_Permits.aspx)

*Parcel data from the City's Open Data portal. I can export them into shapefile to be imported to either qgis or CartoDB (?)

*All relevant info associated with each RPP Area such as time limits and enforcement hours.

So my questions are:

*

*Is there a way to merge these data together effectively?

*It looks like I can overlay the zone map (in pdf) over the parcel layer?

*If so, what tools do I use?

*Do I have to digitize the pdf first?

*How do I actually merge them and keep all the attributes?

Ideally I would want to have one layer for each zone, color coded, so I can turn them on and off.
I know how to create new layers by selecting features in ArcGIS (learned how to do that a long time ago in college), is it going to be similar in QGIS or in the other tools that you recommend?
My goal is for users to toggle over a location and know instantly the nearby parking restrictions.


text:
Q: ftp files via intermediate jump-server In my company we access our remote electronic devices through a jump server. When we need to download files from the devices we do the following:

*

*ssh jump.server.com

*wget ftp//device_ip/filepath (this downloads the file to the jump server)

*scp the jump server from local machine to get the file.

I am trying to simplify this by using ssh port forwarding to be able to download the file directly from the remote devices to our machine. I followed this answer:
ssh -L 9000:device_ip:21 jump.server.com
wget ftp://localhost:9000/filepath

But I am getting the following error:
227 Entering Passive Mode (10,192,1,16,19,129).
trying to connect to 10.192.1.16 port 4993
Closed fd 4
Closed fd 3
couldn't connect to ipaddress port 4993: Connection timed out
Giving up.

The issue is not the passive mode that wget uses because it works when using the old method.
Any suggestions in what could be causing the problem? Our computers run Ubuntu if that helps.

A: FTP uses port 21 for the control connection but then needs for the actual data transfers additional connections using different, dynamically agreed on, ports. This makes it impossible to simply tunnel FTP through a single TCP connection, no matter if active or passive mode.
If your FTP client supports the SOCKS protocol you might try to setup ssh as SOCKS server with the -D option and then use it with FTP passive mode.
Another option would be not to login, get the file and transfer it back, but to do all at once:
$ ssh user@remote wget -O - ftp://host/file > file


text:
Q: How can I do username in reviews on django? I'm doing reviews on django, but I want the user to not be able to enter any name. I want the username in the reviews to match the username of his profile
models.py
 class Reviews(models.Model):
    name = models.CharField('Имя', max_length=100)
    text = models.TextField('Отзыв', max_length=3400)
    parent = models.ForeignKey('self', verbose_name='Родитель', on_delete=models.SET_NULL, null=True, blank=True)
    book = models.ForeignKey(BookModel, verbose_name='книга', on_delete=models.CASCADE)
    name_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

views.py
class MoreInfoView(View):
    """ """
    def get(self, request, id):
        book_info = BookModel.objects.filter(id=id).first()
        stuff = get_object_or_404(BookModel, id=self.kwargs['id'])
        total_likes = stuff.total_likes()
        return render(request, 'bookapp/more_info.html', context={
            'id': id,
            'book_info': book_info,
            'book': BookModel.objects.all(),
            'total_likes': total_likes,
        })

class AddReview(View):
    """Add Review"""
    def post(self, request, pk):
        form = ReviewForm(request.POST)
        book = BookModel.objects.get(id=pk)
        if form.is_valid():
            form = form.save(commit=False)
            form.book = book
            form.save()
        return HttpResponseRedirect(reverse('more_info', args=[pk]))

forms
class ReviewForm(forms.ModelForm):

    class Meta:
        model = Reviews
        fields = ("name", "text", 'name_user')

A: You can add user manually after validating ReviewForm
I also added some changes(suggestions)
models.py
class Reviews(models.Model):
    name = models.CharField('Имя', max_length=100)
    text = models.TextField('Отзыв', max_length=3400)
    parent = models.ForeignKey('self', verbose_name='Родитель', on_delete=models.SET_NULL, null=True, blank=True)
    book = models.ForeignKey(BookModel, verbose_name='книга', on_delete=models.CASCADE, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)

Setting blank=True makes the field optional.
views.py
class MoreInfoView(View):
    """ """
    def get(self, request, id):
        book_info = BookModel.objects.filter(id=id).first()
        stuff = get_object_or_404(BookModel, id=self.kwargs['id'])
        total_likes = stuff.total_likes()
        return render(request, 'bookapp/more_info.html', context={
            'id': id,
            'book_info': book_info,
            'book': BookModel.objects.all(),
            'total_likes': total_likes,
        })

class AddReview(View):
    """Add Review"""
    def post(self, request, pk):
        user = request.user

        # User has to be authenticated to create a review. And backend must
        # validate it. You should raise PermissionDenied as response or
        # redirect user to the login page, or something similar.
        if not request.user.is_authenticated:
            raise PermissionDenied()

        form = ReviewForm(request.POST)
        book = BookModel.objects.get(id=pk)
        if form.is_valid():
            form = form.save(commit=False)
            form.book = book
            form.user = user
            form.save()
        return HttpResponseRedirect(reverse('more_info', args=[pk]))

forms.py
class ReviewForm(forms.ModelForm):

    class Meta:
        model = Reviews
        fields = ("name", "text")

A: I would advise to work with a CreateView [Django-doc] that will simplify a lot of the logic. You can implement this as:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView

class AddReviewView(LoginRequiredMixin, CreateView):
    form_class = ReviewForm

    def get_success_url(self):
        return reverse('more_info', args=[self.kwargs['pk']])

    def form_valid(self, form):
        form.instance.book_id = self.kwargs['pk']
        form.name_user = self.request.user
        return super().form_valid(form)

In your ReviewForm you thus remove the name_user as fields element.

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Note: normally a Django model is given a singular name, so Review instead of Reviews.

Note: Models normally have no …Model suffix. Therefore it might be better to rename BookModel to Book.


text:
Q: Complete x86/x64 JIT Assembler for C Language Do you know something just like this, but embeddable in a C program?

A: Some options:

*

*LibJIT

*GNU Lightning

*The LLVM C bindings

*Compiling modules with a C compiler and dlopening them - it works everywhere!


text:
Q: MongoDB Multiple database vs single database I have a NodeJS project that using mongodb as main database.
Regular, I just use one database for containing all information (users, organization, messages,...)
But now, I need to store one more thing - log data - which grow very very fast.
So I consider store log in other database to keep current database safe and fast.
Does anyone has experience in this, Is that better than single database?

A: Not a real question the mods will certainly say. You have a few options depending on your log data and how / how often you want to access it.

*

*Capped collections if you don't need to store the logs for a long time

*Something like Redis to delay writing to the log and keep the app responding fast

*Use a replica set to distribute the database load.


text:
Q: How modulo will change while moving from Left Hand Side to Right Hand Side? Example. 4a% 10 = 5. What is the value of a? I have equation in the form of $ab \text{ mod } c = d$.  I want to find a value of $a$.  How can I find a value of $a$?  Please help me to find it.
Let's consider following example. $10a \text{ mod } 3 = 5$. What is the value of $a$? In this case how will you calculate a value of $a$? Please give me a solution.
Thanks.

A: Let's consider
$$
 ab\mod c = d
$$
In general this means, according to the definition on wikipedia https://en.wikipedia.org/wiki/Modulo_operation, that
$$
 ab = d + nc \quad n\in \mathbb{N}
$$
then
$$
 a = \frac{d + nc}{b} \quad n\in \mathbb{N}
$$
This means that you have an infinite number of solutions.
To get to a single answer, you might for example state that you want to have the first a that is positive. I can't think of a quick and solid solution for finding such an a. In that case I would simple try solve using Mathematica or similar
$$
 a = \min_n \{ x | x=\frac{d + nc}{b}, n\in\mathbb{Z}, x>0\}
$$

A: If $a,b$ are coprime to $c$, you can invert them in the ring of integers modulo $c$.  If not, you need to remove the common factors, then see if the solution works.  For the question in your text, $10$ and $5$ are both coprime to $3$, so we just reduce modulo $3$ to get $a=2$, though one usually uses $\equiv$ for this and appends $\pmod 3$.
For the question in your title $4$ and $10$ have a common factor $2$.  All numbers of the form $4a$ will be even $\pmod {10}$ so your equation has no solution.


text:
Q: show that an entire function with the nth derivative zero is polynomial of degree at most n-1 f is an entire function with $f^n=0$ for some $n \in \mathbb{N}$. I need to show that f is polynomial of degree at most n-1.
I know that this question was asked before. But I need another approach to solve it. I don't want to use the taylor expansion or the gauchy integral. I need the most basic approach (using only the differentiability of f).

A: It can be proved by induction. If $f'=0$, then $f$ is constant. Now, suppose that $f^{(n)}=0\implies f$ is a polynomial whose degree is smaller than $n$. If $f^{(n+1)}=0$, then $(f')^{(n)}=0$. So,$$f'(z)=a_0+a_1z+\cdots+a_nz^n.$$Therefore, for some constant $C$,$$f(z)=C+a_0z+\frac12a_1z^2+\cdots+\frac1{n+1}a_nz^{n+1}.$$

A: Just integrate repeatedly. $f^{(n-1)}(z)$ is a constant  $c_1$; $f^{(n-2)}(z)=c_2+c_1z$ and so on.

A: According to Wikipedia, $f:\mathbb C \rightarrow \mathbb C$ entire means that there exists a sequence $(a_k)_{k \in \mathbb N} \subseteq \mathbb C$ such that $f$ can be written as a convergent series
$$
f(z) = \sum_{k = 0}^\infty a_k z^k \text{ at every }z \in \mathbb C. \tag{1}
$$
The derivatives of $f$ are also entire, and are given by
$$
f^{(n)}(z) = \sum_{k = n}^\infty k(k-1)\ldots(k-n+1)a_k z^{k-n},\;\forall z \in \mathbb C.
$$
Thus, $f^{(n)}=0$ only iff $a_k = 0$ for all $k \ge n$. By (1), this is equivalent to saying that $f$ is a polynomial function of degree at most $n-1$.


text:
Q: Does HttpUrlConnection have to be set up to work on public wifi connections? The app I'm currently working on is in it's first Beta stage, it was discovered this class couldn't complete its task when using public wifi.
Has anyone had this issue before? Would have anything to do with SSL certificates used by the server it is trying to connect to?
public class NetGameList implements Callable<String> {

    private DatabaseManager DBM = DatabaseManager.getInstance();

    private JSONArray jsonArray;

    @Override
    public String call() throws Exception {

        HttpURLConnection connection;
        JSONObject jsonParam = new JSONObject();

        try {

            URL url = new URL(Constants.NETBUILDGAMELISTURL);
            connection = (HttpURLConnection) url.openConnection();

            jsonParam.put("TAG", Constants.HTTPTHREE);
            jsonParam.put("receiverid", Constants.NETUSERFACEBOOKID);

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //write data to server-------------------------------------------------------------------------
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

            outputStream.write(jsonParam.toString().getBytes("utf-8"));

            //flush&close the stream
            outputStream.flush();
            outputStream.close();

            //Get result from server
            InputStream responseStream = new BufferedInputStream(connection.getInputStream());

            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
            String line = "";

            ArrayList<String> jsonArrays = new ArrayList<String>();

            while ((line = responseStreamReader.readLine()) != null) {

                jsonArrays.add(line);
            }
            responseStreamReader.close();

            for (String game : jsonArrays) {

                JSONObject jsonObject = new JSONObject(game);

                jsonArray = jsonObject.getJSONArray("data");

                for (int i = 0; i < jsonObject.length(); i++) {

                    JSONObject jObject = jsonArray.getJSONObject(i);

                    if (!DBM.gameExists(jObject.get("GameId").toString())) {

                        DBM.addGame(jObject.get("GameId").toString(), jObject.get("SenderId").toString(),
                                jObject.get("GameTrack").toString(), jObject.get("FileLocation").toString(), getDateTime());
                    } else {

                        DBM.updateGames(jObject.get("GameId").toString(), jObject.get("SenderId").toString(),
                                jObject.get("GameTrack").toString(), jObject.get("FileLocation").toString(), getDateTime());
                    }
                }
            }

            responseStream.close();
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return Constants.NETOPCOMPLETE;
    }

    private String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "dd/MM/yyyy", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);
    }
}

A: To use WIFI, you should add the permission:
   <uses-permission android:name="android.permission.INTERNET" />

to your manifest file.

A: Sometimes, "public" wifi requires a web-based login


text:
Q: Token in LocalStorage is there but not being put inside my Axios Instance One of my components is not loading because the token in Local Storage is not being sent in my Axios request.
Here is the flow. I have a Login component that sets the token in Local Storage once the user has been Authenticated. Here is that function:
   AuthService.authenticateEmployee(employee).then((r) => {
      if (r != null && r.data.jwt != null) {
        localStorage.setItem("token", r.data.jwt);
        console.log(r.data.jwt);
        console.log("nav to tickets now");
        this.props.history.push("/tickets");
      }
    });
  };

It then takes you to /tickets which is where my problem lies. The TicketsComponent tries to
validate the token. If its invalid then it should redirect the user back to the login page.
   AuthService.validateToken()
      .then((res) => {
        console.log("step 1");
        if (res == undefined || res == null || !token) {
          this.props.history.push("/login");
        }
      })
      .then(() => {
        console.log("step 2");

        TicketService.getTickets().then((res) => {
          if (this._isMounted) {
            this.setState({ tickets: res.data });
          }
        });
      });

Here is validateToken():
  validateToken() {
    console.log(" about to try validating");
    return AxiosInstance.get("authenticate")
      .then("did it")
      .catch((err) => console.log(err));
  }

And finally, this is where I have pinpointed the problem to:
const AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  headers: { Authorization: `Bearer ${getTokenFromLocalStorage()}` },
});

function getTokenFromLocalStorage() {
  const token = localStorage.getItem("token");
  console.log("the token from local storage is -> " + token);
  if (token === null) {
    return undefined;
  }
  return token;
}

export default AxiosInstance;

If I hardcode the value of the Authorization header to have the same token that is in LocalStorage, then it works. But not when I try to use the getTokenFromLocalStorage function. The function does not even seem to get called. The console.log() is not being printed at all. What is going on? How can I embed my token into this request correctly?
EDIT: I double checked my LocalStorage in developer tools. It was empty before clicking the login button. When I click login, then the token gets populated as it should as seen here:
localStorage
However, it still failed to log me in.
errors
IMPORTANT: So it seems like my getTokenFromLocalStorage only gets called when the Axios Instance is created and not each time it's used. How can I fix this so that the function gets called every time I use the AxiosInstance?
UPDATE: I found out that the token is definitely not being retrieved from getTokenFromLocalStorage since this is the header being sent in the request:
Request Header
However, I can call localStorage.getItem("token") from inside the TicketsComponent AFTER clicking login and AFTER setting the token in the header and it displays the correct token. And I posted an image showing that the token is being set in LocalStorage after clicking login so what's going on?
UPDATE #2: I found this StackOverflow answer but it is of no use for me. Anyone have any ideas? LINK

A: I figured it out. The solution was to use interceptors, a part of Axios Instances. Using interceptors allows you to dynamically set the header for each request since it can change at any time.
const AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
});

AxiosInstance.interceptors.request.use(function (config) {
  // Do something before request is sent
  let token = localStorage.getItem("token");
  config.headers["Authorization"] = "Bearer " + token;
  return config;
});

export default AxiosInstance;

And then it worked.


text:
Q: List View Sliding Window I have a list of numbers and I'd like to select a sliding window of a certain size:
List<double> lst = {3,78,24,25,634,25,478,24};
int WindowSize = 4;

index = 0: return {3};
index = 1: return {3,78};
index = 2: return {3,78,24};
index = 3: return {3,78,24,25};
index = 4: return {78,24,25,634};
index = 5: return {24,25,634,25};
index = 6: return {25,634,25,478};
index = 7: return {634,25,478,24};

This isn't that hard of a concept, but I'm trying to do it with the .Skip() .Take() extension methods.  Is there an easier way to select the WindowSize entries before an item instead of trying to find where the starting point is and then getting the next WindowSize entries?  I'm trying to think of an easier way to do this with linq than having all the bounds checking that is required with Skip() and Take().
You could reverse the list and then do a Count() - index and then a Take() but that doesn't seem efficient.

A: I guess this would require minimal bound checking - just basic sanity checks. See if this works
IEnumerable<double> GetWindow(List<double> lst, int index, int windowSize) {
    if(index >= lst.Length){
        // Throw proper exception
    }
    return lst.Skip(index-windowSize).Take(Math.Min(index,windowSize));
}

A: If you only want to get one window, your accepted answer looks appropriate.
But for iterating more than one window, I would go with something like this:
public static IEnumerable<IEnumerable<TSource>> Window<TSource>(
    this IEnumerable<TSource> source, int size)
{
    var q = new Queue<TSource>(size);

    foreach (var value in source)
    {
        if (q.Count >= size)
            q.Dequeue();
        q.Enqueue(value);
        yield return q;
    }
}


text:
Q: Select and copy features in ArcMap using Python add-in tool I'm trying to add a tool to an add-in toobar to select features from an existing feature class and copy them across to another feature class. I need two tools, one for a point and one for a rectangle. Add-in tools only handle rectangles, so I'm trying to generate the point coordinate off the onMouseDown event and simply use the X and Y feedback I get. The problem is that I can't seem to pass these coordinates to anything usefull to extract the features. I've tried using Environment extents and then doing a simple CopyFeatures, but that's not working as it copies the entire fc and doesn't seem to honour the environment settings I set.
Can I pass coordinates to the Select by Location tool somehow or is there another way of passing coordinates to something to extract by that extent?
This is what I have now:
import arcpy
import pythonaddins
arcpy.overWriteOutput = True

# Replace this with the SDE layer once it's available.
global ELAtemplate, fc
ELAtemplate = r'C:\Data\nsw_map_units.shp'
fc = ""

class DefineUnitsbyPoint(object):
    """Implementation for DefineUnitsbyPoint.tool (Tool)"""
    def __init__(self):
        self.enabled = True
        self.shape = "Rectangle" # Use onMouseDown to get initial extent of the rectangle.
    def onMouseDownMap(self, x, y, button, shift):
        # fc can be assigned from a combo box selection in another class
        global ELAtemplate, fc
        if fc == "":
            pythonaddins.MessageBox('Choose a layer to select from.', 'Choose a Layer', 0)
        else:
            mxd = arcpy.mapping.MapDocument("CURRENT")
            pointGeom = arcpy.PointGeometry(arcpy.Point(x,y), mxd.activeDataFrame.spatialReference)
            arcpy.SelectLayerByLocation_management(ELAtemplate, "INTERSECT", pointGeom, "", "ADD_TO_SELECTION")
            arcpy.CopyFeatures(ELAtemplate, fc)

A: You will probably want to use onMouseDownMap rather than onMouseDown as this returns the location in map coordinates, not window coordinates.
Additionally, be sure to pass in a valid SpatialReference object to the PointGeometry constructor, otherwise it will most likely not work. In the example below I use the spatial reference of the active data frame.
Lastly you may want to specify a search_distance on your SelectLayerByLocation so that point and line features can be selected without clicking on them exactly. In ArcObjects you would normally use ArcMap's selection tolerance in pixels and expand your point's envelope by that amount in map coordinates. I couldn't find a way to access ArcMap's selection tolerance setting in arcpy, but if you want to go with the default of 3 pixels (or pass in your own), you can pass the output of the function in this answer as a search_distance (in inches) to SelectLayerByLocation.
def onMouseDownMap(self, x, y, button, shift):
    mxd = arcpy.mapping.MapDocument("CURRENT")
    pointGeom = arcpy.PointGeometry(arcpy.Point(x, y), mxd.activeDataFrame.spatialReference)
    searchdistance = getSearchDistanceInches(mxd.activeDataFrame.scale)
    lyr = arcpy.mapping.ListLayers(mxd)[0] # assumes you want to select features from 1st layer in TOC
    arcpy.SelectLayerByLocation_management(lyr, "INTERSECT", pointGeom, "%d INCHES" % searchdistance)
    arcpy.RefreshActiveView()

A: I am assuming that you are using the techniques described in the Answer to Is it possible to get the coordinates of a user clicked point in a current MXD with ArcGIS 10.0 ArcPy? earlier today or something similar.
Once you are able to create your point or polygon (rectangle) geometry using something like the code below you should be able to use that as your select_features for Select Layer By Location.
pt=arcpy.PointGeometry(arcpy.Point(x,y))

From there Copy Features should get the features you are after.


text:
Q: EditorFor extension not working for htmlAttributes in Asp.Net MVC 5.1 I have the following code:
public static class HtmlExtendedHelpers
{

    public static IHtmlString eSecretaryEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel,TProperty>> ex, object htmlAttributes, bool disabled )
    {

        if (disabled)
        {
            htmlAttributes.Add(new { @disabled = "disabled" }); //searching for working code as replacement for this line
        }

        return htmlHelper.EditorFor(ex, htmlAttributes);

    }
}

It works when disabled = false and all my alternatives fail when i disabled is true. Then none of the htmlAttributes are getten written.
The variable htmlAttribute has the VALUE ( including htmlAttributes property :)
htmlAttributes: { class = "form-control" }

This is because i have a default class of form-control and i want to add a attribute : disabled with value disabled.
Does anyone know how to implement this correctly?
PS. Since Asp.Net MVC 5.1, there is support for htmlAttributes

A: You can use HtmlHelper.AnonymousObjectToHtmlAttributes
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

if (disabled)
{
    attributes.Add("disabled", "disabled");
}

Alternatively, you could pass the disabled attribute as part of the htmlAttributes object, meaning you wouldn't need the if statement at all.
htmlAttributes: { class = "form-control", disabled = "disabled" }

Depending on whether you have a custom EditorFor template or not, you may need to change how you pass the html attributes to the EditorFor function, as the parameter it accepts - additionalViewData is not the same.
This article explains in more detail.
If you are using a default template, you can pass the html attributes inside another anonymous object:
return htmlHelper.EditorFor(ex, new { htmlAttributes = attributes });

If you have a custom template, you will need to retrieve the html attributes and apply them yourself in the view:
@{
    var htmlAttributes = ViewData["htmlAttributes"] ?? new { };
}

A: You can pass the attributes in the htmlAttributes like below:
htmlAttributes: { class = "form-control", disbaled="disabled" }

Also you can create your Metadata Attribute which can be decorated on your property for which you are using EditorFor.
To create your own Metadata Property you can implement IMetadataAware interface.


text:
Q: Need Help to build a Custom notification read logic for Individual user basis I'm building a custom Notification section, which provides notification or messages to multiple users on any particular object update, I've created a Custom page where I have added a Alert section or notification section, which shows a particular record updates, like there is a custom object lets call it CustomObjA, whenever a record is created or updated with some specific data into that custom object, for that update a message record is generated and which showed on user on the Notification section. now As moment user click or expend the notification section. that notification should be grayed out, means it is seen by that particular user, and next time when that user come to that page it should grayed out those notification which are seen/read by user. So its like our Email read/unread functionality.
how to achieve this functionality.
What I have done so far, I have created a new object called Notification and every time whenever there is any create or update on that custom object (CustomObjA), I wrote a trigger which create a new record in notification object and I'm reading that notification object all the time. On the notification I have created a field called "Status" which include Read/Unread option. Now I want your help to figure out how to set that field as "Read" on basis of every individual user.
P.S. - There are multiple users who sees this notification functionality, so if a UserA seen the message it doesn't mean that UserB also seen that, so userB still able to see that unread mark on the same message in the notification section.
Let me help what's the best way to achieve that.
Thanks in advance!

A: Whatever you have done till now seems good. But since you have many-to-many relationship between User & Notification, you will need a junction object to record whether a particular user has read a notification or not.
Create another object called - NotificationStatusPerUser and have User & Notification as parents. So everytime a User reads a notification, a record will be entered here for that User & that particular notification.
So when another user opens the page, you search through the records of this NotificationStatusPerUser object and see whether their is a record for this User & this Notification, if yes, he has already read the Notification, else he has not.
----OR----
The second best way is to have a long text field(say ReadBy) in Notification which will hold the Ids of the users who has already read the notification in a semicolon separated list. So data in this field will be like-
0054C000000YpDQQA0;0054C000000YpGHYA0;0054C00000UH6QQA0;0054CJHHJUYGpDQQA0

Now, when you load the page, you search in this field whether the current user's id is present or not, if yes, notification is read for him, else no.
Please note, since there is a limit on the length of the field value, if you have large number of users this approach will not work.
Let me know if you have any questions.


text:
Q: Java If NoSuchElementException is returned How can I make an if statement to check if "NoSuchElementException" is returned from a function? Something similar to what I have below.
if (functionReturns == "NoSuchElementException")

A:
How can I make an if statement to check if NoSuchElementException" is
  returned from a function?

If you meant that your function returns a String with the value as NoSuchElementException, use equals instead of == :
if("NoSuchElementException".equals(functionReturns)) { }

If you meant that your function can throw a NoSuchElementException, use a try-catch. The catch block will be triggered when the function throws a NoSuchElementException.
try {
    function();
} catch(NoSuchElementException e) {
     //NoSuchElementException was thrown

}

If you meant that your function actually returns an instance of NoSuchElementException, you can use :
NoSuchElementException.class.isAssignableFrom(functionReturns)

A: If method is throwing exception then simple use try and catch .
like
 boolean isException = false;
    try{
        //method that throws
    }catch(NoSuchElementException e){

      isException = true;
    //or perform what you like
    }

A: First of all NoSuchElementException or any other Exception is basically Thrown by a method not Returned. So you can/should not check it via return type.
The best approach to handle any type of Exception is try catch blocks.  Ex:-
 try {
   // Probable Exception Throwing code
} catch(NoSuchElementException e) {
     // handle/log specific type of error
}
catch(Exception e) {
     // handle/log Generic error if none specific is defined
}

Find more about Exception in the Official Docs here

A: if you are using if statement then there must be thrown more than one error so in java 7
In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch.
Before Java 7 you would write something like this:
try {

    // execute code that may throw 1 of the 3 exceptions below.

} catch(NoSuchElementException e) {//work as if if (functionReturns == "NoSuchElementException")
    logger.log(e);

} catch(NoSuchElementException1 e) {//work as if if (functionReturns == "NoSuchElementException1")
    logger.log(e);

} catch(NoSuchElementException2 e) {//work as if if (functionReturns == "NoSuchElementException2")
    logger.severe(e);
}

As you can see, the two exceptions NoSuchElementException1 and NoSuchElementException2 are handled in the same way, but you still have to write two individual catch blocks for them.
In Java 7 you can catch multiple exceptions using the multi catch syntax:
try {

    // execute code that may throw 1 of the 3 exceptions below.
//combind way to catch multiple error
} catch(NoSuchElementException1 | NoSuchElementException2 e) {
    logger.log(e);

} catch(Exception e) {
    logger.severe(e);
}

Notice how the two exception class names in the first catch block are separated by the pipe character |. The pipe character between exception class names is how you declare multiple exceptions to be caught by the same catch clause.

A: This way worked for me.
if(function.equals("NoSuchElementException"))


text:
Q: jQuery File Paths I'm trying to use jQuery to load a file into a textarea form for the project I'm working on, however, nothing actually loads when the button is clicked.
<html>
<head>
    <title>CodeEditor</title>
    <meta charset = "utf-8">

    <script type = 'text/javascript' src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#editor_area").load("test_file.txt", function(responseTxt, statusTxt, xhr) {
                    if (statusTxt == "success")
                        alert("Load was performed");
                    if (statusTxt == "error")
                        alert("Load encoutnered an error");
                });
            });
        });
    </script>
</head>

<body>
    <button>Get Content</button>
    <main>
        <form>
            <textarea rows = "50" cols = "135" id = "editor_area"></textarea>
        </form>
    </main>
</body>

Here's the relevant code. I'm thinking it's a problem with the file path because I tested jQuery and it was working fine.
EDIT: I added the statusTxt's and it alerts me with the error one.
EDIT 2: This code worked. I was hosting it on a local machine though. When I put the site on a web server, the code worked perfectly.

A: use ajax request and val() instead of load
<script>
     $(document).ready(function(){
        $("button").click(function(){

         $.ajax({
           url : "test_file.txt",
           dataType: "text",
           success : function (data)
                {$("#editor_area").val(data);}
            });
        });
    });
</script>


text:
Q: How can I attach one router link and one dialog box in dropdown in Vue.js? I have to get a dropdown menu and attach the router link to other component and one dialog component for dialog box in it.

    <v-btn round class="mx-2 dropdown-menu" fab small v-bind:style="displayClass(key[2])" v-bind:key="key[1]"
        v-for="(key) in props.item[6]">

        <router-link :to="{ name : 'modifyinfo', params:{prip : key[0], Name : props.item[1], pripId : key[1]}}"> {{displaycase(key[0])}}
        </router-link>

        <dialog :prip_name=props.item[1] :prip_info=key[0]>{{displaycase(key[0])}}</dialog>

    </v-btn>

I need to get the router link and dialog as option in dropdown in the div. Kindly help.

A: I don't understand your question. You want to render the router-link and dialog component when the user hovers on the buttons? or click?


text:
Q: Custom validation with RESTful APIs I am newbie in Java world (came from .Net background). I created a RESTful service using Jersey framework. it has couple of methods. Following is the sample code snippet for Customer service. There are couple more services in my code.
@Path("/CustomerService")
public interface ICustomerService {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/getCustomerInfo")
    Response query(String constraints);

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/getCustomerDetails")
    Response fetchDetails(String customerID);

}

I have some validation logic which I would like to perform at each API which is exposed to the client. I C# world we can define own validation logic. Something like following, This can be applied at method or controller level.
[MyValdationLogic()]

What is the equivalent in Java? How can I write code which can be applied at multiple places over the method.
Also I do not want to allow admin to play with that configuration. I found there is something called as filters but this gets configured in config file. admin can disable it.

A: You can create a Validator class and use that Validator class on your bean for validation. Although, the process is bit lengthy.
Following is one example of doing this -
Jersey Resource
@POST
@Path("/addEmp")
@Produces("text/plain")
public String doOrder(@BeanParam final @Valid Employee emp) {

    // Some implementation here
}

Sample Bean -
Suppose, I want to apply validation on address i.e. either address or city or postcode must be there.
@Address
public final class Employee {

    @FormDataParam("id")
    private String id;

    @FormDataParam("address")
    private String address;

    @FormDataParam("city")
    private String city;

    @FormDataParam("postcode")
    private String postcode;

        // Other member variables

        // Getters and setters

}

Address Annotation -
Define custom Address Annotation
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = AddressValidator.class)
@Documented
public @interface Address {

    String message() default "Address required";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Validator Class -
Here is the validator class contains actual validation logic -
public class AddressValidator implements ConstraintValidator<Address, Employee> {

    @Override
    public boolean isValid(Employee emp, ConstraintValidatorContext constraintValidatorContext) {

    // Check for at least one value
    if((emp.getAddress() != null && !emp.getAddress().equals("") ||
            (emp.getCity() != null && !emp.getCity().equals("")) ||
            (emp.getPostcode() != null && !emp.getPostcode().equals("")))) {
        return true;
    }

    return false;
    }
    public void initialize(Address emp) {
          ...
    }
}

By this way, you can create reusable Validator class. Instead of taking Employee directly in this Validator class, you can take Object class or some parent class and then change the logic accordingly.
You can check more details in bean-validation