text:
Q: jQuery/ JavaScript Problems with adding css class Nowadays i have problem with adding class in my script. I have unique html structure. So i need your advice. I hope that you help me.
The below there is my html code

             CT&M
            (blablabla)

 /

            Invest
            (blablabla)

Look down. there is my css
aside ul li a span:first-child, aside ul li span:first-child {
    display: block;
    text-align: center;
    font-family: "Roboto-Medium";
    font-size: 1.8em;
    color: #060606;
}
aside ul li a span:last-child {
    display: block;
    text-align: center;
    font-family: "Roboto-Medium";
    font-size: 1.05em;
    color: #060606;
}
aside ul li a span.active
{
    color: #007582;
}
aside ul li a span.disactive
{
    color: #060606;
}

And here is my jQuery code:
$(function () {
    $(".CT").one("mouseover", function () {
        $("span.Invest").removeClass("active");
        $("span.CT").addClass("active");
    });

    $(".Invest").one("mouseover", function () {
        $("span.CT").removeClass("active");
        $("span.Invest").addClass("active");
    });
});

I would like doing interesting visual efect. I want to change color when I run onmouseover event but my script don't work properly. Could you ghelp me??
When you have any questions, you write to me.

A: You need to use $(".CT").on(" instead of $(".CT").one("
Using one will unbind the event after the first time the event is fired.
one() vs on()


text:
Q: Mysql query is not accepting in if clause? Here is my code of php which is not working properly....
It is not taking the query which is in if condition and every time it's executing else part....
  <?php
  include('admin/class.php');

** Here is my DB connection**
  $hostname="localhost";
  $username="root";
   $password="";

 $dbhandle = mysql_connect($hostname, $username, $password)
 or die("Unable to connect to MySQL");
  echo "Connected to MySQL<br>";
  $se = mysql_select_db("timesheet1234",$dbhandle)
  or die("Could not select timesheet1234");
 echo "connected to db";

 if(isset($_POST['save']))
   {
   echo "post if";

 $sel=@$_POST['selpro'];
  $mon=@$_POST['mon'];
  $tue=@$_POST['tue'];
  $wed=@$_POST['wed'];
  $thu=@$_POST['thu'];
  $fri=@$_POST['fri'];
  $sat=@$_POST['sat'];
   $sun=@$_POST['sun'];

Here is my code where the problem starts and it's not working properly
  if(isset($_SESSION['user']))
  {
   echo "session user";
        $sql="UPDATE empdaytimesheet SET `project  code`='$sel',`mon`='$mon',`tue`='$tue',`wed`='$wed',`thu`='$thu',`fri`='$fri',`sat`='$sat',`sun`='$sun' where `username`='".$_SESSION['user']."'";

 $res=mysql_query($sql,$dbhandle);
 if($res){
 echo "<script type='text/javascript'>";
 echo "alert('TimeSheet Saved..!')";
 echo "</script>";
 echo "<script type='text/javascript'>";
 echo "window.location='my_timesheet.php'";
 echo "</script>";
 }
  else
 {
 echo "<script type='text/javascript'>";
  echo "alert('Some Error Occured ! Retry..!')";
 echo "</script>";
 echo "<script type='text/javascript'>";
echo "window.location='my_timesheet.php'";
echo "</script>";
}
}
}
?>

A: UPDATE table empdaytimesheet SET...

is not valid SQL. What you mean to do is probably;
UPDATE empdaytimesheet SET...

Also, column names with spaces need to be quoted with - in MySQL's case - backticks, that is;
UPDATE empdaytimesheet SET `project code`=...

What you need to be aware of though is that you're open to SQL injection. If anyone posts a value for sel that contains a single quote, they can rewrite your SQL. For example, using Fiddler to post a value of sel as ',username=' would make your sql update the username column of the table too;
UPDATE empdaytimesheet SET `project code`='',username='',mon=...

In general just putting unchecked post variables into an SQL string is a bad thing. That's one big reason the mysql_* APIs are obsoleted by PDO and mysqli, they have methods for dealing with this.

A: Change
$sql="UPDATE table empdaytimesheet SET project  code='$sel',...

to
$sql="UPDATE empdaytimesheet SET `project  code`='$sel', ...
             ^ no table here     ^             ^ backticks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to switch the owner of a TF workspace? I'm doing some work on a computer that has been used by a colleague. All relevant source code has already been mapped locally, so I would like continue using that workspace without remapping (it takes several hours to do the initial mapping, so that's why I would like to use what is already there).
The local mapping is write-protected when using my account, so I assume a solution is to transfer the ownership? I'm all ears for other workarounds as well.
I've tried the following in VS cmd prompt: tf workspace <workspace-name>;<previous-owner> /newowner:<me> and tf workspace <workspace-name>;<previous-owner>. Both activates an 'Edit workspace' GUI, but I'm not allowed to change anything there.

A: Thanks for the input.
The workaround that ended up working was a bit convoluted (the steps in the blog that Vito linked to didn't work, but it provided some useful tips). I'm not sure if I in reality just did a total remapping with extra steps, but it did at least feel much quicker than last time I set up the work environment from scratch. Here are the steps:

*

*My colleague deleted his his workspace. I had to restart VS for the change to be detected locally.

*I mapped my workspace to my colleagues deleted workspace.

*When VS got all the files there were hundreds of merge conflicts of the type "already exists locally". Ctrl+a to select all conflicts and click "Keep existing version"

*Now there were hundreds of files in "Pending Changes". I did "Undo" on all these.

*Now I was 'up-to-date'

A: Check tf workspaces /updateUserName:OldUserName. You can find the documentation here: How to change the computer name and update the owner name for a workspace, Workspaces Command

A: We could run this command to change the owner of the work space:
tf workspace Workspacename;Currentowner /newowner:newowner /collection:collectionurl

We could also refer to this blog to update the Workspaces owner.


text: Q: How to access appIcons in iOS using privateframewok I want to access app icon by using private framework.There is a private framework MobileIcons.framework in iOS, but  I don't know how to use it to get an app icon.


text:
Q: Initialising reference in constructor C++ I don't think is a duplicate question.  There are similar ones but they're not helping me solve my problem.
According to this, the following is valid in C++:
class c {
public:
   int& i;
};

However, when I do this, I get the following error:
error: uninitialized reference member 'c::i'

How can I initialise successfully do i=0on construction?
Many thanks.

A: Apart from the sweet syntax, a key feature of references is that you are pretty sure that it always point to a value (No NULL value).
When designing an API, it forces user to not send you NULL.
When consuming an API, you know without reading the doc that NULL is not an option here.

A:
A reference must be initialised to
  refer to something.

int a;
class c {
public:
   int& i;
   c() : i (a) {};
};

A: There is no such thing as an "empty reference". You have to provide a reference at object initialization. Put it in the constructor's base initializer list:
class c
{
public:
  c(int & a) : i(a) { }
  int & i;
};

An alternative would be i(*new int), but that'd be terrible.
Edit: To maybe answer your question, you probably just want i to be a member object, not a reference, so just say int i;, and write the constructor either as c() : i(0) {} or as c(int a = 0) : i(a) { }.

A: References have to be initialized upon creation. Thus you have to initialize it when the class is created. Also you have to provide some legal object to reference.
You have to use the initializer in your constructor:
class c {
public:
   c(const int& other) : i(other) {}
   int& i;
};

A: template<class T>
class AVLNode {

private:
       T & data;
public:
       AVLNode(T & newData) {
            data = newData;
        }
};

A: Reference should be initialised either by passing data to constructor or allocate memory from heap if you want to initialize in default constructor.
class Test
{
    private:
        int& val;
        std::set<int>& _set;
    public:
        Test() : val (*(new int())),
                _set(*(new std::set<int>())) {  }

        Test(int &a, std::set<int>& sett) :  val(a), _set(sett) {  }
};

int main()
{
    cout << "Hello World!" << endl;
    Test obj;
    int a; std::set<int> sett;
    Test obj1(a, sett);
    return 0;
}

Thanks


text:
Q: Changing format of some axis labels in ggplot2 according to condition I have a ggplot and I want to highlight only some specific x-axis labels according to a predefined condition.
I know that axis text is controlled by
theme(axis.text = element_text(...))

but this applies to all labels of the axis. What I want is that the formatting change be applied only the labels that have condition = 1.

A: You can include for example ifelse() function inside element_text() to have different labels.
ggplot(iris,aes(Species,Petal.Length))+geom_boxplot()+
  theme(axis.text.x=
          element_text(face=ifelse(levels(iris$Species)=="setosa","bold","italic")))

Or you can provide vector of values inside element_text() the same length as number of levels.
ggplot(iris,aes(Species,Petal.Length))+geom_boxplot()+
 theme(axis.text.x = element_text(face=c("bold","italic","bold"),
                                   size=c(11,12,13)))


text:
Q: Unix: Sync directory with SFTP directory I have a website on my local computer running Mac OS X. I am wondering if there is any built-in command that I can run in the Terminal that will upload that website to my webserver through SFTP. Installing new commands through MacPorts is a possibility. A big bonus would be that it only uploaded the files that needs to be updated and not everything else.
It would also be nice if I can tell it to delete the files on the server that no longer exists locally once in a while.
Any good tips?
Update: This question asked about both SFTP and FTP, but I've only gotten an answer regarding SFTP. rsync seems to do it very well when the server supports ssh, but if I have understood correctly, rsync does not support FTP. I'm still looking for a good solution for FTP, so have opened a different question for it.

A: Use rsync. It's purpose is to sync remote/local files.
rsync -avz --delete source-address destination-address

Please read the documentation in order to understand what are the available options and how to use it. (like the difference between "dir" and "dir/")
Of course, you can also use scp -r, but rsync is the best solution.


text:
Q: Qt Creator 3.1.2 (Qt5) not highlighting typedefs defined with keyword 'using' (C++11) If I use
typedef itk::Image<unsigned char , 3> itkVolumeType;

all the typedefs are highlighted in a different color. But if I use C++11
using itkVolumeType = itk::Image<unsigned char , 3>;

highlighting no longer works.
Any ideas on how to fix this?
I'm using CMake.


text:
Q: How to make an HTTP app HTTPS with HAProxy and SSL Termination Where I work theres an web app that is hosted on windows servers, all users access the application using HTTP, not HTTPS. This is due to some restrictions that the dev team could not solve.
So I thought that i could solve this issue using HAProxy and SSL Termination, so the users would communicate with the proxy first using HTTPs and then the proxy would communicate with the app servers using HTTP. This would be inside a private VLAN so the HTTP traffic cannot be sniffed.
The users access the app using this schema --> http://servername:port/path/to/app
So instead of this, the users should type https://haproxy.domainname:port/path/to/app
and the haproxy should handle the communication against the app servers.
Is this possible? or should i think of another solution to this?
I came up with this:
frontend haproxy.domain.name
    bind ipaddress:port ssl crt /home/cert.pem
    acl is_bdc path -i -m beg /path/to/app
    use_backend web_servers if is_bdc
    default_backend web_servers

backend web_servers
        balance roundrobin
        server server1 ipaddress:port

I can access the app server using this configuration, but the app fills some variables using the URL of the web browser, and as im accessing the app using another URL (haproxy.domain.name instead of the app server hostname) its causing some errors. Is possible to maintain the app server hostname on the url but also keep the SSL termination? The used certificate its a wildcard so adding the domain name would be enought (i think)
Thanks you in advance!

A: Well there are several options to solve your issue.
1.) Tell the app server that it runs behind a reverse proxy and configure the app engine to use haproxy.domain.name as Domain/Host part, something similar to tomcats Proxy Support How-To
2.) you can use the http-response replace-header or replace value to rewrite the URL. This will not work with links in the body of the response.
As you haven't mention the HAProxy version I link to the latest one.
Maybe you will need also to configure the IIS to know that it works behind a reverse proxy, in case you use IIS.


