text:
Q: Why does Vim ignore files in ~/.vim/after/ftplugin? I seem to have a problem with my local Vim configuration but I'm not sure what it is. I need to override some filetype-specific settings. As per multiple tutorials/howtos, I created ~/.vim/after/ftplugin/cpp.vim with appropriate setlocal statements, but it seems not to be read. I checked that ~/.vim/after is in runtimepath.
I worked around this with autocmd FileType cpp setlocal ... in ~/.vimrc, but that is beyond the point. Any advice on how to diagnose/fix this? Or am I just overlooking something obvious?

A: Check the output of:
:filetype

You may need to add
filetype plugin on

to your .vimrc (or at least add 'plugin' to your 'filetype' setting).

A: A good place to start would be to use the :scriptnames command.  Open a C++ file however you normally do and execute
:scriptnames

This will show you the files that Vim has sourced since it was started.


text:
Q: Not start a new page with scanty number of words, lines This script
\documentclass{article}
\usepackage{lipsum}
\begin{document}
\lipsum[1-5]
\lipsum[6][1-2]
\end{document}

produces the output

How can I avoid starting page 2 with such a scanty number of words, lines?

A: You can use TeX's \looseness parameter. If you say \looseness=<number> for a paragraph, TeX will try to make it <number> lines longer than what would have been done otherwise, without exceeding the current \tolerance. <number> may be negative, so in your case, setting \looseness=-1 for one of the paragraphs does the trick:
\documentclass{article}
\usepackage{lipsum}
\begin{document}
\looseness=-1 % make the next paragraph one line shorter than usual
\lipsum[1-5]

\lipsum[6][1-2]
\end{document}

According to the TeXbook, \looseness is reset to zero at the same time as \hangindent, \hangafter, and \parshape are reset to their normal values, which is

at the end of every paragraph, and (by local definitions) whenever it
  enters internal vertical mode.

(TeXbook p. 103)
Therefore, the \looseness=-1 in the above example affects only the first of the five paragraphs produced by \lipsum[1-5]. There is no need to do this assignment in a group.
If I remember correctly, the TeXbook also mentions a trick to spread some looseness among several paragraphs. I could probably find it if you're interested.
As suggested in Skillmon's comment, another way would be to play with penalties, in particular with \widowpenalty (to avoid page breaking before the last line of a paragraph) and \linepenalty (to make TeX's line breaking algorithm more reluctant to add lines to a paragraph: this penalty defines the "base cost" of each line).

redpajama_set_name: RedPajamaStackExchange


text:
Q: FindViewById in view but after loading fragments I want to call findViewById in my ProfileActivity, which has three fragments, in one of these fragments, ProfileFragment, I put 4 empty TextView items so that I can change them according to the logged in user. I can't use getView().findViewById in the fragment because I need to call a large method which is found in the base class, which is extended by ProfileActivity so I can call it there. However, whenever I call findViewById in profileActivity in onCreate method, there is an error as the fragments are not yet created. Any suggestions where i should do this part?
public void setInfo(){

        //TextView name = (TextView)findViewById(R.id.profile_name);
        TextView name1 = (TextView)findViewById(R.id.profile_name1);
        TextView age = (TextView)findViewById(R.id.profile_age);
        TextView gender = (TextView)findViewById(R.id.profile_gender);
        TextView email = (TextView)findViewById(R.id.profile_email);

        User u = getCurrentUser();

        //name.setText(u.getUserName());
        name1.setText("test");
        age.setText("test");
        email.setText("test");
        gender.setText("test");
    }

This code is in ProfileActivity right now and the 4 TextViews are in the fragment.

A: You have to pass the values from ProfileActivity into you ProfileFragment when you instantiate it.
public static final ProfileFragment newInstance(String name, String age, String gender, String email)
{
    ProfileFragment f = new ProfileFragment();
    Bundle bdl = new Bundle();
    bdl.putInt(EXTRA_NAME, name);
    bdl.putInt(EXTRA_AGE, age);
    bdl.putInt(EXTRA_GENDER, gender);
    bdl.putInt(EXTRA_EMAIL, email);
    f.setArguments(bdl);
    return f;
}

@Override
public void onCreate(Bundle savedInstanceState)
{
    name = getArguments().getString(EXTRA_NAME);
    age = getArguments().getString(EXTRA_AGE);
    gender = getArguments().getString(EXTRA_GENDER);
    email = getArguments().getString(EXTRA_EMAIL);

    ...
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile, container, false);
    setUser(view);

    ...

    return view;
}

private void setUser(View view){

    TextView name1 = (TextView) view.findViewById(R.id.profile_name1);
    TextView age = (TextView) view.findViewById(R.id.profile_age);
    TextView gender = (TextView) view.findViewById(R.id.profile_gender);
    TextView email = (TextView) view.findViewById(R.id.profile_email);

    name1.setText(name);
    age.setText(age);
    email.setText(gender);
    gender.setText(email);
}

and then use it like:
public void setInfo(){
  User u = getCurrentUser();
  get[Support]FragmentManager().beginTransaction().replace(R.id.fragment_placehoder_id, ProfileFragment.newInstance(u.getName(), u.getAge(), u.getGender(), u.getEmail())).commit();
}

A: You Must Have Create a java file in for fragment and a layout for that fragment like this:
 public class InvestorProfileFragment{
  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View mRootView = inflater.inflate(R.layout.investor_profile_fragment, container, false);
    init(mRootView);
    return mRootView;
}

public void init(View view) {
    txvName = (TextView) view.findViewById(R.id.txv_name);

}
and do what you want...


text:
Q: Rendering a partial inside a block I'm new to rails. I have this block in my view afrikaans.html.erb
<% @afrikaans.each  do |course| %>

<%= link_to course.name, course.url  %>

    <% if I18n.locale == I18n.default_locale %>

<%= course.description_en %>

    <% else %>

<%= course.description_se %>

    <% end %>

    <% if course.youtube_url.blank? == false %>

<%= raw ApplicationHelper.youtube_embed(course.youtube_url) %>

    <% end %>
    <% if course.language_id == 1 %>

  <%=  image_tag("eng.png", :alt => "England", :class =>"round") %>

    <% else %>

  <%= image_tag("swe.png", :alt => "Sweden", :class =>"round") %>

    <% end %>

    <% if ApplicationHelper.active_link?(course.url) == false %>
      <%= I18n.t('home.broken_link') %>
    <% end %>

<%= course.nbr_of_votes %> <%= I18n.t('home.votes') %>

<% end %>

I also have another file swahili.html.erb with the same structure. I wanted to implement something like this
afrikaans.html.erb
<% @afrikaans.each do |course| %>
 <%= render 'shared/partial' %>
<% end %>

So that I can also have
swahili.html.erb
<% @swahili.each do |course| %>
 <%= render 'shared/partial' %>
<% end %>

The partial will contain the part of the block. I've tried this but it's not working. My question is this even possible in rails and if so what could be the problem. What options do I have if it isn't possible so that I can avoid the repetition since the two files have the same structure?
Update. This One worked out for me. I only needed to add :course => course on the block so that my views becomes something like
<% @afrikaans.each  do |course| %>
  <%= render 'shared/course_body', :course => course %>
<% end %>

Of course I've not named my partial "partial". This was just a matter of asking. Thanks to one @Alexander Panasyuk's answer.

A: Just create shared directory within your app/views path. And create file _partial.html.erb inside shared:

<%= link_to course.name, course.url  %>

    <% if I18n.locale == I18n.default_locale %>

<%= course.description_en %>

    <% else %>

<%= course.description_se %>

    <% end %>
    <% if course.youtube_url.blank? == false %>

<%= raw ApplicationHelper.youtube_embed(course.youtube_url) %>

    <% end %>
    <% if course.language_id == 1 %>

  <%=  image_tag("eng.png", :alt => "England", :class =>"round") %>

    <% else %>

  <%= image_tag("swe.png", :alt => "Sweden", :class =>"round") %>

    <% end %>
    <% if ApplicationHelper.active_link?(course.url) == false %>
      <%= I18n.t('home.broken_link') %>
    <% end %>

<%= course.nbr_of_votes %> <%= I18n.t('home.votes') %>

Then render your partial in afrikaans.html.erb like that:
<% @afrikaans.each do |course| %>
  <%= render 'shared/partial', :course => course %>
<% end %>

or in swahili.html.erb:
<% @swahili.each do |course| %>
  <%= render 'shared/partial', :course => course %>
<% end %>

A: It is most definitely possible, and usually a good idea.
In the future it would be nice if you could post the actual results and/or error messages you get, which would help a lot when trying to help you.
That said, I'm guessing you need to pass the course variable to your partial. Change
<%= render 'shared/partial' %>

to
<%= render 'shared/partial', :course => course %>

Partials do not have access to local variables in other partials. In that sense you can think of each partial as separate methods on the same object instance.

A: <%= render 'shared/partial', locale: 'swahili', course: course %>

You will have local vars 'locale' and 'course' in your partial set to 'swahili' and @course, respectively. Also, I'd advise to name your partials something more meaningful, like 'course'.


text:
Q: how to skip read command in visual fox pro i am calling an old vfp procedure through DO WITH PARA COMMANDS
when the command executes, it displays a form and Waits(Read command)
Can i skip this Read, through programing? so that it doesn't wait..

A: Sounds like a VERY OLD program with an explicit "READ" command...  If you just comment out the read, will that work for you.  Are you trying to otherwise bypass some functionality based on parameters and just have the function continue?  If so, you could put an IF around the read for only the condition that you NEED it to stop.
Also, if the form is a "MODAL" (WindowState = Modal), it will stay on that form until it is closed (or set to hidden) and returns back to calling source to continue execution.
Showing some context of the form, procedure might help other options.


text:
Q: How to get back a pointer provider from `wire.FieldsOf`? I am trying to use google wire to wire a config field and failing hard at it.
I have the following wire entrypoint
type Config struct {
    UserConfig UserConfig
}

func initialize(ctx context.Context, cfg *Config) (*st, func(), error) {
    panic( // panic to be replaced by generated code
        wire.Build(
            InitializeUser,
            wire.FieldsOf(new(Config), "UserConfig"),
        ),
    )
}

func InitializeUser(config *UserConfig) *User {
    // initialize user from user config
}

I am trying to make the UserConfig field in the Configstruct a provider without having to write a simple wrapper initializer just for that.
It is my understanding that wire.FieldsOf is supposed to do exactly this however it does not seem to work (keep geting no provider found for *Config). My guess is it only provides a UserConfig and not a *UserConfig.
Without changing the UserConfig field to a pointer or writing a initializer wrapper that takes a config and returns a *UserConfig, is there any way to do this in wire?


