text:
Q: Getting Matlab handles events or properties The question
How may I get the list of events and properties for a handle of double type, as a figure, axes?
The issue
Matlab documentation says to you to use the WindowButtonDownFcn, WindowButtonMotionFcn, and so on in order to listen to whatever happens at your interface. The issue is that this properties are very limited as the following fact:
Keeping Variables in Scope

When MATLAB evaluates function handles, the same variables are in
  scope as when the function handle was created. (In contrast, callbacks
  specified as strings are evaluated in the base workspace.) This
  simplifies the process of managing global data, such as object
  handles, in a GUI.

Yes, this is perfect, if you don't have to redefine, add, or remove callbacks from your ButtonDownFcn, because if you do so, you will lose the other function handles variable scopes, as you are declaring them at a new scope which may will certainly not contain your so needed variables.
So one way would be to listen to the events themselves, not to properties that are called when the events are actived, and by doing so, you will not have to bother to redeclare your ButtonDownFcn and how to keep your variables at scope, because the other solutions are very slow to implement!. If I could listen to the events directly, as I do with handle.listener or addlistener matlab listening tools, I would not have to bother with that.
One good approach already known
One of the best solutions it seems is this FEX, which empowers the weak matlab WindowButtonDownFcn, WindowButtonDownFcn and whatever properties "listeners" function matlab has, so that you can have any amounts of functions listening to changes at the your graphical interface without having to care if your other functions handles will lose their scope variables.
With this I don't need to get the matlab events as it wrappers everything for me. But it still amuses me that matlab lead your users to use a broken feature instead of documenting the better approach and lead people to wrap everything around so that they can use things as they should be.

Information that may be useful.
I know about the meta.class that will give me all the properties, events and so on that a class have. For one class I have that inherits from a handle:
>> EventMeta = ?Event
EventMeta =

  class with properties:

                     Name: 'Event'
              Description: ''
      DetailedDescription: ''
                   Hidden: 0
                   Sealed: 0
                 Abstract: 0
          ConstructOnLoad: 0
         HandleCompatible: 1
          InferiorClasses: {0x1 cell}
        ContainingPackage: []
             PropertyList: [64x1 meta.property]
               MethodList: [29x1 meta.method]
                EventList: [2x1 meta.event]
    EnumerationMemberList: [0x1 meta.EnumeratedValue]
           SuperclassList: [1x1 meta.class]

with that meta I can get the EventList from my Event class, which are:
>> EventMeta.EventList.Name

ans =

attemptToClick

ans =

ObjectBeingDestroyed

Well, this is not that great thing in this case, since I have implemented it and I know the events it has because I have the source. The thing is, if I can get the metaclass of a figure (if that is possible), I could have access to its implemented Events if they are available at the matlab.

A: As I was improving my question, I managed to find an answer for this (unfortunately it seems that I haven't seem them before at my searchs, and what's worse, some of the links I've opened before…)
Here the undocummented matlab blog shows how to get the handles from a matlab handle object. And it seems that there was already a question about this made at 2011 about this issue here in stackoverflow, and properly answered by @gnovice. The answer is:
>> get(get(classhandle(handle(gcf)),'Events'),'Name')
ans =
    'SerializeEvent'
    'FigureUpdateEvent'
    'ResizeEvent'
    'WindowKeyReleaseEvent'
    'WindowKeyPressEvent'
    'WindowButtonUpEvent'
    'WindowButtonDownEvent'
    'WindowButtonMotionEvent'
    'WindowPostChangeEvent'
    'WindowPreChangeEvent'

I still would like to call your attention to the FEX as another good solution that may give you better possibilities for working with the graphical components offered by matlab.
Usage example:
>> k=handle.listener(gcf,'WindowButtonMotionEvent','disp(''MOVEMENT DETECTED!!'')');
>> MOVEMENT DETECTED!! % When you move the mouse on the figure
>> MOVEMENT DETECTED!!
>> MOVEMENT DETECTED!!
>> MOVEMENT DETECTED!!
>> MOVEMENT DETECTED!!
>> MOVEMENT DETECTED!!
>> delete(k)

A: Under the hood, Handle Graphics (HG) are implemented using the undocumented UDD mechanism, not the usual classdef-style OOP exposed to the user.
That's why you cant directly use the meta.class system to get meta-information on such handles.
As you already found out on Yair Altman's blog, there are undocumented ways to listen to events:
fig = hg.figure(); plot(rand(100,1))
lh = handle.listener(fig, 'WindowButtonDownEvent',@(~,~)disp('clicked'));

If you already have an existing HG object handle (represented with a numeric handle), use handle to convert it to a UDD handle:
f = figure();
fig = handle(f);

and yes I know, the term handle is quite overloaded in MATLAB and may refer to many things

A: Try using get:
fig = gcf();
get(fig)

A: I don't know how to do this.  I can provide some sample code to demonstrate what I think is being asked.  This is a relatively new (therefore unused) Matlab feature:
hh = handle(gca);
lsnr = addlistener(hh,'XLim','PreGet',@(~,~)disp('<<<Getting XLIM values>>>'))

To see the listener in action
>> get(hh,'XLim')
<<<Getting XLIM values>>>
ans =
     0     1

I think the question is how to get lsnr from gca if the value was not stored.
I can't find a way.


text:
Q: Layers of Images using UIImageView I just wanted to confirm, is it possible that we add layers of images using UImageView, one as background and other on top of it. I mean i want to use 2 images one has to be in the background and the other on top of it. ( the size of both these images is 320 x 480 ).
Through the attributes inspector we cant do it. Is there any we can do it through code.
Maybe using subview or something.

A: You need one UIImageView for each image, but they will appear layered as long as the top view is not opaque.  You could put both image views into a third UIView if you want to treat them as a single entity.
Edit:
imageBackground = [[UIImageView alloc] initWithImage:[UIImageNamed:@"background.png"]];
imageForeground = [[UIImageView alloc] initWithImage:[UIImageNamed:@"foreground.png"]];
imageLayered = [[UIView alloc] initWithFrame:[imageBackground frame];

[imageLayered addSubview:imageBackground];
[imageLayered addSubview:imageForeground];

// release all views at some point.

imageLayered is now a UIView with a background and foreground image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to manage multiple haskell installations on macOS? I have on my computer (macOS High Sierra) multiple installations of the standard (Glasgow) Haskell compiler. The oldest one (as far as I can remember) is a minimal installation, while I obtained the most recent version form the "Platform" installer, something like five or six months ago. I'm trying to get rid of the whole ecosystem (ghc, stack, cabal, and friends), mostly because I don't know what tools I will be using in the case I'll plan to get back using the language.
So my questions are:

*

*Where does the minimal/"Platform" installer installs Haskell and all related stuff?

*How can one remove the whole Haskell language and all its components mentioned above (in the case of a "Platform" install, and even in the case of a minimal installation)?
EDIT: I've just remembered of the uninstall-hs command (see also here), should I run this instead of removing files manually?

A: I think I have come up with a solution and I'll answer the latter question first:

*

*All the details I was looking for (what effectively is installed after launching the minimal / "Platform" installer, and, most importantly, where these guys were placed) can be found in the documentation welcome file at /Library/Haskell/Doc/Start.html. More precisely:

On Mac OS X, the Haskell Platform is installed in two major pieces: GHC and Haskell Platform. They are installed respectively in: /Library/Frameworks/GHC.framework and /Library/Haskell. Executables are symlinked in /usr/local/bin [...].

There are also another two or three directories in the home folder, namely ~/.ghc and ~/.stack.

*As said in the OP, the script uninstall-hs done its work, showing a (at least I hope so) comprehensive list of all the files that constitutes the Haskell "sdk" actually installed.
Feel free to post your answers, I hope this post will be useful to the community.


text:
Q: Convergence of probability measures problem Let $\mu_n$ be sequence of probability measures on a polish space $S$ such that for any bounded and continuous $f:S \to \Bbb R$ we have
$$\int fd\mu_n \to \int fd\mu$$
Then I have seen in some place claiming the following:
$$\int h(x_n,y)\mu_n(dy) \to \int h(x,y)\mu(dy)$$
for $h:\Bbb R \times S \to \Bbb R$ and bounded, continuous with $x_n \to x$.
It looks like convergence in product topology is used, I am not much aware of such things

A: By Prokhorov's Theorem (http://en.wikipedia.org/wiki/Prokhorov%27s_theorem), the sequence $(\mu_n)_n$ is (uniformly) tight, i.e. for every $\varepsilon > 0$, there is a compact set $K_\varepsilon \subset S$ such that $\mu_n ( S\setminus K_\varepsilon) < \varepsilon$ for all $n \in \Bbb{N}$.
Now use that the set $L := \{x_n \mid n \in \Bbb{N}\} \cup \{x\}$ is also compact, so that $L \times K_\varepsilon$ is compact.
We can now use that continuous functions on compact sets are uniformly continuous.
Together with the boundedness of $h$, which ensures that
$$
\bigg| \int_{S \setminus K_\varepsilon} h(x_n, y) \, d\mu_n(y)\bigg| \leq C \cdot \mu_n (S \setminus K_\varepsilon) \leq C \cdot \varepsilon,
$$
this should allow you to conclude the proof.
EDIT: Putting all pieces together, we arrive at
\begin{eqnarray*}
 &  & \left|\int h\left(x_{n},y\right)\,{\rm d}\mu_{n}\left(y\right)-\int h\left(x,y\right)\,{\rm d}\mu\left(y\right)\right|\\
 & \leq & \left|\int_{S\setminus K_{\varepsilon}}h\left(x_{n},y\right)\,{\rm d}\mu_{n}\left(y\right)\right|+\left|\int_{K_{\varepsilon}}h\left(x_{n},y\right)-h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)\right|+\left|\int_{K_{\varepsilon}}h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)-\int_{S}h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)\right|+\left|\int_{S}h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)-\int_{S}h\left(x,y\right)\,{\rm d}\mu\left(y\right)\right|\\
 & \leq & C\cdot\varepsilon+\sup_{y\in K_{\varepsilon}}\left|h\left(x_{n},y\right)-h\left(x,y\right)\right|+\left|\int_{S\setminus K_{\varepsilon}}h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)\right|+\left|\int_{S}h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)-\int_{S}h\left(x,y\right)\,{\rm d}\mu\left(y\right)\right|\\
 & \leq & 2C\cdot\varepsilon+\sup_{y\in K_{\varepsilon}}\left|h\left(x_{n},y\right)-h\left(x,y\right)\right|+\left|\int_{S}h\left(x,y\right)\,{\rm d}\mu_{n}\left(y\right)-\int_{S}h\left(x,y\right)\,{\rm d}\mu\left(y\right)\right|\\
 & \xrightarrow[n\to\infty]{} & 2C\cdot\varepsilon,