text:
Q: Blog Delete Action Error? I have a blog style site and under each article there is the usual 'view' 'edit' and 'delete' functions for users once they are signed in. The issue is when I click on 'delete' the link it sends you to the 'view' article page and doesn't delete the article. Can't figure this one out as the delete and view paths are different in my code but do the same thing...??
class ArticlesController < ApplicationController

  before_filter :authenticate_user!, :except => [:index, :show]

# GET /articles
# GET /articles.xml
# display the amount of article on the home page

def index
@articles = Article.published.page(params[:page]).per(6).ordered

respond_to do |format|
  format.html # index.html.erb
 # format.atom #index.atom.builder
  format.xml  { render :xml => @articles }
end
end

 # GET /articles/1
 # GET /articles/1.xml
def show
  @article = Article.find(params[:id])
  @comment = Comment.new(:article=>@article)

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @article }
end
end

...

/controllers/articles_controller
# DELETE /articles/1.xml
 def destroy
@article = Article.find(params[:id])
 authorize! :destroy, @article
@article.destroy

respond_to do |format|
  format.html { redirect_to(articles_url) }
  format.xml  { head :ok }
  end
 end
end

views/articles/_article.html.erb

<%= link_to 'Read', article %>
  <% if can? :update, article %>
 | <%= link_to 'Edit', edit_article_path(article) %> |
 <% end %>

 <% if can? :destroy, article %>
  <%= link_to 'Delete', article, :confirm => 'Are you sure?', :method => :delete %>
<% end %>

A: This may be because you don't have the right javascript files set up. Rails 3 uses unobtrusive javascript to create the DELETE request when you click the link. If the javascript isn't working, it will fall back to doing a GET which will render the show action.
Make sure you have rails.js and prototype.js in your layout. If you are using a javascript framework other than Prototype, you will need to have that framework (jQuery or whatever) along with the appropriate port of rails.js.

A: This line
format.html { redirect_to(articles_url) }

should send it back to your index action, where do you want to end up?

A: This case happen also in my project.
Finnaly I know the cause. It  was because my application.js that located in app/assets/javascript was being replaced by another application.js that I copy when I try to explore about bootstap.
I simply add this 3 rows back:

//= require jquery
//= require jquery_ujs
//= require jquery-ui

to the application.js on the top row its okay.
and put this

on my app/views/layout/application.html.erb
n it work..
in case if the jquery have been install n still error like me :D
sory for bad english :)


text:
Q: Issue with text file importing and manipulation I have a txt file with this in it:
GWashington 83
JAdams 86
What I need to do is read the file, add 5 to the numbers and save it to a new file.
newFile = open('scores2.txt', 'w')
stdLines = [line.strip() for line in open('class_scores.txt')]
scrSep = [line.split(',') for line in stdLines]
print(stdLines, scrSep)
def convert_numbers(s):
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

    g = list(map(convert_numbers, scrSep))
    print(s)
    print(scrSep)

Thank you in advance for your help.
what should happen with this is it should open the file, seperate the lines and seperate the components so then I can turn the numbers into ints and manipulate them. But strip and split are making it harder for the items to be accessed.

A: Never mind I fixed it, just had to call from deeper in the list.
So instead of list[x] I had to do list[x][y]
That uhh... slipped my mind.


text:
Q: update query is not updating record in sql table I am trying to update record in SQL table but not updating record. No errors/exceptions occurred. When I do click on Update button then again same page opens of that respective fileid(primary key). After clicking on Update button, it is not redirecting to filelist.jsp page.
I am referring to this youtube code to implement it in my program. But it is not working in my code.
Here is my code.
This is filelist.jsp
Edit Form
...
<a href="edit.jsp?fileid=<%=rs.getInt("fileid")%>" class="btn btn-warning">Edit

This is edit.jsp

<%
String host="jdbc:mysql://localhost:3306/dmsqms";
Statement stat = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(host,"root","");
%>
<form method="post" action="" onsubmit="return validate();" enctype="multipart/form-data">
<%
stat = conn.createStatement();
String fileid=request.getParameter("fileid");
String data = "select * from dmsfiles where fileid = '"+fileid+"'";
rs = stat.executeQuery(data);
while(rs.next()){
%>
<input type="hidden" name="fileid" value="<%=rs.getInt("fileid")%>">

Form Details

Z id

<input type="text" name="zid" value='<%=rs.getString("zid")%>'/>

First Name

<input type="text" required="" name="firstname" value='<%=rs.getString("firstname")%>'/>

Last Name

<input type="text" required="" name="lastname" value='<%=rs.getString("lastname")%>'/>

...

Status

<select name="status" class="hidden" id="wgtmsr">
<option value="<%=rs.getString(22)%>"><%=rs.getString(22)%></option>
<option value="Public">Reserved</option>
<option value="Team">Implemented</option>
</select>

Select File

<input type="file" name="fileName" multiple="multiple"/>
 <%=rs.getString("filename")%>

<%
}
%>

<button type="submit" class="btn btn-warning" id="updbtn">Update</button>

</form>

<%
  if(request.getParameter("updbtn") != null){
  String z_id = request.getParameter("zid");
  String first_Name = request.getParameter("firstname");
  String last_Name = request.getParameter("lastname");
  String mail_i_d = request.getParameter("mailid");
  String d_iv = request.getParameter("division");

  ...

  String iss_uer = request.getParameter("issuer");
  String sta_tus = request.getParameter("status");
  String file_Name = "";
  String folder_Name = "allfiles";
  String pa_th = folder_Name + File.separator + file_Name;
  Timestamp add_ed_date = new Timestamp(System.currentTimeMillis());

  if(z_id != null && first_Name != null && last_Name != null && mail_i_d != null && d_iv != null && de_pt != null && cost_centercode != null && doc_num != null && doc_Name != null && doc_Type != null && doc_Category != null && doc_classification != null && authorised_by != null && from_date != null && to_date != null && document_level != null && document_general != null && serial_number != null && revision_number != null && iss_uer != null && sta_tus != null && file_Name != null && folder_Name != null && pa_th != null && add_ed_date != null){
                String query = "update dmsfiles set zid=?, firstname=?,lastname=?,mailid=?,division=?,department=?,costcentercode=?,document_number=?,document_name=?,document_type=?,document_category=?,document_classification=?,authorised_by=?,fromdate=?,todate=?,document_level=?,document_general=?,serial_number=?,revision_number=?,issuer=?,status=?,filename=?,path=?,added_date=? where fileid='"+fileid+"'";
                stmt = conn.prepareStatement(query);
                stmt.setString(1,z_id);
                stmt.setString(2,first_Name);
                stmt.setString(3,last_Name);
                stmt.setString(4,mail_i_d);
                stmt.setString(5,d_iv);

                ...

                stmt.setString(23,pa_th);
                stmt.setTimestamp(24, add_ed_date);
                stmt.executeUpdate();
                response.sendRedirect("./filelistJSP.jsp");

            }
            }
%>


text:
Q: JSRuntime is not registered Blazor I have a Blazor Wasm project and when I want to inject the JSRuntime
@inject JSRuntime js

I'm getting this error:
"Cannot provide a value for property 'js' on type 'BlazorApp.Pages.Page'. There is no registered service of type 'Microsoft.JSInterop.JSRuntime'"
Is JSRuntime not registered by default?
How do I register it?
Thanks

A: Try
@inject IJSRuntime JSRuntime

and in method use JSRuntime as object with methods.

A: You need to inject IJSRuntime, not JSRuntime.


text:
Q: Second order linear ODE with polynomial coefficients I am currently stuck at solving an ODE of the form
\begin{equation}
0=\psi''(x)+(\varepsilon-(\alpha x^2-\beta)^2)\psi(x)
\end{equation}
where $\alpha,\beta$ and $\varepsilon$ are real parameters.
Anticipating $\psi\sim\mathrm{e}^{-\alpha x^3/3}$ for large $x$, I made the Ansatz $\psi(x) = f(x)\mathrm{e}^{-\alpha x^3/3}$ and obtain the ODE
\begin{equation}
0=f''(x)-2\alpha x^2 f'(x)+(\varepsilon-\beta^2+2\alpha\beta x^2-2\alpha x)f(x).
\end{equation}
Actually, I am looking for a normalized solution $\sim\mathrm{e}^{-\alpha|x|^3/3}$, where extra care needs to be taken around $x=0$. (I am a physics student and not so much concerned about mathematical rigor right now.)
But any solution would be a first step of course.
I tried a variety of things to solve the second equation:

*

*A powerseries approach $f(x)=\sum_{n=0}^\infty a_n x^n$. I obtain\begin{equation}a_{n+2}=\frac{(\varepsilon-\beta^2)a_n-2\alpha(n+1)a_{n-1}+2\alpha\beta a_{n-2}}{(n+2)(n+1)}\end{equation} for $n\geq 2$, which does not look very promising.

*I also checked A. Polyanins and V.F. Zaitsevs Handbook of Exact Solutions of Ordinary Differential Equations but failed to transform the above ODEs into one given in the book. Wolfram Mathematica was not helpful either.

*I transformed the equation into an system of first order linear ODEs with $g=f'$. However such an approach is only helpful for constant coefficients, right?

I am thankful for any ideas or hints. A particular solution would be very helpful of course, as it would allow me to reduce the order of the ODE and find all solutions.
Note that, while $\alpha$ and $\beta$ are given, I expect constraints on $\varepsilon$ for (normalized) solutions to exist, i.e. I would also appreciate a solution for special values of $\varepsilon$, e.g. $\varepsilon=\beta^2$.
Sorry for any grammatical errors.
Thank you for your help!

A: Hint:
$\psi''(x)+(\varepsilon-(\alpha x^2-\beta)^2)\psi(x)=0$
$\psi''(x)-(\alpha^2x^4-2\alpha\beta x^2+\beta^2-\varepsilon)\psi(x)=0$
Let $\psi(x)=e^{nx^3}u(x)$ ,
Then $\psi'(x)=e^{nx^3}u'(x)+3nx^2e^{nx^3}u(x)$
$\psi''(x)=e^{nx^3}u''(x)+3nx^2e^{nx^3}u'(x)+3nx^2e^{nx^3}u'(x)+(9n^2x^4+6nx)e^{nx^3}u(x)=e^{nx^3}u''(x)+6nx^2e^{nx^3}u'(x)+(9n^2x^4+6nx)e^{nx^3}u(x)$
$\therefore e^{nx^3}u''(x)+6nx^2e^{nx^3}u'(x)+(9n^2x^4+6nx)e^{nx^3}u(x)-(\alpha^2x^4-2\alpha\beta x^2+\beta^2-\varepsilon)e^{nx^3}u(x)=0$
$u''(x)+6nx^2u'(x)+((9n^2-\alpha^2)x^4+2\alpha\beta x^2+6nx+\varepsilon-\beta^2)u(x)=0$
Choose $9n^2-\alpha^2=0$ , i.e. $n=\dfrac{\alpha}{3}$ , the ODE becomes
$u''(x)+2\alpha x^2u'(x)+(2\alpha\beta x^2+2\alpha x+\varepsilon-\beta^2)u(x)=0$
Let $u(x)=e^{kx}v(x)$ ,
Then $u'(x)=e^{kx}v'(x)+ke^{kx}v(x)$
$u''(x)=e^{kx}v''(x)+ke^{kx}v'(x)+ke^{kx}v'(x)+k^2e^{kx}v(x)=e^{kx}v''(x)+2ke^{kx}v'(x)+k^2e^{kx}v(x)$
$\therefore e^{kx}v''(x)+2ke^{kx}v'(x)+k^2e^{kx}v(x)+2\alpha x^2(e^{kx}v'(x)+ke^{kx}v(x))+(2\alpha\beta x^2+2\alpha x+\varepsilon-\beta^2)e^{kx}v(x)=0$
$v''(x)+(2\alpha x^2+2k)v'(x)+(2\alpha(k+\beta)x^2+2\alpha x+k^2+\varepsilon-\beta^2)v(x)=0$
Choose $k=-\beta$ , the ODE becomes
$v''(x)+2(\alpha x^2-\beta)v'(x)+(2\alpha x+\varepsilon)v(x)=0$
Which relates to Heun's Triconfluent Equation.


text:
Q: How to print groups of all local users? I want to print all groups of users stored in /etc/passwd. Seems easy enough, I can just use getpwent() and getgrouplist(). I came with this code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <grp.h>

int main(int argc, char** argv){

    struct passwd* user;
    int nGroups = 20;
    gid_t* groups;
    groups = malloc(nGroups * sizeof(gid_t));
    struct group* gr;
    while(user = getpwent()){
        printf("%s : ", user->pw_name);
        getgrouplist(user->pw_name, user->pw_gid, groups, &nGroups);
        int i;
        for(i = 0; i < nGroups; ++i){
            gr = getgrgid(groups[i]);
            if(gr){
                printf("%s ", gr->gr_name);
            }
        }
        printf("\n");
    }

    free(groups);
    return 0;
}

It gives me this output:
root : root
daemon : daemon
bin : bin
.
.
.
pulse : pulse root
ricenwind : ricenwind adm root root root root root root
vboxadd : daemon

which is clearly wrong, as for example using
groups ricenwind

gives me:
ricenwind : ricenwind adm cdrom sudo dip plugdev lpadmin sambashare

A: If you read the getgrouplist manual page you will see

Up to *ngroups of these groups are returned in the array groups.

The ngroups argument is not only set by the function, it's also used by the function to know how many structures you have allocated for the groups argument.
You need to "reset" the nGroups variable before calling getgrouplist, otherwise the old value set by the previous call to the function will be used:
nGroups = 20;
getgrouplist(user->pw_name, user->pw_gid, groups, &nGroups);

A: You can achieve this using a simple bash script as
!/bin/bash
grep "/bin/bash" /etc/passwd
it would do the result,bcoz all the local user will have /bin/bash or /bin/sh as their shell


text:
Q: How can I publish a nodJS app on aws?
I'm using a free tier version of aws cloud, and have some trouble with loading up a nodeJs Application. I 've tried to follow the documentation of aws but it didn't work unfortunately. I choose the Elastic BeanStalk, from the services, and create a new Application. I choose nodeJs for the preconfigured platform of course. I make a zip with my app, and I really pay attention, to not have any parent folder above package.json, and app.js . As you can see on the picture above, I have a folder "public" which contains additional folders (css,img, javascript code). When I try to upload the project, I get an error message.
"Failed to find package.json. Node.js may have issues starting. Verify package.json is valid or place code in a file named server.js or app.js." In the project view I've got a health status "degraded", and an other error code:      "i-045ac359227e3a9ae"   Severe
I 've tried many php projects on this server, and everything worked fine,but I can't make it work with Node. Could you help me out please?
package.json:
 {
  "name": "kutyapplikacio",

  "version": "1.0.0",

  "description": "Egy alkalmazás kutyáknak és gazdáiknak",

  "main": "server.js",

  "scripts": {
    "test": "test",

    "start": "node server.js"
  },

 "author": "sethdevelop",

 "license": "ISC",

 "dependencies": {

"body-parser": "^1.17.2",

"express": "^4.15.3",

"express-mailer": "^0.3.1",

"express-mysql": "0.0.1",

"express-validator": "^3.2.0",

"mysql": "^2.13.0",

"nodemailer": "^4.0.1",

"nodemailer-smtp-transport": "^2.7.4"

}
}

A: The error message you wrote is :  "Failed to find package.json. Node.js may have issues starting. Verify package.json is valid or place code in a file named server.js or app.js."
From the folder I only see you have app.js file.
And in your package.json, there are server.js:
"main": "server.js",
  "scripts": {
    "test": "test",
    "start": "node server.js"
  }

Perhaps you should change server.js to app.js ?

Update
Since you mentioned they have the same name:
could it be you zipped the folder instead of zipped the files ?
Same problem has been discussed here:
https://forums.aws.amazon.com/message.jspa?messageID=477087
https://forums.aws.amazon.com/thread.jspa?threadID=130140


text:
Q: Iphone Dropped and will not turn on Recently i dropped my phone, with no visibal damage i carried on using it. After a while the phone began 'searching' for a network, i turned the phone off and on again in hope that this would work but the phone wouldn't turn back on. When i got home a put the phone on charge and it showed the apple logo, as if it was turning back on but then went blank again. The phone repeats this process whislt only on charge, when i take the phone of of charge it will not switch on or anything.

*

*Prior to dropping my phone i replaced the battery as tit died for no reason, this worked fine the the new battery was working however if i were to shake the phone i could fell something moving inside, i think the battery is loose and that might be the problem but would like some extra advice

*Also the phone is jailbroken if that can effect the outcomes in any way

*NOTE - The phone does not turn on at all so i cannot factory reset and neither can i get the phone to enter recovery/DFU mode.
Thanks for any help given,
Luke

A: You just need to hold the lock and home button at the same time for about 10-15 seconds and it will turn back on.


text:
Q: Yii - multiple databases with one user authentication I am facing a problem trying to develop an application in Yii (v=1.1). Client wants the application to has multiple databases (one per his customer). That means that we will have unknown number of databases. Also He wants to have only one user authentication system - regard of it, users would have the choise (and the privilleges) to belong in many databases. So I am considering about the way which it could be developed.
Do you have faced something like this?

A: Well you should first better define your goal because it is not that clear to me what you want to accomplish, but how I see it.
Decide where you want to store the users:

*

*Should the same user be able to connect using the same login info to two different customer databases?

*Do you need to manage all users of all customers from one single place?

You could have the following situations:
Store users only in one common database, not in customer databases:

*

*when logging in tell Yii to use the "common" database for the User model

*you could have also a common application that handles user management

*you could also provide the customer with the possibility to manage his own users

*you could either have a "customer" field in the Users table to indicate to what customer it belongs, or you could have a "users_customers" table and after the login screen prompt the user with a "choose customer" screen, so one unique User can login to multiple Customers

Store users only in the customer databases:

*

*if you don't need for a common place to manage users, or don't need to share them between customers, simply have a User table in every Customer database, this way user "alex" could exist in both databases with different login information

*here you could simply add another field in the Login form (yes I've saw one application that does it) for example instead of Username and Password fields, ask for "Office, Username and Password", and the Office would be the name of the Customer database. Or you could even use only Username field and force users to enter something such as "alex@office" as Username, then you split that by "@" and you know to what office it belongs.

*then simply use that information both on Login screen and on session to tell Yii what customer database to connect to

So as you see it could be done in different ways. Once you choose your way, you would need a implementation.
If you don't know how to do the implementation maybe I could provide more technical information related to Yii.


text:
Q: Back to the basics: What's so great about a framework? I'm brand new here and I'd like to start off by asking about WP frameworks. I've seen quite a bit out there, so I'm confused about what to choose for my site.
So here are a few questions:

*

*What is the advantage of a framework in the first place? Specifically, what are the advantages of installing frameworks such as Woo, Thesis, Genesis over designing something for a Wordpress base install directly?

*Are there are any frameworks that are not recommended? I've seen a lot of Genesis bashing in other forums, but I don't understand why this is the case. So I'd like to know what you use and why.
Thanks,
Ray

A: The advantage of using a framework is two-fold:

*

*If using a theme framework to build a regular theme, it can give you a head start by giving you mature code (in most major frameworks, anyway) that you can use as a base for your customizations. This gives you more control of the theme framework code but also creates a bit of a problem: you now have a forked version of the theme and would need to run a comparison tool to incorporate updates from the original theme author.

*If using a theme framework as a parent theme, you can build a child theme that sits on top of the theme framework, allowing you to add your own code or remove things programmatically using actions and filters from the parent theme, without touching the parent theme's code. You allow them to continue developing the theme framework and update to the latest version to avoid having to maintain your own forked version of theme code that you did not write.

There are quite a few different theme frameworks out there. The only ones I've ever used consistently are the UpThemes Framework (which is a theme options framework, not a full theme) and Thematic which has not been updated in quite some time. Obviously, the Woothemes Framework, Genesis, and Hybrid Core are pretty popular ones. I think Genesis and Hybrid Core are great options because of the support packages that come with them and the documentation you get.


text:
Q: Upper bounds for difference of entries between matrices and their inverses in $\mathsf{GL}_k(\mathbb Z)$ Let $a(M)$ be the maximum absolute value of entries of matrix $M\in\mathsf{GL}_k(\mathbb Z)$.
$M^{-1}\in\mathsf{GL}_k(\mathbb Z)$ holds.

What is a good upper bound for $|a(M)-a(M^{-1})|$?

I am thinking whether the dependence could be a little smaller than fully exponential in $k$ for $a(M)\cdot a(M^{-1})$ which will reflect upper bound for $|a(M)-a(M^{-1})|$.

A: For $k=2$, the upper bound is zero.
For $k>2$, there is no upper bound. E.g., let $$M=\pmatrix{1&1&1\cr9&10&11\cr-n&n&3n-1\cr}$$ Then $$M^{-1}=\pmatrix{10-19n&2n-1&-1\cr38n-9&1-4n&2\cr-19n&2n&-1\cr}$$ and $a(M)-a(M^{-1})=(3n-1)-(38n-9)=-(35n-8)$ is unbounded.


text:
Q: How to Debug seemingly empty DOM objects? I am writing a task to import a XML. Debugging is a pain as both var_dump and print_r return seemingly empty objects for DOM objects like DOMElement and DOMNodeList list, looking so:
object(DOMElement)#330 (0) {}
object(DOMNodeList)#335 (0) {}

But they are not empty as I can read the values.
What debugging options have I instead?

A: For a DomDocument I var_dump using the xml output.
var_dump($dom->saveXML());

For a DOMElement, I use (as seen here):
var_dump($domElement->ownerDocument->saveXML($domElement));

But DOMNodeList, I have no idea. Maybe you have to attach/append it to a DomDocument, and then var_dump it.
And btw, not showing internals of a DomDocument is reported (here: Reflection).

A: Solution: i wrote own monitoring function 'dom_test'
    function dom_test($DOM) {
      echo '<h1>'.get_class($DOM).'</h1>';
      // easiest way to traverse:
      echo 'LENGTH: '. @$DOM->length ."\n"; // if NodeList
      echo 'TAG: '. @$DOM->tagName ."\n"; // if Element
      echo 'CHILDS: '. @$DOM->childNodes->length ."\n"; // etc.
    }

hope this could help you!


text:
Q: Disable Portrait interface in iOS 6 In my UIViewController
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

-(BOOL) shouldAutorotate {
    return NO;
}

I should only support Landscape orientation in iOS 6. But it didn't work. It still working auto rotation.
How to fix disable autorotate in iOS 6 ?

A: Found a solution.
I am using viewcontroller with UINavigationController. So, I need to change supportedInterfaceOrientations in UINavigationController.
@interface UINavigationController (autorotate)

@end

@implementation UINavigationController (autorotate)

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

-(BOOL) shouldAutorotate {
    return YES;
}

@end

A: If your entire app will only support landscape, you can just skip the subclass and set your supported interface orientations to Landscape (left) and Landscape (right) in Info.plist


text:
Q: RubyMine - Turning off ability to click in middle of "empty" lines I've recently begun learning Ruby and I'm really enjoying it so far. The IDE I've chosen to use is RubyMine (as it's similar to PhpStorm). There is however one feature which annoys me greatly and I cannot find the configuration for.
What I want to get rid of is:
When coding I am able to click in the middle of a line (where I haven't placed whitespace), and the cursor will jump there and allow me to type there (as if I had placed indented the code a long way before beginning to write).
                                  The result might look something like this.

If I clicked in the middle of the line and began typing.
Does anyone know how to turn this feature off?
If my description is too vague, please let me know.
Thanks in advance!

A: If you find that Allow placement of caret after end of line is already unchecked, try checking the box then exit and restart the IDE. Go back into settings and un-check again.  This was the only way I could get it to work on a fresh install of PhpStorm v3.0.3 - no amount of check/uncheck would disable the behavior without this restart sequence.

A: You need to disable Settings | Editor | Virtual Space | Enable placement of caret after end of line

A: In Rubymine 4.5 I needed to restart in order to get rid off the carets

A: In RubyMine 5.4,
File > Settings > IDE Settings section > Editor > Virtual space "section" >
[*] Allow placement of caret after end of line
Remove the check from the checkbox.
It does not require restarting.

A: In RubyMine 7.1 File > Preferences > Editor > General, Virtual Space section


text:
Q: Are the Theme frame works or Theme builders slow downs the performance? I depend on theme builders like Suffusion for my Multi-Site Installation. Some WP users say the theme frameworks slow downs the performance and load speed. Is that really affects the performance?
A follow up question... is there any chance for performance problem if I enable BuddyPress on same Installation
Thanks !

A: The performance and load speed may be slowed down because of badly coded frameworks, or even well coded frameworks but way too overloaded. so it really depends on what framework or theme builder you are using and each one to its own case.
As for enabling BuddyPress, first you will need a theme that is made for BuddyPress and as far as i can tell Suffusion is not BuddyPress ready (I could be wrong here). And as for performance problem once again that is theme/theme framework depended.


text:
Q: How to perform code analysis in sonarqube in docker in a ASP.NET web application I have the official SonarQube docker image running successfully under http://localhost:32768/ (it is the one provided by Docker)
We want to perform some code analysys with C#.NET, this application is located in a folder called c:\myapplication (that is where I have the prj and sln)
My question is HOW! how can I tell my SonarCube, running in my docker http://localhost:32768/ , I want to analyse my C# code?
Thanks a lot!

A: Since the second answer provided seemed to be windows specific I decided to write down how it can be done in Linux, including the sonarqube installation.
1.) Run the command:
$sudo docker pull sonarqube

This will pull the docker image.
2.) Run the server using the command:
$sudo docker run -d --name sonarqube -p 9000:9000 -p 9092:9092 sonarqube

This will run the sonarqube server.  You can then go to Firefox and visit the server at http://localhost:9000 and login with the password "admin" and user "admin.
------------------------------ Analyzing projects -------------------------------------------------------------------
1.) Download the sonarqube scanner from here:
https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+MSBuild
2.) Unzip and place the files in a folder.
3.) Give executable permissions to the sonarcube file as follows:
$chmod +x <path-to-extracted-folder>/sonar-scanner-3.2.0.1227/bin/sonar-scanner

4.) Create a project using the user interface in firefox (localhost:9000).
5.) Go to the directory where the sln file is at and run the project commands.  They will have one of the following forms:
$SonarScanner.MSBuild.exe begin /k:"project-key"
$MSBuild.exe /t:Rebuild
$SonarScanner.MSBuild.exe end

or
$dotnet <path to SonarScanner.MSBuild.dll> begin /k:"project-key"
$dotnet build
$dotnet <path to SonarScanner.MSBuild.dll> end

Either should work.  Afterward you can see the your results in firefox.

A: To be pedantic about it, SonarQube doesn't analyze code. It presents the results of analyses to you (okay, it does actually do some further metric aggregation and calculation server-side). Instead, you want to tell the SonarQube Scanner for MSBuild to analyze your code. Doing so is fully documented.
Essentially

*

*install the scanner

*execute the Begin step (this tells the scanner to start listening)

*(re)build your solution

*execute the End step (tells the scanner to stop listening and process what it heard)

*browse your project in the SonarQube interface.

The specific commands would look something like this:
SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe end

A: Thanks for your answers, but after a couple of hours, I decided to write a post in my blog in how to do it step by step.
I know that there is plenty of documentation, but there are many bits and pieces to touch before you can see the analysis done properly.
I decided to shared my views and result with you guys,
http://netsourcecode.blogspot.co.uk/2017/01/continuous-code-quality-with-net.html
have fun!


text:
Q: translating Matlab's bitget() extreme value to python I got hold of Matlab code containing such a loop:
for n = 1:2^10,
bitget(n-1,10)*2^4;
end;

The problem I have is that Matlab (Octave) apparently adds padding bits to the right as such:
octave:15> bitget(5,1:10)
ans =

   1   0   1   0   0   0   0   0   0   0

and therefore:
octave:14> bitget(5,10)
ans = 0

while python does not add those bits, and therefore yields an error.
For this particular situation, am I right in believing that the above Matlab line bitget(n-1,10)*2^4; can be translated to python as (lambda x: 1 if x == 2**9 else 0)(n)*2**4, since Matlab bitget(5,10) would in my opinion only yield 1 if the binary representation of n spans 10 bits, i.e. 2^9 in this case?

A: I think you're misinterpreting the output of Octave. Let's try your example with a different value so we can see what's going on.
>> dec2bin(13)
ans = 1101

>> bitget(13,1:10)
ans =

  1  0  1  1  0  0  0  0  0  0

As you can see, the order of the bits has been reversed. In bitget, bit 1 is the least significant bit, or 2**0 and bit 10 is 2**9. It's not padding on the right, it's just reading 0 bits from a numerical type that's larger than the 4 bits required to store the value 13.
Now, bitget will return 1 whenever the specified bit is 1, regardless of the state of the other bits. So bitget(n-1,10) will return 1 not only for 2**9 = 512, but also for any other value with that bit set; in this case, any value in the range 512..1023. The equality comparison in your Python function won't give you that so you'll need to change it to a bitwise AND:
(lambda x: 1 if x & 2**9 else 0)(n)*2**4

Here I've changed == to & and 2**10 becomes 2**9 to match the value of the 10th bit.


text:
Q: XSLT - Select content between two special characters I have a xml like this,
<doc>

text1 <xml version="1.0" encoding="UTF-16"
        standalone="yes"?> text2

</doc>

I need to remove the text content between < and > form above text using XSLT. So expected output is,
<doc>

text1 text2

</doc>

I tried to use regex but I'm wondering how I can catch text between < and > form regex.
Any idea how I can do this using XSLT?

A: This Should Work.
(<(?:.?\n?)*>)

Then Replace with "" (empty)
Input:
<doc>

text1 <xml version="1.0" encoding="UTF-16"
        standalone="yes"?> text2

</doc>

Output:
<doc>

text1  text2

</doc>

See: https://regex101.com/r/0o9hol/1

A: Using just XSLT-1.0 you can achieve this by applying the following template:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" />

  <xsl:template match="p">
    <xsl:value-of select="concat(normalize-space(substring-before(text(), '<')),' ',normalize-space(substring-after(text(), '>')))" />
  </xsl:template>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

This template just copies all nodes with the identity template and applies a special treatment to all
 elements.
The special treatment of the
 nodes extracts the text() nodes before < and after > while normalizing the space character occurrence(reducing their count to one) and concatenates the result.
That's all.


text:
Q: What is a word that means "something that is commonly known, but not commonly talked about"? For example, nobody likes to use the restroom after they take a shower because you slide around on the seat, but that's not something commonly talked about between persons.
Or the well understood, but un-discussed feeling you get when you feel a bug or something crawling on you before you fall asleep, even though you know it's not a bug, but just a sensation.
It could not be of English origin.

A: Open secret — M-W

noun a supposedly secret but generally known matter
"It's an open secret that he's been cheating on his wife."

Open secret — Wikipedia

An open secret is a concept or idea that is "officially" secret or restricted in knowledge but is actually widely known; or it refers to something that is widely known to be true but which none of the people most intimately concerned is willing to categorically acknowledge in public.

A: It's not single-word, but there's a good fit in common knowledge.

something that is known to many people but often not made known officially

Cambridge

A: I'm at a loss for a single word, but this type of thing is commonly described as "something people don't talk about." "Something people don't talk about" isn't necessarily taboo; it's just considered unpleasant, uncomfortable, or rude to discuss with others, though there is an unspoken, implicit understanding that most people have knowledge of or experience with the unmentioned "something."
As a single word, I would refer to the "something people don't talk about" as an unpleasantness, though by definition it isn't necessarily "something people don't talk about."
Example:

The unpleasantness of accidentally getting poop on your hand when changing a baby's diaper is something people don't (usually) talk about.

A: As you say "It could not be of English origin", the adjective taboo comes to mind.

late 18th century: from Tongan tabu 'set apart, forbidden'; introduced
into English by Captain Cook.

Definition: "not acceptable to talk about or do" (Mirriam Webster)
examples:

Filipina helper Liz (not her real name) battled bed bugs in June 2012
in Tai Wong Street in Wan Chai. She says the pests covered the 500 sq
ft hostel, which was home to 10 helpers. "They were on the walls, on
my towels and on the carpet." Travellers also spread the problem. Bed
bugs are a bigger issue in hotels than the industry will admit.
"People don't talk about it because it's taboo, but it's definitely
happening"
http://www.scmp.com/lifestyle/health/article/1402401/bed-bug-infestations-are-rise-and-pests-are-hard-kill
Get kids talking about the loo, say NGOs, and it will help break down
a major barrier to education in the developing world: cultural taboos
about sanitation.
https://www.theguardian.com/global-development-professionals-network/2015/nov/19/reading-writing-and-sanitation-how-kids-are-key-to-ending-toilet-taboos

A: unspoken truth (thanks be to @hatchet)
Also, as a variation on the term unspoken rule, we could coin the phrase unspoken culture.

Finally, Carl Jung's collective unconscious seems apt here.
Wikipedia

According to Jung, the human collective unconscious is populated by instincts and by archetypes: universal symbols such as the Great Mother, the Wise Old Man, the Shadow, the Tower, Water, the Tree of Life, and many more.
Jung considered the collective unconscious to underpin and surround the unconscious mind, distinguishing it from the personal unconscious of Freudian psychoanalysis. He argued that the collective unconscious had profound influence on the lives of individuals, who lived out its symbols and clothed them in meaning through their experiences. The psychotherapeutic practice of analytical psychology revolves around examining the patient's relationship to the collective unconscious.

A:
Tacit \Tac"it\, a. [L. tacitus, p. p. of tacere to be silent, to
       pass over in silence; akin to Goth. [thorn]ahan to be silent,
       Icel. [thorn]egja, OHG. dag[=e]n: cf. F. tacite. Cf.
       {Reticent}.]
       Done or made in silence; implied, but not expressed; silent;
       as, tacit consent is consent by silence, or by not
       interposing an objection. -- {Tac"it*ly}, adv.
       [1913 Webster]
       The tacit and secret theft of abusing our brother in
       civil contracts.                         --Jer. Taylor.
 [1913 Webster]

A: Perhaps narrower than you are looking for, but unmentionable comes to mind. Unmentionable typically connotes the subject is well known, but not spoken about, due to embarrassing or offensive aspects.
I say "perhaps narrower" because your question doesn't limit the lack of discussion as being due to an embarrassing or offensive characteristic.

A: Your examples seem different to me.

For example, nobody likes to use the restroom after they take a shower because you slide around on the seat, but that's not something commonly talked about between persons.

I would say that's probably considered impolite to discuss, like the details of your bowel movements. You probably wouldn't discuss it at a business meeting or the dinner table, but you might with your doctor. ("I sprained my wrist when I slipped off the toilet...")

Or the well understood, but un-discussed feeling you get when you feel a bug or something crawling on you before you fall asleep, even though you know it's not a bug, but just a sensation.

I don't know of any social barrier to talking about that; it just might not be interesting enough.

A: The reasons why people shy away from discussing such topics vary, so corralling all of them into a single term is challenging. grateful mentioned taboo in another answer. Other broad terms for subjects that may make others uneasy are rude or gauche.
"Toilet humor" is not discussed in polite company because it is considered tacky. Sex jokes and objectifying humor are off-color, crude, or obnoxious. We don't generally announce the results of colonoscopies to or share unedited, graphic birth videos with mere acquaintances because the topics are uncomfortable or awkward.  Revealing one's exact income to someone whom the speaker has not engaged in an accounting or legal capacity is seen as boastful, unfiltered, or—itself crudely characterized—douchey.
The last is interesting because it is borrowed from an unmentionable (also mentioned in another answer) bathroom subject as a pejorative for immoderate behavior.


text:
Q: Problem in VariationsRootLanding.ascx and a Domain entry I have a problem with my client's live environment and a concept known as Variations in SP2007.
They're domain, http://www.clientweb.co.za forcefully redirects the user to http://www.clientweb.co.za/en/pages/home.aspx but causes an error within the VariationsRootLanding.ascx with a FileNotFound exception. I tried to search the webs for similar issues but not a lot of help has been given around why this error occurs.
I found a blog post where the guy explains that AAM entries for the domain name might not exist. I have verified the entries in AAM and they all appear (at least for me) fine. The error occurred after we extended http://www.clientweb.co.za to a new port so we can enable Forms Authentication on the site (live deployment) and now we cannot get around this error.
Update
-- Hi guys, just an update to this one. The problem occured in the load-balanced environment where the user as redirected from front-end-x to front-end-y and could not deduce the culture info from front-end-x. This was an oversight on our part as part of the deployment.
Thanks,
Eric


text:
Q: C++ typedefs requiring ::type Trying to start with BGL, which means I'm starting with a lot of typedefs:
#include <iostream> //std::cin, std::cout
#include <tuple> //std::tie

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>

using namespace boost;
typedef adjacency_list<vecS,vecS,undirectedS,no_property,property<edge_weight_t,int> > Graph;
typedef graph_traits<Graph> Traits;
typedef Traits::vertex_descriptor Vertex;
typedef Traits::edge_descriptor Edge;
typedef property_map<Graph, edge_weight_t>::type EdgeWeightMap; //::type necessary (why?)

int main(int argc, char* argv[]){
    int n = ...;
    Graph g(n);
    EdgeWeightMap weight_of;
    Edge e;
    bool success;
    int s,t,w;
    std::cin >> s >> t >> w;
    tie(e,success) = add_edge(s,t,g);
    if(success)weight_of[e] = w;
}

And I was wondering just why the ::type in the typedef for EdgeWeightMap was necessary. If I omit it, I get

error: no match for 'operator[]' (operand types are

'EdgeWeightMap {aka boost::property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> >, boost::edge_weight_t>}'

and

'Edge {aka boost::detail::edge_desc_impl<boost::undirected_tag, unsigned int>}'

)
     weight_of[e] = w;

(Sorry about the format, the typedefs' < and > seem to be interfering with the blockquote)
And indeed, when I try
EdgeWeightMap weight_of = get(edge_weight,g);

I get an

error: conversion from

'boost::detail::adj_list_any_edge_pmap::bind_<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> >, boost::property<boost::edge_weight_t, int>, boost::edge_weight_t>::type {aka boost::adj_list_edge_property_map<boost::undirected_tag, int, int&, unsigned int, boost::property<boost::edge_weight_t, int>, boost::edge_weight_t>}'

to non-scalar type

'EdgeWeightMap {aka boost::property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> >, boost::edge_weight_t>}'

requested
    EdgeWeightMap weight_of = get(edge_weight,g);

Now, I can see these are different types, what I don't get is why they differ. And as I kind of would prefer to avoid surprises, could somebody please enlighten me as to when the ::type is required and when it must not be used?

A: From reading the property_map documentation, the "property_map" template is designed to provide types, not be a type. The property_map structure contains exactly two types. type and const_type, for mutable and immutable types respectively.


text:
Q: Android gps/network getting current location I have this code for receiving LatLng of current location of the user in my app
it works fine most of the time until i turn on gps, it stops working then and goes onto the part of the code which says that no provider is enabled and redirects to a location, i have tried many fixes, this is my best so far, but it is still really bad, i cant figure out a fix.
       public static LatLng getCurrentLocation(final Context context)
        {
                LocationManager locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                String locProvider = locMgr.getBestProvider(criteria, false);
                Location location = locMgr.getLastKnownLocation(locProvider);

                if(location != null) return new LatLng(location.getLatitude(), location.getLongitude());

                boolean isGPSEnabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);

                boolean isNWEnabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                Criteria criteria2 = new Criteria();
                criteria2.setAccuracy(Criteria.ACCURACY_FINE);
                criteria2.setCostAllowed(true);

                if (locMgr != null) {
                    location = locMgr.getLastKnownLocation(locMgr.getBestProvider(criteria2, true));
                    if(location == null) {
                            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                            location = locMgr.getLastKnownLocation(locMgr.getBestProvider(criteria2, true));
                            if(location != null) return new LatLng(location.getLatitude(), location.getLongitude());
                    } else
                        return new LatLng(location.getLatitude(), location.getLongitude());
                }

                if(isNWEnabled) {
                    if (locMgr != null) {
                        location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if(location != null) return new LatLng(location.getLatitude(), location.getLongitude());}
                }
                if (isGPSEnabled) {
                     if (locMgr != null) {
                            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if(location != null) return new LatLng(location.getLatitude(), location.getLongitude()); }
                }
                if (location == null){
                    Toast.makeText(context, "No location provider activated, using saved location", Toast.LENGTH_LONG).show();
                    SharedPreferences settings = context.getSharedPreferences("MyApp_Settings", 0x0);
                    String uLa = settings.getString("LATITUDE", "");
                    String uLo = settings.getString("LONGITUDE", "");
                    double lat = 0 ;
                    double lng = 0 ;
                    if (!(uLa.equals(""))) {
                        lat = Double.parseDouble(uLa);
                        lng = Double.parseDouble(uLo);
                        return new LatLng(lat, lng);
                    } else {
                        AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
                        builder2.setTitle("Location");
                        builder2.setMessage("No Location Services Enabled, Do You Want to Open Location Settings?");
                        builder2.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                         });
                        builder2.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                         });
                        builder2.show();
                        Toast.makeText(context, "Using Random Location", Toast.LENGTH_LONG).show();
                        return new LatLng(34, -94);
                    }
                }
/*                if(location == null) {
                    Toast.makeText(context, "Using Random Location", Toast.LENGTH_LONG).show();
                    return new LatLng(34, -94);
                } */
                return new LatLng(location.getLatitude(), location.getLongitude());
        }

i am looking for suggestions to improve this code and fix the gps provider


text:
Q: Creating legend around html INPUT box, not fieldset I would like to create a legend directly on a normal html input box. When you create a normal input with type text for example, html automatically creates a box with a border for this input. If I add a fieldset and legend tag to this input field, another box is create around it. I would like my legend to look like the attached picture image attached below from the site https://jiji.com.gh/registration.html.
I tried to do this by removing the border around the input field using css like so:
.signup-form input  {
border: 0px;

}
and HTML:
<form class=signup-form>
<fieldset>
<legend>Enter email</legend>
<input type="email" name="emailaddress">
</fieldset>
</form>

But this creates a much bigger box than I would like, although it actually produces what I'm trying to do. Any better ideas on how I can do this to have a neat form with legend like used on the site I mentioned?


text:
Q: Bash script to loop through values in a variable host_list=abc@xyz.com,cde@xyz.com,zbe@xyz.com

I want to write loop in bash script to scroll through each of this host_list & try to grep a particular string 'abc@xyz.com'. if its present then return yes or no


text:
Q: How to handle quick incoming network packages ? On my application i receiving UDP packages and i need to analyze them.
When package1 get to my machine - i must lock some scope and make the analyzing before analyzing package2.
The network get package all the time and there is a possible case the while i analyzing package1 ... the network layer got package2 and package3 and they are waiting for analyzing.
I can add any package to concurrentQueue - but i afraid that adding to this queue is using lock and while the queue is locked and two package2 and package3 are received and are on waiting ... and the lock is release .. then there is possible case that package3 will be added before package2 ... and then package3 will be analyze before package2 and this is a bug.
someone have other solution ?

A: The ConcurrentQueue is a lock-free thread-safe implementation of the standard queue data structure. It means that Adding/Removing from queue will not lock it.
And if you call Enqueue it will add item to queue for sure. ( This method hasn't return value and hasn't any throwing exceptions ).
It means in the ConcurrentQueue items will be in the same sequence in which  the Enqueue method has been called.
Example, how Enqueue can be implemented:
public void Enqueue(T item) {
    int insertIndex = Interlocked.Increment(ref m_high);
    m_array[insertIndex] = item;
}

Note: If you get package1 and package2 in same time with different threads, it mean that in any case architecture of program is broken. If package1 and package2 are logicaly nested, how client can sent them in same time. If somehow client sent them in same time, you can't handle it.


text:
Q: How can i use global scss variables overwrite my node modules I created a personal UI-framework (react-components),and want to share the framework with some of my projects.
For good management, I want to upload my framework on NPM.
I used SCSS for my framework consisting of one global SCSS variables file.
How would I approach this if I want to use a different global variable value for each project? I want to set my global variable file out of the node-modules folder.
Would this affect global variables into the node-module from out of the node-modules folder?
Any solution would be greatly appreciated.

A: SCSS allows you to define default values for variables, which can be overruled.
Example file in your project app.scss
$some_color: blue;
@import 'node_modules/yourframework/main'; // This is your frameworks main file

Example file in your framework node_modules/yourframework/main.scss
$some_color: red !default;
body{
   background-color: $some_color;
}

This will result in your body's background being blue.
Good luck!


text:
Q: Is it possible to change system volume with UIButton instances? I"m trying to avoid MPVolumeView  because it doesn't provide much leeway for customization. Basically, I want to implement a volume control that lets the user set the voice volume of a caller ahead of time. This is what that screen is going to look like:

I want to use UIButton to create the increase and decrease volume buttons and I'm thinking of implementing a target action mechanism in IB like this:
- (IBAction)increaseVolume:(id)sender
{
    [someVolumeObject setVolume:[systemVolume volume] + 1];
}

- (IBAction)decreaseVolume:(id)sender
{
    [someVolumeObject setVolume:[systemVolume volume] - 1];
}

Does anyone know if there's a class out there that will allow me to extract system volume elements and increment them this way(basically without having to use MPVolumeView)?

A: try like this,
1.define property and synthesize to your MPMusicPlayerController object,
@property (nonatomic, retain) MPMusicPlayerController *musicPlayer;
@synthesize musicPlayer;

2.take one float variable as,
   float volume_control=0;

3.use NSNotification in your viewDidLoad method as below to change the volume,
self.musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                       selector:@selector(handleExternalVolumeChanged:)
                           name:MPMusicPlayerControllerVolumeDidChangeNotification
                         object:self.musicPlayer];
[self.musicPlayer beginGeneratingPlaybackNotifications];

4.define Method for handleExternalVolumeChanged:  as,
- (void)handleExternalVolumeChanged:(id)notification {
  volume_control = self.musicPlayer.volume;
}

5.Now define your volume Control buttons to increase/decrease Volume,
-(IBAction)decrease_volume:(id)sender{
  if (volume_control>0) {
      self.musicPlayer.volume =self.musicPlayer.volume-0.1;
      volume_control-=0.1;
      }
   }
 -(IBAction)increase_volume:(id)sender{
    if (volume_control<1) {
    self.musicPlayer.volume =self.musicPlayer.volume+0.1;
    volume_control+=0.1;
   }
  }

hope it will helps you..


text:
Q: How can I programmatically save Wagtail Pages With Orderable Objects I have the model:
class HomePage(Page):
    content_panels = Page.content_panels + [
        InlinePanel('homepage_content', label="Homepage Content")
    ]
    template = 'home.html'

I have the Orderable object:
class HomePageContent(Orderable):
    page = ParentalKey(HomePage, on_delete=models.SET_NULL, related_name='homepage_content', null=True)
    principal_welcome_message = models.TextField()
    the_way_we_teach = RichTextField()
    meet_our_teachers = RichTextField()
    meet_our_students = RichTextField()

    # Editor panels configuration

    panels = [
        FieldPanel('principal_welcome_message'),
        FieldPanel('the_way_we_teach'),
        FieldPanel('meet_our_teachers'),
        FieldPanel('meet_our_students'),
    ]

This is how I save a HomePage object [programmatically]:
root = Page.objects.get(title="Root").specific

school_home_page = HomePage(title="Home Page")
root.add_child(instance=school_home_page).save_revision().publish()

site = Site.objects.first():

site.root_page = school_home_page
site.save()

This is how I save the HomePageContent object [programmatically]:
home_page_content = HomePageContent(
    page=school_home_page,
    principal_welcome_message="Default statement",
    the_way_we_teach="Default Tech",
    meet_our_teachers="Default developers",
    meet_our_students="Default analysts"
)

With this setup above, I cannot get the HomePageContent object to be saved along side the HomePage object. I have also tried adding the HomePageContent as a child object to the HomePage object, still no progress...
If you know any [standard] way to save Orderable objects associated with Page objects via ParentalKey alongside the corresponding Page object [programmatically and not via the admin interface], your help is greatly needed. Thank you.


text:
Q: Mark a word like in whatsapp android I want to mark in yellow some word inside a textview, like whatsapp did in their application.
What I've tried was to use html tag:
tv.setText(" hello  world");
but it doesn't work, it doesn't mark the word and the tags are part from the text.

A: Let's say you have a TextView tv, and you want to set yellow color to the text "hello" of "hello world".
TextView tv = (TextView) findViewById(R.id.textView);

Spannable word = new SpannableString("hello world");

word.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(word);

In third line, I'm setting YELLOW color to the word "hello". "hello" starts from index position 0 and ends in index position 5. After setting the span, set the Spannable word as text of TextView tv.
Here's documentation on setSpan()
setSpan (Object what, int start, int end, int flags)

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere. See Spanned for an explanation of what the flags mean. The object can be one that has meaning only within your application, or it can be one that the text system will use to affect text display or behavior. Some noteworthy ones are the subclasses of CharacterStyle and ParagraphStyle, and TextWatcher and SpanWatcher.

Spannable section

This is the interface for text that has markup objects attached to ranges of it. Not all text classes have mutable markup or text

A: You need to create Spannable and specify color for specific text range. Like in the following answer: https://stackoverflow.com/a/3514435/1099716

A: Try this,
myTextView.setText(Html.fromHtml(text + "" + CepVizyon.getPhoneCode() + "

"
        + getText(R.string.currentversion) +someString));

A: All the other answers are relevant, and are personally what I would use, but in the interest of increased flexibility note that it is also possible to apply html formatting with the Html class:
tv.setText(Html.fromHtml("Coloured Text"))


text:
Q: How can i achieve this requirement by creating an custom object and creating a visual force page Hi Can any one suggest me on this requirement .
PFA Screenshot
I need to add the next 6 quarters and the quantity by keeping the default sales price. giving an rough calculation of the total revenue .
As per my plan : I will be creating an custom object with the fields required and then calling them through VF page.
Any help is very much appreciated.

A: Custom objects are helpful when you are going to preserve data to use later.
Here as i could understand you need to show results according to some fix values for a fixed time interval. So, It means that your data is not going to be increasing with respect to time. It will always for 6 quarters.
I would recommend to create a visualforce page which will do some calculation by fetching some values from existing object records and show on page in a user-friendly way.
If you think that your requirement can be enhanced in later time and some major functionality can be added on visualforce page then you can design the  visualforce apex controller to support custom object when required.
Another thing, using a well designed custom object will solve various complexity on visualforce page design.


text:
Q: Java BufferedReader.readLine() not waiting for user input I am having an issue with my instance of BufferedReader not waiting for the user to input before moving forward.
static BufferedReader in;

public class {
    public static void main(String[] args) {
        try{
            in = new BufferedReader(new InputStreamReader(System.in));
            String input;
            System.out.println("prompt");
            input = in.readLine();
            if(input.equals("Y")){
                //do something
            }else {
                //do something else
            }
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

What happens is I when I run the program, it simply skips over the in.readLine() and throws a null exception at the if statement. I am at a loss on what is happening, as I used the same code for another project that still works.
Thanks!

A: Found the answer. Using gradle to run the program and my task didn't have the parameter for standardInput = System.in. Still getting used to project building software!

A: Yes you have to treat the exception, just add this:
public static void main(String[] args) throws IOException {

        in = new BufferedReader(new InputStreamReader(System.in));
        String input;
        System.out.println("prompt");
        input = in.readLine();
        if(input.equals("Y")){
            System.out.println("it works !!");
        }else {
            System.out.println("it's not a Y :(");
        }
    }


text:
Q: Как расшифровать полученый код python У меня есть код:
result = []
data = b'hello'
for b in data:
    result.append(list(map(int, f'{b:08b}')))
print(result)

Он выводит:
[[0, 1, 1, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 1, 1]]

Вопрос: Как можно расшифровать полученный результат (т.е. сделать обратную функцию)

A: a = [[0, 1, 1, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 1, 1]]

def decode(seq: list[list[int]]) -> bytes:
    return bytes(int(''.join(str(bit) for bit in bits), base = 2) for bits in seq)

print(decode(a))
# hello


text:
Q: NestJS - how to check if JWT can access specific endpoint Let's say I have 3 endpoints: A is for generating JWT token, B for accessing data of user X and C for accessing data of user Y. Now, what I want to do is, that I can from recieved token somehow in controller guards figure out, if user can access endpoint.
So, token generated for user X can only access endpoint B, token generated for user Y can only access endpoint C.
Token has to be generated at endpoint A, since users sign in at same form.
If question is unclear ask in comment.

A: You Can do that by specifying in the payload a role, by this role you set a guard on each endpoint which role has the access to it. let me give an example:
I believe that you have a function where you fill you payload kind of this function :
    createJwtPayload(user){
    let data: JwtPayload = {
        userData: user,
        companyId : user.company.id,
        role:user.role.name, // for us this where we specify the role for our User
    };

   ......
}

Now We have to create guards we need to specify access for x endpoints
let start with Admin Guard:
    @Injectable()
            export class AdminGuard implements CanActivate {
        async canActivate(context: ExecutionContext): Promise<boolean> {
         const request = context.switchToHttp().getRequest();

      if (!request.headers.authorization) {
        return false;
      }
      request.user = await this.validateToken(request.headers.authorization);
       if( request.user.role == ROLES.SUPER_ADMIN) {
          return true;
        }
       return false;
             }

         async validateToken(auth: string) {
            ......
      }

lets make the second guard we call it EmployeGuard :
 ....
@Injectable()
export class EmployeGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();

      if (!request.headers.authorization) {
        return false;
      }
      request.user = await this.validateToken(request.headers.authorization);
         if( request.user.role == ROLES.COMPANY_ADMIN ||  request.user.role == ROLES.USER) {
          return true;
        }
       return false;
  }

  async validateToken(auth: string) {
    ......
}

Now to use these guards we just need to use  @UseGuards() in our endpoint :
      @Post()
    @UseGuards(AdminGuard)
    async addCompany(@Res() res, @Body() createDto: CompanyDto) {
      ........
    }

   @Get(':companyID')
    @UseGuards(EmployeGuard)
    async getcompany(@Res() res, @Param('companyID') companyID) {
       ....
     }

Bonus: you can @useGuards on the controller to make sure the all endpoints use it


text:
Q: If $g$ is an element in an abelian group $G$ and $H\leqslant G$, must there exist an $n$ such that $g^n\in H$? Let $G$ be an abelian group and $H$ a subgroup of $G$. For each $g \in G$, does there always exist an integer $n$ such that $g^{n} \in H$?

A: This is evident that if $[G:H]=n<\infty$ then $\forall g\in G, g^n\in H$.

A: No. Let $G=\mathbb{Z}\times\mathbb{Z}$, $H=\{(x,0)\}$. Then $(0,1)^n\notin H$ for any $n>0$

A: Hint: For $n\geq 1$: we can find find a counterexample subgroup $H\leq G$, with $G =(\mathbb{Z}, +)$ which is infinite and cyclic: Put $H = \{e\} = \{0\} \leq G$.

A: If you mean: there exists $n\geq 1$ such that...
Take $G=\mathbb{Z}$ and $H=\{0\}$.
If not, $n=0$ will always do.

A: No.  Let $G = \mathbb{Z}^2$.  Let $H = <(1,0)>$.  What is $(0,1)^n$?

A: Consider the circle group $\Bbb{T} = \{e^{ix}\mid x\in\Bbb{R}\}$, and consider the subgroup given by $H = \{z\in\Bbb{T}\mid z^n = 1\textrm{ for some }n\in\Bbb{Z}\setminus\{0\}\}$. $e^i\in\Bbb{T}$ can never satisfy $e^{in} = 1$ for any $n\in\Bbb{Z}\setminus\{0\}$.

A: If $G$ is periodic, then yes: if $n$ is the order of $g$ then $g^n=1\in H$.
Otherwise - no. Let $G=H\oplus K$ is torsionless, $x\in K, x\ne 1$. Then for all $n$ $x^n\not\in H$.


text:
Q: Python 2.7: Create a new df column with substring from string in another column I have a pandas dataframe, and I would like to create a new column with a substring of a string contained in a column.
For eg. "race" column contains the word "2016_Lap_JAPANESE_Third_Times.csv", i would like to extract the word 'japanese'.
An approach i am taking now is to compare if the word is in a list, if yes, inpute that value to the new column.
race_names = ['japanese'] -> i have along list of elements in this listand and multiple names in "race" column.

    for i,row in df_fp2.iterrows():
        for name in race_names:
            if name in df_fp2.loc[i,'race']:
                df_fp2.loc[i,'name'] = str(name) + " Grand Prix"

Df converted to dictionary.
{'driverRef': {151: 'button',
  152: 'button',
  153: 'button',
  154: 'button',
  155: 'button'},
 'driver_no': {151: 22, 152: 22, 153: 22, 154: 22, 155: 22},
 'milliseconds': {151: 1339994.0,
  152: 692245.0,
  153: 96286.0,
  154: 94547.999999999985,
  155: 114725.0},
 'name': {151: 'J.BUTTON',
  152: 'J.BUTTON',
  153: 'J.BUTTON',
  154: 'J.BUTTON',
  155: 'J.BUTTON'},
 'race': {151: '2016_Lap_JAPANESE_Third_Times.csv',
  152: '2016_Lap_JAPANESE_Third_Times.csv',
  153: '2016_Lap_JAPANESE_Third_Times.csv',
  154: '2016_Lap_JAPANESE_Third_Times.csv',
  155: '2016_Lap_JAPANESE_Third_Times.csv'},
 'time': {151: 1339.9939999999999,
  152: 692.245,
  153: 96.286000000000001,
  154: 94.547999999999988,
  155: 114.72499999999999}}

This is an array of unique elements in "race" column of df, as the arrangement of words are different, i cannot simply strip the words in front and behind each country name.
array(['2016_Lap_ABU_Third_Times.csv', '2016_Lap_BRASIL_Third_Times.csv',
       '2016_Lap_CHINESE_Third_Times.csv',
       '2016_Lap_JAPANESE_Third_Times.csv',
       '2016_Lap_MAGYAR_Third_Times.csv',
       '2016_Lap_SINGAPORE_Third_Times.csv', '2016_Lap_Third_Times.csv',
       '2016_Lap_UNITED_Third_Times.csv',
       'AUSTRALIAN_2016_Lap_Third_Times.csv',
       'BAHRAIN_2016_Lap_Third_Times.csv',
       'BELGIAN_2016_Lap_Third_Times.csv',
       'CANADA_2016_Lap_Third_Times.csv',
       'ESPANA_2016_Lap_Third_Times.csv',
       'EUROPE_2016_Lap_Third_Times.csv',
       'MALAYSIA_2016_Lap_Third_Times.csv',
       'Mexico_2016_Lap_Third_Times.csv',
       'RUSSIAN_2016_Lap_Third_Times.csv'], dtype=object)

A: If in race_names are all possible extracted words use str.extract:
import re
race_names = ['japanese']
pat = '|'.join(r"{}".format(x) for x in race_names)
df['name'] = df['race'].str.extract('('+ pat + ')', expand=False, flags=re.I) + " Grand Prix"
print (df)
    driverRef  driver_no  milliseconds                 name  \
151    button         22     1339994.0  JAPANESE Grand Prix
152    button         22      692245.0  JAPANESE Grand Prix
153    button         22       96286.0  JAPANESE Grand Prix
154    button         22       94548.0  JAPANESE Grand Prix
155    button         22      114725.0  JAPANESE Grand Prix

                                  race      time
151  2016_Lap_JAPANESE_Third_Times.csv  1339.994
152  2016_Lap_JAPANESE_Third_Times.csv   692.245
153  2016_Lap_JAPANESE_Third_Times.csv    96.286
154  2016_Lap_JAPANESE_Third_Times.csv    94.548
155  2016_Lap_JAPANESE_Third_Times.csv   114.725

Maybe is possible also use replace and str.strip:
df = pd.DataFrame({'race':['2016_Lap_ABU_Third_Times.csv', '2016_Lap_BRASIL_Third_Times.csv',
       '2016_Lap_CHINESE_Third_Times.csv',
       '2016_Lap_JAPANESE_Third_Times.csv',
       '2016_Lap_MAGYAR_Third_Times.csv',
       '2016_Lap_SINGAPORE_Third_Times.csv', '2016_Lap_Third_Times.csv',
       '2016_Lap_UNITED_Third_Times.csv',
       'AUSTRALIAN_2016_Lap_Third_Times.csv',
       'BAHRAIN_2016_Lap_Third_Times.csv',
       'BELGIAN_2016_Lap_Third_Times.csv',
       'CANADA_2016_Lap_Third_Times.csv',
       'ESPANA_2016_Lap_Third_Times.csv',
       'EUROPE_2016_Lap_Third_Times.csv',
       'MALAYSIA_2016_Lap_Third_Times.csv',
       'Mexico_2016_Lap_Third_Times.csv',
       'RUSSIAN_2016_Lap_Third_Times.csv']})

df['name'] = (df['race'].replace(['_Third_Times.csv','Lap', '\d+'], '', regex=True)
                        .str.strip('_'))
print (df)
                                   race        name
0          2016_Lap_ABU_Third_Times.csv         ABU
1       2016_Lap_BRASIL_Third_Times.csv      BRASIL
2      2016_Lap_CHINESE_Third_Times.csv     CHINESE
3     2016_Lap_JAPANESE_Third_Times.csv    JAPANESE
4       2016_Lap_MAGYAR_Third_Times.csv      MAGYAR
5    2016_Lap_SINGAPORE_Third_Times.csv   SINGAPORE
6              2016_Lap_Third_Times.csv
7       2016_Lap_UNITED_Third_Times.csv      UNITED
8   AUSTRALIAN_2016_Lap_Third_Times.csv  AUSTRALIAN
9      BAHRAIN_2016_Lap_Third_Times.csv     BAHRAIN
10     BELGIAN_2016_Lap_Third_Times.csv     BELGIAN
11      CANADA_2016_Lap_Third_Times.csv      CANADA
12      ESPANA_2016_Lap_Third_Times.csv      ESPANA
13      EUROPE_2016_Lap_Third_Times.csv      EUROPE
14    MALAYSIA_2016_Lap_Third_Times.csv    MALAYSIA
15      Mexico_2016_Lap_Third_Times.csv      Mexico
16     RUSSIAN_2016_Lap_Third_Times.csv     RUSSIAN


text:
Q: Using ptrace to reverse ls readout doesn't seem to work I've been following some instructions on how to use ptrace that are found here. I am on ubuntu 14.04, x64, and I have been altering bits of the example code to work with my x64 machine, such as eax to rax, and changing 4s to 8s where appropriate. The forth example is supposed to reverse the output of ls, but it does not. I get this:
bin       Debugger.depend  dummy1.s       main_tut2.cpp  main_tut4.cpp  obj
Debugger.cbp  Debugger.layout  main_tut1.cpp  main_tut3.cpp  main_tut5.cpp
bin       Debugger.depend  dummy1.s       main_tut2.cpp  main_tut4.cpp  obj
Debugger.cbp  Debugger.layout  main_tut1.cpp  main_tut3.cpp  main_tut5.cpp

And I believe I should be getting it reversed if my code works correctly, something like this:
jbo ppc.4tut_niam ppc.2tut_niam s.1ymmud dneped.reggubeD nib
ppc.5tut_niam ppc.3tut_niam ppc.1tut_niam tuoyal.reggubeD pbc.reggubeD
jbo ppc.4tut_niam ppc.2tut_niam s.1ymmud dneped.reggubeD nib
ppc.5tut_niam ppc.3tut_niam ppc.1tut_niam tuoyal.reggubeD pbc.reggubeD

I have found an error in the code printed in the page I linked above (here) which is 20 lines up from the bottom in my code, but I think I have corrected that. This is the incorrect line:
                str = (char *)calloc((params[2] + 1) * sizeof(char));

It has one arguement but needs two. I believe it should be:
                str = (char *)calloc(params[2] + 1, (params[2] + 1) * sizeof(char));

But if I have that wrong, I would be happy to be corrected. I also tried:
                str = (char *)calloc(1, (params[2] + 1) * sizeof(char));

I'm still not sure which would be correct, if either...
Is this the reason why it's not working? Or is it something else, maybe another problem relating to being on x64 that I haven't accounted for? Bonus points for anyone who can tell me what calloc is doing in this instance and why the second arguement is as it is.
EDIT:
I have just tried printing str both before and after the reversal... it's just a bunch of question marks. When I debug, it seems the entire contents of str is -1s. This further suggests that something is wrong with my call to calloc()...
Anyway, here is my version of the code:
#include <iostream>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>         // For fork()
//#include <linux/user.h>   // For constants ORIG_EAX for 32bit etc
#include <sys/user.h>       // For constants ORIG_RAX for 64bit etc
#include <sys/reg.h>
#include <sys/syscall.h>    // For SYS_write etc
#include <cstring>          // For strlen()

/** ptrace(enum __ptrace_request,   // behaviour of ptrace
           pid_t pid,               // Process ID
           void *addr,              // Address to read in user area
           void *data);             //
**/

/**
PTRACE_TRACEME,   PTRACE_PEEKTEXT, PTRACE_PEEKDATA, PTRACE_PEEKUSER,   PTRACE_POKETEXT,
PTRACE_POKEDATA,  PTRACE_POKEUSER, PTRACE_GETREGS,  PTRACE_GETFPREGS,  PTRACE_SETREGS,
PTRACE_SETFPREGS, PTRACE_CONT,     PTRACE_SYSCALL,  PTRACE_SINGLESTEP, PTRACE_DETACH
**/

const int long_size = sizeof(long);

void reverse(char *str) {

    int i, j;
    char temp;

    for (i = 0, j = strlen(str) - 2; i <= j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

void getData(pid_t child, long addr, char *str, int len) {

    char *laddr;
    int i, j;
    union u {
        long val;
        char chars[long_size];
    } data;

    i = 0;
    j = len / long_size;
    laddr = str;

    while(i < j) {
        data.val = ptrace(PTRACE_PEEKDATA, child, addr + i * 8, NULL);
        memcpy(laddr, data.chars, long_size);
        i++;
        laddr += long_size;
    }

    j = len % long_size;

    if (j != 0) {
        data.val = ptrace(PTRACE_PEEKDATA, child, addr + i * 8, NULL);
        memcpy(laddr, data.chars, j);
    }

    str[len] = '\0';
}

void putData(pid_t child, long addr, char *str, int len) {

    char *laddr;
    int i, j;
    union u {
        long val;
        char chars[long_size];
    } data;

    i = 0;
    j = len / long_size;
    laddr = str;

    while(i < j) {
        memcpy(data.chars, laddr, long_size);
        ptrace(PTRACE_POKEDATA, child, addr + i * 8, data.val);
        i++;
        laddr += long_size;
    }

    j = len % long_size;

    if (j != 0) {
        memcpy(data.chars, laddr, j);
        ptrace(PTRACE_POKEDATA, child, addr + i * 8, data.val);
    }
}

int main()
{
    pid_t child;
    child = fork();

    if (child == 0) {

        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execl("/bin/ls", "ls", NULL);

    } else {

        long orig_rax;
        long params[3];
        int status;
        char *str, *laddr;
        int toggle = 0;

        while(1) {

            wait(&status);
            if (WIFEXITED(status))
                break;

            orig_rax = ptrace(PTRACE_PEEKUSER, child, 8 * ORIG_RAX, NULL);

            if (orig_rax == SYS_write) {

                if (toggle == 0) {

                    toggle = 1;
                    params[0] = ptrace(PTRACE_PEEKUSER, child, 8 * RBX, NULL);
                    params[1] = ptrace(PTRACE_PEEKUSER, child, 8 * RCX, NULL);
                    params[2] = ptrace(PTRACE_PEEKUSER, child, 8 * RDX, NULL);
                    str = (char *)calloc(params[2] + 1, (params[2] + 1) * sizeof(char));

                    getData(child, params[1], str, params[2]);
                    reverse(str);
                    putData(child, params[1], str, params[2]);

                } else {

                    toggle = 0;
                }
            }

            ptrace(PTRACE_SYSCALL, child, NULL, NULL);
        }
    }

    execl("/bin/ls", "ls", NULL);

    return 0;
}

Any assistance would be greatly appreciated!

A: So thanks to @melpmene and @MarkPlotnick for the answers. I have struggled to figure out some of the other answers covering the same topic, and another resource I found that suggested how to convert the x32 code to x64 code wasn't entirely accurate (at least for my system), so here is what I needed to do:
1)
str = (char *)calloc(params[2] + 1 * sizeof (char))

should be
str = (char *)calloc(params[2] + 1, sizeof (char))

2)
EBX, ECX and EDX should be replaced by RDI, RSI and RDX


text:
Q: Why does this execute and summon command throw an error? I am trying to summon a lightning bolt when a repeating command block detects an arrow on grass, but every time the command block runs it throws the error:

Failed to execute 'summon' on Arrow.

I'm on Minecraft Bedrock version 1.12.1.
Command:
/execute @e[type=arrow] ~ ~ ~ detect ~ ~-1 ~ grass 1 summon lightning_bolt

A: Currently, your command is executing at all arrows which are on a block of grass with a metadata of 1; typical grass blocks don't have a metadata of 1. In order to fix this, set the value of 1 to -1, resulting in:
/execute @e[type=arrow] ~ ~ ~ detect ~ ~-1 ~ grass -1 summon lightning_bolt

The value of -1 tells Minecraft to ignore metadata instead of check for it.


text:
Q: How to integrate facebook with my weebly website I have a website developed on weebly. I want to integrate my website with facebook registration and login so that members can login on my site through their facebook login information. Weebly gives me an option to have a custom html through which i can get a code to allow the facebook login onto my website

A: Weebly does not provide you access to PHP , the only option you have is javascript, i have written a working script based on js-sdk specially for weebly websites, this script will allow users to login via facebook and auto-fill up the sign up form with their facebook data.


text:
Q: command line prettify BSON been working with mongo recently, which means a ton of very large nested hashes in (basically) json format. Currently I am piping json through python -mjson.tool in emacs, which works great for json, but bson also includes ObjectId("key"), and ISODate("date") (for example, {"_id": ObjectId("4ec319b0e35c1f1063000015"), "date": ISODate("2011-11-16T00:00:00Z")} which are not valid json, and causes the python lib to puke.
Does anyone know of a more lenient prettifier? Or some other way to accomplish the job for BSON. I don't even mind if the solution drops the wrapping functions, it is more to be able to visualize a deeply nested json datastructure easier


text:
Q: The generate if condition must be a constant expression I am trying to create an Immediate Generator for RISC-V assembly, but I have encountered an error with if statement.
Here is my code in Verilog:
module signextend(in, out, sel);
    parameter nin = 32;
    parameter nout = 32;
    input [nin-1:nin-25] in;
    input [2:0] sel;
    output [nout-1:0] out;

    if (sel == 3'b000)
        begin
            assign out[19:0] = in[31:12];
            assign out[31:20] = {12{in[31]}};
        end
    else if (sel == 3'b001)
        begin
            assign out[11:0] = in[31:20];
            assign out[31:12] = {20{in[31]}};
        end
    else if (sel == 3'b010)
        begin
            assign out[4:0] = in[24:20];
            assign out[31:5] = 0;
        end
    else if (sel == 3'b011)
        begin
            assign out[3:0] = in[11:8];
            assign out[4:9] = in[30:25];
            assign out[10] = in[7];
            assign out[11] = in[31];
            assign out[31:12] = {20{in[31]}};
        end
    else if (sel == 3'b100)
        begin
            assign out[4:0] = in[11:7];
            assign out[11:5] = in[31:25];
            assign out[31:12] = {20{in[31]}};
        end
    else if (sel == 3'b101)
        begin
            assign out[9:0] = in[21:30];
            assign out[10] = in[20];
            assign out[18:11] = in[19:12];
            assign out[19] = in[31];
            assign out[31:20] = {12{in[31]}};
        end
    else
        assign out = 32'hxxxx;
endmodule

The problem exists in each if statement:

The generate if condition must be a constant expression.

A: You need to put all your code inside an always block and remove the assigns:
always @(*) begin
  if (sel == 3'b000)
      begin
          out[19:0] = in[31:12];
          out[31:20] = {12{in[31]}};
      end
  else if (sel == 3'b001)
    // etc

An always block contains a little bit of software (your if statements) that models a little bit of hardware (the resulting combinational logic).
It is legal to have an if statement outside an always (or initial) block, but then it means something different. Then it means conditional including of hardware, ie if some condition is true, include this hardware. Such a condition has to be static, ie fixed at compile time. It cannot be an input, like your sel. If you think about it, that makes total sense: how could you create some hardware that magically appears and disappears depending on the value of some input? You can't. That is why you are getting your error.
You need to remove the assigns, because while it is legal to have an assign inside an always block, it means something weird. Never do it.