text:
Q: rename text file to the content text (batch) (powershell) Ok as the title says, i need a way to rename a text document, to the text there are in the text document, so if the document have this text (cake) then it need to rename the file name to cake.

A: Here is a pseudo code in batch that use a Regex with a vbscript in order to read and match the first word in the text file when reads from it, and then if the file is not empty, the script will rename your text file with the variable extracted from the vbscript.
How to test this code ?
Just Copy and paste this code below and save it as Rename-First-Word-Content.bat and create a text file named Test.txt in the same folder of your batch and write some words on it and save it. Finally just double click on the batch and see the result !
@echo off
Set "InputFile=Test.txt"
Call :Extract "%InputFile%" NewName
If defined NewName (
    echo NewName = "%NewName%"
    Ren "%InputFile%" "%NewName%.txt"
)
pause & exit
::-----------------------------------------------------------------------------------
:Extract <InputFile> <Variable NewName to be Set>
(
    echo WScript.StdOut.WriteLine Extract(Data^)
    echo Function Extract(Data^)
    echo Dim strPattern,oRegExp,Matches
    echo Data = "%~1"
    echo Data = WScript.StdIn.ReadAll
    echo strPattern = "[^-_\\/:;\x22*.?<>|]([\w\-]+)"
    echo Set oRegExp = New RegExp
    echo oRegExp.Global = False
    echo oRegExp.IgnoreCase = True
    echo oRegExp.Pattern = strPattern
    echo set colMatches = oRegExp.Execute(Data^)
    echo For Each Match in colMatches
    echo    Content = Match.Value
    echo Next
    echo Extract = Content
    echo End Function
)>"%tmp%\%~n0.vbs"
@For /f "delims=" %%i in ('cscript //nologo "%tmp%\%~n0.vbs" ^< "%~1" 2^>nul') do Set "%2=%%i"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::----------------------------------------------------------------------------------


text:
Q: Add a tint/color to a submit button in IE8 via CSS while retaining "glassy" look? I'm writing a web app.  It's only ever going to be used with IE8, so I'm not concerned with the behavior of any other browsers here.
So: I know how to custom-style a button using CSS properties e.g. background-color, border, and so on.  However, when you apply styles that way, the resulting button looks like a blocky table cell, nothing like the nice, glassy-looking button that IE8 renders by default.
Is there some way to add a tint to the nice glass-looking button?  I.e., it looks just like it normally does, but with a red outline instead of blue, and a red highlight on mouse-over?
Or is this something I'm going to have to do by hand with images?  Again, IE8-specific methods are perfectly acceptable.
Thanks!
-dan

A: There isn't really a filter that will get you as close to the default in IE, though you can get pretty close using the button tag and standard css. It will not look the same in all versions of IE though.
Here's the filter reference though if you want to try other things.

A: Regardless of browser, one of the quickest, easiest, most widely tested methods for styling buttons via markup is Jquery UI's button  It's a matter of adding a few tags to the class element, and you've got a button based on an  link, button, or input field.  For styling, you can handle styling via CSS, or via the very well done ThemeRoller option, where you can control everything from text size to background type via a simple gui interface--and you can change on the back end or even the user end on the blink of an eye, even via drop down.
One caveat, since IE is non-standards compliant, rounded buttons fail gracefully to square--with proper styling.
I realize that you have determined that you can use a proprietary solution for IE, and in your case it might be just fine over the long term.  But in my experience, that's a really dangerous path to follow.  What if the actual long term is longer than your anticipated "long term?"  You're specifying that it's acceptable to be proprietary to a browser that's well behind the accepted standards, is already a version behind, and uses unsupported (by universal standards) solutions to solve problems.  Conceivably, that version is going to get tougher and tougher to find, and if Microsoft holds true to their patterns, once you install IE9 it will effectively render your computer difficult of downgrading.  And, I can't emphasize enough that IE's market share is dropping like a rock, which is scary considering basically 95% of the machines out there have it pre-installed.  All it's going to take is one overzealous IT director with "security in mind" to render your programming efforts moot.  Sorry for the rant, but IE proprietary code has bit me hard more than a few times...

A: I'd have to double-check, but you should be able to use a combination of a background color and use a transparent PNG or GIF as the "background image" to add the highlights.
All things being equal, I've rather embraced the flat, square button - finding ways to make it work well with the design - but then again I've always been a straight line, square edge kind of guy. :)
As others have mentioned, you do want to be mindful (within reason) of what you may have to handle. It's quite possible that before the next re-write you're going to have to deal with IE9 - writing code that works well in IE8 and IE9 would be the most prudent approach.

A: Have a look at http://www.webdesignerwall.com/demo/css-buttons.html and also http://css3pie.com/.
Combining those you can get nice looking buttons in IE as well..


text:
Q: winsock server trouble shooting Ive written and compiled a server program that is meant to echo onto the the screen whatever the client application types in, the code is as below.
/*Server */
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;

const int winsock_version = 2;
#define PORT "3490"
#define MAX_NUM_CONNECTIONS 10

int main(void){

    WSADATA wsadata;

    if (WSAStartup(MAKEWORD(winsock_version,0),&wsadata) == 0){
        cout<<"-WSAStartup Initialized." << endl;

        struct addrinfo hints,*res;
        int sock_fd;

        memset(&hints,0,sizeof hints);
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_PASSIVE;

        if (getaddrinfo(NULL,PORT,&hints,&res) != 0){
            cout<<"-Call to getaddress was unsucceful." << endl;
        }

        if( (sock_fd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1){
            cout<<"-Unable to Create socket." << endl;
        }

        if ( (bind(sock_fd, res->ai_addr, res->ai_addrlen)) != -1 ){
            cout<<"-binding successful." << endl;
        }

        if ( (listen(sock_fd,MAX_NUM_CONNECTIONS)) != -1){
            cout<<"-Listening for incoming connections." << endl;
        }
        //-------------------------------------------------------------

        struct sockaddr_storage incming_info;
        socklen_t sin_size;
        sin_size = sizeof incming_info;

        int new_fd;

        new_fd = accept(sock_fd, (struct sockaddr*)&incming_info,&sin_size);
        if (new_fd == -1){
            cout<<"-Accepting error." << endl;
        }
        if(new_fd == INVALID_SOCKET){
            cout<<"-INVALID SOCKET ERROR." << endl;
        }
        closesocket(new_fd);
        //-------------------------------------------------------------

        cout<<"Connected?" << endl;

        while(true){
            int ret_val;
            char buffer[128];
            ret_val = recv(new_fd,buffer,sizeof(buffer),0);
            if(ret_val == -1){
                cout<<"Receiving Error." << endl;
                break;
            }else if(ret_val == 0){
                cout<<"Connection has been closed!." << endl;
                break;
            }else{
                cout<<"---Server Echoeing what was recieved from client---" << endl;
                cout<<"Server: " << buffer << endl;

            }
            closesocket(new_fd);
        }
        cout<<"-Closing connection" << endl;

    }else{
        cout<<"-WSAStartup Initialization failed." << endl;
        if(WSACleanup()!=0){
            cout<<"-WSACleanup Successful." << endl;
        }else{
            cout<<"-WSACleanup Failed." << endl;
        }
    }
    return 0;
}

The whole thing compiles and runs, however when I try to use putty and connect to localhost on port 3490 the server dies and prints out "Receiving Error". what is causing this problem?

A: Immediately after you accept the new socket into new_fd, you call closesocket on it (below).  You should not do that until you are done receiving.  If you want to close the listener socket at this point, you should be calling closesocket(sock_fd) instead.
  int new_fd;

    new_fd = accept(sock_fd, (struct sockaddr*)&incming_info,&sin_size);
    if (new_fd == -1){
        cout<<"-Accepting error." << endl;
    }
    if(new_fd == INVALID_SOCKET){
        cout<<"-INVALID SOCKET ERROR." << endl;
    }
    closesocket(new_fd);


text:
Q: Importance sampling - computing the mean of unnormalised importance weights I am completing an assignment for self-study, and am experiencing some confusion over some elementary algebra concerning importance sampling.
The context is as follows:

Given a random distribution $p(x)$ on $x = [x_1, ..., x_D]^T \in \mathbb{R}^D$, suppose we want to perform inference $\mathbb{E}_{p(x)}[f(x)]$ using importance sampling, with $q(x)$ as the proposal distribution. According to importance sampling we draw $L$ IID samples $x^{(1)}, x^{(2)}, ..., x^{(L)}$ from $q(x)$ and we have
$$\mathbb{E}_{q(x)}[u_i] \approx \frac{1}{\sum^L_{i=1}u_i} \sum^L_{i=1} f(x^{(i)})u_i$$
where $u_i$ are the (unnormalised) importance weights $u_i = \frac{p(x^{(i)})}{q(x^{(i)})}$.

Computing the mean of the unnormalised importance weights.
Now if I want to compute the mean of the unnormalised importance weights under the proposal distribution $\mathbb{E}_{q(x)}[u_i]$, and assuming that $p$ is already normalised, is the following argument valid?
$$\begin{align}
\mathbb{E}_{q(x)}[u_i] &= \mathbb{E}_{q(x)}\left[ \frac{p(x^{(i)})}{q(x^{(i)})} \right] \\
&= \int \frac{p(x^{(i)})}{q(x^{(i)})} q(x) dx\\
&= \int \frac{p(x^{(i)})}{q(x^{(i)})} q(x^{(i)}) dx^{(i)} \\
&= \int p(x^{(i)}) dx^{(i)} \\
&= 1
\end{align}$$
I have a feeling there is something wrong with this argument, in particular in going from the 2nd to the 3rd equality. The confusion is whether it is appropriate to "cancel" the proposal distributions as I have done. Whilst grappling with this, I tried to write down exactly what each quantity is.
In words, I understand that I the unnormalised importance weights $u_i$ are a deterministic, scalar function of a random vector $x^{(i)} \in \mathbb{R}^D$, and hence are random variables. And that in computing the expectation, I am drawing $x^{(i)} \sim q(x)$, computing the ratio $u_i = p(x^{(i)}) / q(x^{(i)})$, and taking an average of this by weighting this with all possible values that $x$ can take under the proposal distribution $q(x)$. However I am still unsure.
Some assistance would be greatly appreciated.

A: The confusion stands with the simultaneous use of $x$ and $x^{(i)}$: the $x^{(i)}$'s are iid from $q(\cdot)$ and hence what need be checked is that
\begin{align}
\mathbb{E}_{q}[u(x)] &= \mathbb{E}_{q}\left[ \frac{p(x)}{q(x)} \right] \\
&= \int_{\mathbb R^D} \frac{p(x)}{q(x)} q(x) \text dx\\
&= \int_{\mathbb R^D} p(x) \text dx \\
&= 1
\end{align}


text:
Q: SQL Script run on this server but don't on other server I have an weird issue with SQL Server. I have a small trigger that makes a request to a web service on update.
I have tested that code, it worked fine.
But when I move that code to another SQL Server machine, it does not run. No error are raised.
Update: if I call a "Get" request, it's ok. With "Post" request, that SQL Server can't handle it. Both servers run on Windows 2012
My code to call request:
DECLARE @dbName NVARCHAR(50)
DECLARE @wsAction NVARCHAR(50)
DECLARE @secret NVARCHAR(255)
DECLARE @url NVARCHAR(MAX)
DECLARE @idArray NVARCHAR(MAX)
DECLARE @triggerTime DATETIME

SET @dbName = 'dbname' + '/notification/object'
SET @secret = 'a key'
SET @url   = 'https://myserver/api/1.0.0/customer/databaseName='
SET @idArray = '1,2,3'
SET @wsAction = '"action": "modify"'

IF(@idArray <> '')
BEGIN
    DECLARE @Object INT;
        DECLARE @body NVARCHAR(MAX)
    SET @url = @url + @dbName;
    SET @body = '{"ids": [' + @idArray + '], ' + @wsAction +'}'

    EXEC sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
    EXEC sp_OAMethod @Object, 'setOption', null, 2, 13056 -- by pass ssl
    EXEC sp_OAMethod @Object, 'open', NULL, 'post', @url,'false'
    EXEC sp_OAMethod @Object, 'setRequestHeader', null, 'secret', @secret
    EXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Accept-Encoding', 'gzip, deflate'
    EXEC sp_OAMethod @Object, 'send', NULL, @body
    Declare @ResponseText as Varchar(8000);
    Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
    Select @ResponseText
    EXEC sp_OADestroy @Object
END

The "GET" request I test:
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
                                                          'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
                                                          'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Select @ResponseText

Exec sp_OADestroy @Object

A: I found the problem
A known bug with "msxml3.dll":
https://support.microsoft.com/en-us/kb/2968741
And this link helps me alot:
http://www.sqlservercentral.com/scripts/Miscellaneous/30867/
To get the error information


text:
Q: Vigenère Cipher - Python I'm attempting a Vigenere cipher for a class. I'm to use the key word "friends" to unlock the coded message. I can't seem to get the values of the key phrase to add to the values of the coded phrase correctly. I think somehow I'm not iterating through the 'key' properly, but I'm unsure how to trouble shoot.
#following code will attempt to use the key word 'friends', to unlock the coded phrase stored under 'message'.
    message ="dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!"
    alpha = "abcdefghijklmnopqrstuvwxyz"
    punc = ".!? \/$@^%&*'"

    #defining function that will take the coded 'message' and the 'key' phrase, as inputs.
    def decoder(message, key):
        decoded = ""
    #attempting to iterate through the key phrase to obtain it's value, print() here is used to test that the values are seen
        for k in key:
            if k not in punc:
                key_val = alpha.find(k)
                print(key_val)
    #iterating through the 'message' variable to find it's values and exclude the punctuation/spaces.Then, add the 'message'
    #values and 'key' values to get the coded message.
        for letters in message:
            if letters not in punc:
                message_val = alpha.find(letters)
                decoded += alpha[(message_val + key_val) % 26]
            else:
                decoded += letters
        return decoded
    #output is incorrect.
    decoder(message,"friends")

A: for letters in message:
    if letters not in punc:
        message_val = alpha.find(letters)
        key_val=alpha.find(key[counter])
        print(key[counter])
        decoded += alpha[(message_val + key_val) % 26]
        counter+=1
        if counter==7:
            counter=0

    else:
        decoded += letters
return decoded


text:
Q: How can I run a python script on the command line through the click of an HTML Button? I know similar questions have been asked before, and I've done a TON of looking around.
Currently what I am doing is I'm running a python script to create an HTML page (a list of statuses for various applications we run), and then I'm using nginx to serve the content on one of our DNS records.
Since I don't want to constantly run the python application, and create huge logs, I decided the next best option would simply to have an HTML button that the user could press -- triggering the python script to remake the HTML file, and then reload the page.
Before I list what I've tried.. I just want to point out that I cannot use a php solution as there's server issues with running PHP.
First, I tried to run some AJAX POST and that ended up just displaying the script in text for..

function postData(input) {
        $.ajax({
            type: "POST",
            url: "/status.py",
            data: { param: input },
            success: callbackFunc
        });
    }

function callbackFunc(response) {
    // do something with the response
    alert(response)
}

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
    postData("Hello world")
});

