text:
Q: passing value from iOS native code to cordova I have some values generated from my native code that I would like to pass to phonegap. These data are generated in real time and are not directly influenced by the user's actions through the phonegap gui.My native code is part of a plugin that I made.
What is the best way to approach this? I want to have a function to send data over anytime and have a listener on the cordova side.  I'm using Cordova 1.5 with Xcode 4.3.
Here is what I have so far:
swipe.js:
var swipe={
     callNativeFunction: function (success, fail, resultType) {
    return Cordova.exec( success, fail,
                        "ca.swipe",
                        "nativeFunction",
                        [resultType]); }

};

index.html:
...

function callNativePlugin( returnSuccess ) {
            swipe.callNativeFunction( nativePluginResultHandler, nativePluginErrorHandler, returnSuccess );
        }

        function nativePluginResultHandler (result) {
            alert("SUCCESS: \r\n"+result );
        }

        function nativePluginErrorHandler (error) {
            alert("ERROR: \r\n"+error );
        } ...
Hey, it's Cordova!

      <button onclick="callNativePlugin('success');">Success</button>
      <button onclick="callNativePlugin('error');">Fail</button>

   ...

swipe.h:
...
@interface swipe : CDVPlugin
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end

swipe.m:
...
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {

    NSLog(@"Hello, this is a native function called from PhoneGap/Cordova!");

    //get the callback id
    NSString *callbackId = [arguments pop];
    NSString *resultType = [arguments objectAtIndex:0];
    NSMutableArray *GlobalArg=arguments;

    CDVPluginResult *result;
    if ( [resultType isEqualToString:@"success"] ) {
       result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"Success :)"];
       //writes back the smiley face to phone gap.
       [self writeJavascript:[result toSuccessCallbackString:callbackId]];
    }

...

The code that I have right now has nothing for doing what I want. I'm not really sure how to setup the code in both cordova and native.

A: Sounds like you need to be able to talk back down to PhoneGap from objective C, in which case you should be able to use something like:
 NSString *jsResult = [theWebView stringByEvaluatingJavaScriptFromString:@"hello()"];
 NSLog(@"jsResult=%@",jsResult);

And if you have a JS function like "hello" in your index.html like this:
function hello(){return "hello";}

Its a way of talking back to your PhoneGap web layer

A: create a class of type CDVPlugin
import #import  in that class
initialize a handler method .h class
- (void)Device:(CDVInvokedUrlCommand *)command;

and implement the method in .m class
- (void)openDevice:(CDVInvokedUrlCommand *)command{
    CDVPluginResult *pluginResult = nil;
    BOOL checkOpenDevice=NO;
     pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:checkOpenDevice];
       [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

in this way through self.commandDelegate your data will be able to reach to the cordova class
if the .js file hit(calls) that particular method which is initialized in .h class.


text:
Q: Asymptotic expansion for $u_{n+1}=u_n+\ln(u_n)$ Do you know how to get an asymptotic expansion up to $o(1)$ when $n\longrightarrow +\infty$ for $(u_n)_{n\in\mathbb{N}}$ defined by $u_0>1$ and $\forall n\in\mathbb{N},\; u_{n+1}=u_n+\ln(u_n)$ ? Thank you.
Edit : if the problem was easier, I would like to find an equivalent for $v_{n+1}=v_n\times\ln(v_n)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I put my python GUI made in wxpython on a web browser? I have a GUI which I wrote in wxpython which runs on my PC.
Now, I want to be able to port the program so that it can run from a browser, and I will be able to access it remotely.
Is it possible to do this with wxpython? If not, is it possible to port the program in some way so that it runs from the browser but isn't the main page? Ideally, I don't want to have to rewrite any of the GUI code.
Thanks

A: There's been some talk of doing something like this on the wxPython users list, but nothing has come of it that I'm aware of. You can read some more about the stuff that that ticket refers to here:

*

*https://groups.google.com/forum/#!topic/wxpython-users/RPpt9IqzGpo
However, it sounds like it uses wxPython Phoenix, which itself is pretty beta as it doesn't have all the functionality (or widgets) that classic does. If you want to create a web page with Python, you would be better off using a Python web framework such as Django, TurboGears, Sphinx, bottle, flask or one of the others.
If you want to create a web browser with wxPython, try the webview widget.


text:
Q: Construct irreducible representation from eigenvalues Let $\lambda_1, \ldots, \lambda_n$ be roots of unity in $\mathbb{C}$. Can we always find a finite group $G$,  an element $g \in G$ and an irreducible representation $\rho: G \to \mathrm{GL}_n(\mathbb{C})$ such that $\rho(g)$ has eigenvalues $\lambda_1,\ldots,\lambda_n$?
What if $\mathbb{C}$ is replaced by another algebraically closed field?
What if $\mathbb{C}$ is replaced by another field, not necessarily algebraically closed, and "irreducible" replaced by "indecomposable"?
Thanks in advance!

A: Let $\lambda_{1},\ldots,\lambda_{n}$ be roots of unity in $\mathbb{C}$ and let $g$ be the diagonal matrix with $\lambda_{i}$ in the $(i,i)$ entry. Let $H$ be the subgroup of monomial matrices whose nonzero entries are always $\pm 1$ (so a matrix in $H$ has exactly one nonzero entry in each row and each column, and this entry is either $1$ or $-1$). Finally, let $G$ be the group generated by $g$ and $H$ and let $\rho:G\to GL_{n}(\mathbb{C})$ be the embedding representation.
First note that $G$ is finite. To see this, let $m$ denote the order of $g$ and let $X$ be the group of diagonal matrices with $m^{\text{th}}$ roots of unity along the diagonal. The group $H$ normalizes $X$ and $g\in X$, so $G\leq HX$. Since $H$ and $X$ are both finite, so is $HX$; consequently, $G$ is finite too.
The representation $\rho$ is irreducible because its restriction to $H$ is irreducible---see Jyrki Lahtonen's comment below. Here's another reason why the restriction of $\rho$ to $H$ is irreducible: a useful theorem of Burnside states that a representation $\varphi:G\to GL_{n}(\mathbb{C})$ of a finite group $G$ is irreducible if and only if the associated algebra homomorphism $\varphi:\mathbb{C}G\to M_{n}(\mathbb{C})$ from the group ring into the matrix algebra is surjective (the associated algebra homomorphism extends the original group representation, which explains the abuse of notation). Now, the restriction of $\rho$ to $H$ is just the embedding of $H$ in $GL_{n}(\mathbb{C})$. In order to apply the theorem of Burnside and deduce that this restriction is an irreducible representation, we need only show that the algebra generated by $H$ in $M_{n}(\mathbb{C})$ is the entire matrix algebra.
Claim: The $\mathbb{C}$-algebra generated by $H$ contains the set $S$ of matrices that have exactly one nonzero entry.
Since every matrix in $M_{n}(\mathbb{C})$ is a linear combination of matrices in $S$, if the claim is true then the algebra generated by $H$ is the whole matrix algebra. So then: let $A\in S$, and say that the unique nonzero entry of $A$ is $a$ and lives in the $(i,j)$ entry. Let $I^{(i,j)}$ be the identity matrix with columns $i$ and $j$ swapped. Note that $I^{(i,j)}\in H$ and has a $1$ in the $(i,j)$ entry. Let $J$ be the diagonal matrix with $-1$'s along the diagonal except in the $(i,i)$ entry, where we place a $1$. Let $J^{(i,j)}$ be the matrix $J$ with columns $i$ and $j$ swapped. Note that $J^{(i,j)}\in H$ and that this matrix looks like $I^{(i,j)}$ except that all entries besides the $(i,j)^{\text{th}}$ have been multiplied by $-1$. Finally, the claim follows because
\begin{equation*}
A=\dfrac{a}{2}\left(I^{(i,j)}+J^{(i,j)}\right)
\end{equation*}
and the term on the right is an element of the $\mathbb{C}$-algebra generated by $H$. (I prefer Jyrki Lahtonen's explanation, but sometimes it's nice to have more than one for reassurance.)
By construction, the eigenvalues of $\rho(g)$ are precisely $\lambda_{1},\ldots,\lambda_{n}$.
I believe the same construction or a similar one would work over any field, but I don't have time to check the details right now.


text:
Q: How to add comments on a view? I'm learning Rails and I try to add a comment function.
I have this error when I try to add a comment:
No route matches [POST] "/advertisements/1"
How can I say to Rails : "Hey dude, I would like you go to my comments#create function"
#app/views/advertisements/show.html.erb
<% if @current_user %>
    <%= render "comments/form", comment: @comment %>
<% end %>

#app/views/comments/_form.html.erb
<%= form_with(model: comment, local: true) do |form| %>

    <%= form.text_area :content %>

    <%= form.hidden_field :user_id, :value => @current_user.id %>

    <%= form.hidden_field :advertisement_id, :value => @advertisement.id %>

    <%= form.submit %>

<% end %>

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController

  # GET /comments/new
  def new
    @comment = Comment.new
  end

  # POST /comments
  # POST /comments.json
  def create
    @comment = Comment.new(comment_params)

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:content, :user_id, :advertisement_id)
    end
end