\end{eqnarray*}
where the last step used the uniform continuity of $h$ on $L\times K_\varepsilon$ and the assumption on the convergence $\mu_n \to \mu$ (in the sense of your assumption). As $\varepsilon > 0$ was arbitrary, this establishes the claim.


text:
Q: Use common JS libs inside sandboxed iframes I plan to build a module system for my webapp that uses sandboxed iframes and the postMessage API to securely run custom user modules. The iframe blocks all DOM access and should only communicate through an interface provided by me which checks some permissions and provides data.
The system itself is very simple and works fine with vanilla js code inside the modules, however I want to allow developers to use common frameworks/libs to ease development, i.e. by using Vue for data binding.
What is the best way to provide such functionality to the modules? Performance is a huge factor since several dozens of such modules might run at the same time. Is it secure to let sandboxed modules share libs?

A: Good advice: Unfortunately, iframe sandboxing goes both ways. In general (with a few exceptions: mainly postMessage and pages that satisfy the same-origin policy), an iframe is effectively a separate webpage and cannot be accessed from the host page, and vice-versa. It's probably a better alternative to just request that the individual developers use lightweight libraries.
Bad advice: If you hosted the other devs' files yourself, they could access each other, but having stuff accessible between iframes in this way is certainly not ideal- and doing it this way is a really bad idea, as it exposes you to all sorts of scripting-related attacks; not to mention the fact that the separate iframes would probably accidentally interfere with one another in unexpected ways if you shared Javascript variables between them. Don't do it this way unless you explicitly trust every single developer here to behave properly and code well (i.e. you're in the same workplace). Actually, just don't do it this way at all.
If you really really want to do this, though: an iframe whose target is hosted on the same website can access its parent page through the global variable parent (i.e. parent in an iframe is the same as window in the host, parent.$ would be the parent's jQuery object, and parent.document.getElementById is the same as document.getElementById). A parent page can access its same-origin iframes with document.getElementById("the id of the iframe").contentWindow (and .contentWindow.document, etc. will work here too), but again, if you hosted the code of potentially-malicious developers on your page to get around the same-origin policy, you'd be giving these developers access to your page and any information, including passwords, that your users type on it.


text:
Q: How to select an element with 2 classes i have this elements

I want apply to element with class a and b the color #666.
How can I do this with CSS?

A: You can chain class selectors without a space between them:
.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

A: Just chain them together:
.a.b {
  color: #666;
}


text:
Q: To replace % marks but not \% in Perl Regex I am thinking how you can replace [^\]% marks but not \% marks in the sed -command of this answer.
I think look-behind is not necessary.
My current Sed command but I think Perl is a must here
cat something | sed 's#%.*</#</#'

which removes also everything after the % sign i.e. all comments in LaTeX but not percentage values.
My unsuccessful Perl attempt
cat something | perl 's#[^\]%.*</#</#'

where I do not know how I make Perl to take the standard output of cat.
Data
------------------------------
Protocol of pre-eclampsia
------------------------------
Monitoring in 90\% cases

Antihypertensives when % this is a comment, please, remove me!
$SBP/DBP > 160/110$; slowly.
------------------------------

Desired output
------------------------------
Protocol of pre-eclampsia
------------------------------
Monitoring in 90\% cases

Antihypertensives when
$SBP/DBP > 160/110$; slowly.
------------------------------

How can you replace % signs but not \%?
If you can do this by Sed, please, comment.

A: Like many, if not most, text parsing tools, perl can take input from the command line, there's no need for cat. You just need -e which lets you pass a script as a command line parameter and -n which means "run the script on each line of input". ALternatively, you can use the -p switch which means "run the script on each line of input, then print that line". These two commands are equivalent (but the second is a classic useless use of cat, use the first) :
perl -pe 's/foo/bar/' file
cat file | perl -pe 's/foo/bar/'

Now, if I understand correctly, you want to delete all LaTeX comments (though that's not what your question states). If so, a lookbehind is the easiest way:
perl -pe 's/(?<!\\)%.*//' file

Your regex should also work, you just need to keep the character you matched before the % and escape the backslash:
perl -pe 's/(^|[^\\]+)%.*/$1/' file

You can do the same thing with GNU sed:
sed -r 's/(^|[^\\])%.*/\1/' file

A: If you just want to replace what follows % but not what follows \%, in Perl, the easiest way is with a negative lookbehind: match %.* only if it isn't preceded by a backslash.
perl -pe 's/(?<!\\)%.*//'

However this won't match something like Hello world.\\%wibble. For that, you need to check that the % is preceded by an even number of backslashes. You can't do that with a lookbehind, because Perl's lookbehinds only support fixed-length patterns. Instead, match the backslashes in the regexp, and use a lookbehind to ensure that the regexp captures them all.
perl -pe 's/(?<!\\)((?:\\\\)*)%.*/$1/'

You can do that with tools that don't support lookbehind as well. In this case, you'll need to either use a tricky succession of replacement commands or match the backslashes and copy them to the replacement text.
sed -e 's/^\(\(\\\\\)*\)%.*/\1/' -e 's/\([^\\]\(\\\\\)*\)%.*/\1/'

Note that if you're processing a LaTeX document, there are other percent signs that might need to stay, for example in verbatim blocks. That can't be done with regexps alone.

A: A common idiom to replace unescaped characters in perl is with:
$ printf '%s\n' '% \% \\% \\\%' | perl -pe 's/(\\.)|%/$1||"<replacement>"/ge'
<replacement> \% \\<replacement> \\\%

So to remove everything starting from an unescaped %:
perl -pe 's/(\\.)|%.*/$1/g'

If your sed supports -E (FreeBSD/GNU):
sed -E 's/(\\.)|%.*/\1/g'

Or with GNU sed:
sed 's/\(\\.\)\|%.*/\1/g'

Where the alternation RE operator is not available (as in standard basic RE), you could often use \{0,1\} instead:
sed 's/\(\(\(\\.\)\{0,1\}[^\\%]*\)*\)\(%.*\)\{0,1\}/\1/'


text:
Q: PHP search is not working in multiple database tables I'm trying to do a search form where you can search in multiple database tables, and its working when i search in only one table but when i try with two tables im getting a "Undefined index" error.
This is the html code :

            Customer Name
            Email
            Address

        <?php print("$searchoutput"); ?>

And this is the php code above html tag.
The code for searching is in the second php tag:
 <?php include("includes/database.php"); ?>
 <?php

$query = "SELECT
        costumers.id,
        costumers.first_name,
        costumers.last_name,
        costumers.email,
        costumer_addresses.address,
        costumer_addresses.address2,
        costumer_addresses.city,
        costumer_addresses.state,
        costumer_addresses.zipcode
        FROM costumers
        Inner Join costumer_addresses
        on costumer_addresses.costumer=costumers.id
        order by join_date DESC";

$result=$mysqli->query($query) or die ($mysqli->error.__LINE__);

?>
<?php
    $searchoutput='';
    if(isset($_POST['search'])){
    $searchq=$_POST['search'];
    $searchq=preg_replace("#[^0-9a-z]#i", "", $searchq);

   $query = mysqli_query($mysqli,"SELECT * FROM costumer_addresses WHERE address LIKE '%$searchq%' OR address2 LIKE '%$searchq%' OR city LIKE '%$searchq%' OR state LIKE '%$searchq%'
        UNION
        SELECT * FROM costumers WHERE first_name LIKE '%".$searchq."%' OR last_name LIKE '%".$searchq."%' OR email LIKE '%".$searchq."%' ") OR die($mysqli->error.__LINE__);

    $count = mysqli_num_rows($query);
    if($count == 0){
        $searchoutput = 'There was no search results!';
    }else{
        while($row = mysqli_fetch_array($query)){
            $first_name=$row['first_name'];
            $last_name=$row['last_name'];
            $email=$row['email'];
            $address=$row['address'];
            $address2=$row['address2'];
            $city=$row['city'];
            $state=$row['state'];

            $searchoutput.='
';
            $searchoutput.=''.$row['first_name'].' '.$row['last_name'].'	';
            $searchoutput.=''.$row['email'].'	';
            $searchoutput.=''.$row['address'].' '.$row['city'].' '.$row['state'].'	';
            $searchoutput.='Edit	';
            $searchoutput.='
';

        }
    }
}
?>

A: Please use
$query = mysqli_query($mysqli,"SELECT * FROM costumers where first_name like '%$searchq%' or last_name like '%$searchq%' or email like '%$searchq%'
    UNION
    SELECT * FROM costumer_addresses where address like '%".$searchq."%' or address2 like '%".$searchq."%' or city like '%".$searchq."%' or state like '%".$searchq."%' ") or die($mysqli->error.__LINE__);

instead of
  $query = mysqli_query($mysqli,"SELECT * FROM costumers where first_name like '%$searchq%' or last_name like '%$searchq%' or email like '%$searchq%'
    UNION
    SELECT * FROM costumer_addresses where address like '%$searchq%' or address2 like '%$searchq%' or city like '%$searchq%' or state like '%$searchq%' ") or die($mysqli->error.__LINE__);


text:
Q: wxPython, capturing an output from subprocess in real-time I'm working on application in wxPython which is a GUI for a command line utility. In the GUI there is a text control which should display the output from the application. I'm launching the shell command using subprocess, but I don't get any output from it until it has completed.
I have tried several solutions but none of them seems to work. Below is the code I'm using at the moment (updated):
       def onOk(self,event):
        self.getControl('infotxt').Clear()
        try:
            thread = threading.Thread(target=self.run)
            thread.setDaemon(True)
            thread.start()

        except Exception:
            print 'Error starting thread'

    def run(self):
        args = dict()
        # creating a command to execute...

        cmd = ["aplcorr", "-vvfile", args['vvfile'], "-navfile", args['navfile'], "-lev1file", args['lev1file'], "-dem", args['dem'], "-igmfile", args['outfile']]

        proc = subprocess.Popen(' '.join(cmd), shell=True, stdout=subprocess.PIPE, stderr.subprocess.PIPE)

        print
        while True:
            line = proc.stdout.readline()
            wx.Yield()
            if line.strip() == "":
                pass
            else:
                print line.strip()
            if not line: break
        proc.wait()

class RedirectInfoText:
    """ Class to redirect stdout text """
    def __init__(self,wxTextCtrl):
        self.out=wxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

class RedirectErrorText:
    """ Class to redirect stderr text """
    def __init__(self,wxTextCtrl):
        self.out.SetDefailtStyle(wx.TextAttr())
        self.out=wxTextCtrl

    def write(self,string):
        self.out.SetDefaultStyle(wx.TextAttr(wx.RED))
        self.out.WriteText(string)

In particular I'm going to need the output in real-time to create a progress-bar.
Edit: I changed my code, based on Mike Driscoll's suggestion. It seems to work sometimes, but most of the time I'm getting one of the following errors:

(python:7698): Gtk-CRITICAL **: gtk_text_layout_real_invalidate:
  assertion `layout->wrap_loop_count == 0' failed

or

(python:7893): Gtk-WARNING **: Invalid text buffer iterator: either
  the iterator is uninitialized, or the characters/pixbufs/widgets in
  the buffer have been modified since the iterator was created. You must
  use marks, character numbers, or line numbers to preserve a position
  across buffer modifications. You can apply tags and insert marks
  without invalidating your iterators, but any mutation that affects
  'indexable' buffer contents (contents that can be referred to by
  character offset) will invalidate all outstanding iterators
  Segmentation fault (core dumped)

Any clues?

A: The problem is because you are trying to wx.Yield and to update the output widgets from the context of the thread running the process, instead of doing the update from the GUI thread.

*

*Since you are running the process from a thread there should be no need to call wx.Yield, because you are not blocking the GUI thread, and so any pending UI events should be processed normally anyway.

*Take a look at the wx.PyOnDemandOutputWindow class for an example of how to handle prints or other output that originate from a non-GUI thread.

A: This can be a little tricky, but I figured out one way to do it which I wrote about here: http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/
After you have set up the redirection of the text, you just need to do something like this:
def pingIP(self, ip):
    proc = subprocess.Popen("ping %s" % ip, shell=True,
                            stdout=subprocess.PIPE)
    print
    while True:
        line = proc.stdout.readline()
        wx.Yield()
        if line.strip() == "":
            pass
        else:
            print line.strip()
        if not line: break
    proc.wait()

The article shows how to redirect the text too. Hopefully that will help!


text:
Q: How to access localhost from docker to mobile? I want to view the apps from mobile devices. I have tried to use the ip address of my laptop but i still cant accessed to the apps from mobile devices. I can run the apps locally in my laptop but not in other devices although they are using the same network WIFI. I have tried to add ENV HOST 0.0.0.0 which helps to solve connection outside but it still cannot be accessible in my mobile devices. Is there any solution for this ?
Docker File
FROM node:16.14.0-alpine3.15 as builder
ENV HOST 0.0.0.0
WORKDIR /app

COPY . .

RUN yarn install \
  --prefer-offline \
  --frozen-lockfile \
  --non-interactive \
  --production=false

RUN yarn generate

RUN rm -rf node_modules && \
  NODE_ENV=production yarn install \
  --prefer-offline \
  --pure-lockfile \
  --non-interactive \
  --production=true

# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=builder /app/.output/public /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Docker-compose file
version: '3'
services:
    backend:
        image: python:3.6
        volumes:
            - ./backend:/backend
        ports:
            - 8000:8000
        command: bash -c "cd ./backend && pip install -r requirements.txt && python manage.py migrate && python manage.p>
    frontend:
        build:
            context: ./frontend
            dockerfile: Dockerfile
        logging:
            driver: "json-file"
            options:
                max-file: "5"
                max-size: 50m
        restart: unless-stopped
        ports:
            - 3001:80


text:
Q: how to index categorical features in another way when using spark ml The VectorIndexer in spark indexes categorical features according to the frequency of variables.  But I want to index the categorical features in a different way.
For example, with a dataset as below, "a","b","c" will be indexed as 0,1,2 if I use the VectorIndexer in spark. But I want to index them according to the label.
There are 4 rows data which are indexed as 1, and among them 3 rows have feature 'a',1 row feautre 'c'. So here I will index 'a' as 0,'c' as 1 and 'b' as 2.
Is there any convienient way to implement this?
 label|feature
-----------------
    1 | a
    1 | c
    0 | a
    0 | b
    1 | a
    0 | b
    0 | b
    0 | c
    1 | a

A: If I understand your question correctly, you are looking to replicate the behaviour of StringIndexer() on grouped data. To do so (in pySpark), we first define an udf that will operate on a List column containing all the values per group. Note that elements with equal counts will be ordered arbitrarily.
from collections import Counter
from pyspark.sql.types import ArrayType, IntegerType

def encoder(col):

  # Generate count per letter
  x = Counter(col)

  # Create a dictionary, mapping each letter to its rank
  ranking = {pair[0]: rank
           for rank, pair in enumerate(x.most_common())}

  # Use dictionary to replace letters by rank
  new_list = [ranking[i] for i in col]

  return(new_list)

encoder_udf = udf(encoder, ArrayType(IntegerType()))

Now we can aggregate the feature column into a list grouped by the column label using collect_list() , and apply our udf rowwise:
from pyspark.sql.functions import collect_list, explode

df1 = (df.groupBy("label")
       .agg(collect_list("feature")
            .alias("features"))
       .withColumn("index",
                   encoder_udf("features")))

Consequently, you can explode the index column to get the encoded values instead of the letters:
df1.select("label", explode(df1.index).alias("index")).show()
+-----+-----+
|label|index|
+-----+-----+
|    0|    1|
|    0|    0|
|    0|    0|
|    0|    0|
|    0|    2|
|    1|    0|
|    1|    1|
|    1|    0|
|    1|    0|
+-----+-----+


text:
Q: How to pass through pages using selenium and c# This is most likely a error of logic in my code.
In first place, what i'm trying to do is:

*

*go to the respective page of my website which is in this case link and collect the data, with my public void GDataPicker.

*now where i want you to help me is, i use the following code to see if the button next exists in the webpage, and collect it's respective data, but always give me the same error:

OpenQA.Selenium.StaleElementReferenceException: 'stale element reference: element is not attached to the page document
    (Session info: chrome=58.0.3029.110)
    (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.15063 x86_64)' , i think it's probably because i don´t update my NextButtonElement.

Code:
Boolean ElementDisplayed;
try
{
    Gdriver.Navigate().GoToUrl("http://www.codigo-postal.pt/");
    IWebElement searchInput1 = Gdriver.FindElement(By.Id("cp4"));
    searchInput1.SendKeys("4710");//4730
    IWebElement searchInput2 = Gdriver.FindElement(By.ClassName("cp3"));
    searchInput2.SendKeys("");//324
    searchInput2.SendKeys(OpenQA.Selenium.Keys.Enter);
    IWebElement NextButtonElement = Gdriver.FindElement(By.XPath("/html/body/div[4]/div/div/div[2]/ul/li[13]/a"));
    GDataPicker();

    while (ElementDisplayed =  NextButtonElement.Displayed)
    {
        GDataPicker();
        Gdriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2000));
        NextButtonElement.SendKeys(OpenQA.Selenium.Keys.Enter);
    }
}
catch (NoSuchElementException i)
{
    ElementDisplayed = false;
    GDataPicker();
}

A: I cant help you with C#, however StaleElementReferenceException occurs when the element you act upon is still in the dom but has been replaced with an identical one. what i would do is catch that exception and find the element again
catch (StaleElementReferenceException i)
    {

        IWebElement NextButtonElement = Gdriver.FindElement(By.XPath("/html/body/div[4]/div/div/div[2]/ul/li[13]/a"));

    }

http://www.seleniumhq.org/exceptions/stale_element_reference.jsp

A: I would use ExpectedConditions.ElementToBeClickable with the dynamic wait feature selenium has.
var wait = new WebDriverWait(GDriver, TimeSpan.FromSeconds(5));
IWebElement NextButtonElement = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("/html/body/div[4]/div/div/div[2]/ul/li[13]/a")));

ExpectedConditions.ElementToBeClickable does exactly what you want it to do, wait a little bit until the element is displayed and not stale.
        /// <summary>
    /// An expectation for checking an element is visible and enabled such that you
    /// can click it.
    /// </summary>
    /// <param name="locator">The locator used to find the element.</param>
    /// <returns>The <see cref="IWebElement"/> once it is located and clickable (visible and enabled).</returns>
    public static Func<IWebDriver, IWebElement> ElementToBeClickable(By locator)
    {
        return (driver) =>
        {
            var element = ElementIfVisible(driver.FindElement(locator));
            try
            {
                if (element != null && element.Enabled)
                {
                    return element;
                }
                else
                {
                    return null;
                }
            }
            catch (StaleElementReferenceException)
            {
                return null;
            }
        };
    }

From https://github.com/SeleniumHQ/selenium/blob/master/dotnet/src/support/UI/ExpectedConditions.cs


text:
Q: Test method threw exception: Couldn't find window with title Calculator I have one problem for each UI test on my computer:Test method threw exception: Couldn't find window with title Calculator. Of course, window is present and its name is "Calculator"(checked by inspect). The same situation is for others UI elements.
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TestStack.White;
    using TestStack.White.Factory;
    using TestStack.White.UIItems;

    namespace UnitTestProject3
    {
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {
                using (var application = Application.Launch("Calc.exe"))
                {
                    var calculator = application.GetWindow("Calculator", InitializeOption.NoCache);

                    // do something with the application
                    var b7 = calculator.Get<Button>(TestStack.White.UIItems.Finders.SearchCriteria.ByText("7"));
                    b7.Click();

                    application.Close();

                }
            }
        }
    }

What could it be?
Thanks in advance for your help.

A: Teststack White does not support UWP applications such as Calculator on Windows 10. For supporting UWP apps, you can use:

*

*UIAComWrapper branch from white (partially working)

*Switch to UIA3

More information here


text:
Q: GDB Packs Missing? I run GDB on a program and get this after setting breakpoint main:
Missing separate debuginfos, use: debuginfo-install glibc-2.17-55.el7.x86_64
What exactly does it want?

A: It means that you should install a debuginfo package of the program you debugged. The package's name is always like this:
{package-name}-debuginfo.x86_64.

It is the package which includes the source code of the program you used, so when you debug the program it can locate many information like source file, line number and so on.


text:
Q: LINQ does multiple, instead of one, iterations through a collection and then some I have this class:
public class SimHasher {
    int count = 0;

    //take each string and make an int[] out of it
    //should call Hash method lines.Count() times
    public IEnumerable<int[]> HashAll(IEnumerable<string> lines) {
        //return lines.Select(il => Hash(il));
        var linesCount = lines.Count();
        var hashes = new int[linesCount][];
        for (var i = 0; i < linesCount; ++i) {
            hashes[i] = Hash(lines.ElementAt(i));
        }
        return hashes;
    }

    public int[] Hash(string line) {
        Debug.WriteLine(++count);
        //stuff
    }
}

When I run a program that calls HashAll and passes it an IEnumerable<string> with 1000 elements, it acts as expected: loops 1000 times, writing numbers from 1 to 1000 in the debug console with the program finishing in under 1 second. However if I replace the code of the HashAll method with the LINQ statement, like so:
public IEnumerable<int[]> HashAll(IEnumerable<string> lines) {
    return lines.Select(il => Hash(il));
}

the behavior seems to depend on where HashAll gets called from.
If I call it from this test method
[Fact]
public void SprutSequentialIntegrationTest() {
    var inputContainer = new InputContainer(new string[] {
        @"D:\Solutions\SimHash\SimHashTests\R.in"
    });
    var simHasher = new SimHasher();
    var documentSimHashes = simHasher.HashAll(inputContainer.InputLines); //right here
    var queryRunner = new QueryRunner(documentSimHashes);
    var queryResults = queryRunner.RunAllQueries
        (inputContainer.Queries);

    var expectedQueryResults = System.IO.File.ReadAllLines(
        @"D:\Solutions\SimHash\SimHashTests\R.out")
        .Select(eqr => int.Parse(eqr));
    Assert.Equal(expectedQueryResults, queryResults);
}

the counter in the debug console reaches around 13,000, even though there are only 1000 input lines. It also takes around 6 seconds to finish, but still manages to produce the same results as the loop version.
If I run it from the Main method like so
static void Main(string[] args) {
    var inputContainer = new InputContainer(args);
    var simHasher = new SimHasher();
    var documentSimHashes = simHasher.HashAll(inputContainer.InputLines);
    var queryRunner = new QueryRunner(documentSimHashes);
    var queryResults = queryRunner.RunAllQueries
        (inputContainer.Queries);
    foreach (var queryResult in queryResults) {
        Console.WriteLine(queryResult);
    }
}

it starts writing out to the output console right away, altough very slowly, while the counter in the debug console goes into tens of thousands. When I try to debug it line by line, it goes straight to the foreach loop and writes out the results one by one. After some Googling, I've found out that this is due to LINQ queries being lazily evaluated. However, each time it lazily evaluates a result, the counter in the debug console increase by more than 1000, which is even more than the number of input lines.
What is causing so many calls to the Hash method? Can it be deduced from these snippets?

A: The reason why you get more iterations than you would expect is that there are LINQ calls that iterate the IEnumerable<T> multiple times.
When you call Count() on an IEnumerable<T>, LINQ tries to see if there is a Count or Length to avoid iterating, but when there is no shortcut, it iterates IEnumerable<T> all the way to the end.
Similarly, when you call ElementAt(i), LINQ tries to see if there is an indexer, but generally it iterates the collection up to point i. This renders your loop an O(n2).
You can easily fix your problem by storing your IEnumerable<T> in a list or an array by calling ToList() or ToArray(). This would iterate through IEnumerable<T> once, and then use Count and indexes to avoid further iterations.

A: IEnumerable<T> does not allow random access.
The ElementAt() method will actually loop through the entire sequence until it reaches the N'th element.


text:
Q: ePub submission issue in NookPress.com After uploading an ePub file to NookPress.com,an error appeared which said
"An Error Occurred Processing Content
FATAL:referenced resource missing in the package"
I have checked my HTMLs,Content.opf & ncx files and found no such problem in data,
I have tested my ePub file with ePub checker,It is showing nothing wrong with the ePub file created by me.
If anyone faced the same issue & would able to resolve it,Do let me know,I have been tangling with this problem since long.
Thanks

A: I wrestled with this same problem for most of a day. Finally, I submitted my EPUB file to EPUB Validator (http://validator.idpf.org/), which will give you more information about what the problem is exactly. In my case, I did not put "http://" in front of my website in an anchor tag. I had some other issues, too, but these were mainly warnings that I went ahead and stamped out.
Hopefully, this will help you out and get you over the hump.


text:
Q: How do I create a GitLab webhook? I've read that GitLab is capable of sending messages to other servers via "web hooks" but I can't find where one would create one.
Can someone point me in the right direction?

A: All the answers I've found in official documentation and on Stack Overflow for finding web hooks are incorrect. The admin area > hooks page does NOT contain web hooks. It contains system hooks, which fire when you create/delete projects and users and things like that. This is not what you want.
To find your web hooks, go to the specific project > settings > web hooks (on sidebar in GitLab 6.1.0) page. These will fire on post-receive for the project in question. You can use a service like RequestBin to see what the payload looks like and to ensure you're firing these off correctly for debugging purposes.

A: For group level hooks:
visit: https://gitlab.com/groups/<yourgroup>/hooks
For group project level hooks:
visit: https://gitlab.com/yourgroup/yourproject/hooks

A: You can see an example of GitLab system hook, with  a web_hook.rb creation in this GitHub project.

In gitlab, as admin, go to "Hooks" tab, create hook as: http://your.ip.goes.here:8000
or change the port on line 175 of the script.

For web hooks, see Jamey's more accurate answer.
You can inspect the result of a webhook with a service like RequestBin.
Another example of webhook interpretation: this question.
Be aware though that a few issues remain with gitlab webhook:

*

*it is not always firing

*There's no URL nor namespace key present on system's webhook

A: With version 8.16.1, I found the web hooks under
specific project > settings > integrations

A: I recommend using GitLabForm - configuration as code tool for GitLab - to configure webhooks with code like this:
project_settings:
  my_group/my_project:
    hooks:
      hooks:
      'http://127.0.0.1:5000/hooks/my-hook-endpoint':
        push_events: false # this is set to true by GitLab API by default
        merge_requests_events: true
        token: some_secret_auth_token

Disclosure: I wrote this tool and my company open-sourced it.


text:
Q: nv-websocket-client self-signed certificate I am trying to connect to a WSS server on my intranet with a self signed certificate. I have used Volley for HTTPS and TooTallNate library for WSS and I have been able to set SSLContext to accept all certificates. I am currently switching to nv-websocket-client so that I can add custom headers but, for the love of god, cant seem to bypass SSL certificate verification. I continue to run into the error message "The certificate of the peer...does not match the expected hostname". The code is exactly what is in the docs? is something different in v2.2? Here is the code I am using,
SSLContext context = NaiveSSLContext.getInstance("TLS");

ws = new WebSocketFactory().setSSLContext(context).setConnectionTimeout(5000)
            .createSocket("wss://192.168.1.164/chat/")
            .addListener(new WebSocketAdapter() {
                @Override
                public void onTextMessage(WebSocket websocket, String message) {
                    // Received a text message.
                   }
                @Override
                public void onConnectError(WebSocket websocket, WebSocketException e){
                    mTextView.setText(e.getMessage());
                }
            });
ws.connectAsynchronously();`

Can somebody help me. Thank you!

A: The author for the package has addressed it as an issue with a new feature in v2.3
WebSocketFactory.setVerifyHostname(false)

https://github.com/TakahikoKawasaki/nv-websocket-client/issues/116


text:
Q: Supporting multiple incompatible versions of C++ library I wrote a Ruby C++ extension to wrap Google's re2 regular expression library but a recent update to the library changed the interface of the Match() function from:
bool Match(const StringPiece& text,
           int startpos,
           Anchor anchor,
           StringPiece *match,
           int nmatch) const;

To:
bool Match(const StringPiece& text,
           int startpos,
           int endpos,
           Anchor anchor,
           StringPiece *match,
           int nmatch) const;

(Note the new int endpos argument.)
My question is: is it possible for me to support both versions of this library in one extension despite the fact that re2 does not seem to specify any kind of VERSION constant that I can introspect?
Ideally, I want to be able to try the newer version (with 6 arguments) and, failing that, fall back to the older version (as I am able to backfill the endpos argument easily).
At the moment my code is like this:
matched = p->pattern->Match(text_as_string_piece, 0, (int)RSTRING_LEN(text), RE2::UNANCHORED, 0, 0);

But if you have the older version of re2, it needs to be:
matched = p->pattern->Match(text_as_string_piece, 0, RE2::UNANCHORED, 0, 0);

A: From what I know, you can't. This would require you to link with both the old and the new versions of RE2, which would make namespaces collide.
Unless there exists a version of this method that ressembles the old version, you're stuck with the new version.
If you want to be able to compile your extension for both versions, then you have to modify your compiling steps to define some flag that you control.
#ifdef RE2_ODLFORMAT
matched = p->pattern->Match(text_as_string_piece, 0, RE2::UNANCHORED, 0, 0);
#else
matched = p->pattern->Match(text_as_string_piece, 0, (int)RSTRING_LEN(text), RE2::UNANCHORED, 0, 0);
#endif

Then to compile your code, you'd do something along those lines:
make RE2_OLDFORMAT=1 all # compile for old version
make all # default target is for new version

A: The traditional answer is to generate a config.h or whatever at installation time.
That is, at installation you will detect which version of re2 is installed, and then define a symbol in config.h depending on this:
// config.h
#ifndef CONFIG_H_INCLUDED
#define CONFIG_H_INCLUDED

#define RE2_MATCH_6_ARGS 1

#endif // CONFIG_H_INCLUDED

And then, you can use this:
#if defined(RE2_MATCH_6_ARGS) && RE2_MATCH_6_ARGS == 1
  matched = p->pattern->Match(text_as_string_piece, 0, (int)RSTRING_LEN(text), RE2::UNANCHORED, 0, 0);
#else
  matched = p->pattern->Match(text_as_string_piece, 0, RE2::UNANCHORED, 0, 0);
#endif

This is a stable solution, and should work well.

Another possibility is to hack the system...
Provide a definition of both Match functions in a wrapper library:

*

*Match5 throws an error (please link to re2)

*Match6 forwards to Match5.

The thing is (in the Unix world...), if a symbol has already been loaded, it will not be overwritten by a new definition. So as long as re2 is loaded first you end up in one of those two scenarios:

*

*old re2: your (wrapper) library provides a definition of Match6 which forwards to the re2 provided definition of Match5

*new re2: the call directly goes to the definition of Match6 that re2 provided

Much more brittle. Requires a wrapper library around re2. Unlikely to work with static linking (never tried though...). But does not require a ./configure step.


text:
Q: Local rule for the product of two cellular automata Consider two one-dimensional cellular automata $(A^{\mathbb Z},F)$ and $(B^{\mathbb Z},G)$ with alphabets $A$ and $B$ and global rules $F: A^{\mathbb Z} \to A^{\mathbb Z}$ and $G: B^{\mathbb Z} \to B^{\mathbb Z}$ corresponding to the local rules $f: A^m \to A$ and $g: B^n \to B$ respectively.
Consider the product cellular automaton $(A^{\mathbb Z} \times B^{\mathbb Z}, F \times G)$. These kinds of products are commonly used in dynamical systems to construct interesting examples (or counterexamples).
My question: Is there a way to re-code the product cellular automaton above on a one-dimensional configuration space? That is, can we find a (somehow) equivalent cellular automaton $(C^{\mathbb Z}, H)$ with a global rule $H: C^{\mathbb Z} \to C^{\mathbb Z}$ induced by an explicit local rule $h: C^k \to C$ which is more convenient to study?

A: Assuming that my edits to your question indeed reflect your intent correctly, the answer seems simple (and, indeed, was basically already sketched by Ville Salo in a comment above).
First, let's assume that the local rules $f$ and $g$ for the original cellular automata have the same neighborhood size, i.e. that $m = n$.  (If that's not the case, you can always increase the size of the smaller neighborhood to make them equal.)
Now, we make use of the fact that the sets $A^{\mathbb Z} \times B^{\mathbb Z}$ and $(A \times B)^{\mathbb Z}$ are naturally isomorphic, with the isomorphism mapping any pair of configurations $(x_i)_{i \in \mathbb Z} \in A^{\mathbb Z}$ and $(y_i)_{i \in \mathbb Z} \in B^{\mathbb Z}$ to the configuration $(x_i, y_i)_{i \in \mathbb Z} \in (A \times B)^{\mathbb Z}$. (Of course, this works just as well with any index set, not just $\mathbb Z$.)
Thus, we can simply represent the product automaton as $(C^{\mathbb Z}, H)$, where the alphabet $C = A \times B$ of the product automaton consist of pairs of symbols $(x, y)$, with $x \in A$ and $y \in B$, and where the global rule $H$ is induced by the local rule $h: C^n \to C$ defined as: $$h((x_1, y_1), …, (x_n, y_n)) = (f(x_1, …, x_n), g(y_1, …, y_n)).$$
That is, to evaluate the local rule $h$, we take the $n$-letter word $((x_1, y_1), …, (x_n, y_n)) \in C^n$, unpack it into the words $(x_1, …, x_n) \in A^n$ and $(y_1, …, y_n) \in B^n$, pass those into $f$ and $g$ respectively and return the pair of resulting symbols.
Of course, arguably all this formalism just obscures the underlying idea, which is that the product of two cellular automata simply consists of the two automata running in parallel without interacting, and that (when the automata share the same lattice) this can be equivalently interpreted as a single CA where each cell on the lattice stores a pair of states, one for each of the original automata, and the two halves of the state pairs evolve under their respective rules without influencing each other in any way.


text:
Q: textFieldShouldReturn not being called after upgrade in Swift 4 I have a view controller with a few UITextFields on it. When a UITextField has focus, if I tap on the Return key on the keyboard, I go to the next UITextField. If the next UITextField is below the keyboard, I move the view up.
All was fine until yesterday when I upgraded the app to Swift 4, after a few changes. Now it's no longer working. I loaded the Swift 3 version and it's working just fine. The problem is I don't see any difference and I can't figure it out.

class ServerWizardVC: UIViewController, UITextViewDelegate, UIDocumentMenuDelegate, UIDocumentPickerDelegate, FileManagerDelegate

@IBOutlet weak var tfServerURL: UITextField!
@IBOutlet weak var tfServerUser: UITextField!
@IBOutlet weak var tfServerPassword: UITextField!
@IBOutlet weak var tfServerPort: UITextField!

override func viewDidLoad()
{
    print("ServerWizardVC > viewDidLoad")

    super.viewDidLoad()

    tfServerURL.tag = 0

    registerForKeyboardNotifications()
    deregisterFromKeyboardNotifications()
}

override func viewWillAppear(_ animated: Bool)
{
    print("ServerWizardVC > viewWillAppear")

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

func registerForKeyboardNotifications()
{
    print("ServerWizardVC > registerForKeyboardNotifications")

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}

func deregisterFromKeyboardNotifications()
{
    print("ServerWizardVC > deregisterFromKeyboardNotifications")

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWillShow(notification:NSNotification)
{
    print("ServerWizardVC > keyboardWillShow")

    let userInfo:NSDictionary = notification.userInfo! as NSDictionary
    let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height

    keyboardHeightValue = keyboardHeight
}

@objc func keyboardWasShown(notification: NSNotification)
{
    print("ServerWizardVC > keyboardWasShown")
}

@objc func keyboardWillBeHidden (notification: NSNotification)
{
    print("ServerWizardVC > keyboardWillBeHidden")
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    print("ServerWizardVC > textFieldShouldReturn")

    if let nextField = tfServerURL.superview?.viewWithTag(textField.tag + 1) as? UITextField
    {
        nextField.becomeFirstResponder()

        checkTextFieldPosition(tfTag: textField.tag + 1)
    }
    else
    {
        vMainView.frame.origin.y = 0

        textField.resignFirstResponder()
    }

    return false
}

func checkTextFieldPosition(tfTag : Int)
{
    print("ServerWizardVC > checkTextFieldPosition")

    let keyboardTop = mainViewHeight - keyboardHeightValue
    let tfServerPasswordTop =  tfServerPassword.frame.origin.y

    if(tfTag == 3)
    {
        if((keyboardTop < tfServerPasswordTop) && (vMainView.frame.origin.y == 0))
        {
            let yPosition = vMainView.frame.origin.y - keyboardHeightValue + 100
            vMainView.frame.origin.y = yPosition
        }
    }
}

The reason I blame this on the Swift 4 upgrade is that I didn't even touch this class and everything else works fine.
Is there anything I'm missing?

A: textFieldShouldReturn is a UITextFieldDelegate function, but your class conforms to UITextViewDelegate instead. Replace the conformance with UITextFieldDelegate:
class ServerWizardVC: UIViewController, UITextFieldDelegate, UIDocumentMenuDelegate, UIDocumentPickerDelegate, FileManagerDelegate


text:
Q: Check if user liked a page in facebook works only on me? I have a strange problem, I'm trying to see if user liked a page, but it only works on me ?
I do it this way. What could be the problem ?
 FB.api('/me/likes/' + page_id, function(api_response) {
            try {
                if ((api_response.data[0].name) != undefined){
               }else{
              }
            }
            catch (e) {
            }
        });

And this way.
  var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid=me()";
 FB.api(
        {
            method: 'fql.query',
            query: fql_query
        },
        function(rows) {
              if (rows.length == 1) {

              } else {

      }
          });

It works when I am in my account , but when I logg into someone else`s It doesn't ? This is from application in my account and sandbox mode is OFF so I think it should work, but it doesn't .

A: Check the permissions on the facebook page (page_id).  Is the other user you're trying to use able to pull page stats?  Most likely the user does not have manage page permissions.

A: Did this other account explicitly grant Like permissions for your app?
If not, then this is by design. Unless the other user account has granted permission for your app to request likes, your app won't be able to query the user.


text:
Q: How to add markers and store them in a model attribute using Google Maps api and Play framework I'm currently trying to develop a web app with Play and thereby I would like to integrate Google Maps which works quite well so far.
In this app, the user should be able to add a marker by entering an address. This address has to be coded to get the LatLng values and the marker should be display on map as long as the user doesn't delete it.
My code looks like this:
As you can see, I added one example marker at the beginning. Adding a new one works very well. But when I refresh the whole page, Google Maps is reloading again and only displays the example marker but none of the new ones.
My questions:
1) Is it possible to let Google Maps remeber the new markers when they are available?
2) Is there any possibility to store the LatLng values in a Play model as an String attribute? This could help me to reload all positions from the DB while reloading the Map and redisplay all the markers. But it seems to be impossible to run the codeAdress() function inside a play statement like this: @{Place.store(codeAddress())}. This doesn't work.
Main.html (template for every html page)

....

Maps.js:
function initialize() {

    var latlngCenter = new google.maps.LatLng(12.345, 12.345);
    var latlngExample = new google.maps.LatLng(12.345, 12.345);

    var mapOptions = {
        center : latlngCenter,
        zoom : 12,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    var contentString = 'text';

    var infowindow = new google.maps.InfoWindow({
        content : contentString
    });

    var pinColor = "72EC0E";
    var pinImage = new google.maps.MarkerImage(
            "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"
                    + pinColor, new google.maps.Size(21, 34),
            new google.maps.Point(0, 0), new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage(
            "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
            new google.maps.Size(40, 37), new google.maps.Point(0, 0),
            new google.maps.Point(12, 35));

    var markerExample = new google.maps.Marker({
        position : latlngExample,
        map : map,
        icon : pinImage,
        shadow : pinShadow,
        title : 'Title'
    });

    google.maps.event.addListener(markerExample, 'click', function() {
        infowindow.open(map, markerExample);
    });

    geocoder = new google.maps.Geocoder();

}

function codeAddress(query) {
    var address = query;
    geocoder.geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map : map,
                position : results[0].geometry.location
            });
            alert("Alert1");
        } else {
            alert("No result");
        }
    });
    return results[0].geometry.location;
}

index.html (extending from main)
#{field 'parking.street'} street <input
            type="text" class="form-control" name="${field.name}" id="address"
            maxlength="50" placeholder="street"> #{/field}
        <button type="button" class="btn btn-success" onclick="codeAddress()">add</button>

A: *

*You can keep all of the markers a user adds inside of a javascript array. This would allow you to keep track of all the markers the user adds for the current page load.  Because you keep track of the markers you could do things like remove the markers from the map, if you wanted.

*I am not familiar with java or play, but if java/play is rendering your template, calling a javascript function codeAddress will not work.  perhaps the easiest way to persist a user added marker would create a controller method something like /marker/add and make an ajax request to that method everytime a user adds a marker.


text:
Q: Separating TypeScript and JavaScript files I cloned project from tour of heroes tutorial https://angular.io/docs/ts/latest/guide/setup.html.
And I want to separate .js files to another directory, because now I have .ts, .js and .js.map files all together in one directory.
I tried solve it following the answer from: Separate Angular2 TypeScript files and JavaScript files into different folders, maybe 'dist' but after changes in systemjs.config.js and tsconfig.json I get an error:
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost/:18 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/app/app.module
    Error: XHR error (404 Not Found) loading http://localhost:3000/app/app.module
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3000/app/app.module as "./app/app.module" from http://localhost:3000/main.js
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3000/app/app.module as "./app/app.module" from http://localhost:3000/main.js

A: Add
   "files.exclude": {
    "**/*.js.map": true,
    "**/*.js": {
        "when": "$(basename).ts"
    }
},

to your user settings


text:
Q: Convert Age variable into ordinal variable I'm new to R here.
How can I convert numeric variables into ordinal variables? For example, let's say I want to recode age into four categories (<65, 66-75, 75-85, 85+):
Age
55
60
65
70
75
80
85
90
95

becomes
Age
Young-Old
Young-Old
Med-Old
Med-Old
Med-Old
Old
Old
Old-Old
Old-Old

A: You could easily do so with dplyr's case_when:
library(dplyr)
age <- c(55, 60, 65, 70, 75, 80, 85, 90, 95)

age2 <- case_when(age <= 65 ~ 'Young-Old',
                  between(age, 66, 75) ~ 'Med-Old',
                  between(age, 76, 85) ~ 'Old',
                  age >= 86 ~ 'Old-Old'
                  )
age2 <- as.factor(age2)

A: You can do this using cut command.
age <- c(55, 60, 65, 70, 75, 80, 85, 90, 95)
breaks <- c(0,65,75,85,Inf)
age_transformed <- cut(age,breaks = breaks)

levels(age_transformed)
levels(age_transformed)[1] = "Young-Old"
levels(age_transformed)[2] = "Med-Old"
levels(age_transformed)[3] = "Old"
levels(age_transformed)[4] = "Old-Old"


text:
Q: Reverse proxy in aws to s3 I am trying to migrate a Scala play website to GatsbyJS and uploading the build to s3.
My website is multilingual, so the generate gatsby routes are like
de-DE/lp/press
nl-NL/lp/press
fr-NL/lp/press

The current website can be like
example.de
example.nl
fr.example.nl

Is there some easy way in aws to take a url like fr.example.nl/lp/press and serve from s3 with the url fr-NL/lp/press

A: With S3 you cannot but maybe with Cloudfront yes. Create a S3 Bucket with all website and a cloufront (one for each language).
Example: cloudfront of fr.example.nl pointing to the subfolder (/fr-NL) of the S3 Bucket. Gatsby isn't distribute languages in subdomain, therefore you will have to manually create the link between the languages (language switcher, etc).
There's a plugin in order to make gatsby multilingual, but that plugin does subfolder for each language instead of subdomains.


text:
Q: kinit errors - authentication to AD 2008 I am trying to have my application authenticate using AD credentials. I am using kinit to test after creating the krb5.ini file. I believe all the realm information is correct in the ini file but continue to receive the below error when testing with kinit.
Exception: krb_error 0 Cannot find any provider supporting ARCFOUR No error
KrbException: Cannot find any provider supporting ARCFOUR
    at
 sun.security.krb5.internal.crypto.ArcFourHmacEType.encrypt(ArcFourHm
 cEType.java:68)
    at
  sun.security.krb5.internal.crypto.ArcFourHmacEType.encrypt(ArcFourHm
    cEType.java:60)
    at sun.security.krb5.EncryptedData.<init>(EncryptedData.java:122)
    at sun.security.krb5.KrbAsReq.init(KrbAsReq.java:355)
    at sun.security.krb5.KrbAsReq.<init>(KrbAsReq.java:180)
    at sun.security.krb5.internal.tools.Kinit.<init>(Kinit.java:253)
    at sun.security.krb5.internal.tools.Kinit.main(Kinit.java:107)
 Caused by: java.security.NoSuchAlgorithmException: Cannot find any provider
 suporting ARCFOUR
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at
  sun.security.krb5.internal.crypto.dk.ArcFourCrypto.encrypt(ArcFourCrpto.java:279)

A: You need to enable RC4-HMAC in both your krb5.ini config and the conf/security/java.security
I think RC4 got blacklisted in Oracle JDK (>= 1.8.u060) for known insecurities together with MD5, but it is strictly required for key exchange by the MS Active Directory Kerberos implementation.
Maybe you have to re-enable it by removing RC4 from jdk.tls.disabledAlgorithms and jdk.certpath.disabledAlgorithms of your JDKs conf/security/java.security.
See https://www.java.com/en/configure_crypto.html for more information.


text:
Q: Digital multimeter - How does the wrong probe insert (input) alarm work? I'm using a digital multimeter (UT61E) and it doesn't have the "Wrong Probe Insert" alarm feature.
I mean when I select the Voltage Measurement with the knob but leave the probes in the Current Terminal, it will sound an alarm and vice versa.
I made this mistake all the time, so I want to build a circuit to do this and mod it on my multimeter.
I've been googling for a while but can't find out how this circuit is made. Maybe a simple idea or some explanation of the principle would help me a lot.
I really don't understand how the meter knows if the probe is inserted or not?

A: The meter's microprocessor knows what position the knob is in. It can also know what terminal the probe is in by a switch at the bottom of the hole.

A: They detect whether a testlead is plugged in and when that state does not match the selected range a signal is buzzed and displayed.
The implementation of the detection is dependent on the manufacturer. These two methods are very common:

*

*electrical - splitting the input jack contact and detecting a current across both halves caused by the plug shorting them together

*optical - shining light through the input and detecting the interruption of the light beam caused by the plug
Electrical (split input jack)
With the split input jack they can send a signal to one of the jack halves. When the testlead is plugged in, the signal is shorted over to the other halve and can be detected by the microprocessor.
See EEVblog episode #99 at 20:55 (direct download and other infos here)
Dave shows the input jacks of a Extech multimeter and explains why they do what you ask for.
This is the board viewed from the top:

(Source: EEVblog episode #99)
This is the board viewed from the bottom:

(Source: EEVblog episode #99)
Here's another example of a Keysight multimeter:

The mechanical construction is quite different but the jack is split too. Dave shows this a second later.
Source: EEVblog episode #832 at 17:10 (direct download and other infos here)
Optical
This type of input alert uses a (infrared) LED sending a lightbeam through a transparent input jack. When the plug enters the jack, the lightbeam gets interrupted.
In case of the Fluke multimeter this type of input alert is used to ensure the waterproofing.
See EEVblog episode #64 at 9:30 (direct download and other infos here)
Dave shows the board and input jacks of a Fluke 28 II multimeter.
This shows the LED and photodiodes on the board:

(Source: EEVblog episode #64 info page)
This shows the transparent jacks of the case:

(Source: EEVblog episode #64 video)

so I want to build a circuit to do this and mod it on my multimeter.

I don't think that you should do that.

*

*Input protection on a multimeter is not trivial (Dave's videos on multimeter tear downs explain much about that). With bodging some input alert into the multimeter you risk to disturb necessary spacing and clearance.

*If the processor does not have a firmware that supports input alert adding such a modification is not done with just some wire. Not to speak about splitting the input jack.
Note: there might be other ways of input jack signalling like buttons or light barriers, but I don't think they're as reliable as real junctions.


text:
Q: Python 2.7 simple password While if with break/"loop", doesn't get to the "False" part Trying myself now at a little more simple stuff as a bloody python newbie:
Read into it here and there but still quite don't get it.
This code works, but if entering a wrong password, it doesn't print out that the password is wrong. It just asks again to enter the right password, which is fine. But without printing that it's the wrong password.
I like small, readable and simple code so I did it this way, but can you tell me where is my mistake?
Edit: I tried searching this in stackexchange and various google sites too. Although it's one of the most simple things, I always got examples that where way different and where I had a hard time understanding it. Now I got it. (First 2 answers)
while True:
    password = raw_input('Enter Password: ')
    if password == 'secret':
        print 'Password correct!'
        break
    if password == False:
        print 'Password incorrect!'

According to how I understood it: The code doesn't even get to run to the point of "if password == False:" and only does a "break" until the 'secret' has been entered.
Could it be that I have to move the part
if password == False:
    print 'Password incorrect!'

somewhere else to it to work?
Thanks a lot for every kind help!

A: I think you are looking for something like:
while True:
    password = raw_input('Enter Password: ')
    if password == 'secret':
        print 'Password correct!'
        break
    else:
        print 'Password incorrect!'

This will run true until the password is correct and then break out of the loop.
What you where trying to do is to check to if it was equal to 'secret' and then doing a separate check to see if the value is a boolean(false)
What the section above does is checks the password against 'secret' and if the user input is not equal to 'secret' this will return 'password incorrect'

A: Just another way to do it.
while True:
    password = raw_input('Enter Password: ')
    if password == 'secret':
        print 'Password correct!'
        break
    print 'Password incorrect!'

When your password is correct the while loop will break. Otherwise the error message will be shown.

A: to test if password does not equal 'secret', add an else block.
while True:
    password = raw_input('Enter Password: ')
    if password=='secret':
        print 'Password Correct!'
        break
    else: #in other words, if password != secret
        print 'Password incorrect!'


text:
Q: Is it returning an empty variable? I'm currently working on a HangmanProject in high school. "newWord" is the variable that contains the word chosen in the dictionary file at random. in the makeList method you can see it pull the word randomly. And there is a System.out.println("this: " + newWord); so I can test to see if the word is successfully pulled from the external file. It then returns the newWord, but when back into the main method, it is empty, and therefore empty throughout the rest of the program. Can someone please assist my issue?
public class HangmanProject {
    public static void main(String args[]) {
        String newWord = " ";
        int letterNumber = 0;

        makeList(newWord);

        countLetters(newWord, letterNumber);
        System.out.println("this: " + newWord);
        displayBoard(letterNumber, newWord);
    }

    public static String makeList(String newWord) {
        do{
            try(Scanner s = new Scanner(new File("dictionary.txt"))) {
            ArrayList<String> list = new ArrayList<String>();
                while (s.hasNext()) {
                    list.add(s.next());
                }

            Random random = new Random();
            int index = random.nextInt(list.size());
            newWord = list.get(index);
            } catch (IOException e) {
                System.out.println("Error Found");
            }
        } while (!(newWord.length() >= 5));
        System.out.println("this: " + newWord);
        return newWord;
    }

A: You don't do anything with the value you return. Just assign it somewhere and you should be OK. Moreover, since makeList doesn't use its value, just declare it as a local variable:
String newWord = makeList();


text:
Q: How to get required function to work by comparing numbers? I have written a code in assembler emulator emu8086 of comparing x + c with 0 and I need my functions to work by result of comparison.
f1, when x + c < 0
f2, when x + c = 0
f3, when x + c > 0

    MOV ax, x[si]
    MOV bl, c
    CBW
    ADD ax, bx
    CBW
    CMP ax, 0
    JE f2;
    JL f1;
    JG f3 ;

I am expecting to get f2 function work when ax(x + c) is equal to zero, f1 to work when ax(x+c) is less than zero and f3 when ax(x+c) is greater than zero, but somehow it only does f2 and f3 correctly, I get f2 done instead of f1, I can not understand what is wrong.
Even when I am writing
    JE f1;
    JL f1;
    JG f1 ;

it still doesn't do f1, does f2 instead of f1, but if I delete f3 out of my code, then f1 get's done.
functions look like:
f1: MOV ax, 2
    IMUL a
    JO kl1  ;
    MOV bx, x[si]
    CMP bx, 0
    JG mod
    NEG bx
mod:    ADD ax, bx
MOV dx, ax
    JO kl1

f2: MOV ax, 6
    ADD ax, 3
    JO kl1
    JMP re
f3: MOV ax, 4

    JO kl1
    JMP re

A: CBW extends AL into AX. You want to extend BL into BX.
I suggest you load c into AL, use CBW, and then add x.


text:
Q: MySQL unexpected syntax error during JDBC execution I'm executing a script through a Java web service I wrote to execute on a MySQL database.
When executing the query in phpMyAdmin it completes successfully, however as soon as it is executed by my web service it returns:

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @OBJECTIVE_1_DESCRIPTION := OBJECTIVE_DESCRIPTION, @OBJECTIVE_1_LVL := OB' at line 1

The following query is executed as a prepared statement read from a .sql file:
(This is only a snippet of the relevant code, I have added new lines to improve readability, in the actual file the query there are only new lines after each ";")
SET @USER_ID = ?,
@EMAIL = ?,
@NAME = ?,
@SURNAME = ?,
@SUBURB = ?,
@CITY = ?,
@PASSWORD = ?,
@RELIABLE_OCR_RESULTS = 0,
@HOUSEHOLD_SIZE = 0,
@DATE = NOW(),
@OBJECTIVE_1_ID = '4E2DEA7B-037A-4958-8696-2B73EDD3E08E',
@NEW_OBJECTIVE_1_ID = 'E46027A1-CE36-4413-9E64-7A217FFB9CEB',
@OBJECTIVE_1_DESCRIPTION = REPLACE(@OBJECTIVE_1_DESCRIPTION, '*', @OBJECTIVE_1_TARGET),
@OBJECTIVE_1_PROGRESS  = 0.0,
@OBJECTIVE_1_COMPLETED  = 0,
@COMPLETED_OBJECTIVES = NULL,
@NEW_OBJECTIVE_1_DESCRIPTION = REPLACE(@NEW_OBJECTIVE_1_DESCRIPTION, '*', @NEW_OBJECTIVE_1_TARGET),
@NUM_COMPLETED_OBJECTIVES = 0;

SELECT @OBJECTIVE_1_DESCRIPTION := OBJECTIVE_DESCRIPTION, @OBJECTIVE_1_LVL := OBJECTIVE_LEVEL, @OBJECTIVE_1_TARGET := OBJECTIVE_COMPETION_COUNT, @REWARD_1_CODE := OBJECTIVE_REWARD , @OBJECTIVE_1_REWARD := REWARD_VALUE, @OBJECTIVE_1_REWARD_TYPE := REWARD_TYPE
FROM Objectives
JOIN Objective_Reward_Codes
ON REWARD_ID = OBJECTIVE_REWARD
WHERE OBJECTIVE_ID = @OBJECTIVE_1_ID;

SELECT @NEW_OBJECTIVE_1_DESCRIPTION := Objectives.OBJECTIVE_DESCRIPTION, @NEW_OBJECTIVE_1_LVL := Objectives.OBJECTIVE_LEVEL, @NEW_OBJECTIVE_1_TARGET := Objectives.OBJECTIVE_COMPETION_COUNT, @NEW_REWARD_1_CODE := Objectives.OBJECTIVE_REWARD , @NEW_OBJECTIVE_1_REWARD := Objective_Reward_Codes.REWARD_VALUE, @NEW_OBJECTIVE_1_REWARD_TYPE := Objective_Reward_Codes.REWARD_TYPE
FROM Objectives
JOIN Objective_Reward_Codes
ON Objective_Reward_Codes.REWARD_ID = Objectives.OBJECTIVE_REWARD
WHERE OBJECTIVE_ID = @NEW_OBJECTIVE_1_ID;
DELIMITER ;

Is it possible that it is caused by the version of Tomcat or the encoding of the query sent by the JDBC?


text:
Q: BASH ignore e-mail addresses that have been sent e-mail in past 24 hours I have a BASH script like the below:
cat limit_mail.out | while read num email limit orders; do
    echo "Sending mail to '$email'"
    printf "$email_template" "$email" "$num" "$limit" "$orders" |
    sendmail -oi -t
done

How can I make it so that when an e-mail is sent the e-mail address is saved with date and time in a text file, and then a check so that no e-mail address receives more than 1 e-mail within 24 hours?

A: One approach would be to create a file per recipient, and use the file's timestamp.
MAIL_TIMESTAMPS=/var/cache/mailstamps
mkdir "$MAIL_TIMESTAMPS"

cat limit_mail.out | while read num email limit orders; do
    echo "Sending mail to '$email'"
    email_hash="$(md5sum <<< "$email" | cut -d' ' -f1)";
    # Check that a timestamp file doesn't exist, or that it was modified over 24h ago
    if ! test -n "$(find "$MAIL_TIMESTAMPS" -mtime -1 -name "$email_hash")"; then
      touch "$MAIL_TIMESTAMPS/$email_hash" # Update timestamp
      printf "$email_template" "$email" "$num" "$limit" "$orders" |
      sendmail -oi -t
    fi
done

Edit: I've added hashing of the email address. It was something I was planning to do anyway, but Aleks-Daniel's code for that is so nice and concise that I've borrowed it here, changing only from sha256sum to md5sum. MD5 is faster, and though it has potential issues I don't think they will be a problem here (of course you're free to choose). Hashing also avoids the issue of special characters upsetting find's filename matching.

A: Using timestamps in a file:
DELAY_FOLDER='myTempFolder/'
DELAY=$((24*60*60)) # one day

while read num email limit orders; do
    echo "Sending mail to '$email'"
    if [[ -f $DELAY_FOLDER/$email ]] && (( $(cat "$DELAY_FOLDER/$email") + DELAY > $(date +%s) )); then
        echo "email has been sent already"
    else
        printf "$email_template" "$email" "$num" "$limit" "$orders" | sendmail -oi -t
        echo "$(date +%s)" > "$DELAY_FOLDER/$email"
    fi
done < limit_mail.out

Also, if you don't want anybody to see email addresses in a temp folder, you can use md5 or sha sums to cover your addresses. Like this:
DELAY_FOLDER='myTempFolder/'
DELAY=$((24*60*60)) # one day

while read num email limit orders; do
    echo "Sending mail to '$email'"
    emailsha=$(sha256sum <<< "$email" | cut -d' ' -f1)
    if [[ -f $DELAY_FOLDER/$emailsha ]] && (( $(cat "$DELAY_FOLDER/$emailsha") + DELAY > $(date +%s) )); then
        echo "email has been sent already"
    else
        printf "$email_template" "$email" "$num" "$limit" "$orders" | sendmail -oi -t
        echo "$(date +%s)" > "$DELAY_FOLDER/$emailsha"
    fi
done < limit_mail.out


text:
Q: good metrics for array of strings distance I have to arrays, S & T, containig words (lowercased, trimmed, without diacritics). Number of words can be different. (most of the data is a kind of proper names, rather short (<5))
I need to find a good metrics (and its implementation, or maybe even research paper) which allows to calculate level of the  similiarity of those arrays
Some ideas I have so far:

*

*scoring all words which are presents in both arrays

*scoring all words which are presents in the same place in both arrays

*scoring longest common sequences

*all above + taking into account relative position of index (more important at the beginning)

*some type of levensthein (insert / delete count) using words instead of characters

any other ideas?

A: For me, it looks like modeling documents using bag-of-words models
http://en.wikipedia.org/wiki/Bag-of-words_model
Depending on your application, you can use different criteria for comparing two bag-of-words feature vectors like what you said in your application. In addition, there are models based on learning statically relationship between different words/sentences, such as topic models http://en.wikipedia.org/wiki/Topic_model

A: If the arrays are rather short then you can find the optimal pairing of the words given some rubric of word similarity. Then have some scoring layered on top for how far the string has to be rotated/contorted for the optimal pairings to be paired. This could be some kind of multiplier or maybe some other system.
One metric of word similarity which we recently learning about in Natural Language Processing is Levenshtein Distance. There's other more complex variants such as the Smith-Waterman algorithm (its linked on the wiki page). These algorithms are meant to measure orthographic similarity, so they are used in morphological analysis to give an idea of how similar words are based on appearance. The Smith-Waterman algorithm says that if one word is contained within the other word then they're are extremely similar no matter how long the suffix/prefix is.

A: If the strings are Western names, Soundex might be a starting point.


text:
Q: When using the abbreviation etc., should it be parenthetical, i.e. enclosed between commas? I was re-reading The Elements of Style when I noticed a remark I had previously overlooked in the third rule of usage (Enclose parenthetic expressions between commas.).

The abbreviations etc., i.e., and e.g., the abbreviations for academic degrees, and titles that follow a name are parenthetic and should be punctuated accordingly.
Eg: Letters, packages, etc., should go here.

I understand why the other abbreviations are parenthetical, but am not convinced whether etc. should be parenthetic.

A: Etc. is parenthetical by definition: it provides incidental or supplementary information, not definitional.  It means and other things, and if you wrote it out, you'd enclose the phrase in commas, wouldn't you? Whether it should be enclosed by commas in running text is a matter of style, and you should be guided by your manual of style, either the one you've chosen or one thrust upon you. You've apparently chosen Strunk and White. If it helps, the Chicago Manual of Style agrees with S&W, although it says the usage should be discouraged.


text:
Q: How do i change Rails routing from controller/:id to controller/:name in Rails 3? Just as the topic say. I want to change the default controller/:id routing to controller/:name instead in Rails 3. In Rails 2 you used named routing with something like this:
config/routes.rb
map.location 'location/:name',
  :controller => 'your_controller', :action => 'your_action'

alternate named route
map.location 'goto/:name', :controller => 'location', :action => 'your_action'

examples of URL specification in a view
<%= link_to 'foo', location_url({:name => 'foo'}) %>
<%= link_to 'bar', location_path({:name => 'bar'}) %>

But i'm sure there is another (better) way in Rails 3.

A: If the :name is a unique identifier of the object, you can you https://github.com/norman/friendly_id for general permalink support for ActiveRecord.
Just by specified
has_friendly_id :name
you'll get automatically routing like
http://example.com/states/washington
instead of
http://example.com/states/4323454

A: Not sure but may this would help you.
match 'user_delete/:name', :to => 'sessions#destroy'
this is same as
map.user_delete '/user_delete/:name', :controller => 'sessions', :action => 'destroy'

A: Try this:
match 'location/:name' => 'your_controller#your_action', :as => location

A: If you have location.name, then you could link_to it like this:
<%= link_to 'foo', location_path(location.name) %>

will give you the url /locations/:name
as opposed to
<%= link_to 'foo', location %> #same as <%= link_to 'foo', location_path(location) %>

which will give you /locations/:id


text:
Q: Группировка связи многие ко многим в форме Django подскажите как в шаблоне Django вывести форму такого вида:

models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
from .util import image_file_name

class SpecializationGroup(models.Model):
    name = models.CharField(max_length=250, verbose_name=_('Название'))

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _('Группа специализации')
        verbose_name_plural = _('Группы специализаций')

class Specialization(models.Model):
    name = models.CharField(max_length=250, verbose_name=_('Название'))
    group = models.ForeignKey(SpecializationGroup, verbose_name=_('Группа'))

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _('Специализация')
        verbose_name_plural = _('Специализации')

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,  verbose_name=_('Пользователь'))
    birthDate = models.DateField(null=True, blank=True, verbose_name=_('Дата рождения'))
    image = models.ImageField(upload_to=image_file_name, null=True, blank=True, verbose_name=_('Изображение профиля'))
    phone = models.CharField(max_length=20, null=True, blank=True, verbose_name=_('Номер телефона'))
    url = models.URLField(max_length=250, null=True, blank=True, verbose_name=_('Веб сайт'))
    town = models.ForeignKey(Towns, null=True, blank=True, verbose_name=_('Город'))
    status = models.ForeignKey(Statuses, default=1, verbose_name=_('Статус'))
    summary = models.TextField(null=True, blank=True, verbose_name=_('Резюме'))
    skype = models.CharField(max_length=100, null=True, blank=True, verbose_name='Skype')
    specializations = models.ManyToManyField(Specialization, blank=True, verbose_name='Специализации')

    def __str__(self):
        return self.user.username

    class Meta:
        verbose_name = _('Профиль пользователя')
        verbose_name_plural = _('Профили пользователей')

forms.py
from django import forms
from django.contrib.auth.models import User
from .models import *

class SpecializationForm(forms.ModelForm):
    specializations = forms.ModelMultipleChoiceField(queryset=Specialization.objects.all(), widget=forms.CheckboxSelectMultiple())

    class Meta:
        model = UserProfile
        fields = ('specializations',)

A: Для начала, необходимо отсортировать специализации в форме по группам:
specializations = forms.ModelMultipleChoiceField(queryset=Specialization.objects.all().order_by('group'), widget=forms.CheckboxSelectMultiple())

Следующим шагом, вы можете в шаблоне пройти циклом по объектам из queryset.
Пример шаблона:
{% for choice in form.mychoices.field.queryset %}
    {% ifchanged choice.group %}
        <label>{{ choice.group.name }}</label>
    {% endifchanged %}
    <label>
        <input type="checkbox" name="specializations" value="{{ choice.id }}">
        {{ choice.name }}
    </label>
{% endfor %}

Либо, вы можете сделать на подобии следующего:
{% for choice in form.mychoices.field.choices %}
    {{ choice.0 }}
{% endfor %}

Похожая задача


text:
Q: Shopify GraphQL Admin API rate limiting cost and sleep time I am trying to consume Shopify GraphQL API for Admin in PHP ( Laravel ).
Rate limiting and throttling works differently in GraphQL api as compared to REST api, its calculated based on the cost of the query.

Few points to keep in mind:

*

*Maximum available cost is 1000 for one api call (query).

*If you have consumed some points from 1000, every second, 50 points will be restored.

*If you have less points of cost in your bucket, and you make a query of cost higher than that, it will throttle.

The query that I am passing to api has an estimated cost of 502, represented by requestedQueryCost. Whereas, actualQueryCost represents the actual response returned by the api for a specific shop.

In above snapshot, its the worst case scenario, requestedQueryCost is equal to acutalQueryCost for a store with heavy number of orders.

Now, when this query is executed I have consumed 502 points, 498 left, 1 second elapsed, 50 points added = 548 , and I can make a second api call to fetch second page of data. After second api call I will have less points left, so I will have to put sleep for 1 or 2 seconds to gain the points to make api call.

In the case shown in snapshot, i had to put 10 seconds sleep wait in order to restore 500 points to make next api call.
Problem: How to best decide sleep (wait) time for different shops? We don't want all shops to wait for 10 seconds even if they have less query cost.
Note: For code reference, see my answer below.

A: You get a clean slate of cost calls per shop. If one shop is at zero, you may still have 1000 waiting for you on another shop. You should ensure your calling mechanism is clear on that! Only sleep a thread per shop. You should be able to assign a request to a thread, so that if it sleeps you are still operating with other threads. I would be laughing my ass off if PHP operated with one thread assigned to all requests. That would be so 1982 computing!

A: Below is my rough draft of a solution, still looking for expert opinion on how to effectively handle it so that each Shop has to wait for the time they deserve, according to the amount of data. Please advise.
public function getRequiredOrders()
{
    $firstRequestTimeStamp = now();
    $ordersGraph = $this->shop->api()->graph($this->firstQuery())->body->orders;
    $this->transform($ordersGraph); //transforming to required format

    $previousRequestTimeStamp = $firstRequestTimeStamp;

    while($ordersGraph->pageInfo->hasNextPage) {

        $nextRequestTimeStamp = now();
        $timeElapsed = $nextRequestTimeStamp->diffInSeconds($previousRequestTimeStamp);
        $restoredPoints = $timeElapsed * 50; //50 points are restored every 1 second
        $pointsLeft = $this->shop->api()->getApiCalls('graph', 'left');
        $totalPointsLeft = $pointsLeft + $restoredPoints;

        if($totalPointsLeft >=502){ //one must know the maximum cost of their query
            $lastEdgeCursor = end($ordersGraph->edges)->cursor;
            $nextQuery = $this->nextQuery($lastEdgeCursor);
            $previousRequestTimeStamp = $nextRequestTimeStamp;
            $ordersGraph = $this->shop->api()->graph($nextQuery)->body->orders;
            $this->transform($ordersGraph);
        }else{
            sleep(1);
            continue;
        }

    }
    return $this->allOrders;
}


text:
Q: NullPointerException when trying to execute SQL I'm getting a NullPointerException when trying to run some SQL against the database.
I have a class called CustomApp, which extends Application. This class creates a data helper class, which controls the creation and opening of a database. The instance of this data helper class is called data - the database inside this class is called db.
I then have my own class where I store static database functions for easy access - allowing me to perform the standard database stuff with only a single line of code. This is a class called Db, with a nested static class inside called Functions. Therefore, if I want to for example, insert a contact, I just call the Db.Functions.insertContact() function. The problem I'm having is on a function called 'setupDb()` that just runs table creation strings if the tables don't already exist.
My CustomApp class:
public class CustomApp extends Application
{

public static CustomDataHelper data;

public static CustomApp app;

@Override
public void onCreate()
{
    super.onCreate();

    app = this;
    data = new CustomDataHelper();
}
}

My CustomDataHelper class:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CustomDataHelper {

private static final int DATABASE_VERSION = 1;
public SQLiteDatabase db = null;

public CustomDataHelper()
{
    SQLiteOpenHelper o = new MyOpenHelper(CustomApp.app, "MyData.db");
    this.db = o.getWritableDatabase();
}
// Rest of standard DataHelper class

private class MyOpenHelper extends SQLiteOpenHelper
{
    MyOpenHelper(Context context,String DatabaseName)
    {
        super(context, DatabaseName, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
          // Standard data code here
    }

}
}

Relevant code from Db class:
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Db
{
public static Contact contact = null;

static final String TAG = "DbFunctions";
public static class Functions
{
    static final String TABLE_CONTACTS = "Contact";
    static final String CONTACTS_ID = "id";
    static final String CONTACTS_FNAME = "firstName";
    static final String CONTACTS_LNAME = "lastName";
    static final String CONTACTS_MOBNUM = "mobileNumber";
    static final String CONTACTS_SQL = "create table if not exists " + TABLE_CONTACTS +
            "(" + CONTACTS_ID + " text not null, " + CONTACTS_FNAME + " text null, " + CONTACTS_LNAME + " text null, " +
            CONTACTS_MOBNUM + " text null)";

    static final String ALL_SQL = CONTACTS_SQL;

    public static boolean setupDb()
    {
        try
        {
            CustomApp.data.db.execSQL(ALL_SQL);
            return true;
        }
        catch (Exception ex)
        {
            Log.e(TAG, ex.getMessage());
            return false;
        }
    }
}
}

When I call the line of code: Db.Functions.setupDb();, I get the NullPointerException.
My logcat:
07-09 16:24:26.596: E/AndroidRuntime(18660): FATAL EXCEPTION: main
07-09 16:24:26.596: E/AndroidRuntime(18660): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testproj/com.example.testproj.MainActivity}: java.lang.NullPointerException: println needs a message
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.os.Looper.loop(Looper.java:137)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.ActivityThread.main(ActivityThread.java:4921)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at java.lang.reflect.Method.invokeNative(Native Method)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at java.lang.reflect.Method.invoke(Method.java:511)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at dalvik.system.NativeStart.main(Native Method)
07-09 16:24:26.596: E/AndroidRuntime(18660): Caused by: java.lang.NullPointerException: println needs a message
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.util.Log.println_native(Native Method)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.util.Log.e(Log.java:297)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at com.example.testproj.Db$Functions.setupDb(Db.java:55)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at com.example.testproj.MainActivity.onCreate(MainActivity.java:16)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.Activity.performCreate(Activity.java:5206)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
07-09 16:24:26.596: E/AndroidRuntime(18660):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
07-09 16:24:26.596: E/AndroidRuntime(18660):    ... 11 more

So I used breakpoints to track down which line of code was causing the problem, and its CustomApp.data.db.execSQL(ALL_SQL);. Now I found that this is because the data object is actually null - but why is this? When CustomApp is created, it should automatically have instantiated the datahelper object 'data' - which, in turn, should have automatically instantiated the database object. So that leaves me pretty stumped. Any help is greatly appreciated.

A: In method setupDb() you are calling Log.e(TAG, ex.getMessage()); - but in this case ex.getMessage() returns null.  I don't know what your exception is, so can't comment on why, but one way to see what's going on is to do
Log.e(TAG, ex.toString());

A: I found out what the problem is. The reference to my CustomApp class had been somehow removed from my manifest by Eclipse (even though I definitely added it in). I'll keep an eye out to make sure this doesn't happen again.


text:
Q: How to debug Go program taking 100% CPU randomly I have a Go application which randomly starts using 100% CPU after its running for 2-3 days. The CPU usage stays 100% unless the application is killed. I haven't been able to figure out which goroutine is causing the issue. I installed pprof there which works as expected when application is running normally but when CPU goes to 100% even pprof stops responding.
I was able to get the following stacktrace logs by running kill -3 1
https://gist.github.com/lokesh-wise/1804b3dc4fe2df2d31f97fae70e1d6f8
(There are 2 log files, one for application running in bad state (100% CPU) and other for application running in good state.)
Any idea which goroutine is the culprit or how can I find what's causing 100% CPU?