Then I attempted to create a node application and have come to learn that nodejs runs server side and cannot be called in HTML.. whoops.
Here is a look at the nginx config file
server {
  listen 80;

  server_name mydnsrecord.com;

  charset UTF-8;

  location ~ /.svn/ { deny all; }
  location ~ /.git/ { deny all; }

  location / {
    expires -1;

    alias /path/to/index/;
    index index.html;

    add_header "X-UA-Compatible" "IE=edge";
    add_header "X-Frame-Options" "DENY";

    proxy_set_header      X-Real-IP          $remote_addr;
    proxy_set_header      X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header      Host               $http_host;
  }

  error_page  405     =200 $uri;

}

If anyone could point me in the direction or give me some tips on how I can achieve this, that would be amazing.
Thanks.

A: You can't simply link to your python script.
You need to create an API endpoint on your server that will, in turn, run the python script and return a result
Here's a resource that will send you in the right direction:
how to set up uwsgi and nginx to serve python apps on ubuntu
P.S. - Your question is too broad for Stack Overflow


text:
Q: How to handle AsyncTask failure Is there a specific way to handle failure in an AsyncTask? As far as I can tell the only way is with the return value of task. I'd like to be able to provide more details on the failure if possible, and null isn't very verbose.
Ideally it would provide an onError handler, but I don't think it has one.
class DownloadAsyncTask extends AsyncTask<String, Void, String> {

    /** this would be cool if it existed */
    @Override
    protected void onError(Exception ex) {
        ...
    }

    @Override
    protected String doInBackground(String... params) {
    try {
            ... download ...
        } catch (IOException e) {
            setError(e); // maybe like this?
        }
    }
}

A: I modified Nicholas's code a bit, should you want to do something in the UI thread in exception.
Remember the AsyncTask can only be executed once after instantiated.
class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {

    private Exception exception = null;

    protected abstract void onResult(Result result);

    protected abstract void onException(Exception e);

    protected abstract ... realDoInBackground(...);

    @Override
    final protected void onPostExecute(Result result) {
        if(result != null) {
            onResult(result);
        } else {
            onException(exception);
        }
    }

    @Override
    protected ... doInBackground(...) {
        try {
            return realDoInBackground(...);
        } catch(Exception e) {
            exception = e;
        }
        return null;
    }
}

A: What I always do is create a new Object (you can call it AsyncTaskResult or whatever you like) that can get returned with doInBackground. This Object would have two things:

*

*The expected result (String in your example)

*Error code or even if you want, the Exception object itself or a wrapped version of it. Anything that basically will help you handling error if any occurs

I would then return this object to postExecute() and let that method check for the error, if there is then I handle it accordingly, otherwise I take the expected result and do whatever with it.
The object would be something like:

     public class AsyncTaskResult<T extends Object> {
            Exception exception;
            T asyncTaskResult;

            public void setResult(T asyncTaskResult) {
                this.asyncTaskResult = asyncTaskResult;
            }

            public T getResult() {
                return asyncTaskResult;
            }

            public void setException(Exception exception) {
                this.exception = exception;
            }

            public boolean hasException() {
                return exception != null;
            }

            public Exception getException() {
                return exception;
            }
        }

And your code becomes :

    /** this would be cool if it existed */
    protected void onError(Exception ex) {
        // handle error...
    }

    @Override
    protected AsyncTaskResult<String> doInBackground(String... params) {
        AsyncTaskResult<String> result = new AsyncTaskResult<String>();
        try {
            // ... download ...
        } catch (IOException e) {
            result.setException(e);
        }

        return result;
    }

    @Override
    protected void onPostExecute(AsyncTaskResult<String> result) {
        if(result.hasException()) {
            // handle error here...
            onError(result.getException());
        } else {
            // deal with the result
        }
    }

A: You can do this yourself pretty easily by creating a subclass of AsyncTask.  Perhaps something like ErrorHandlingAsyncTask.  First create an abstract callback method onException(Exception e).  Your doInBackground(Generic... params) method should wrap all of its code in a try-catch block.  In the catch block, call out to onException(Exception e) passing in your exception.
Now, when you need this functionality, just override your new ErrorHandlingAsyncTask class.
Quick and dirty pseudo code:
class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {
    protected abstract void onException(Exception e);

    protected abstract ... realDoInBackground(...);

    protected ... doInBackground(...) {
        try {
            return realDoInBackground(...);
        } catch(Exception e) {
            onException(e);
        }
    }
}