HTML form rendered (why he has "/advtertisements/1" in action input
<form action="/advertisements/1" accept-charset="UTF-8" method="post">

<input type="hidden" name="authenticity_token" value="pJOwu9LyhQmj4uSYhyeBKD66Zab+kJf9bR1m+eJJ1Fj+kznMl/4rVz69ucPa2gkuOc/yUB8rPLWhpH+6GHWaqQ==" />

    <textarea name="content" id="content">
</textarea>

    <input value="1" type="hidden" name="user_id" id="user_id" />

    <input value="1" type="hidden" name="advertisement_id" id="advertisement_id" />

    <input type="submit" name="commit" value="Save " data-disable-with="Save " />

</form>

#config/routes.rb
Rails.application.routes.draw do

  resources :comments, only: [:new, :create]
  resources :advertisements
  resources :users, only: [:new, :create] do
    collection do
      get :login, to: 'sessions#new', as: "login"
      post :login, to: 'sessions#create'
      delete :logout, to: 'sessions#destroy', as: "logout"
    end
  end
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

#app/controllers/advertisements_controller.rb
before_action :set_advertisement, only: [:show, :edit, :update, :destroy]

...

# GET /advertisements/1
# GET /advertisements/1.json
def show
  @comments = @advertisement.comments.all
end

...

private
# Use callbacks to share common setup or constraints between actions.
def set_advertisement
  @advertisement = Advertisement.find(params[:id])
end

I know hidden_fields and form like mine are probably not the best option to do this kind of thing btw but I'm still learning. Thank you for your help !

A: Why didn't my original code work?
The most likely cause is that you're passing the wrong thing to the partial. Passing an instance of Advertisement would cause the form to use the path /advertisements/1.
What a better solution?
Start by a creating nested route:
# config/routes.rb
resources :advertisements do
  resources :comments, shallow: true
end

This lets you create comments for a specific advertisements by sending a POST request to:
POST /advertisements/:advertisements_id/comments

You can setup the form to post to the nested route by passing an array:
#app/views/comments/_form.html.erb
<%= form_with(model: [local_assigns[:advertisement], comment], local: true) do |form| %>

    <%= form.text_area :content %>

    <%= form.submit %>

<% end %>

Using local_assigns(:advertisement) lets you use the same partial for nested and non-nested views (edit/update) without risking a NoMethod error if its not passed. The array is compacted so a nil won't matter.
And then setup your controller so that it uses params[:advertisement_id] which will be passed as part of the request path and gets the user id from the session instead.
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  # callbacks help you avoid duplication
  before_action :set_advertisement, only: [:new, :create, :index]

  # GET /advertisements/1/comments/new
  def new
    @comment = @advertisement.comments.new
  end

  # POST /advertisements/1/comments
  def create
    @comment = @advertisement.comments.new(comment_params) do |c|
      c.user = current_user # here I'm assuming you have a method that fetches the user from the session
    end
    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:content)
    end

    def set_advertisement
      @advertisement = Advertisement.find(params[:advertisement_id])
    end
end

Make sure you're rendering the partial correctly:
<%= render 'comments/form', advertisement: @advertisement, comment: @comment %>

To link to the "new" action you can use:
<%= link_to "Add a comment", new_advertisement_comment_path(@advertisement) %>


text:
Q: IF $||T||\leq 1$ Then, $T(I-T^{*}T)^{1/2}$ = $(I-TT^{*})^{1/2}T$ Let $T$ be a bounded linear operator on a hilbert space $H$ over complex numbers with $||T||\leq 1$.
Then I need to show that $T(I-T^{*}T)^{1/2}$ = $(I-TT^{*})^{1/2}T$.
I was able to show that equality holds when $h$ $\in$ $Ker((I-T^{*}T)^{1/2}$ and $h \in$ $Ker(I-TT^{*})^{1/2}$.
Any ideas how to go ahead and prove this in general?

A: The original version of the question asked to show that $T(I-T^{*}T)^{1/2}=T(I-TT^{*})^{1/2}$. There's a counterexample to that below.
For the current version: Note first that by continuity we may assume that $||T||<1$. Now the function $(1-z)^{1/2}$ is holomorphic in the unit disk, so it has a power series $$(1-z)^{1/2}=\sum c_nz^n\quad(|z|<1).$$Hence $$(I-T^*T)^{1/2}=\sum c_n(T^*T)^n$$and $$(I-TT^*)^{1/2}=\sum c_n(TT^*)^n.$$The result follows since $$T(T^*T)^n=(TT^*)^nT.$$
Having already written up the counterexample to the original version we may as well include it: Let $T$ be the right shift on $\ell_2(\Bbb N)$: $$Tx=(0,x_1,x_2,\dots).$$Then $$T^*x=(x_2,x_3,\dots).$$So $T^*T=I$, hence $$T(I-T^*T)^{1/2}=0.$$But $$TT^*x=(0,x_2,x_3,\dots),$$so $$(I-TT^*)x=(x_1,0,0,\dots),$$so$$(I-TT^*)^{1/2}x=(x_1,0,0,\dots),$$hence $$T(I-TT^*)^{1/2}x=(0,x_1,0,0,\dots).$$


text:
Q: Merge two different files using specific columns after a match and add N/A when no match File 1
Time        C-ID        Room            Info        N_Range ErrorCodes  Stability   Position    Profile Configuration   N-East  EAST    North
10:29:18    13832216    1Tr1Tr1Tr10     VILNARPN    AIN         6       STABLE      default     1600    8               LINK    R8      1
10:29:18    1498684     1Tr1Tr1Tr11     VILNARPN    UAN         6       STABLE      default     1600    5030            LINK    R8      1
10:29:18    1498684     1Tr1Tr1Tr12     VILNARPN    AN          6       STABLE      default     1600    5030            LINK    R8      1
10:29:18    2492427     1Tr1Tr1Tr13     VILNARPN    AN          7       STABLE      default     1600    5030            LINK    R8      1
10:29:18    1002527     1Tr1Tr1Tr14     TDAT00      AN          6       STABLE      default     1600    8               LINK    R8      1
10:29:18    1002527     1Tr1Tr1Tr15     TDAT00      UAN         6       STABLE      default     1600    8               LINK    R8      1
10:29:18                1Tr1Tr1Tr18     TDAT00      AN          5       STABLE      default     1600    8               LINK    R8      1
10:29:18    1569109     1Tr1Tr1Tr19     RTEDLOJ0    AIN         6       STABLE      default     1600    8               LINK    R8      1

File 2
Number          Action      Time      Repeat    Oas  Restriction    Status      Priority
AA_B_43645175   REBUILD     15:29:18    2       OAS     NONE        PENDING     HIGH
AA_B_43652334   REBUILD     10:29:18    0       OAS     NONE        PENDING     LOW
AA_B_43652684   REBUILD     10:29:18    1       OAS     NONE        PENDING     LOW
AA_B_43653840   CHANGED     13:29:18    0       OAS     NONE        PENDING     MEDIUM
AA_B_43667706   REBUILD     10:29:18    2       OAS     NONE        PENDING     LOW
AA_B_43723080   REBUILD     10:29:18    4       OAS     NONE        PENDING     LOW
AA_B_43747934   CHANGED     10:29:18    1       OAS     NONE        PENDING     MEDIUM
AA_B_43766744   REBUILD     10:29:18    0       OAS     NONE        PENDING     LOW
AA_B_43908075   REBUILD     11:29:18    1       OAS     NONE        PENDING     LOW
AA_B_43963533   REBUILD     12:29:18    0       OAS     NONE        PENDING     HIGH
AA_B_43964358   NEW         13:29:18    3       OAS     NONE        PENDING     LOW
AA_B_43964533   REBUILD     14:29:18    0       OAS     NONE        PENDING     MEDIUM
AA_B_43964678   NEW         15:29:18    0       OAS     NONE        PENDING     LOW

if File1's first column matches File2's third column then print:

*

*Columns from File1: 2, 3, 6, and 7

*Columns from File2: 7 and 8

*mark N/A when there is no match

I tried
awk 'NR==FNR{a[$1,$3];next}{print $2,$3,$6,$7,$2,$3a[$1]?a[$1]:"NA"}'

it didn't even do the Match
so I tried
awk -F 'NR==FNR{a[$1,$3];next} ($7,$8) in a' {print $2,$3,$6,$7,$2,$3a[$1]?a[$1]:"NA"}'

but it didn't work everything was marqued N/A
Desired Output
C-ID     Room        ErrorCodes     Stability   Status     Priority
1569109  1Tr1Tr1Tr19     6           STABLE     PENDING    LOW
1569109  1Tr1Tr1Tr19     6           STABLE     PENDING    LOW
1569109  1Tr1Tr1Tr19     6           STABLE     PENDING    LOW
1569109  1Tr1Tr1Tr19     6           STABLE     PENDING    LOW
1569109  1Tr1Tr1Tr19     6           STABLE     PENDING    MEDIUM
1569109  1Tr1Tr1Tr19     6           STABLE     PENDING    LOW

A: Put File2 in an array and run each line from File1 over it
#!/usr/bin/awk -f
# syntax ./merge-all.awk File2 File1

BEGIN {
  FS=","
  OFS=","
  lineCount=0
}

# Put File2 records into an array
FNR == NR {
  entries[lineCount, "time"]=$3
  entries[lineCount]=$7 OFS $8
  lineCount+=1
  next
}

# Print headers
FNR == 1 {
  print $2, $3, $6, $7, entries[0]
  next
}

# Print a record for each record in File2 while handling each File1 record
{
  matchFound=0
  for (i=1; i < lineCount; i++) {
    if (entries[i, "time"] == $1) {
      print $2, $3, $6, $7, entries[i]
    } else {
      print $2, $3, $6, $7, "N/A", "N/A"
    }
  }
}

Here is the output of this command:
$ ./merge-all.awk File2 File1 | tr ',' ' ' | column -t
C-ID      Room         ErrorCodes  Stability  Status   Priority
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
13832216  1Tr1Tr1Tr10  6           STABLE     PENDING  LOW
13832216  1Tr1Tr1Tr10  6           STABLE     PENDING  LOW
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
13832216  1Tr1Tr1Tr10  6           STABLE     PENDING  LOW
13832216  1Tr1Tr1Tr10  6           STABLE     PENDING  LOW
13832216  1Tr1Tr1Tr10  6           STABLE     PENDING  MEDIUM
13832216  1Tr1Tr1Tr10  6           STABLE     PENDING  LOW
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
13832216  1Tr1Tr1Tr10  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr11  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr11  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr11  6           STABLE     PENDING  MEDIUM
1498684   1Tr1Tr1Tr11  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr11  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr12  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr12  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr12  6           STABLE     PENDING  MEDIUM
1498684   1Tr1Tr1Tr12  6           STABLE     PENDING  LOW
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
1498684   1Tr1Tr1Tr12  6           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     PENDING  LOW
2492427   1Tr1Tr1Tr13  7           STABLE     PENDING  LOW
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     PENDING  LOW
2492427   1Tr1Tr1Tr13  7           STABLE     PENDING  LOW
2492427   1Tr1Tr1Tr13  7           STABLE     PENDING  MEDIUM
2492427   1Tr1Tr1Tr13  7           STABLE     PENDING  LOW
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
2492427   1Tr1Tr1Tr13  7           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr14  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr14  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr14  6           STABLE     PENDING  MEDIUM
1002527   1Tr1Tr1Tr14  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr14  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr15  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr15  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr15  6           STABLE     PENDING  MEDIUM
1002527   1Tr1Tr1Tr15  6           STABLE     PENDING  LOW
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
1002527   1Tr1Tr1Tr15  6           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     PENDING  LOW
null      1Tr1Tr1Tr18  5           STABLE     PENDING  LOW
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     PENDING  LOW
null      1Tr1Tr1Tr18  5           STABLE     PENDING  LOW
null      1Tr1Tr1Tr18  5           STABLE     PENDING  MEDIUM
null      1Tr1Tr1Tr18  5           STABLE     PENDING  LOW
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
null      1Tr1Tr1Tr18  5           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     PENDING  LOW
1569109   1Tr1Tr1Tr19  6           STABLE     PENDING  LOW
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     PENDING  LOW
1569109   1Tr1Tr1Tr19  6           STABLE     PENDING  LOW
1569109   1Tr1Tr1Tr19  6           STABLE     PENDING  MEDIUM
1569109   1Tr1Tr1Tr19  6           STABLE     PENDING  LOW
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A
1569109   1Tr1Tr1Tr19  6           STABLE     N/A      N/A

Note that I added in the string "null" to the dataset where there was a missing C-ID as without any value there awk will shift all the columns left.


text:
Q: ypcat passwd returns error with NIS I have set up and installed NIS server on my Ubuntu platform Ubuntu 14.04.3 LTS
It all is going well and ive followed these instructions, ive added a user and all seems to be good, however when logged in a  root I get the following error
# ypcat passwd
No such map passwd.byname. Reason: No such map in server's domain

Any ideas on how to get around this error


text:
Q: MX-FS-03V 433 MHz transmitter will it function with a coil missing? I'm planning to make a project using the MX-FS-03V 433 MHz transmitter and the corresponding MX-05 receiver with a couple of Arduinos for short range radio communication.  Range will be at most 10 meters.
I got a couple of these from Amazon, but one thing has me puzzled.  This is a picture of the transmitter:

note that in the lower right corner are three unoccupied through holes.  The extreme lower right one is where I will solder the antenna, but the other two have me puzzled.  Looking at other pictures of this transmitter, there seem to be several revisions if the silk-screen on the PCB is anything to go by, and some have a second coil soldered between the two holes not used by the antenna, e.g. this one:

So what's going on here?  I'm not that much of an expert, but I know enough to believe that removing a coil from an RF circuit is likely to have some pretty major effects.  For one project, it is vital that I work at 433 MHz, so I'd like to have some idea of what I'm getting myself into.

A: They can't work without a vital component in place. That inductor provides power to the high-frequency oscillator.
Luckily somebody else has gone to the effort of analyzing the issue.
Review this website.
FS1000A 433 MHZ TRANSMITTER – L2 MISSING
Here is the schematic from that site.


text:
Q: Spring boot:java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'edit' available as request attribute I'm working on my "Edit" site,which can change the data on the existing webpage.
I'm getting this error and can't find the problem on my code.
My controller:
    @PostMapping("editKursInfo")
    public String editKursInfo(Model model,
            @Valid @ModelAttribute("edit") Kurs kurs,
            BindingResult bindingresult)
        {
        if (bindingresult.hasErrors()) {
            model.addAttribute("edit", kurs);
            return "editKursInfo";
        }
        model.addAttribute("kurs", kurs);
     // model.addAttribute("edit", kurs);
        data.saveKurs(kurs);
        return "editKurs";
        }

Thymeleaf:
                <form action="editKursInfo" method="POST"
                th:object="${edit}">

                <input th:field="*{kursName}"
                type="text"
                align="left"
                class="form-control"
                style="width:250px;"
                th:errorclass="is-invalid"
                id="kursNameInput"
                value=""/>

Javascript:

the part of error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'edit' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.checkErrors(FieldUtils.java:212) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.hasErrors(FieldUtils.java:71) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.spring5.expression.Fields.hasErrors(Fields.java:58) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]

A: You have to set the edit attribute on the model before actually showing the page. So you need to have a GET-mapped method, something like the following:
@GetMapping(value = "/editKursInfo")
public String viewEditKursPage(Model model) {
   Kurs kurs = new Kurs();
   model.addAttribute("edit", kurs);
   return "editKursInfo";
}


text:
Q: Save Int Data into Text File in C++ I working on saving Data into text file and compare it with another text file. Below is the code I worked on:
    ofstream outfile;
    outfile.open("Data",ios::out | ios :: binary);
    for(x=0; x<100; x++)
    {
       printf("data- %x\n", *(((int*)pImagePool)+x));
       int data =  *(((int*)pImagePool)+x);
       //outfile<<(reinterpret_cast<int *>(data))<<endl;
       outfile<<(int *)data<<endl;
    }

The result from printf is 24011800 and result read from text file is 0x24011800
Why there is  0x appeared? Do we able to remove it?
What is the difference between reinterpret_cast<int *> & (int *) but both giving the same result?

A: It's because you cast it as a pointer, so the output will be a pointer.
Since data is a normal value variable, just write it as usual:
outfile << data << '\n';

I also recommend you stop using printf when programming C++, there no reason to use it. Instead output using std::cout:
std::cout << "data- " << *(((int*)pImagePool)+x) << '\n';

Or if you want hexadecimal output
std::cout << "data- " << std::hex << *(((int*)pImagePool)+x) << '\n';

A: "%x" is a specifier for a hexadecimal number. Check this table: http://www.cplusplus.com/reference/cstdio/printf/
Use "%d" to output a decimal.
EDIT: About the casting, see this:
Reinterpret_cast vs. C-style cast

A: This is a very simple example using the ofstream f. The most complicated part are the parameters passed to the open, specifically std::ios::out which specifies the file direction. You could also use std::ios:in for reading from a file along with cin.
// ex5.cpp

#include <string>
#include <iostream>
#include <fstream>
#include "hr_time.hpp"
#include >ios>

int main(int argc, char * argv[])
{
    CStopWatch sw;
    sw.startTimer() ;

    std::ofstream f;
    f.open("test.txt",std::ios::out ) ;
    for (int i=0;i<100000;i++)
    {
      f << "A very long string that is number " << i << std::endl;
    }
    f.close() ;
    sw.stopTimer() ;
    std::cout << "This took " << sw.getElapsedTime() << " seconds" << std::endl;
    return 0;
}


text:
Q: How to use the middleware to check the authorization before entering each route in express? I want to check the authorization of the users of my web app when they entered the url. But when I used an individually middleware to check the authorization, it's useless for the already existing routes, such as:
function authChecker(req, res, next) {
    if (req.session.auth) {
        next();
    } else {
       res.redirect("/auth");
    }
}

app.use(authChecker);
app.get("/", routes.index);
app.get("/foo/bar", routes.foobar);

The authChecker is unabled to check the authority of the users who entered the two urls.
It only works for the unspecified urls.
And I saw a method that I can put the authChecker between the route and the route handler,
such as:
app.get("/", authChecker, routes.index);

But How can I achieve it in a simple way rather than putting the authChecker in every route?

A: As long as
app.use(authChecker);

is before
app.use(app.router);

it will get called for every request.  However, you will get the "too many redirects" because it is being called for ALL ROUTES, including /auth.  So in order to get around this, I would suggest modifying the function to something like:
function authChecker(req, res, next) {
    if (req.session.auth || req.path==='/auth') {
        next();
    } else {
       res.redirect("/auth");
    }
}

This way you won't redirect for the auth url as well.

A: There are may ways to approach this problem but here is what works for me.
I like to create an array of middleware for protected and unprotected routes and then use when necessary.
var protected   = [authChecker, fetchUserObject, ...]
var unprotected = [...]

app.get("/", unprotected, function(req, res){
  // display landing page
})

app.get("/dashboard", protected, function(req, res){
  // display private page (if they get this far)
})

app.get("/auth", unprotected, function(req, res){
  // display login form
})

app.put("/auth", unprotected, function(req, res){
  // if authentication successful redirect to dashboard
  // otherwise display login form again with validation errors
})

This makes it easy to extend functionality for each middleware scopes by editing the array for each type of route. It also makes the function of each route more clear because it tells us the type of route it is.
Hope this helps.

A:
But when I used an individually middleware to check the authorization, it's useless for the already existing routes

Express will run middleware in the order added to the stack. The router is one of these middleware functions. As long as you get your authChecker into the stack BEFORE the router, it will be used by all routes and things will work.
Most likely you have the router before authChecker because you have routes defined prior to getting your authChecker into the stack. Make sure to put all your app.use calls before any calls to app.get, app.post, etc to avoid express's infuriating implicit injection of the router into the middleware stack.


text:
Q: How To use any Parameter value for VaryByParam in caching page? <%@ OutputCache Duration="10" VaryByParam="Button1" %>

I type the above code to vary text of Button but it does not vary the value .

A: VaryByParam refers to query string parameters. Not the value of buttons or other controls.
For example:
http://www.example.com/mypage.aspx?id=10
http://www.example.com/mypage.aspx?id=20

Would be cached separately if you set:
<%@ OutputCache Duration="10" VaryByParam="id" %>


text:
Q: How to use the dot notation to call a Cordova plugin? I have a project where I'm using Ionic2 / Cordova Plugins / Android.
$ mkdir stackoverflow-question
$ cd stackoverflow-question
$ git clone https://github.com/napolev/stackoverflow-question.git .
$ npm install
$ ionic platform add android
$ ionic run android -l

This project works properly. It is basically a Hello World project. When you click the button on the screen you get the message Hello, World returned by a Cordova plugin.
My problem is that on the line 17:
https://github.com/napolev/stackoverflow-question/blob/75ecff023a250e14752762582a078d038957c89a/src/pages/home/home.ts#L17
I wanna use:
window.hello.greet(...)
instead of
window["hello"].greet(...)
but when I use: window.hello.greet(...) I get the error:
Property 'hello' does not exist on type 'Window'.

As you can see on the following image:

Any idea on how to use the dot notation to make use of a custom Cordova plugin?
[EDIT 1]
As per @sebaferreras suggestion on his comment I changed the code in the following way and it is working properly:
import { Component } from "@angular/core";
import { NavController } from "ionic-angular";

@Component( {
    selector: "page-home",
    templateUrl: "home.html",
})
export class HomePage {

    private window: any = window;
    private greet: string;

    constructor(
        public navCtrl: NavController,
    ) {}

    private doGreet() {
        this.window.hello.greet("World", (message) => {
            this.greet = message;
        }, () => {
            this.greet = "[ERROR]";
        });
    }
}

but I would like to know:

*

*is it a good practice to do: private window: any = window;

*is there any other type more specific than any that I can use on the line above?

A: Since that error is just Typescript complaining about knowing nothing of a hello property in the window object, you can cast the window object to any like this:
(<any>window).hello.greet(...)

Edit
If you want to avoid the cast to any, you could create your own class based on the Window class like this:
export interface IGreetingService {
    greet(): void; // Here you can add any function signature
}

export class CustomWindow extends Window {
    hello: IGreetingService;
}

Then you could use it like this:
(<any>CustomWindow).hello.greet(...)

Or
private window: CustomWindow = window; // The cast is being done here!
this.window.hello.greet(...)

A: Usually you use custom plugins in Ionic/Cordova like this:
Add following line at the top of your file:
declare var NameOfTheJsModule

You can find the name of the js-module in plugin.xml of the plugin under the name property:
<js-module src="www/inappbrowser.js" name="inappbrowser">
  ...
</js-module>

so in this case:
delcare var inappbrowser;

and to use it e.g.:
this.inappbrowser.show();


text:
Q: Static function was declared but never referenced error For the following code in C:
file.h
// declaration of extern function
extern void extFunc();

file.c
#include "file.h"

// declaration of static function
static void localFunc(uint32_t const input);

// definition of static function
void localFunc(uint32_t const input)
{
   // do something
}

// definition of extern function
void extFunc()
{
  // do something
}

When I compile the above code for ARM ISA target, I get compiler error saying

Error[Pe177]: function "localFunc" was declared but never referenced in C:\Users\admin\git\file.c

How to get rid of it ?

A:

Error[Pe177]: function "localFunc" was declared but never referenced in C:\Users\admin\git\file.c

How to get rid of it ?

localFunc() is declared static.  This means that the version of that function appearing in file.c is not accessible by name from other translation units.  Your compiler is telling you that it is not accessed by name from the same translation unit either, and no pointer by which it could be called is exposed, so the function definitely is not called at all.  It is dead code.
Normally this kind of issue warrants a warning instead of an error, but perhaps your compiler is especially strict, or you have enabled an option turns warnings into errors, so as to force you to resolve all diagnostics that otherwise would be just warnings.  In any event, there are several possible solutions, but these are the most likely:

*

*Delete localFunc() and its forward declaration from file.c, or comment them out, or suppress them via conditional compilation directives.  This assumes that it is intentional that they are going unused.

*Insert live code that calls localFunc().  This only makes sense if it was some kind of mistake that localFunc() was not being called within the translation unit already.


text:
Q: xlsx to pdf with python in an aws lambda? I saw websites proposing this service. Can't we mimic it ?
It seems like we always need Windows so we have to make an EC2 to make it work ? I didn't find A win32 layer for the AWS Lambda.
xlsx to pdf


text:
Q: Unique object identifiers from a for loop I am trying to create unique objects from each row read out of a CSV file.
The problem is creating a unique ID for each object. I thought of creating a list with all my objects first, but I don't always know how many items are contained within the CSV file. How can I generate a unique ID for each object that isn't random? I understand that I can't use a string to define an object, but I don't know how to get around that.
class House():
    def __init__(self,x,y,number,price):
        self.x = x
        self.y = y
        self.number = number
        self.price = price

    def __str__(self):
        result = " Latitude: {} '\n' Longitude: {} '\n' Price: {} '\n' House Number: {}".format(self.x,self.y,self.price,self.number)
        return result

def acquire_data():
    with open('example.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    for row in reader:
        main= "House{}".format(int(row[2]))
        main = House(row[0],row[1],row[2],row[3])
        print row

A: EDIT after long discussion
(...)

def acquire_data():
    with open('example.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    houses = {}
    for row in reader:
        housenumber = int(row[2])
        house = House(row[0],row[1],row[2],row[3])
        houses[housenumber] = house

    print houses[5]   # print house number 5
    print houses[5].price   # print price of house number 5

A: class House():
    def __init__(self,x,y,number,price,id):
        self.x = x
        self.y = y
        self.number = number
        self.price = price
        self.id = id

    def __str__(self):
        result = " Latitude: {} '\n' Longitude: {} '\n' Price: {} '\n' House Number: {}".format(self.x,self.y,self.price,self.number)
        return result

def acquire_data():
    with open('example.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    houses = {}
    for row in reader:
        #main= "House{}".format(int(row[2]))
        tmp = House(row[0],row[1],row[2],row[3],id)
        houses[id] = tmp
        id += 1
        print row
    return houses


text:
Q: Complete set of commutating obsevables and Uncertainity Relation In quantum mechanics, I read that when operators corresponding to observable commute, then they form a complete set that can define the state of the system.
But in the case of $1$ dimension, we say that, since $\hat{x}$ (position) and $\hat{p}$ (momentum) don't commute, so to define the state of a system, we only need one of them.
Since, $\Delta X \Delta P = \dfrac{h}{4\pi}$, the "uncertainty" in position and momentum is bound by uncertainty relation, knowing uncertainty in one, we can calculate minimum uncertainty in other, but knowing the expectation value of one, will not allow us to calculate the expectation value of other. Then how can only one of them, represent the complete state of a system?

A: When we say that you can completely specify the state of a system using a complete set of commuting operators, we can mean two related (almost equivalent) things:

*

*If a given state is a simultaneous eigenstate of the complete set of commuting operators, then the eigenvalues associated with the state corresponding to each of the operators (in the complete set of commuting operators) completely characterizes the system. For example, in the one dimensional case you mention, if you know that the state is an eigenstate of position operator with eigenvalue $x_0$ then you know the state completely, in particular, it would be $\delta(x-x_0)$ in position basis. You can calculate everything of interest using this. Similarly, if you know that the the state is an eigenstate of momentum operator with eigenvalue $p_0$ then you know the state completely, in particular, it would be $\exp(ip_0x)$ in position basis. You can calculate everything of interest using this as well.

*Now, if the given state is not a shared eigenstate of a given complete set of commuting operators then you can still completely characterize the given state by listing the inner product of the given state with the eigenstates of the complete set of commuting operators. For example, in your example, since the position operator forms a complete set of commuting operators, for a generic state $\vert \psi \rangle$, you can completely characterize it by listing $\langle x \vert \psi \rangle = \psi(x)$ for all $x$. You can calculate everything of interest using $\psi(x)$ as you know.
The reason I said that the two bullet points are equivalent is that even if a given state is not a shared eigenstate of a given complete set of commuting operators, you can always find another complete set of commuting operators (which might not be physically interesting) and characterize the given state by listing the associated eigenvalues of the operators in this other set. Now, you can find the inner products of the given state with the eigenstates of the original complete set of commuting operators by a change of basis from the basis spanned by the other complete set of commuting operators to the original complete set of commuting operators.
Finally, when we say that a complete set of commuting operators can be used to fully characterize a state, it doesn't mean that knowing the expectation values of each of the operators would determine the state completely (so that you can calculate expectation values of any generic operator). In order to do something like that, you need a tomographically complete set of operators, i.e., a set of operators that form an operator basis for the vector space of operators on a Hilbert space. See a related recent question of mine: How to recognize a tomographically complete set of operators?


text:
Q: Error instantiating java chain-code of fabric-samples I am having trouble instantiating java chain code on fabric 1.4.3, I did not changed anything, not even the names of the organisations or the channel.
Following are the steps that I followed:

*

*download binaries using command curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/scripts/bootstrap.sh | bash -s

*set the path export PATH=/bin:$PATH

*cd fabric-samples/fabcar

*run the script ./startfabric.sh java
Then I get this error while instantiating the java chain code

Error: could not assemble transaction, err proposal response was not successful, error code 500, msg chaincode registration failed: container exited with 1

Although I can install and run the javascript chain code provided in fabcar sample perfectly.
Platform information
Fabric-samples branch : release-1.4
Docker: 19.03.2
Go version: go1.12.7 darwin/amd64
Node version: v8.16.0
OS: Mac Mojave

A: I had same issue with Fabric-samples branch 1.4 on fabric 1.4.4 .
I updated following dependency from 1.4.3 to 1.4.4 in build.gradle file which solved the issue.
dependencies {
    implementation 'org.hyperledger.fabric-chaincode-java:fabric-chaincode-shim:1.4.4'
}


text:
Q: Find out what actual font used for Java font I create a font object in Java using
new Font("Arial, Helvetica, Helv", 1, 10);

Neither Arial nor Helvetica is installed on my computer. How do I find out what actual font gets used? Does OpenJDK have it's own fonts?

A: As I know OpenJDK is not shipped with font like Oracle JDK, so very likely you are loading your font from your operating system.
Are you sure what is being displayed is "Arial, Helvetica, Helv"? Base on Java Doc, if the font cannot be found, Java will try to load the closer font family/face, or proceed with some algorithm to achieve the desired style. You can check the link to read more.


text:
Q: jQuery modify image's parent a tag depending on image src I have a page that loads an image at random. With jQuery, I'd like to check the image's src and, depending on what that src contains, modify the href of the image's parent a tag.
Here's what I've written so far, with no luck:

jQuery(document).ready(function($) {
    $('.hero .inner a img').each(function(i){
        var img = $(this),
        imgSrc = img.attr('src');

        if(imgSrc.contains('copy-2.png')){
            img.parent().attr('href', 'http://google.com');
        }
     }
}

A: Try with this:
http://jsfiddle.net/RLQLh/5/
and with http://jsfiddle.net/RLQLh/6/
with your selector
$('.hero .inner a img').each(function(i){

both use
if(imgSrc.indexOf('copy-2.pn') !== -1)

instead of string Contains()

A: Try this:
$(document).ready(function () {
    $('img').each(function(){
        var img = $(this);
        var imgSrc = img.attr('src');

        if(imgSrc.contains('copy-2.png')){
            img.parent('a').attr('href', 'http://google.com');
        }
     });
});


text:
Q: How to read binary files from HTTP using C/C++ sockets I'm writing Http-Client which takes URL on somefile, download it and save it on a disk. Like curl does.
I can use only C/C++ with std:: and libc. I have no problems with downloading text files like XML, CSV or txt, because they were saved like it should be and if to open them in editor - it's ok, there's that text which was expected. But when i download tar or pdf and trying to open them, it tells that files are corrupted.
Here's 2 main methods of my class HttpClient. HttpClient::get - send Http-request to the host, which is mentioned in URL, and calls the 2nd main method - HttpClient::receive which defines what kind of data there is - binary or text, and write whole Http-request body in a file using binary or text mode.
All other methods i decided not to show, but i can if someone needs.
HttpClient::get:
bool HttpClient::get() {
    std::string protocol = getProtocol();
    if (protocol != "http://") {
        std::cerr << "Don't support no HTTP protocol" << std::endl;
        return false;
    }
    std::string host_name = getHost();

    std::string request = "GET ";
    request += url + " HTTP/" + HTTP_VERSION + "\r\n";
    request += "Host: " + host_name + "\r\n";
    request += "Accept-Encoding: gzip\r\n";
    request += "Connection: close\r\n";
    request += "\r\n";

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cerr << "Can't create socket" << std::endl;
        return false;
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(HTTP_PORT);

    raw_host = gethostbyname(host_name.c_str());
    if (raw_host == NULL) {
        std::cerr << "No such host: " << host_name << std::endl;
        return false;
    }

    if (!this->connect()) {
        std::cerr << "Can't connect" << std::endl;
        return false;
    } else {
        std::cout << "Connection established" << std::endl;
    }

    if (!sendAll(request)) {
        std::cerr << "Error while sending HTTP request" << std::endl;
        return false;
    }

    if (!receive()) {
        std::cerr << "Error while receiving HTTP response" << std::endl;
        return false;
    }

    close(sock);
    return true;
}

HttpClient::receive:
bool HttpClient::receive() {
    char buf[BUF_SIZE];
    std::string response = "";
    std::ofstream file;
    FILE *fd = NULL;

    while (1) {
        size_t bytes_read = recv(sock, buf, BUF_SIZE - 1, 0);

        if (bytes_read < 0)
            return false;

        buf[bytes_read] = '\0';
        if (!file.is_open())
            std::cout << buf;

        if (!file.is_open()) {
            response += buf;
            std::string content = getHeader(response, "Content-Type");

            if (!content.empty()) {
                std::cout << "Content-Type: " << content << std::endl;
                if (content.find("text/") == std::string::npos) {
                    std::cout << "Binary mode" << std::endl;
                    file.open(filename, std::ios::binary);
                }
                else {
                    std::cout << "Text mode" << std::endl;
                    file.open(filename);
                }

                std::string::size_type start_file = response.find("\r\n\r\n");
                file << response.substr(start_file + 4);
            }
        }
        else
            file << buf;
        if (bytes_read == 0) {
            file.close();
            break;
        }
    }
    return true;
}

I can't find help, but i think that binary data is encoded in some way, but how to decode it?

A:
I can't find help, but i think that binary data is encoded in some way, but how to decode it?

You don't explain why you think this way but the following line from your request might cause some encoding you don't handle:

request += "Accept-Encoding: gzip\r\n";

Here you explicitly say that you are willing to accept content encoded (compressed) with gzip. But looking at your code you are not even checking if the content es declared as encoded with gzip by analyzing the Content-Encoding header.
Apart from this the following line might cause a problem too:

request += url + " HTTP/" + HTTP_VERSION + "\r\n";

You don't show what HTTP_VERSION is but assuming that it is 1.1 you also have to deal with Transfer-Encoding: chunked too.

A: Thanks everyone.
I solved this problem by changing response += buf; to response.append(buf, bytes_read); and file << buf; to file.write(buf, bytes_read);.
It was stupid to write binary data like null-terminating string.


text:
Q: What is the meaning of this Code in the Constructor I'm trying the ASP.Net Signalr example. In the example here is a code to improve the signalr performance server side in the Hub.
Here is the Code..
        public class Broadcaster
        {
            private readonly static Lazy<Broadcaster> _instance =
                new Lazy<Broadcaster>(() => new Broadcaster());
            // We're going to broadcast to all clients a maximum of 25 times per second
            private readonly TimeSpan BroadcastInterval =
                TimeSpan.FromMilliseconds(40);
            private readonly IHubContext _hubContext;
            private Timer _broadcastLoop;
            private ShapeModel _model;
            private bool _modelUpdated;
            public Broadcaster()
            {
                // Save our hub context so we can easily use it
                // to send to its connected clients
                _hubContext = GlobalHost.ConnectionManager.GetHubContext<MoveShapeHub>();
                _model = new ShapeModel();
                _modelUpdated = false;
                // Start the broadcast loop
                _broadcastLoop = new Timer(
                    BroadcastShape,
                    null,
                    BroadcastInterval,
                    BroadcastInterval);
            }
            public void BroadcastShape(object state)
            {
                // No need to send anything if our model hasn't changed
                if (_modelUpdated)
                {
                    // This is how we can access the Clients property
                    // in a static hub method or outside of the hub entirely
                    _hubContext.Clients.AllExcept(_model.LastUpdatedBy).updateShape(_model);
                    _modelUpdated = false;
                }
            }
            public void UpdateShape(ShapeModel clientModel)
            {
                _model = clientModel;
                _modelUpdated = true;
            }
            public static Broadcaster Instance
            {
                get
                {
                    return _instance.Value;
                }
            }
        }

        public class MoveShapeHub : Hub
        {
            // Is set via the constructor on each creation
            private Broadcaster _broadcaster;
            public MoveShapeHub()
                : this(Broadcaster.Instance)
            {
            }
            public MoveShapeHub(Broadcaster broadcaster)
            {
                _broadcaster = broadcaster;
            }
            public void UpdateModel(ShapeModel clientModel)
            {
                clientModel.LastUpdatedBy = Context.ConnectionId;
                // Update the shape model within our broadcaster
                _broadcaster.UpdateShape(clientModel);
            }
        }

    public class ShapeModel
    {
        // We declare Left and Top as lowercase with
        // JsonProperty to sync the client and server models
        [JsonProperty("left")]
        public double Left { get; set; }
        [JsonProperty("top")]
        public double Top { get; set; }
        // We don't want the client to get the "LastUpdatedBy" property
        [JsonIgnore]
        public string LastUpdatedBy { get; set; }
    }

I have a question that what is the meaning of this line..
 public MoveShapeHub()
                : this(Broadcaster.Instance)
            {
            }

It says its for set via the constructor on each creation
What does that mean? Is there any other way to write that???

A: This syntax calls another constructor in your class.
This means that a call like this:
public MoveShapeHub() : this(Broadcaster.Instance) {}

Will call this constructor
public MoveShapeHub(Broadcaster broadcaster)


text:
Q: Paper.init is not called Im working on Android Studio app and during my work al last i implement a class that try to print something via a printer bluetooth.
I use the printooth library but when it's time to intent this new activity, it give me thi exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testaapplication0209, PID: 11325
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testaapplication0209/com.example.testaapplication0209.PrintActivity}: io.paperdb.PaperDbException: Paper.init is not called
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2768)

And here my PrintActivity:
public class PrintActivity extends AppCompatActivity implements PrintingCallback {

Printing printing;
Button btnPrint, btnPairUnpair;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_print);
    initView();
}

private void initView() {

    btnPrint = findViewById(R.id.btnPrint);
    btnPairUnpair = findViewById(R.id.btnPairUnpair);

    if (printing != null)
        printing.setPrintingCallback(this);

    //event
    btnPairUnpair.setOnClickListener(view -> {
        if (Printooth.INSTANCE.hasPairedPrinter())
            Printooth.INSTANCE.removeCurrentPrinter();
        else {
            startActivityForResult(new Intent(PrintActivity.this, ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
            changePairAndUnpair();
        }
    });

    btnPrint.setOnClickListener(view -> {
        if (!Printooth.INSTANCE.hasPairedPrinter())
            startActivityForResult(new Intent(PrintActivity.this, ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
        else {
            printData();
        }
    });

    changePairAndUnpair();

}

private void printData() {
    ArrayList<Printable> printables = new ArrayList<>();
    printables.add(new RawPrintable.Builder(new byte[]{27,100,4}).build());

    //Add Text
    printables.add(new TextPrintable.Builder()
            .setText("Hello World").setCharacterCode(DefaultPrinter.Companion.getCHARCODE_PC1252())
            .setNewLinesAfter(1)
            .build()
    );

    //Custom Text
    printables.add(new TextPrintable.Builder()
    .setText("Hello World custom text")
    .setLineSpacing(DefaultPrinter.Companion.getLINE_SPACING_60())
    .setAlignment(DefaultPrinter.Companion.getALIGNMENT_CENTER())
    .setEmphasizedMode(DefaultPrinter.Companion.getEMPHASIZED_MODE_BOLD())
    .setUnderlined(DefaultPrinter.Companion.getUNDERLINED_MODE_ON())
    .setNewLinesAfter(1)
    .build());

    printing.print(printables);
}

private void changePairAndUnpair() {
    if (Printooth.INSTANCE.hasPairedPrinter()){
        btnPairUnpair.setText(new StringBuilder("Dissocia").append(Printooth.INSTANCE.getPairedPrinter().getName().toString()));
    } else {
        btnPairUnpair.setText("Associa Stampante");
    }
}

@Override
public void connectingWithPrinter() {
    Toast.makeText(this, "Connesione alla stampante", Toast.LENGTH_SHORT).show();
}

@Override
public void connectionFailed(String s) {
    Toast.makeText(this, "CFailerd: " +s, Toast.LENGTH_SHORT).show();
}

@Override
public void onError(String s) {
    Toast.makeText(this, "Error: " +s, Toast.LENGTH_SHORT).show();
}

@Override
public void onMessage(String s) {
    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}

@Override
public void printingOrderSentSuccessfully() {
    Toast.makeText(this, "Ordine mandato alla stampante", Toast.LENGTH_SHORT).show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == ScanningActivity.SCANNING_FOR_PRINTER && resultCode == Activity.RESULT_OK)
        initPrinting();
    changePairAndUnpair();
}

private void initPrinting() {
    if(!Printooth.INSTANCE.hasPairedPrinter())
        printing = Printooth.INSTANCE.printer();
    if (printing != null)
        printing.setPrintingCallback(this);
}
}

and here in ApplicationPrintActivity where i instance the printooth:
public class ApplicationPrintActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Printooth.INSTANCE.init(this);

}
}

A: Not an Android developer but this seems more of a mis-understanding.
PrintActivity directly extends AppCompatActivity, it doesn't "pass-by" ApplicationPrintActivity#onCreate, and thus Paper.init isn't called, at all.
Edit PrintActivity#onCreate to include that call.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Printooth.INSTANCE.init(this);

    setContentView(R.layout.activity_print);
    initView();
}


text:
Q: Remember user in Ionic Firebase app I'm writing an Ionic app using Firebase as the back end and am struggling trying to keep users logged in.
I've tested on Android only at the moment.
When the app launches, I log the user in with firebase.auth().signInWithEmailAndPassword.
After logging in, if the user presses the physical back button a couple of times to close the app, then they launch the app again, they have to log in again because the app has lost their credentials (firebase.auth().currentUser is null).
I'd like the app to remember the user on the device when they have logged in, and only log them out if they specifically hit the app logout button.
Here's the code in my app.js
angular.module('starter', [
    'ionic',
    'firebase',
    'starter.loginController',
    'starter.resetemailController',
    'starter.signupController',
    'starter.dashboardController',
    'starter.sidebarController'
])

.run(function ($ionicPlatform, $rootScope, $state, CONFIG) {
    $ionicPlatform.ready(function () {
        if (window.cordova && window.cordova.plugins.Keyboard) {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            // Don't remove this line unless you know what you are doing. It stops the viewport
            // from snapping when text inputs are focused. Ionic handles this internally for
            // a much nicer keyboard experience.
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
    });

    // on stateChange event if state requires authentication and user not logged in, go to login state
    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        var user = firebase.auth().currentUser;
        if (toState.authRequired && !user) {
            $state.go("login");
            event.preventDefault();
        }
    });

    // initialise firebase
    firebase.initializeApp({
        apiKey: 'xxxxxxxxx',
        authDomain: 'xxxxxxx.firebaseapp.com',
        databaseURL: 'https://xxxxxx.firebaseio.com',
        storageBucket: 'xxxxxxxxxx.appspot.com',
        messagingSenderId: 'xxxxxxxxxxxxxx'
    });

})

.config(['$stateProvider', '$urlRouterProvider', '$ionicConfigProvider', function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

    $ionicConfigProvider.navBar.alignTitle('center');

    $stateProvider

    .state('app', {
        url: '/app',
        abstract: true,
        templateUrl: 'shared/sidebar/sidebarView.html',
        controller: 'sidebarController'
    })

    .state('app.dashboard', {
        url: '/dashboard',
        views: {
            'menuContent': {
                templateUrl: "components/dashboard/dashboardView.html",
                controller: "dashboardController"
            }
        },
        authRequired: true
    })

    .state('login', {
        cache: false,
        url: '/login',
        templateUrl: "components/login/loginView.html",
        controller: "loginController"
    })

    .state('signup', {
        url: '/signup',
        templateUrl: "components/signup/signupView.html",
        controller: "signupController"
    })

    .state('reset', {
        url: '/reset',
        templateUrl: "components/resetemail/resetemailView.html",
        controller: "resetemailController"
    })

    // this is a workaround to prevent the $stateChangeStart firing multiple times
    $urlRouterProvider.otherwise(function ($injector) {
        var $state = $injector.get('$state');
        $state.go('app.dashboard');
    });

}])

When the user logs in, the $urlRouterProvider.otherwise makes the app go to the dashboard as the initial state.
The following code re-routes to the login state if the user is null
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
    var user = firebase.auth().currentUser;
    if (toState.authRequired && !user) {
        $state.go("login");
        event.preventDefault();
    }
});

This all works great, but once the user closes the app, I want the app to remember the user so next time they launch, they will go straight to the dashboard state rather than having to log in each time.
I don't store anything at the moment when a user logs in - do I need to store some credentials in local storage or something?
I've read about JWT but I don't fully understand how to create or use them.
I've seen some posts mention firebase.auth().currentUser.getToken(true) but again, I don't know what to do with it - do I need to store this token somewhere after login?
Sorry if this is all a bit vague; I'm really new to this and much of it is over my head at the moment.


text:
Q: Infinispan equivalent of IMap.values(Predicate) Is there an equivalent of Hazelcast's IMap.values(Predicate) for Infinispan ? And possibly non-blocking (async) ?
Thanks.

A: It depends on what you trying to do. Infinispan extends Java's Stream functionality so you can use the Stream interface to get the filtered values.
Examples
//filter by key
cache.values().stream()
    .filterKeys(/*set with keys*/)
    .forEach(/*do something with the value*/) //or collect()

//filter by key and value
cache.getAdvancedCache().cacheEntrySet().stream()
    .filter(entry -> /*check key and value using entry.getKey() or entry.getValue()*/)
    .map(StreamMarshalling.entryToValueFunction()) //extract the value only
    .forEach(/*do something with the value*/; //or collect()

Infinispan documentation about streams here.


text:
Q: how to save id in controller? I have a action which i am calling it  two time
Controller.php
UserController extends Controller {
    public actionCopy($id = false){

    if($id){
    //redireting to a view
    }
    else{
    //rediredtion to a differnet view
    }

    }
}

I am getting a id first then from first view i am again coming to Copy action with no id so else part is running nw but in this i want to get the $id which i get from first request.
I have tried to define a global variable in controller like
Controller.php
    UserController extends Controller {
public $user;
        public actionCopy($id= false){

        if($id){
    $this->user = $id;
        //redireting to a view
        }
        else{
        echo $this->user ;// but it has nothing
        //rediredtion to a differnet view
        }

        }

    }

and set it like this.
I know that if condition is not executing so $id has no value but i set $this->user first time then why it has no value.
Any help is appreaciated

A: Just try this,
class UserController extends Controller {
    public actionCopy($id = false){
        if($id){
            //set up a session here
            Yii::app()->session['_data_id'] = $id;

            //remaining code here
        }
        else{
            $id=isset(Yii::app()->session['_data_id'])?Yii::app()->session['_data_id']:NULL; // the id you want from previous request
            if($id!=NULL){
                //remaining code
                unset(Yii::app()->session['_data_id']); //clear it after use
            }
        }
    }
}


text:
Q: Scraping a web page using Beautiful soup import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
url = input('Enter -')
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html,'html.parser')

tags = soup('a')
for tag in tags:
    print(tag.get('herf',None))

I used this link to test my code http://www.dr-chuck.com/page1.htm
The output is: NONE
the output should be this link http://www.dr-chuck.com/page2.htm

A: Simple typo, there.
Change 'herf'to 'href'in tags.get
  import urllib.request, urllib.parse, urllib.error
    from bs4 import BeautifulSoup
    url = input('Enter -')
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html,'html.parser')

    tags = soup('a')
    for tag in tags:
        print(tag.get('href',None))

outputs
#http://www.dr-chuck.com/page2.htm


text:
Q: Hotfix installation on SharePoint 2010 farm? We are going to install the hotfix - http://support.microsoft.com/kb/2553031, would like to clarify few points.

*

*does the SharePoint & IIS services need to be stopped before installing?

*do need to follow any sequence like start with CA server, index, query, app & WFEs?

*shall we run parallelly on the servers?

*do we need to run the configuration wizard on the servers in the same sequence?

*does the system reboot required?

*does it change the DB schema?

*how to rollback if it does not installed successfully?

*is there any known issue with this hotfix?

A: 1) No
2) No
3) Sure
4) No
5) Possibly
6) Yes
7) Rebuild farm and restore from backup (you did back up before installing, right?)
8) Go straight to the December CU instead

A: To address point 7 specifically, if your entire farm is virtualized as most are these days then you can simply take snapshots of the VMs prior to applying the patch.  Naturally, you should also have full SQL Backups as well, just in case.
Also, you should apply the patch to a dev or QA farm prior to applying it to production.  Not only does this give you a chance to test the patch, but it also would would answer most of the questions you list.


text:
Q: Pass get parameter to controler in Laravel How do I pass a get variable to a controller in Laravel?
I have:
$languages = array('zh');
$locale = Request::segment(1);
if (in_array($locale, $languages)) {
    App::setLocale($locale);
} else {
    $locale = null;
}
Route::group(array('prefix' => $locale), function() {
    ...
    Route::get('/search/{q}', array('as' => 'search', 'uses' => 'ProductsController@index'));
    ...
});

If I try to return q from within the controller using Input::get('q'); I get nothing.

A: Route::get('/search/{q}', array('as' => 'search', 'uses' => 'ProductsController@index'));

the {q} here isn't GET variable.
you can take the value like this.
public function index($q)
{
     echo $q;
}

A: It's not a GET parameter but an URL parameter. There's a little difference in that.
Url paramters will be passed (in the order they appear) to the controller action.
So all you have to do, is use the argument that gets automatically passed to the function in the controller.
public function index($q){
    echo $q;
}


text:
Q: How to use Git push/pull with source(text) files only? I guess its actually two questions:
(1) My IDE generates a particular directory structure (which I don't want to alter) with files of different types which are mainly of two kind ... i.e. source(text) vs. binary. I want to work with an online git repository. Whats the best git practice to push/pull only the first kind of files (source/text type) and completely ignore the human non-readable kinds of files like binaries ?
(2) Isn't it better and simpler to have all the  project file types generated by my IDE (text + binary) under source control when working with remote repositories as backups etc?
Note: I am using msysgit/Gitbash command line git on windows 7 with visualC#/.net and Monodevelop/mono as IDEs

A: (1) You can tell git to simply ignore the binary files by placing expressions in a .gitignore file as described in the git docs.
(2) Typically, it's better to not check in files that are generated by your IDE or build process, since it's easy to regenerate them and it's a maintenance headache when your IDE changes the files between check-ins.


text:
Q: addEventListener method with dynamically created table I am new to addEventListener method. I am trying to use onClick event on my dynamically created js table to change the cell values, but table vanishes when I put the addeventlistener code line inside the function. I am trying to give each cell a dynamic id.and then add an addeventlistener method using these lines of code:
s.setAttribute('id',"tab"+v);
         document.getElementById("tab"+v).addEventListeners("click",function(){var g=document.getElementById("tab"+v);
         g.innerHTML="changed";},false);

        v++;

Can anyone explain to me how can I solve this?
<html>
<head>
<title>table dynamic</title>
<style>
*{margin:0px;padding:0px;}

.tableShape{
    width:300px;
    height:300px;
    font-size:30px;
    text-align:centre;
    color:red;
    border:1px solid red;

}
.rowShape{height:33%;width:33%;border:1px solid black;}

</style>
</head>
<body>
<script>
var i,j,v=1;
var arr=new Array(3);
for(i=0;i<3;i++){
arr[i]=new Array(3);
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
arr[i][j]=1;
}}

function tabs(){
   var k,t;
    var m=document.createElement("table");
    m.setAttribute('class',"tableShape");

    for(var  k = 0;k < 3; k++){
    var p=m.insertRow(k);
       for( var t = 0;t < 3; t++){
         var s=p.insertCell(t);
         s.setAttribute('class',"rowShape");
        s.innerHTML+=arr[k][t];
    s.setAttribute('id',"tab"+v);
         document.getElementById("tab"+v).addEventListeners("click",function(){var g=document.getElementById("tab"+v);
         g.innerHTML="changed";},false);

        v++;
         }
         }
         document.body.appendChild(m);
    }

    window.onLoad=tabs();
</script>
</body>
</html>

A: You have to be aware of the fact, that the callback function you give as parameter to addEventListener() is first evaluated when the event happened - so it then takes the value of "v".
What you need is a local copy of v's value - you can achieve this by a closure, like this:
s.setAttribute('id', "tab" + v);
document.getElementById("tab" + v).addEventListeners("click", (function(val) {
        return function() {
            var g = document.getElementById("tab" + val);
            g.innerHTML = "changed";
        };
        })(v), false);

    v++;

You can find a simple example closure here: http://jsfiddle.net/9JAG2/
Cheers
Florian


text:
Q: FormatException: Invalid character (at character 12) in Dart/flutter I am trying to build the following URI in flutter but a got an error.
the code:
void main() {
String APIHOST = 'hammbwdsc02/visoon-backend';
var uri = Uri.https(APIHOST, '/path', {'q': 'dart'});
print(uri);
}

(this code is tested: https://dartpad.dev/?null_safety=true)
output:
Uncaught Error: FormatException: Invalid character (at character 12)
hammbwdsc02/visoon-backend
           ^

Does someone know why am I getting this error?

A: As explained by julemand101 in the comments, hostnames cannot contain the / character.
In your example the hostname should be hammbwsc02 and the visoon-backend should be added to the path. Like so:
void main() {
  String APIHOST = 'hammbwdsc02';
  var uri = Uri.https(APIHOST, '/visoon-backend/path', {'q': 'dart'});
  print(uri);
}

The structure of the URL is explained in more detail here: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL


text:
Q: Copy-to-clipboard and downloadhandler not working when Shiny App deployed on Ubuntu server I developed my Shiny apps in Windows. All features (including copy-to-clipboard and download buttons) work as expected.
However, when I deploy it in our AWS Server (ubuntu), the copy-to-clipboard and download buttons fail.
Any ideas? Thanks!
shiny::observeEvent(input$copy_cross, {
clipr::write_clip(eval(parse(text = "x = as.data.frame.matrix(table(sel()[,1],sel()[,2]))")), row.names= T, col.names = NA)
})

output$download_cross <- shiny::downloadHandler(
  filename = function() {paste("Crosstabs (Counts).xlsx")},
  content  = function(file) {
    openxlsx::write.xlsx(x = as.data.frame.matrix(table(sel()[,1],sel()[,2])), file, sheetName = "Crosstabs", row.names= T, col.names = T, append=F)
  }
)

I also tried using xclip as suggested in this article
How to write to clipboard on Ubuntu/Linux in R?. However, it's also not working.


text:
Q: How to test Sql server 2005 queries when you have 2008 r2 installed I have installed sql server 2008 r2 Management studio but the server has sql server 2005 database. Is there any why i can test the queries which will work on sql server 2005 that i write in sql server 2008.
I have sample queries which work in sql server 2008 but not in 2005.
CREATE TABLE #Tmp
(
    NoOfMembers int,
    AverageAge int
)
insert into #Tmp(NoOfMembers,AverageAge)

Values((Select Count(*)NoOfMembers  From Customer where Confirmed = 1),
(Select AVG(CONVERT(int,Age)) AverageAge From Customer where Confirmed = 1)
)
select * From #Tmp

Any help
Thanx in advance

A: You can use the sql 2008 management studio against a 2005 sql server without problems. If your SQL statement is fired against the database and do not work in sql 2005, the server will answer with an error message.
If you have a sql 2008 and want to test against 2005 you can set compatibility mode to 2005, that works as well.
Your posted sql statement want to use a subquery in your values part. That don't work on sql2005 and produce a error. If you need this in 2005, create a scalar function e.g. and use this instead.
EDIT:
Well if you want to insert data into a table using a sql at all without the VALUESstatement you can do it like this:
CREATE TABLE #Tmp
(
    NoOfMembers int,
    AverageAge int
)

INSERT INTO #Tmp(NoOfMembers,AverageAge)
SELECT COUNT(*), AVG(CONVERT(int,Age))
FROM Customer WHERE Confirmed = 1

SELECT * FROM #Tmp

A:
Well this is how you can make it work on SQL Server 2005.

CREATE TABLE #Tmp
(
    NoOfMembers int,
    AverageAge int
)

insert into #Tmp(NoOfMembers,AverageAge)
    (Select Count(*), AVG(CONVERT(int,Age)) From Customer where Confirmed = 1)

select * From #Tmp


text:
Q: Using IPMI inside a python script (OpenIPMI) I'd like to use IPMI to set a machine to PXE boot (i.e. ipmitool -I lan -U username -P password -H ipaddress chassis bootdev pxe) and then power cycle it (i.e. ipmitool -I lan -U username -P password -H ipaddress chassis power cycle).  However, I'd like to do this in a python script so I'm trying to use OpenIPMI and its python bindings.
I can't seem to find any documentation on OpenIPMI for a python script and I'm not sure how to correctly apply IPMI commands (making sure the machine is in the right state so the commands don't fail).  Can someone please show me some pointers or resources on using OpenIPMI (or an alternative) to operate IPMI commands in python?  Thanks!

A: For something so simple it is much easier to just run those commands using the subprocess module.
However, if you still choose the openimpi module here is an example of how to use it:
http://www.mail-archive.com/ipmitool-devel@lists.sourceforge.net/msg01445.html

A: I found the document IPMI – A Gentle Introduction with OpenIPMI very helpful. It gives good understanding where/how to get the information. As I understood Python can talk to "shared Library" over using Swig. I hope it will help you.


text:
Q: Spring MVC, Spring Security, Simply Require Username I have a Spring 3 MVC website using Spring Security 3.1.0RC2. Currently I am using the org.springframework.security.ldap.authentication.ad.ActiveDirectoryAuthenticationProvider for log-in. For demo purposes, my boss just wants to have to enter a username (any username) and not have it validated against anything, instead, just grant access. Is there some way I can make sure the user entered a username and that's it?

A: Why not just write your own AuthenticationProvider.
class MyAuthProvider implements AuthenticationProvider {
    public Authentication authenticate(Authentication authentication) {
        // add code to populate GrantedAuthority list if needed.
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new GrantedAuthorityImpl("ROLE_1"));
        authorities.add(new GrantedAuthorityImpl("ROLE_2"));
        authorities.add(new GrantedAuthorityImpl("ROLE_3"));
        return new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(),
            authentication.getCredentials(),
            authorities);

    }

    public boolean supports(Class<?> authentication) {
        return true;
    }
}

In your spring security config:
<security:authentication-manager>
    <security:authentication-provider ref="myAuthenticationProvider" />
</security:authentication-manager>
<bean id="myAuthenticationProvider" class="MyAuthProvider"/>

UPDATE 1
See above for how to add authorities (granted roles) to the user.


text:
Q: Retrieving PlotRange from BarChart in Mathematica 11 Further to the accepted answer to this question: Retrieving PlotRange from BarChart, how can this be done in version 11?
In version 7 it worked like this.

In version 11 it doesn't work.

Code for copy & paste
bc = BarChart[{1, 2, 3, 4}, PerformanceGoal -> "Speed"];
Options[bc, PlotRange]
AbsoluteOptions[bc, PlotRange]

Further to J.M.'s comment Charting`get2DPlotRange[] is not a perfect replacement for AbsoluteOptions although it is of some use.
Here is a more complex example for illustration:
vals = {37.0186, 40.9317, -56.0248, -21.9255};
{vmin, vmax} = Through[{Min, Max}[vals]];
interval = If[Max[0, vmax] - Min[0, vmin] > 50, 20, 10];
frameticks = {#, #, {0, 0.01}} & /@ ((Range[21] - 11)*interval);
f[l_, p_, r_] := BarChart[vals, LabelingFunction -> (Placed[Round[#1],
       If[Round[#1] < 1, l, After]] &), BarOrigin -> Left,
   BarSpacing -> 0.8, PlotRangePadding -> {interval, p},
   Frame -> {{False, False}, {True, False}}, Ticks -> None,
   FrameTicks -> {{None, None}, {frameticks, None}},
   PerformanceGoal -> "Speed", PlotRange -> {All, r}];

in Version 7
Print[chart = f[Right, 0.4, {0, 6.4}]];
PlotRange /. AbsoluteOptions[chart, PlotRange]

{{-56.0248, 40.9317}, {0., 6.4}}

in Version 11
chart = f[Before, 0, {0.5, 4.5}];
Print[Show[chart,
   Graphics[{GrayLevel[0.3], AbsoluteThickness[0.25],
     Style[Line[{{0, 0.5}, {0, 4.5}}], Antialiasing -> False]}]]];
Charting`get2DPlotRange[chart]

{{-76.0248, 60.9317}, {0.722222, 4.27778}}

However, further to rcollyer's comment
Charting`get2DPlotRange[chart, False]

{{-56.0248, 40.9317}, {0.722222, 4.27778}}

The x minimum and maximum match version 7.

A: You could use my function graphicsInformation to do this:
bc=BarChart[{1,2,3,4},PerformanceGoal->"Speed"];
"PlotRange" /. graphicsInformation[bc]

{{-0.0840242, 5.09461}, {-0.0860215, 4.21505}}

For your other examples:
"PlotRange" /. graphicsInformation[f[Right, 0.4, {0, 6.4}]]
"PlotRange" /. graphicsInformation[f[Before,0,{0.5,4.5}]]

{{-76.0248, 60.9317}, {-0.4, 6.8}}
{{-76.0248, 60.9317}, {0.5, 4.5}}


text:
Q: Submit form twice display error of blank input I made a form for my website using php, Ajax & jquery. When i submit the form with some inputs 1st time it works fine and but the second time without reloading the page it shows errors. The html input tags are simple with using class id and type attr.
What i want here is the code also runs for the second time if user submit form.
php and jquery:
 if(isset($_POST['submit'])){
        $name = $_POST['name'];
        $website = $_POST['website'];
      //  $category = $_POST['category'];
        $toscheckbox = $_POST['toscheckbox'];

        $errorEmpty = false;
        $website_error = false;
        $name_error = false;
        $toscheckbox_error = false;

        if(empty($name) || empty($website) || empty($toscheckbox)){
            echo "Please fill in all fields!";
            $errorEmpty = true;
        }
        elseif (!filter_var($website, FILTER_VALIDATE_URL)){
            echo "Write a valid URL!";
            $website_error = true;
        }
        elseif (!preg_match("/^[a-zA-Z0-9][a-zA-Z0-9 \t]*$/", $name)) {
          echo "Please check your Website Name";
          $name_error = true;
        }
        else {
            echo "Thanks your submission listed in our Database!";
        }
    }
    else {
        echo "There was something wrong with your form";
    }

EDIT html:
<input class="form-control" id="name" type="text" name="name">
<input name="toscheckbox" class="form-check-input" id="toscheckbox" type="checkbox" value="ToS">
<input class="form-control form-control" id="website" type="text" name="website">


text:
Q: How can I toggle between kubernetes context of various deployed apps? When I deploy each app using kubernetes/cluster/kube-up.sh over aws I set context using :
CONTEXT=$(kubectl config view | grep current-context | awk '{print $2}')

kubectl config set-context $CONTEXT --namespace=${PROJECT_ID}

I do this for multiple apps and each deploys fine.  However I then need to be able to toggle between kubernetes context to interact with an arbitrary deployed app (view logs/ do a kubectl exec )
Here is how to show all my contexts
kubectl config view --output=json

{
    "kind": "Config",
    "apiVersion": "v1",
    "preferences": {},
    "clusters": [
        {
            "name": "aws_kubernetes",
            "cluster": {
                "server": "https://52.87.88.888",
                "certificate-authority-data": "REDACTED"
            }
        },
        {
            "name": "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster",
            "cluster": {
                "server": "https://104.196.888.888",
                "certificate-authority-data": "REDACTED"
            }
        }
    ],
    "users": [
        {
            "name": "aws_kubernetes",
            "user": {
                "client-certificate-data": "REDACTED",
                "client-key-data": "REDACTED",
                "token": "taklamakan"
            }
        },
        {
            "name": "aws_kubernetes-basic-auth",
            "user": {
                "username": "admin",
                "password": "retrogradewaif"
            }
        },
        {
            "name": "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster",
            "user": {
                "client-certificate-data": "REDACTED",
                "client-key-data": "REDACTED",
                "username": "admin",
                "password": "emptyadjacentpossible"
            }
        }
    ],
    "contexts": [
        {
            "name": "aws_kubernetes",
            "context": {
                "cluster": "aws_kubernetes",
                "user": "aws_kubernetes",
                "namespace": "ruptureofthemundaneplane"
            }
        },
        {
            "name": "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster",
            "context": {
                "cluster": "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster",
                "user": "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster",
                "namespace": "primacyofdirectexperience"
            }
        }
    ],
    "current-context": "aws_kubernetes"
}

you can see in above I have deployed two apps ... when I try the obvious to choose my kubernetes context
kubectl config set-context  gke_primacyofdirectexperience_us-east1-b_loudhttpscluster  --namespace=${PROJECT_ID}

... outputs
context "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster" set.

kubectl config set-cluster "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster"

... outputs
cluster "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster" set.

it then just hangs when I issue commands like
kubectl describe pods --namespace=primacyofdirectexperience

perhaps I am missing the command to also set user since in above json each deployed app gets its own user name ???
UPDATE
kubectl config use-context gke_primacyofdirectexperience_us-east1-b_loudhttpscluster

... outputs
switched to context "gke_primacyofdirectexperience_us-east1-b_loudhttpscluster".

however now when I issue any kubectl command ... for example
kubectl get pods

.... outputs
Unable to connect to the server: x509: certificate signed by unknown authority

which is an error I have never seen before ... no doubt due to the toggle issue
Even with above error message /kubernetes/cluster/kube-down.sh was able to teardown the cluster so there is hope toggling will work !

A: To switch between contexts use use-context:
kubectl config use-context gke_primacyofdirectexperience_us-east1-b_loudhttpscluster

Any kubectl commands applied now will be applied to that cluster (using the primacyofdirectexperience namespace, since you set that as the default for the cluster).
kubectl get pods

Will now get all pods gke_primacyofdirectexperience_us-east1-b_loudhttpscluster on the primacyofdirectexperience namespace. To use a different namespace, you can apply the namspace flag:
kubectl get pods --namespace=someothernamespace

To switch contexts again, just run use-context again:
kubectl config use-context aws_kubernetes

Now,
kubectl get pods

will run on the aws_kubernetes cluster, using the default namespace.
You can always see which context kubectl is currently using by running:
kubectl config current-context

A: To extend the answer (provided by @Pixel Elephant), which explains how to "use-context" to achieve switching between multiple configurations, it is worth to mention that sometimes it is handy to switch between two contexts that differ only by the namespace. You can achieve this by editing your ~/.kube/config to copy the context and change only the namespace.
Alternatively, you can write a short script that will edit the namespace with kubectl set-context $(kubectl config current-context) --namespace <nsname>.
These answers should answer your question completely. However if you are looking for handy tools to simplify the daily use of those commands even more, then users usually try to automate such context switch with some cli script.
I got inspired by kubectx and kswitch scripts, which I can recommend for most cases. They are helping with solving the switching task, but were breaking for me on some bigger or less standard configurations of ~/.kube/config. So I created a sys-exec invocation wrapper and a short-hand around kubectl.
If you call k without params you would see an intercepted prompt to switch context.
Switch kubectl to a different context/cluster/namespace.
Found following options to select from:
 >>> context: [1] franz
 >>> context: [2] gke_foo_us-central1-a_live-v1
 >>> context: [3] minikube
 --> new num [?/q]:

Further, k continues to act as a short-hand. The following is equivalent:
kubectl get pods --all-namespaces
k get pods -A
k p -A


text:
Q: Python Searching for certain keywords in a string Right now i have a list of each separate key word is there a way to make this into one array or string and search for individual words instead of having to separate each key word and make it repeatable?
keywordlist = ("pricing")
keywordlist1 = ("careers")
keywordlist2 = ("quotes")
keywordlist3 = ("telephone number")
keywordlist5 = ("about")
while True:
    question1 = raw_input("Is there anything I can help with today?   ")
    question_parts = question1.split(" ")
    for word in question_parts:
        if word.lower() in keywordlist:
            print("Yah i can show you some pricing:   ")
        elif word.lower() in keywordlist1:
            print("Here is our career page and feel free to apply:  ")
        elif word.lower() in keywordlist2:
            print("yah i can show you to our quote page: ")
        elif word.lower() in keywordlist3:
            print("Yah here is our contact page and feel free to contact us: ")
        elif word.lower() in keywordlist5:
            print("Here is some information about us:")
        goagain = raw_input("Would you like any More Help? (Yes/No)")
        if goagain == "Yes":
            #Get values again
            pass #or do whatever
        elif goagain != "Yes":
            print ("Bye!")
    break

A: You can use a dictionary
keywords = {"pricing": "Yah i can show you some pricing:   "
            "careers": "Here is our career page and feel free to apply:  "
            "quotes": "yah i can show you to our quote page: "
            "telephone": "Yah here is our contact page and feel free to contact us: "
            "about": "Here is some information about us:"}
while True:
    question1 = raw_input("Is there anything I can help with today?   ")
    question_parts = question1.lower().split()
    for word in question_parts:
        if word in keywords:
            print(keywords[word])
    goagain = raw_input("Would you like any More Help? (Yes/No)")
    if goagain == "Yes":
        #Get values again
    else:
        print ("Bye!")
        break

A: use regular expressions
import re
KEYWORD_MAPPING = {
        "pricing": "Yah i can show you some pricing:",
        "careers": "Here is our career page and feel free to apply:",
        "quotes": "yah i can show you to our quote page:",
        "telephone": "Yah here is our contact page and feel free to contact us: ",
        "about": "Here is some information about us:"
}

def search_for_keyword(question):
    keyword_pattern = r'{}'.format('|'.join(KEYWORD_MAPPING.keys()))
    keyword = re.search(keyword_pattern, question, re.I).group()
    if not keyword:
         return False
    print(KEYWORD_MAPPING[keyword])
    return True

while True:
        question = input('enter a question')
        status = search_for_keyword(question)
        if not status:
             break


text:
Q: sqlite query duplicating data in results I have a sqlite DB with multiple tables representing employees of a hospital. Each one has in common a firstname, lastname, and category column.  I want to simply list the first name, last name and category of all the workers of the hospital.
My query is:
Select Volunteer.*, Nurse.*, Administrator.*, doctor.firstname, doctor.lastname, doctor.category
FROM Volunteer, Nurse, Administrator, doctor
WHERE Volunteer.category = 'Volunteer'
OR Nurse.category = 'Nurse'
OR Administrator.category = 'Administrator'
OR doctor.category = 'doctor'

Each table has 8-10 entries, so I would expect the query to return about 40 rows.  It returns about 1000 instead.
I am new to SQL, and understand why the number of rows being returned is happening.  I believe I need to use a LEFT JOIN statement, but I dont understand the structure very well.  Could someone help correct my query and I will work backwards to figure out the rest?  Thanks.

A: The issue is that you are doing a join where all you want to do is to union the tables:
(Select firstname, lastname, category
FROM Volunteer
UNION
Select firstname, lastname, category
FROM Nurse)
UNION
(Select firstname, lastname, category
FROM Administrator
UNION
Select firstname, lastname, category
FROM doctor)

The form of the above is correct. I am not sure if needs more parentheses.


text:
Q: Check server logs through terminal I use AWS. I want to check server logs through terminal on mac. I have ssh key and logged in to server through terminal. I want to run server code and see its logs.
How to do it?

A: I found log files under /var/log directory. There were so many log files in this directory. I needed to use sudo, otherwise I get permission denied.