A: You can simply save the exception in a field and check it in onPostExecute() (to ensure that any error handling code is run on the UI thread). Something like:
new AsyncTask<Void, Void, Boolean>() {
    Exception error;

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
             // do work
             return true;
        } catch (Exception e) {
            error = e;

            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            Toast.makeText(ctx, "Success!",
                Toast.LENGTH_SHORT).show();
         } else {
            if (error != null) {
                Toast.makeText(ctx, error.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

}

A: I combined momo's and Dongshengcn's answers, and created my own base class with both background and foreground exception handling (in case you want to do some serious error logging)
The thing is, my code encapsulates all of the ResultOrError class stuff and simply lets you return the normal result or throw an exception
public abstract class HandledAsyncTask<Params, Progress, Result> extends
        AsyncTask<Params, Progress, ResultOrException<Result>> {

    /**
     * Wraps the calling of the {@link #doTask(Object[])} method, also handling
     * the exceptions possibly thrown.
     */
    protected final ResultOrException<Result> doInBackground(Params... params) {
        try {
            Result res = doTask(params);
            return new ResultOrException<Result>(res);
        } catch (Exception e) {
            onBackgroundException(e);
            return new ResultOrException<Result>(e);
        }
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to
     * {@link #doTask(Object[])} by the caller of this task. This method can
     * call {@link #publishProgress(Object...)} to publish updates on the UI
     * thread.
     *
     * @param params
     *            The parameters of the task.
     * @return A result, defined by the subclass of this task.
     */
    protected abstract Result doTask(Params[] params);

    /**
     * Handles calling the {@link #onSuccess(Object)} and
     * {@link #onFailure(Exception)} methods.
     */
    @Override
    protected final void onPostExecute(ResultOrException<Result> result) {
        if (result.getException() != null) {
            onFailure(result.getException());
        } else {
            onSuccess(result.getResult());
        }
    }

    /**
     * Called when an exception was thrown in {@link #doTask(Object[])}. Handled
     * in the background thread.
     *
     * @param exception
     *            The thrown exception
     */
    protected void onBackgroundException(Exception exception) {
    }

    /**
     * Called when the {@link #doTask(Object[])} method finished executing with
     * no exceptions thrown.
     *
     * @param result
     *            The result returned from {@link #doTask(Object[])}
     */
    protected void onSuccess(Result result) {
    }

    /**
     * Called when an exception was thrown in {@link #doTask(Object[])}. Handled
     * in the foreground thread.
     *
     * @param exception
     *            The thrown exception
     */
    protected void onFailure(Exception exception) {
    }
}

class ResultOrException<TResult> {

    /**
     * The possibly thrown exception
     */
    Exception   mException;

    /**
     * The result, if no exception was thrown
     */
    TResult     mResult;

    /**
     * @param exception
     *            The thrown exception
     */
    public ResultOrException(Exception exception) {
        mException = exception;
    }

    /**
     * @param result
     *            The result returned from the method
     */
    public ResultOrException(TResult result) {
        mResult = result;
    }

    /**
     * @return the exception
     */
    public Exception getException() {
        return mException;
    }

    /**
     * @param exception
     *            the exception to set
     */
    public void setException(Exception exception) {
        mException = exception;
    }

    /**
     * @return the result
     */
    public TResult getResult() {
        return mResult;
    }

    /**
     * @param result
     *            the result to set
     */
        public void setResult(TResult result) {
            mResult = result;
        }
    }


text:
Q: Magento 1: pros and cons of disabling the indexing on mass product import I've got a custom script that automatically import a lot of products at once.
I've seen here and there that it is a huge performance improvement to disable indexing when mass importing products.
My questions are:

*

*Is that sentence true ?

*What are the pros / cons of disabling the indexing before importing ?

A: Pros:

*

*it will be faster because it does not index each product at a time.

Cons:

*

*you won't see your changes real time. You will have to build the indexes manually when you are done.

Simple as that.
I say you should disable it. It's worth it.


text:
Q: Postgresql Streaming Replication on Windows failover Hello i have setup streaming replication using PostgreSQL 11 on Windows working OK.
How can i manually use the replica ( it is hot_standby=on ) in case Master fails ?
What are the steps i have to perform to the replica ?

A: Like the documentation says, there are three ways to promote a standby server:

*

*run pg_ctl promote on the command line.

*create a trigger file (if you have configured the standby server accordingly).

*from v12 on, you can also execute
SELECT pg_promote();


text:
Q: pytorch concat layers with sequential So I used nn.Sequential several times before but now I'm experiencing a weird error where one layer will send 3 outputs to the next one instead of two (like expected)
I have defined my layer as :
class BidirectionalGRU(nn.Module):
    def __init__(self, rnn_dim, hidden_size, dropout=0.0, batch_first=False):
        super(BidirectionalGRU, self).__init__()

        self.BiGRU = nn.GRU(
            input_size=rnn_dim,
            hidden_size=hidden_size,
            num_layers=1,
            batch_first=batch_first,
            bidirectional=True,
        )

    def forward(self, x, hidden):
        x, hidden = self.BiGRU(x)
        return x, hidden

And I use it in my code here:
class Listener(nn.Module):
    def __init__(
        self, input_feature_dim_listener, hidden_size_listener, num_layers_listener
    ):
        super(Listener, self).__init__()
        assert num_layers_listener >= 1, "Listener should have at least 1 layer"
        self.hidden_size = hidden_size_listener
        self.gru_1 = nn.Sequential(
            BidirectionalGRU(
                rnn_dim=input_feature_dim_listener,
                hidden_size=hidden_size_listener,
                batch_first=True,
            ),
            BidirectionalGRU(
                rnn_dim=hidden_size_listener * 2,
                hidden_size=hidden_size_listener,
                batch_first=True,
            ),
            BidirectionalGRU(
                rnn_dim=hidden_size_listener * 2,
                hidden_size=hidden_size_listener,
                batch_first=True,
            ),
            BidirectionalGRU(
                rnn_dim=hidden_size_listener * 2,
                hidden_size=hidden_size_listener,
                batch_first=True,
            ),
        )

    def initHidden(self):
        return torch.zeros([2, 8, 512])

    def forward(self, x):
        x = x.squeeze().permute(0, 2, 1)
        fake_hidden = self.initHidden()
        output, hidden = self.gru_1(x, fake_hidden)
        #output, hidden = self.gru_2(output, hidden)
        #output, hidden = self.gru_3(output, hidden)
        #output, hidden = self.gru_4(output, hidden)
        return output, hidden

This DOESNT WORK and throws me an error:
    las(spectrograms, spectrograms, 0.5)
  File "/Users/jaime/anaconda3/envs/torch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "caca.py", line 116, in forward
    listener_feature, hidden = self.listener(batch_data)
  File "/Users/jaime/anaconda3/envs/torch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "caca.py", line 84, in forward
    output, hidden = self.gru_1(x, fake_hidden)
  File "/Users/jaime/anaconda3/envs/torch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
TypeError: forward() takes 2 positional arguments but 3 were given

But If i define every layer manually instead of using nn.Sequential and pass the output,hidden myself then it works:
class Listener(nn.Module):
    def __init__(
        self, input_feature_dim_listener, hidden_size_listener, num_layers_listener
    ):
        super(Listener, self).__init__()
        assert num_layers_listener >= 1, "Listener should have at least 1 layer"
        self.hidden_size = hidden_size_listener
        self.gru_1 = BidirectionalGRU(
            rnn_dim=input_feature_dim_listener,
            hidden_size=hidden_size_listener,
            batch_first=True,
        )
        self.gru_2 = BidirectionalGRU(
            rnn_dim=hidden_size_listener * 2,
            hidden_size=hidden_size_listener,
            batch_first=True,
        )
        self.gru_3 = BidirectionalGRU(
            rnn_dim=hidden_size_listener * 2,
            hidden_size=hidden_size_listener,
            batch_first=True,
        )
        self.gru_4 = BidirectionalGRU(
            rnn_dim=hidden_size_listener * 2,
            hidden_size=hidden_size_listener,
            batch_first=True,
        )
    def initHidden(self):
        return torch.zeros([2, 8, 512])

    def forward(self, x):
        x = x.squeeze().permute(0, 2, 1)
        fake_hidden = self.initHidden()
        output, hidden = self.gru_1(x, fake_hidden)
        output, hidden = self.gru_2(output, hidden)
        output, hidden = self.gru_3(output, hidden)
        output, hidden = self.gru_4(output, hidden)
        return output, hidden

This works perfectly. I would like to make my code create multiple layers based on an argument and using nn.Sequential with a for loop inside would allow it.


text:
Q: Can hardware registers be mapped to userspace I'm developing an LED driver on Freescale MPC8306. In driver code, I do ioremap on GPIO registers and call remap_pfn_range upon the remapped GPIO register address, then, call mmap in userspace to map the GPIO register to userspace. I haven't done this before and I want to know if this method work or not. Can some help me? Thanks in Advance.

A: You should be using /dev/mem interface for accessing the GPIO registers. A good reference for controlling LEDs via GPIOs on another embedded board is given here.

A: An easier way would probably just to mmap the relevant offset of /dev/mem in your userspace program directly. This allows you to access the physical memory layout by seeking into it.
AFAIK, this is what the RaspberryPi developers have done to make GPIO memory mapped I/O registers available to userspace programs.


text:
Q: Create table with dynamic columns I'm working on PostgreSQL 9.1, and I have the following tables:
element(element_id int, name varchar, category_id int)

category(category_id int, name varchar)

characteristic(characteristic_id int, name varchar, unit varchar)

category_characteristic(characteristic_id, category_id)

element_characteristic(element_id, characteristic_id, value)

Imagine the following tables:
elements
 ---------------------
|id|name    |category |
-----------------------
|1 |'item 1'|1        |
|2 |'item 2'|2        |
|3 |'item 3'|1        |
 ---------------------

category
 ----------------
|id|name         |
|----------------|
|1 | 'category 1'|
|2 | 'category 2'|
 ----------------

characteristic
 --------------------------------
|id|name               |unit     |
 --------------------------------
|1 |'characteristic 1' | 'unit 1'|
|2 |'characteristic 2' | 'unit 2'|
|3 |'characteristic 3' | 'unit 3'|
|4 |'characteristic 4' | 'unit 4'|
|5 |'characteristic 5' | 'unit 5'|
|6 |'characteristic 6' | 'unit 6'|
 --------------------------------

category_characteristic
 ------------------------------
|category_id|characteristic_id |
|------------------------------
|1          |1                 |
|1          |2                 |
|1          |4                 |
|1          |5                 |
|2          |1                 |
|2          |3                 |
|2          |5                 |
 ------------------------------

element_characteristic
 ---------------------------------------
|id_element|id_characteristic|value     |
|---------------------------------------|
|1         |1                |'value a' |
|1         |2                |'value b' |
|1         |4                |'value c' |
|1         |5                |'value d' |
|2         |1                |'value e' |
|2         |3                |'value f' |
|2         |5                |'value g' |
|3         |1                |'value h' |
|3         |2                |'value i' |
|3         |4                |'value j' |
|3         |5                |'value k' |
 ---------------------------------------

And now I want to get the following tables:
 category 1
 ---------------------------------------------------------------------------
|name   |characteristic 1|characteristic 2|characteristic 4|characteristic 5|
| --------------------------------------------------------------------------|
|item 1 |value a         |value b         |value c         |value d         |
|item 3 |value h         |value i         |value j         |value k         |
 ---------------------------------------------------------------------------

category 2
 -----------------------------------------------------------
|name   |characteristic 1|characteristic 3|characteristic 5|
| ----------------------------------------------------------
|item 2 |value e         |value f         |value g         |
 ----------------------------------------------------------

I'm trying to understand what is the best procedure to go trough. I've read the tablefunc documentation but I just can't figure out how to make that procedures dynamically because there will be N entries on the category table. Some kind of directions will be very appreciated.

A: Solution:
SELECT *
FROM   crosstab (
        'SELECT e.name, c.name, ec.value
         FROM   elements e
         JOIN   element_characteristic ec ON ec.id_element = e.id
         JOIN   characteristic c ON c.id = ec.id_characteristic
         ORDER  BY 1, 2',

        'SELECT DISTINCT name
         FROM   characteristic
         ORDER  BY 1')
AS tbl (
  name text
 ,characteristic_1 text
 ,characteristic_2 text
 ,characteristic_3 text
 ,characteristic_4 text
 ,characteristic_5 text
 ,characteristic_6 text
 );

Test setup:
CREATE TEMP TABLE elements(id int, name text, category int);
INSERT INTO elements VALUES
 (1, 'item 1', 1)
,(2, 'item 2', 2)
,(3, 'item 3', 1);

CREATE TEMP TABLE element_characteristic(id_element int
                                        ,id_characteristic int, value text);
INSERT INTO element_characteristic VALUES
 (1,1,'value a')
,(1,2,'value b')
,(1,4,'value c')
,(1,5,'value d')
,(2,1,'value e')
,(2,3,'value f')
,(2,5,'value g')
,(3,1,'value h')
,(3,2,'value i')
,(3,4,'value j')
,(3,5,'value k');

CREATE TEMP TABLE characteristic (id int, name text, unit text);
INSERT INTO characteristic VALUES
 (1,'characteristic 1', 'unit 1')
,(2,'characteristic 2', 'unit 2')
,(3,'characteristic 3', 'unit 3')
,(4,'characteristic 4', 'unit 4')
,(5,'characteristic 5', 'unit 5')
,(6,'characteristic 6', 'unit 6');

Result:
  name | characteristic 1 | characteristic_2 | characteristic_3 | characteristic_4 | characteristic_5 | characteristic_6
-------|------------------|------------------|------------------|------------------|------------------|----------------
item 1 | value a          | value b          | <NULL>           | value c          | value d          | <NULL>
item 2 | value e          | <NULL>           | value f          | <NULL>           | value g          | <NULL>
item 3 | value h          | value i          | <NULL>           | value j          | value k          | <NULL>

The solution for your problem is to use the crosstab() variant with two parameters.
The query outputs all items. Add a WHERE clause to the first query to filter for category.
The second parameter (another query string) produces the list of output columns, so that NULL values in the data query (the first parameter) are assigned correctly.
Check the manual for the tablefunc extension, and in particular crosstab(text, text):
I have posted a couple of answer concerning crosstab() functions of the tablefunc module. This search will give you more examples and explanation.


text:
Q: Calculating dates based on the current date Can any one help me to calculate the past six months,1 year , 2 year dates based on the current date using C#. for example, suppose my current date is 09-11-2012 i need to find out the dates 09-05-2012, 09-05-2010,09-05-2009 etc. I know its a mathematical trick, but i am looking for similar implementation with C#.

A: Just use the built-in date and calendaring library.
The quick way is to use the DateTime class, but if you want to do things correctly then you'd use the Calendar class, which give you more control over culture-specific information (because Monday is the first day of the week in China, but not in the France).
Anyway:
DateTime currentDate  = new DateTime( 2012, 11, 09 ); // assuming 9th November 2012
DateTime sixMonthsAgo = currentDate.AddMonths( -6 );
DateTime yearAgo      = currentDate.AddYears( -1 );
DateTime twoYearsAgo  = currentDate.AddYears( -2 );

As an aside, please don't write dates in "dd-mm-yyyy" format (neither with slashes or dashes) because it's ambiguous - this site has a large US audience and for some reason 'merkins use "mm/dd/yyyy", which makes no sense to me. The ideal format is "yyyy-MMM-dd" (where "mmm" is the three-letter month name, e.g. "Jan", "Feb", "Mar", etc), or at least in "yyyy-mm-dd" format, which is more compliant with ISO 8601).

A: Use DateTime
DateTime value = new DateTime(2012, 11, 09);
DateTime nYearsAgo = value.AddYears(-n);

A: The trick is to use the .AddMonths() or .AddYears() methods on your DateTime object, and supply a negative value to effect a subtraction.

A: You could take a look at the DateTime Methods, more specifically the AddMonths and AddYears.


text:
Q: I am trying to filter ascending, descending, old price promotional-price to be shown in the public page if request.GET.get("sort", False):
    category_products = category_products.filter(old_price=request.GET.get("sort"))

A: You probably want to .order_by(…) [Django-doc] the value:
    chosen_genders = request.GET.getlist("gender", False)
    if chosen_genders:
        category_products = category_products.filter(gender__in=chosen_genders)
    if request.GET.get('sort') in ('old_price', '-old_price', 'title', '-title'):
        category_products = category_products.order_by(request.GET['sort'])
I strongly advise to check if the value is in a list of values, since ordering by an arbitrary field can result in exposing data you do not want to expose: a hacker could use binary search to determine the value of a field.


text:
Q: Send image to printer using sockets on port 9100 I'm currently able to send text to a printer (like EPSON TM20-II) using Swift. The printer receives the data and prints it without any problems. (For that, I'm encoding my string in UTF-8)
My custom class for the socket :
class OutSocket {

    var addr: String
    var port: Int
    var task: NSURLSessionStreamTask!

    init(host: String, port: Int){
        print("init")
        self.addr = host
        self.port = port
        setupConnection()
    }

    func setupConnection() {
        print("setup")
        let session = NSURLSession(configuration: .defaultSessionConfiguration())

        task = session.streamTaskWithHostName(addr, port: port)
        self.task.resume()
    }

    func send(data: NSData) {
        self.task.writeData(data, timeout: 5.0) { (error) in
            if error == nil {
                print("Data sent")
            } else {
                print("Nope")
            }
        }
    }
}

And I'm using it like this :
let socket = OutSocket(host: "192.168.1.42", port: 9100)
socket.send((itemText + "\n").dataUsingEncoding(NSUTF8StringEncoding)!)

I can send an image to the printer, but it only prints me the data characters.
How can I print an image, and not the data characters ?
I saw the Epson SDK but I want it to works with any printer that support TCP/IP printing. I tried to encode my image in base64 but still not print the image.
here the code :
let socket = OutSocket(host: "192.168.1.42", port: 9100)
let image = UIImage(named: "name-logo")
let imgData = UIImagePNGRepresentation(image!)
let imgEncoded = imgData!.base64EncodedDataWithOptions(.Encoding64CharacterLineLength)
socket.send(imgEncoded)

Thanks in advance,


text:
Q: ``Plain Vanilla'' Statistical Images with LaTeX I am looking to produce some very basic (nothing fancy), easily modifiable, statistical images for illustrative purposes in Latex. Such as these:

Although it may not be clear from the images, there is a little shading in the critical regions.
If someone could show me how to achieve this with basic Latex code, so that I may modify it without too much difficulty for many variations (such as test questions and the like), I would be grateful.
Thank you.


text:
Q: Running a script continuously while schedule the other I have two scripts that I would like to run simultaneously. While one will be scheduled to run every minute, I would like the second to continuously run.
I also would like both to run according to a schedule.
This is what I have so far:
import numpy as np
import time

import schedule
import time

def job():
starttime=time.time() #runs every minute with 1 minute sleep
while True:
     %run "script_1.py"
     time.sleep(60.0 - ((time.time() - starttime) % 60.0))

schedule.every().monday.at("14:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)

I need to squeeze script_2 in this script and make it run continuously within this schedule.
Note: I am using jupyter notebook
Thanks

A: The APScheduler package has flexible job scheduling (e.g. run every minute, run every monday at 14:00, etc) and it can run multiple jobs.


text:
Q: My Custom Widget does not save in sidebar I created a custom widget, but it's not saving if I click on save. When I refresh the page it is not saved. My code looks like follows
     <?php
/**  * Plugin Name: Sending a
     Contact SMS  * Plugin URI:
     http://www.test.co.za  * Description:
     Allows you to send a contact SMS to
     website owner  * Author: test  *
     Version: 1.0  * Author URI:
     http://test.co.za
     */

     class sendSMS extends WP_Widget {

         function sendSMS() {
               $widget_ops = array(
                   'classname' => 'sendSMS',
                   'description' => 'Allows you to add a small contact form that will send out an sms to the user.',
               );
               $control_ops = array( 'id_base' => 'smsForm-widget' );
               $this->WP_Widget( 'smsForm-widget', 'Send SMS', $widget_ops, $control_ops);  }

         function form ($instance) {
             $defaults = array('title'=> __('Example', 'example'), 'name' =>  __('John Doe', 'example'), 'number' => __('+27825656994', 'example'), 'message' =>  __('Tell Us', 'example') );
             $instance = wp_parse_args( (array) $instance, $defaults );
             ?>

                        <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?>
                        <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" />

                        <label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e('Your Name:', 'name'); ?>
                        <input id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo $instance['name']; ?>" />

                        <label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e('Your Cellphone Number:', 'number'); ?>
                        <input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" value="<?php echo $instance['number']; ?>"  />

                        <label for="<?php echo $this->get_field_id( 'message' ); ?>"><?php _e('Your Message:', 'message'); ?>
                        <textarea id="<?php echo $this->get_field_id( 'message' ); ?>" name="<?php echo $this->get_field_name( 'message' ); ?>"><?php echo $instance['message']; ?></textarea>

             <?php

         }

         function update ($new_instance, $old_instance) {
            $instance = $old_instance;

            /* Strip tags (if needed) and update the widget settings. */
            $instance['title'] = strip_tags( $new_instance['title'] );
            $instance['name'] = strip_tags( $new_instance['name'] );
            $instance['number'] = $new_instance['number'];
            $instance['message'] = $new_instance['message'];

            return $instance;

         }

         function widget ($args,$instance) {
            extract( $args );

            /* Our variables from the widget settings. */
            $title = apply_filters('widget_title', $instance['title'] );
            $name = $instance['name'];
            $number = $instance['number'];
            $message = $instance['message'];

            /* Before widget (defined by themes). */
            echo $before_widget;

            /* Display the widget title if one was input (before and after defined by themes). */
            if ( $title )
                    echo $before_title . $title . $after_title;

            /* Display name from widget settings if one was input. */
            if ( $name )
                    printf( '
' . __('Hello. My name is %1$s.', 'example') . '
', $name );

            if ( $number )
                    printf( '
' . __('Hello. My number is %1$s.', 'example') . '
', $name );

            if ( $message )
                    printf( '
' . __('Hello. My message is %1$s.', 'example') . '
', $message );

            /* After widget (defined by themes). */
            echo $after_widget;  }

        }

        function load_sms_form() {  register_widget( 'sendSMS' ); }

        add_action('widgets_init', 'load_sms_form');

         // register the widget

        ?>

A: there no "id_base" key in $control_ops; from what I know it only accepts width/height.
move it
the id_base is the first argument you have there in WP_Widget()

A: the ID of sidebar (in php function) should not contain upparcase char (smsForm-widget)) !!!


text:
Q: pause, stop or delay game start during count down In a game I am working on I wish to implement a counter at the start of a game and I want to pause, stop or delay all actions( animations, timers etc) in the game until the counter finishes counting and displays a label and the game actions resumes.
please how do I get around this?

A: you can implement something like that
-(void) pauseGame  {
    [sprite1 pauseSchedulerAndActions];
    [sprite2 pauseSchedulerAndActions];
    [self pauseSchedulerAndActions];
}

-(void) resumeGame  {
    [sprite1 resumeSchedulerAndActions];
    [sprite2 resumeSchedulerAndActions];
    [self resumeSchedulerAndActions];
}

simply dont pause the label/sprite that is performing the counter.
Keep in mind that pauseSchedulerAndAction will pause a Node, but not its childs, so you can easly pause a layer without pausing a counter inside it.


text:
Q: I cant drop tables after uninstalling plugin in WP, why? In uninstall.php I have this part of code, when I delete my plugin after it, I see that in my db I have all my plugin tables:
<?php
function my_plugin_remove_database()
{
    global $wpdb;
    $quiz_categories_table      =   $wpdb->prefix . 'aysquiz_quizcategories';
    $quizes_table               =   $wpdb->prefix . 'aysquiz_quizes';
    $questions_table            =   $wpdb->prefix . 'aysquiz_questions';
    $question_categories_table  =   $wpdb->prefix . 'aysquiz_categories';
    $answers_table              =   $wpdb->prefix . 'aysquiz_answers';
    $reports_table              =   $wpdb->prefix . 'aysquiz_reports';
    $themes_table               =   $wpdb->prefix . 'aysquiz_themes';
    $wpdb->query("DROP TABLE IF EXISTS `".$quiz_categories_table."`");
    $wpdb->query("DROP TABLE IF EXISTS `".$quizes_table."`");
    $wpdb->query("DROP TABLE IF EXISTS `".$questions_table."`");
    $wpdb->query("DROP TABLE IF EXISTS `".$question_categories_table."`");
    $wpdb->query("DROP TABLE IF EXISTS `".$answers_table."`");
    $wpdb->query("DROP TABLE IF EXISTS `".$reports_table."`");
    $wpdb->query("DROP TABLE IF EXISTS `".$themes_table."`");
}

register_uninstall_hook( __FILE__, 'my_plugin_remove_database' );

A: User following command for force deletion of tables:
SET foreign_key_checks = 0;
drop table ...
SET foreign_key_checks = 1;

A: First you must delete parent tables because if you will delete your parent table first , your child tables cant find parent by foreign key, this is my code after changing
$wpdb->query("DROP TABLE IF EXISTS `".$answers_table."`");
$wpdb->query("DROP TABLE IF EXISTS `".$questions_table."`");
$wpdb->query("DROP TABLE IF EXISTS `".$quizes_table."`");
$wpdb->query("DROP TABLE IF EXISTS `".$reports_table."`");
$wpdb->query("DROP TABLE IF EXISTS `".$themes_table."`");
$wpdb->query("DROP TABLE IF EXISTS `".$quiz_categories_table."`");
$wpdb->query("DROP TABLE IF EXISTS `".$question_categories_table."`");


text:
Q: How can I solve Android SDK problem for flutter? I had been using Android Studio for developing android projects. Later I downloaded flutter plugins to continue with flutter. But I keep having Android SDK problem and I can't run any flutter project neither on Android studio nor on VScode. Does anyone know how to solve this issue?
Flutter_Doctor

A: You need to set your Android SDK Path Like this:

and your Flutter SDK path should appear here as:


text:
Q: Selenium Webdriver Code Snippet for broken Links I was trying to use the following code snippet to verify if all the links are working or not

links = driver.find_elements_by_css_selector("a")
for link in links:
    if requests.head(link.get_attribute('href')).status_code == 200:
        print("valid link")
    else:
        print("Broken Link")

It gives me this error message in the console:
raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'javascript:window.print()'

A: javascript:window.print() opens a print dialog, it is totally normal that requests has no idea what to do with it. You may want to filter "links" like javascript:window.print(), javascript:alert("something").
You probably want to find your links with something more like this:
links = driver.find_elements_by_xpath('//a[contains(@href, *) and not(contains(@href, "#") or contains(@href, "javascript:"))]')

This should return all anchors, except the ones which contain # or javascript: as href value ("contain" is a partial match filter).
You may want to finetune the xpath to consider values invalid which do not contain . or / (relative addresses may be found with no protocol or server url if a base url is defined).


text:
Q: Image Upload not working, iOS Swift Multipart I have to upload an image to the server, but i am getting unusual behaviour,
if let imgdata = UIImageJPEGRepresentation(#imageLiteral(resourceName: "vishal"), 0.2) {

        let headers: HTTPHeaders = [
            "token": authToken,
            "Content-type": "multipart/form-data"
        ]

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(imgdata, withName: "image", fileName: "image.png", mimeType: "image/png")
        }, usingThreshold: UInt64.init(), to: url, method: .patch, headers: headers) { (result) in
            switch result{
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    print("Succesfully uploaded")
                    if let _ = response.error{
                        return
                    }
                    if let value = response.result.value {
                        let json = JSON(value)
                        print(json)
                    }
                }
            case .failure(let error):
                print("Error in upload: \(error.localizedDescription)")
            }
        }
    }

in a new project, this code works fine and uploads the image to the server, but in my old project for the same code, api call is successful but image is not uploaded
Please help


text:
Q: Why would I want to use CRaSH? Justed stumbled across CRaSH and although it looks mighty interesting, I'm wondering why a Java developer should invest time & energy into learning (yet another) shell language. What sort of standard- and cool-applications can CRaSH be used for? Is this like a Groovy-version of Jython?
I guess, when the dust settles, I'm looking for CRaSH's "wow" factors. I'm sure they're there, but after spending ~20 minutes perusing the documentation I'm just not seeing them. Thanks in advance!

A: Possible Uses
Fast Prototyping
You could do this with Groovy or others, so that's not a very strong point, but as CRaSH gives you code-level access to the JVM and the processes it runs, it may come in handy to just keep a JVM running and experiment with small code snippets (for instance, using it as a REPL to implement solutions to StackOverflow questions).
The JCR extension would seem potentially useful to supplement this, by giving you shell access to remote repositories, and contains a notion of workspace to separate projects.
Interacting with a Running Process
I could see this being an interesting use case. I don't know of many good process inspection command-line tools for JVM processes, apart from the JDK-packaged ones. CRaSH might help in interacting with them in novel ways.
For instance, you can use the Attach Mode to attach to a running JVM, and then use the thread command to ls, dump or interrupt threads.
You could also write some additional control commands for non-programmers to use CRaSH to perform routine maintenance and monitoring.
Content Repository Management
The JCR extension seems to be very interesting as well, as it would give a Java-scriptable access to remote development environments.   It could also simply allow content-editors to access and edit remote content, when used in the context of CMS-type apps built on top of a JCR-capable content repository.
What Others Say About CRaSH

*

*An introductory blog post by the CRaSH author, about its use at eXoPlatform. And the fact that it is officially supported by eXoPlatform is an indicator that's it potentially good stuff :)

*Not much to read, but of interest: French technologist Didier Girard re-posted it.

Summary
Basically, I see it as a power-user or administrator interface to JVM processes, built on top of Groovy and networking protocols. So it combines the power of scripting with a nice facade and some built-in connectors.

Note on Flexibility
I agree with SK-logic: most of this can be done with most JVM-languages, and they provide more and flexibility. But CRaSH might provide a shorter path to achieving such goals.
The same applies to the JCR extension capabilities: you can achieve this by glueing together a few age-old and time-tested tools. But this might be a shorter and simpler path (like commands for the heroku platform, or PaaS services, for instance).


text:
Q: String or binary data would be truncated - Finding column Issue

I know there have been questions on this subject but I just can't seem to get them to work for me.
I am executing a Stored Procedure and i am getting the error message - String or binary data would be truncated.
My table design is as follows:
@import_source nchar(50),
@JBJOB nchar(50),
@JBCONS nchar(50),
@JBRTC1 nchar(10),
@JBRTL1 nchar(10),
@JBRTC2 nchar(10),
@JBRTL2 nchar(10),
@JBRTC3 nchar(10),
@JBRTL3 nchar(10),
@JBRTD1 int,
@JBRTT1 int,
@JBRTD2 int,
@JBRTT2 int,
@JBRTD2 int,
@JBRTT2 int

The Stored Procedure I am executing is as follows:
exec spDataImport_INS_FJBJB1P @import_source=N'CONTROL',@JBJOB=N'01G04478X2       ',@JBCONS=N'LIC0050198',@JBRTC1=N'GB ',@JBRTL1=N'DAG ',@JBRTC2=N'TH ',@JBRTL2=N'LKR ',@JBRTC3=N'   ',@JBRTL3=N'    ',@JBRTD1=20140204,@JBRTT1=1200,@JBRTD2=0,@JBRTT2=0,@JBRTD3=0,@JBRTT3=0

I just can't seem to find the issue with the Stored Procedure.


text:
Q: -mimplicit-it compiler flag not recognized I am attempting to compile a C++ library for a Tegra TK1. The library links to TBB, which I pulled using the package manager. During compilation I got the following error
/tmp/cc4iLbKz.s: Assembler messages:
/tmp/cc4iLbKz.s:9541: Error: thumb conditional instruction should be in IT block -- `strexeq r2,r3,[r4]'

A bit of googling and this question led me to try adding -mimplicit-it=thumb to CMAKE_CXX_FLAGS, but the compiler doesn't recognize it.
I am compiling on the tegra with kernal 3.10.40-grinch-21.3.4, and using gcc 4.8.4 compiler (thats what comes back when I type c++ -v)
I'm not sure what the initial error message means, though I think it has something to do with the TBB linked library rather than the source I'm compiling. The problem with the fix is also mysterious. Can anyone shed some light on this?

A: -mimplicit-it is an option to the assembler, not to the compiler. Thus, in the absence of specific assembler flags in your makefile (which you probably don't have, given that you don't appear to be using a separate assembler step), you'll need to use the -Wa option to the compiler to pass it through, i.e. -Wa,-mimplicit-it=thumb.
The source of the issue is almost certainly some inline assembly - possibly from a static inline in a header file if you're really only linking pre-built libraries - which contains conditionally-executed instructions (I'm going to guess its something like a cmpxchg implementation). Since your toolchain could well be configured to compile to the Thumb instruction set - which requires a preceding it (If-Then) instruction to set up conditional instructions - by default, another alternative might be to just compile with -marm (and/or remove -mthumb if appropriate) and sidestep the issue by not using Thumb at all.

A: Adding compiler option:
-wa
should solve the problem.


text:
Q: How to find commas amongst any letters in strings and remove commas using regex? I use code:
    import sys
    import os
    import re
fa = open('C:\\file1.txt', 'r')
fb = open('C:\\file2.txt', 'w')
for line in fa:
    fb.write(line.replace(([a-z][\,][a-z]),([a-z][a-z]))
fa.close()
fb.close()

file1.txt contains strings Save,Buy,Go and Build,do,it. I need regex expressions to change the strings to SaveBuyG Builddoit.
I tried regex above but it does not work. I need to find in strings parts with commas between letters.
The commas shall be deleted in strings  while reading file1 (note there are no whitespaces between words) in order to convert in standard way to csv.
If the code is not compatible with regex can you paste necessary code?

A: You can use re.sub from the re module with lookahead assertions:
>>> re.sub('([a-zA-Z]),(?=[a-zA-Z])', r'\1', 'SaveBuyGo Builddoit to Builddoit 1,2 a,b,c,d Save,Buy,Go')
'SaveBuyGo Builddoit to Builddoit 1,2 abcd SaveBuyGo'

Note that it removes the comma between Build and do, but not between 1 and 2.

A: You can't use regex with string.replace function. In your case you could use re package if you insist on regex:
import re
re.sub(r'([A-Za-z]),([A-Za-z])', r'\1\2','Save,Buy,Go , Build,do,it')

the output will be:
'SaveBuyGo , Builddoit'

A: fileinput = open('INFILE.txt', 'r')
fileoutput = fileinput.read()
#fileinput.close()
replace = re.sub(r'([A-Za-z]),([A-Za-z])', r'\1', fileoutput)
print replace
replaceout = open('OUTFILE.txt', 'w')
replaceout.write(replace)

#CHANGE TO r'\1' OR r'\1\2' DEPENDING HOW MANY COMMAS YOU SEE AMONG LETTERS
#WORKING CODE TO READ FILE FINDING AND DELETING COMMAS AMONG LETTERS AND
#WRITING TO NEW FILE


text:
Q: Vue.js Scoped CSS - how to match root element? I have the following components:
Component 1:

<template>

        ...
        <component2></component2>
        ...

</template>

Component 2:

<template>

        ...

</template>

Because the root element of Component 2 also has class root, the style of Component 1's root element is also applied to Component 2. How can I prevent this? Is there a way to match on only the root element of a component (and not its children), without crude workarounds like ensuring that all root class names are unique?

Edit:
Relevant GitHub issue: https://github.com/vuejs/vue-loader/issues/957
Seems like there is currently no simple fix to this and the non-trivial workaround is to use CSS modules instead of scoped CSS.

A: if you want to use variables for your components, put all the variables on the app.vue (parent) and then use into your components (children)


text:
Q: SVD and homogeneous equation Suppose a $m \times n$ matrix $A$, and column vector $h$. ($A$'s rank is equal or smaller then $n$(=$h$'s length).)
If, $$ Ah=0 $$
then $h$ can be the last column of $V$ where $A = UDV^T $.
($UDV^T$ is taken by SVD)
How can I prove this?

A: If $v_i$ is the $i$th right singular vector, $\sigma_i$ is the $i$th singular value, $u_i$ is the $i$th left singular vector, and $e_i$ is the $i$th standard basis vector, then
$$Av_i=U D V^T v_i = U D e_i = U (\sigma_i e_i)=\sigma_i u_i.$$
The first step follows by the fact that $V$ is orthogonal, the others follow from $Be_i=b_i$ for any matrix $B$.
Can you conclude?

A: Homogenous equations $Ax=0$ only have two possible solutions, the trivial solution $(x_1=x_2=...=x_n=0)$ or infinitely many solutions depending on the rank of the matrix. If the matrix is rank-deficient, there are singular values that are zero. This means that $σ_i$ is zero and thus Ian's answer completes to $Av_i = 0$, which makes $v_i$ a solution to the equation. In a full rank case, all singular values $σ_i$ are non-zero and thus there only exists the trivial solution.


text:
Q: Which of the statements is/are TRUE?

Let $K = \big [k_{i,j} \big ]_{i,j = 1}^{\infty}$ be an infinite matrix over $\Bbb C$ (the set of all complex numbers) such that
$(\text {i})$ for each $i \in \Bbb N$ (the set of all natural numbers), the $i^{\text {th}}$ row $(k_{i,1},k_{i,2}, \cdots )$ of $K$ is in $\ell^{\infty}$ and
$(\text {ii})$ for every $x = (x_1,x_2, \cdots) \in \ell^{1},$ $\sum\limits_{j = 1}^{\infty} k_{i,j}\ x_j$ is summable for all $i \in \Bbb N,$ and $(y_1,y_2, \cdots ) \in \ell^{1}$ where $y_i = \sum\limits_{j = 1}^{\infty} k_{i,j}\ x_j.$
Let the set of all rows of $K$ be denoted by $E.$ Consider the following statements $:$
$\text {P}\ :\ $ $E$ is a bounded set in $\ell^{\infty}.$
$\text {Q}\ :\ $ $E$ is a dense set in $\ell^{\infty}.$
$$\begin{align*} \left (\ell^{1}  = \left \{ \left (x_1,x_2, \cdots \right )\ :\ x_i \in \Bbb C, \sum\limits_{i=1}^{\infty} \left |x_i \right | < \infty \right \} \right ) \\ \left ( \ell^{\infty}  = \left \{ \left (x_1,x_2, \cdots \right )\ :\ x_i \in \Bbb C, \sup\limits_{i \in \Bbb N} \left |x_i \right | < \infty \right \} \right   ) \end{align*}$$
Which of the above statements is/are TRUE $?$
$(\text A)$ Both $\text P$ and $\text Q.$
$(\text B)$ $\text P$ only.
$(\text C)$ $\text Q$ only.
$(\text D)$ Neither $\text P$ nor $\text Q.$

How do I solve this problem? Any help will be highly appreciated.
Thank you very much.
EDIT $:$ What I can see is that the column vectors of $K$ are in $\ell^{1}.$ Can it help anyway? I think $E$ is bounded but for that we need only to show that the sequence $\bigg \{ \sup\limits_{j \in \Bbb N} \left |k_{i,j} \right | \bigg \}_{i=1}^{\infty}$ of real numbers is bounded. How do I show that?
Suppose the sequence $\bigg \{ \sup\limits_{j \in \Bbb N} \left |k_{i,j} \right | \bigg \}_{i=1}^{\infty}$ of real numbers is unbounded then we can find a strictly increasing sequence $\big \{i_r \big \}_{r=1}^{\infty}$ of natural numbers such that $$\sup\limits_{j \in \Bbb N} \left |k_{i_r,j} \right | > r,\ \text {for each}\ r \in \Bbb N.$$ So $\exists$ another sequence $\big \{j_r \big \}_{r = 1}^{\infty}$ of natural numbers such that $$\left |k_{i_r,j_r} \right | > r,\ \text {for each}\ r \in \Bbb N.$$ Now this would yield a sequence $\bigg \{\left |k_{i_r,j_r} \right | \bigg \}_{r = 1}^{\infty}$ of real numbers such that $$\left |k_{i_r,j_r} \right | > r,\ \text {for each}\ r \in \Bbb N.\ \ \ \ \ \ (1)$$
Now how do I proceed? I think that I have to somehow use condition $(\text {ii} )$ here. Since the column vectors of $K$ are in $\ell^1$ we have for any fixed $j \in \Bbb N$ $$\lim\limits_{r \to \infty} \left |k_{i_r,j} \right | = 0.$$
So in particular if we take $j=j_r$ then we have $$\lim\limits_{r \to \infty} \left | k_{i_r,j_r} \right | = 0$$ which contradicts $(1).$ Is it correct what I have argued? Please verify it.
I don't think the last argument is true. The matrix $K$ may be such that for each $r \in \Bbb N,$ $j_r$'s could have been distinct and $k_{i_r,j_r}$ is the last non-zero entry in the $j_r^{\text {th}}$ column and $\left |k_{i_r,j_r} \right | = r + 1 > r.$ That's why I get stuck and can't able to proceed further.

A: $E$ is countable and thus never dense in the non-separable space $\ell^\infty$.
Asumption (ii) says that $T:\ell^1\to \ell^1$, $T(x)=\left(\sum\limits_{j=1}^\infty k_{i,j}x_j\right)_{i\in\mathbb N}$ is a well-defined map which is obviously linear. Show that its graph is closed (because it is continuous with respect to the weaker topology of coordinate-wise convergence on the range) to conclude its continuity. This gives you a uniform bound
$$
c=\sup\{\sum_{i=1}^\infty\left|\sum_{j=1}^\infty k_{i,j}x_j\right|: x\in\ell^1,\|x\|_1\le 1\}<\infty.
$$
For fixed $i_0,j_0$ plug in the sequence $x$ which has only $0$ entries but at the $j_0$-th spot where the entry is the sign of $k_{i_0,j_0}$ (in the complex case, the sign of $z\in\mathbb C\setminus\{0\}$ is $|z|/z$). This gives $|k_{i_0,j_0}|\le c$ for all $(i_0,j_0)$ and hence the boundedness of the set of rows in $\ell^\infty$.

Instead of the closed graph theorem it is also possible to use the uniform boundedness principle for the maps $T_i(x)=\sum\limits_{j=1}^\infty k_{i,j}x_j$. This would require an assumption  weaker than (ii).


text:
Q: Dynamically adding textbox to span or div with JQ Mobile... refresh? I want to dynamically add a textbox to a span or div or whatever.. I'm doing this:
 $('#optionsArea').append('<input type="text" class="q1Options" name="q1Options" data-theme="b" value="" />');

This works however, the textboxes do not come in as a JQ Mobile style text box... I know that the refresh command is used on most form elements...but have tried it with .text and .textbox and couldnt get it to change.
Can someone tell me how to add these as JQMobile textboxes.

A: I found the answer -- sorry for posting prematurely (I can delete this if it is wished or it might be good to leave it up as its not immediately apparent) --unless you actually read the docs :)
Calling
$('input').textinput();

does the trick!
http://jquerymobile.com/demos/1.0/docs/forms/textinputs/index.html  -- Bottom of this page is where I found it.


text:
Q: Selenium cannot find element on website (chrome/Java) Trying to test/learn selenium to login
the error - Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible
package com.indeed.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class test1 {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver",
        "C:\\Users\\****\\Desktop\\neww\\trainingfiles\\chromedriver.exe.exe");
        WebDriver driver = new ChromeDriver();

        driver.get("http://www.neopets.com/login/index.phtml");
        driver.findElement(By.name("username")).sendKeys("test1");
    }
    private static void sleep(int i) {
    }
}

A: I had a look at that web page. The problem is that there are two input fields with the name "username". One of them is not visible. Probably Selenium is getting that one. What you should do is:
List<WebElement> elements = driver.findElements(...);

and then get the second one (or the first, whatever), then try:
elements.get(1).sendKeys(...);


text:
Q: Netbeans PHP (Mac OSX) doesn't include full PHP Code Completion? I have just downloaded the Netbeans with PHP Bundle but when i run it, there is NO fully php code completion.
For very basic examples:

*

*mysql_fetch_array

*substr

*explode
It doesn't come up even with this basic funcions/methods/etc code completion inside PHP. So what is the Netbeans with PHP Bundle for? Why is it bundled as PHP, without even code completion as a basic need?
Anyone know how can i make it work?

A: I still don't understand your question. For example, for mysql_fetch_array, NetBeans IDE offers the code completion options mysql_fetch_array($result) and mysql_fetch_array($result, $result_type='MYSQL_BOTH'). For substr NetBeans offers substr($string, $start) and substr($string, $start, $length=null). What beyond this were you expecting?
Also, you might have more success posting at NetBeans PHP Users Forum


text:
Q: Duplicate tags with react-helmet This question might feel like a duplicate of an already asked question but the thing is I am not able to get any proper answers.
Using react-helmet-async creates duplicate tags instead of removing the previous tags. Now using       data-react-helmet="true" on the tags in index.html was not working for me. Adding data-rh="true" works fine for me. The problem is when I use data-rh="true" in tags, on other pages these tags from index.html does not come up. I would like them to behave as default tags and whenever I want to update the tags I use helmet there.
These are the tags in the Head of the index.html file.
<link id="favIconApple" rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/favicon/apple-touch-icon.png" data-rh="true" />
    <link id="favIcon32" rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/favicon/favicon-32x32.png" data-rh="true" />
    <link id="favIcon16" rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/favicon/favicon-16x16.png" data-rh="true" />

And this is the code for the helmet in one of the js files
<Helmet>
        <meta charSet="utf-8" />
        <title>{title}</title>
        {description?.length ? (
          <meta name="description" content={description} />
        ) : null}
        {icon?.length ? (
          <>
            <link
              id="favIconApple"
              rel="apple-touch-icon"
              sizes="180x180"
              href={icon}
            />
            <link
              id="favIcon32"
              rel="icon"
              type="image/png"
              sizes="32*32"
              href={icon}
            />
            <link
              id="favIcon16"
              rel="icon"
              type="image/png"
              sizes="16x16"
              href={icon}
            />
          </>
        ) : null}
      </Helmet>


text:
Q: ITextSharp, won't add second row to PdfPTable I'm trying to add a header and footer to my PDF using an ITextEvent,
My OnEndPage method is shown below.
The following line:
pdfTab.AddCell(pdfCell3);

is throwing an error "Object reference not sent to instance of an object"
The other two cells add fine and the pdf renders properly if I don't add the 3rd cell.
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
{
     base.OnEndPage(writer, document);

    BaseFont Calibri = BaseFont.CreateFont(@"C:\windows\fonts\calibri.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
    BaseFont CalibriBold = BaseFont.CreateFont(@"C:\windows\fonts\calibrib.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);

    Font baseFontSmall = new Font(Calibri, 10, Font.BOLD, Color.BLACK);
     Font baseFontNormal = new Font(Calibri, 12, Font.NORMAL, Color.BLACK);
     Font baseFontBig = new Font(CalibriBold, 12, Font.BOLD, Color.BLACK);

    Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);

    //Create PdfTable object
    PdfPTable pdfTab = new PdfPTable(2);

     create separate cells to include image logo and 2 separate strings
    //Row 1
    PdfPCell pdfCell1 = new PdfPCell();
    PdfPCell pdfCell2 = new PdfPCell(new Phrase("Doctors name", baseFontNormal));

    //row2
    PdfPCell pdfCell3 = new PdfPCell(new Phrase("Date and stuff", baseFontNormal));

    pdfCell1.Colspan = 1;
    pdfCell2.Colspan = 1;
    pdfCell3.Colspan = 2;

    String text = "Page " + writer.PageNumber + " of ";

    //Add paging to footer
    {
        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
        cb.ShowText(text);
        cb.EndText();
        float len = bf.GetWidthPoint(text, 12);
        cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
    }

    //set the alignment of all three cells and set border to 0
    pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
    pdfCell2.HorizontalAlignment = Element.ALIGN_RIGHT;
    pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
    //pdfCell4.HorizontalAlignment = Element.ALIGN_RIGHT;

    pdfCell2.VerticalAlignment = Element.ALIGN_TOP;
    pdfCell3.VerticalAlignment = Element.ALIGN_BOTTOM;
    pdfCell1.Border = 0;
    pdfCell2.Border = 0;
    pdfCell3.Border = 0;

    //add all three cells into PdfTable
    pdfTab.AddCell(pdfCell1);
    pdfTab.AddCell(pdfCell2);
    pdfTab.AddCell(pdfCell3);

    pdfTab.TotalWidth = document.PageSize.Width - 80f;
    pdfTab.WidthPercentage = 70;

    //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
    //first param is start row. -1 indicates there is no end row and all the rows to be included to write
    //Third and fourth param is x and y position to start writing
    pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
    //set pdfContent value

    //Move the pointer and draw line to separate header section from rest of page
    cb.MoveTo(40, document.PageSize.Height - 100);
    cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
    cb.Stroke();

    //Move the pointer and draw line to separate footer section from rest of page
    cb.MoveTo(40, document.PageSize.GetBottom(50));
    cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
    cb.Stroke();
}

Stack Trace
at iTextSharp.text.pdf.PdfPRow.set_RTL(Boolean value)
at iTextSharp.text.pdf.PdfPTable.AddCell(PdfPCell cell)
at ITextEvents.OnEndPage(PdfWriter writer, Document document) in c:\TFS\PSA\Source           Code\App_Code\ITextEvents.cs:line 145

at iTextSharp.text.pdf.PdfDocument.NewPage()
at PhysComp.UI.CreateSummaryReports.WritePdfLine(Tbl_ProvidersRecord NameRecord, PdfContentByte& Cb, BaseFont Font, Int32 FontSize, Int32 Alignment, String text, Int32 xPos, Int32& yindex, Int32 rotation) in c:\TFS\PSA\Source Code\SummaryReport\CreateSummaryReports.aspx.cs:line 346

at PhysComp.UI.CreateSummaryReports.printInvoice(PdfContentByte& Cb, Int32& yindex, Tbl_ProvidersRecord NameRecord, Invoices_By_CheckRecord invoice, Dictionary`2 ChequeAmounts) in c:\TFS\PSA\Source Code\SummaryReport\CreateSummaryReports.aspx.cs:line 295

at PhysComp.UI.CreateSummaryReports.printInvoices(PdfContentByte& Cb, Int32& yindex, Tbl_ProvidersRecord NameRecord, List`1 Invoices, Dictionary`2 ChequeAmounts) in c:\TFS\PSA\Source Code\SummaryReport\CreateSummaryReports.aspx.cs:line 272

 at PhysComp.UI.CreateSummaryReports.CreatePDF(Tbl_ProvidersRecord NameRecord, DateTime StartDate, DateTime EndDate) in c:\TFS\PSA\Source Code\SummaryReport\CreateSummaryReports.aspx.cs:line 133


text:
Q: Anchor view at the bottom - ConstraintLayout I'm trying to make a UI using ConstraintLayout according to following requirement.
Show textView below recyclerView if list has less item and not touching the bottom.
If list is long then textView must be anchored at the bottom, it should not move out of the screen.
Can anyone help me regarding this?
Here is the sample code:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/lighterGrey"
        android:paddingBottom="@dimen/space_20"
        tools:context=".ui.settings.AddressFragment">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/address_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/black"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/address_toolbar"
            app:layout_constraintBottom_toBottomOf="parent">

            <TextView
                android:id="@+id/address_profile_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space_20"
                android:padding="@dimen/space_12"
                android:text="@string/address_profile_label"
                android:textColor="@color/grey"
                android:textSize="@dimen/text_medium"
                android:textStyle="bold"
                app:layout_constraintTop_toTopOf="parent" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/address_profile_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space_8"
                android:background="@color/white"
         app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintTop_toBottomOf="@id/address_profile_title" />

            <TextView
                android:id="@+id/address_shipping_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space_20"
                android:padding="@dimen/space_12"
                android:text="@string/address_shipping_label"
                android:textColor="@color/grey"
                android:textSize="@dimen/text_medium"
                android:textStyle="bold"
                app:layout_constraintTop_toBottomOf="@id/address_profile_list" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/address_shipping_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space_8"
                android:background="@color/white"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                app:layout_constraintTop_toBottomOf="@id/address_shipping_title" />

            <TextView
                android:id="@+id/address_add_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/space_20"
                android:padding="@dimen/space_12"
                android:text="@string/address_add_new_label"
                android:textColor="@color/black"
                android:textSize="@dimen/text_medium"
                android:textStyle="bold"
                app:layout_constraintTop_toBottomOf="@id/address_shipping_list" />

            <com.google.android.material.progressindicator.CircularProgressIndicator
                android:id="@+id/address_progress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/space_150"
                android:indeterminate="true"
                android:indeterminateTint="@color/black"
                android:minWidth="@dimen/spinner_min"
                android:minHeight="@dimen/spinner_min"
                android:visibility="gone"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Kindly let me know the corrections needed.

A: Set the RecyclerView up with 0dp (match_constraints) for its width and height. When you do this set the start/top/end/bottom constraints to parent. match_parent should not be used for children of a ConstraintLayout.
Set the RecyclerView in a packed vertical chain with a vertical bias of 0.0. This will move the TextView immediately below the RecyclerView and move the RecyclerView to the top of the layout.
For the RecyclerView set app:layout_constraintHeight_default="wrap". This will cause the RecyclerView to wrap its content when but not exceed the limits of its constraints. See here.
Here is a sample layout:
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_light"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintVertical_chainStyle="packed"
        tools:itemCount="50" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/recyclerView" />

</androidx.constraintlayout.widget.ConstraintLayout>

You can change the item count for the RecyclerView to see how it works.
Here is the layout with an item count of 50:

and with an item count of 25: