text:
Q: Warning: Unsuccessful read: Matching failure in format I am having issues reading data from a serial port.
Most of the time, the code works and I am able to successfully read in 1000 data points for both z and y.
Sometimes, no data is read from the serial port, and sometimes only 40 data points are read from the serial port rather than the expected 1000. I receive this warning when performing the read.

Warning: Unsuccessful read: Matching failure in format.. Subscripted assignment dimension mismatch.

What does this warning mean and how can I change the code below to prevent it.
clk
clear all
delete(instrfindall);
b = serial('COM2','BaudRate',9600);
fopen(b);
k = 1;
n = 0;
while(n < 1000)
    z(k) = fscanf(b, '%d');
    y(k) = fscanf(b, '%d');
    n = n + 1;
    k = k + 1;
end

A: You are correct that the problem is timing. The error message indicates that the serial port did not receive as many bytes as it required to create a value with the format you specified before it timed out. For simple examples, the code you have works fine, but as you discovered, it is not robust.
You have to know two things before you start:

*

*Does your serial device send data in "lines", using a line
terminator character, or not?

*How many bytes do you expect to
read each time you read data from the serial port?

Then there are two approaches:
A) Procedural Wait (easier, less robust): Add a statement in your code which waits until a certain number of bytes have been received, and then reads them.
numBytes = 10; % read this many bytes when ready
% make sure serial object input buffer is large enough
serialport = serial('COM100','InputBufferSize',numbytes*10);

fopen(serialport);

while 1
    ba = serialport.BytesAvailable;
    if ba > numBytes
        mydata = fread(serialport, numBytes);
        % do whatever with mydata
    end
    drawnow;
end

fclose(serialport);

B) Object Callback (more advanced/complex, potentially more robust): Defined a callback function which is executed whenever a certain condition is met. The callback function handles the data from the serial device. The execute condition is either:

*

*a) a certain number of bytes has been received

*b) a line terminator
character has been received

The following example uses condition a). It requires two functions, one for your main program and one for the callback.
function useserialdata
% this function is your main program

numBytes = 10; % read this many bytes when ready
% make sure serial object input buffer is large enough
serialport = serial('COM100','InputBufferSize',numbytes*10);

% assign the callback function to the serial port object
serialport.BytesAvailableFcnMode = 'byte';
serialport.BytesAvailableFcnCount = numBytes;
serialport.BytesAvailableFcn = {@getmydata,numBytes};
serialport.UserData.isnew = 0;

fopen(serialport);

while 1
    if serialport.UserData.isnew > 0
        newdata=ar.UserData.newdata; % get the data from the serial port
        serialport.UserData.isnew=0; % indicate that data has been read

        % use newdata for whatever

    end
end

fclose(serialport);

function getmydata(obj,event,numBytes)
% this function is called when bytes are ready at the serial port

mydata = fread(obj, numBytes);
% return the data for plotting/processing
if obj.UserData.isnew==0
    obj.UserData.isnew=1; % indicate that we have new data
    obj.UserData.newdata = mydata;
else
    obj.UserData.newdata=[obj.UserData.newdata; mydata];
end

Obviously these are toy examples, and you will have many other details like timeouts, error handling, program responsiveness, etc to consider, depending on the details of how the serial device works. See the matlab help file for "Serial Port Object Properties" for more information.


text:
Q: Power Query with Additional Column I am using a power query to read rows indexes by an item number from one file I receive to one file I am maintaining. I need to add some columns that are editable by me (cell editing), in a way that when the query is refreshed, these values will remain in the same row, with the same item number (these columns are additional remarks, dates and categories I need to keep for each item).  I have tried to expand the table generated by the power query (dragging the bottom right corner) and adding some columns this was. However, when I refresh the query, if the items in the query change order, the values in the additional columns do not match with the loaded description anymore.  My current solution is having another sheet (table) with the item number and remarks, and merging the two queries into one sheet. I'd like to be able to it in one sheet with one query.

A: For anyone who was looking for an answer to the above question. I was able to do the exact functionality by using a self-referencing table in the Power Query and merging it with the new data.
Basically, you add a new query from table and you load it as a connection.
Then, edit you original query and merge the new table query to it.
Expand your "Remarks" columns.
Your remarks will be read before any query refresh and loaded with the new query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Distribute private Android app through Google Play without EMM We have an app that we distribute to under 100 users in about 20 customer organizations. At the moment we the newest apk -file is just published to a url.
We are trying to use MS AppCenter distribution and that is working pretty nicely except for the initial install when the app is opening a webpage for distribution enrollment and the the app is not always reopened.
Is there a way to publish an app to Google Play as a "private" app so that you don't find it in Google Play search or lists but have to have the url to app to access it the first time?
Our customers don't have EMM.


text:
Q: @media queries NOT WORKING (While uploaded to Google Drive) NOTE that media queries run perfectly while viewed offline , But it is not working while uploaded to Google Drive and hosted via drive to web..
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BROWN</title>
    <link rel="stylesheet" href="index.css">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=KoHo&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Merriweather&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Newsreader&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans&display=swap" rel="stylesheet">

brown

New Apple iPhone 11 (64GB) - Black

Price:₹ 53,250.00

Know More

<button type = "submit" id = "buy-now-p-id-1">Buy Now</button>

New Apple MacBook Pro with Apple M1 Chip

Price: ₹ 1,16,790.00

Know More

<button type = "submit" id = "buy-nowp-id-2">Buy Now</button>

New Apple Watch SE (GPS + Cellular, 44mm)

Price: ₹ 36,900.00

Know More

<button type = "submit" id = "buy-now-p-id-3">Buy Now</button>

JBL Tune 750BTNC by Harman Over-Ear Wireless

Price: ₹ 5,799.00

Know More

<button type = "submit" id = "buy-now-p-id-4" >Buy Now</button>

THE HTML PAGE LINKS ARE ALL GOOD I TRIPLE CHECKED IT
* {
    margin:0;
    padding:0;
    text-decoration:none;
    box-sizing:border-box;
}
#mainbar {
    display:flex;
    height:90px;
    align-items:center;
}
#mainbar h1 {
    margin-left:100px;
    font-family:'KoHo', sans-serif;
    font-size: 45px;
}
img {
    height:230px;
    width:230px;
    margin-left: 10px;
    border-radius:5px;
    box-shadow:0px 0px 10px black;
}
h2 {
    font-size: 28px;
    font-family: 'Merriweather', serif;
}
h3 {
    font-family: 'Playfair Display', serif;
    font-size: 25px;
}
h4 {
    font-family: 'Newsreader', serif;
    font-size: 25px;
}
a {
    font-size: 25px;
    font-family: 'Roboto', sans-serif;
    color:red;
}
ul {
    margin-left:30px;
    list-style:none;
    line-height:45px;
}
button {
    color:black;
    background-color:white;
    width:90px;
    height:40px;
    font-size: 15px;
    border-radius:5px;
    border:2px solid grey;
    box-shadow:0px 0px 2px black;
    font-family: 'Noto Sans JP', sans-serif;
    transition : 1s ease-in-out ;
    /* transition-duration:1;  */
}
#box {
    height:250px;
    display:flex;
    align-items:center;
    border-top:1px solid grey;
    border-bottom:1px solid grey;
    box-shadow:0px 0px 10px black;
    margin-top:10px;
}
span {
    color:rgb(27, 55, 179);
    font-family: 'Noto Sans', sans-serif;
}
#contents {
    display:flex;
    flex-direction: column;
}
#contents #box #p-id-1_description {
    display:flex;
    flex-direction: column;
}
*MEDIA QUERIES NOT SHOWING UP*
@media (max-width:850px) {
    img {
        height:200px;
        width:200px;
        margin-left: 10px;
        border-radius:5px;
        box-shadow:0px 0px 10px black;
    }
    h2 {
        font-size: 24px;
        font-family: 'Merriweather', serif;
    }
    h3 {
        font-family: 'Playfair Display', serif;
        font-size: 22px;
    }
    h4 {
        font-family: 'Newsreader', serif;
        font-size: 22px;
    }
}
@media (max-width:700px) {
    img {
        height:180px;
        width:180px;
        margin-left: 10px;
        border-radius:5px;
        box-shadow:0px 0px 10px black;
    }
    h2 {
        font-size: 21px;
        font-family: 'Merriweather', serif;
    }
    h3 {
        font-family: 'Playfair Display', serif;
        font-size: 19px;
    }
    h4 {
        font-family: 'Newsreader', serif;
        font-size: 18px;
    }
    ul {
        margin-left:30px;
        list-style:none;
        line-height:40px;
    }
}
@media (max-width:550px) {
    img {
        height:150px;
        width:150px;
        margin-left: 10px;
        border-radius:5px;
        box-shadow:0px 0px 10px black;
    }
    h2 {
        font-size: 18px;
        font-family: 'Merriweather', serif;
    }
    h3 {
        font-family: 'Playfair Display', serif;
        font-size:16px;
    }
    h4 {
        font-family: 'Newsreader', serif;
        font-size: 16px;
    }
    a {
        font-size: 19px;
        font-family: 'Roboto', sans-serif;
        color:red;
    }
    ul {
        margin-left:30px;
        list-style:none;
        line-height:35px;
    }
}
@media (max-width:400px) {
    #mainbar h1 {
        margin-left:50px;
        font-family:'KoHo', sans-serif;
        font-size: 45px;
    }
    #box {
        height:180px;
        display:flex;
        align-items:center;
        border-top:1px solid grey;
        border-bottom:1px solid grey;
        box-shadow:0px 0px 10px black;
        margin-top:10px;
    }
    img {
        height:125px;
        width:125px;
        margin-left: 10px;
        border-radius:5px;
        box-shadow:0px 0px 10px black;
    }
    h2 {
        font-size: 14px;
        font-family: 'Merriweather', serif;
    }
    h3 {
        font-family: 'Playfair Display', serif;
        font-size:15px;
    }
    h4 {
        font-family: 'Newsreader', serif;
        font-size: 14px;
    }
    a {
        font-size: 15px;
        font-family: 'Roboto', sans-serif;
        color:red;
    }
    ul {
        margin-left:30px;
        list-style:none;
        line-height:30px;
    }
}
@media (max-width:350px) {
    #box {
        height:220px;
        display:flex;
        align-items:center;
        border-top:1px solid grey;
        border-bottom:1px solid grey;
        box-shadow:0px 0px 10px black;
        margin-top:10px;
    }
    img {
        height:110px;
        width:110px;
        margin-left: 10px;
        border-radius:5px;
        box-shadow:0px 0px 10px black;
    }
    h2 {
        font-size: 13px;
        font-family: 'Merriweather', serif;
    }
    h3 {
        font-family: 'Playfair Display', serif;
        font-size:13px;
    }
    h4 {
        font-family: 'Newsreader', serif;
        font-size: 12px;
    }
    a {
        font-size: 15px;
        font-family: 'Roboto', sans-serif;
        color:red;
    }
    ul {
        margin-left:30px;
        list-style:none;
        line-height:30px;
    }
    button {
        color:black;
        background-color:white;
        width:80px;
        height:30px;
        font-size: 15px;
        border-radius:5px;
        border:2px solid grey;
        box-shadow:0px 0px 2px black;
        font-family: 'Noto Sans JP', sans-serif;
        transition : 1s ease-in-out ;
        /* transition-duration:1;  */
    }
}

This is working offline but when viewed ig Google Drive the media query desent show up.
This is the link to that site you can see that the media queries are not showing up

A: You can use @media screen or use !important and ascend the max-width css order.I mean the smallest width should go top from the ohtres.


text:
Q: why does my two-dimensional array print all 0s? I have a 2-D array named Maze. it is a global variable. I hard coded the data at each position in my setData() method. but when I try to print my array down below it prints all 0s. why is that? thank you.
public class Maze
{
    int [][] maze = new int[4][6];
    public void setData()
    {
        maze[0][0] = 1; maze[0][1] = 0; maze[0][2] = 1; maze[0][3] = 1; maze[0][4] = 0; maze[0][5] = 1;
        maze[1][0] = 0; maze[1][1] = 0; maze[1][2] = 1; maze[1][3] = 0; maze[1][4] = 0; maze[1][5] = 0;
        maze[2][0] = 1; maze[2][1] = 0; maze[2][2] = 1; maze[2][3] = 0; maze[2][4] = 1; maze[2][5] = 0;
        maze[3][0] = 0; maze[3][1] = 0; maze[3][2] = 0; maze[3][3] = 0; maze[3][4] = 1; maze[3][5] = 1;
    }

    public void printMaze()
    {
        System.out.println("The matrix: ");

        for (int m=0; m<4; m++)
        {
            for (int n=0; n<6; n++)
                System.out.print(maze[m][n]);
            System.out.println();
        }
    }
}

public class MazeTester
{
    public static void main (String [] args)
    {
        Maze mmgg = new Maze();

        mmgg.printMaze();
    }
}

A: You need to run setData to put all your values in.
   public static void main (String [] args)
   {
      setData();
      printMaze();
   }

A: You never call the setData() method so the array is full of 0's which are the default value.

A: Your array prints all 0s because you never initialize it (you just declared setData() and you didn't call it), thus its elements get default values which are 0 for int variables.
If you don't want to use the setData() method, you can initialize your array in an init bloc:
     {
          maze[0][0] = 1; maze[0][1] = 0; maze[0][2] = 1; maze[0][3] = 1; maze[0][4] = 0; maze[0][5] = 1;
          maze[1][0] = 0; maze[1][1] = 0; maze[1][2] = 1; maze[1][3] = 0; maze[1][4] = 0; maze[1][5] = 0;
          maze[2][0] = 1; maze[2][1] = 0; maze[2][2] = 1; maze[2][3] = 0; maze[2][4] = 1; maze[2][5] = 0;
          maze[3][0] = 0; maze[3][1] = 0; maze[3][2] = 0; maze[3][3] = 0; maze[3][4] = 1; maze[3][5] = 1;
      }

In that way, you just have to instantiate your classe Maze and call the method printMaze():
  public static void main ( String[] args ) {

        Maze mmg = new Maze();
        mmg.printMaze ();

       }

A: Just as jnd said, you will need to invoke the setData() method on your object reference - mmgg, like so:
mmgg.setData();
Also, to answer your question the reason why it prints all 0s; as you have observed is that upon instantiation of the object (this happens via the 'new' operator) the compiler sets your class's member variables to "reasonable" defaults.
Here are the defaults - which explain why your int values from your maze 2D array were zero after your Maze class was instantiated but without calling your setData() method...

*

*byte    [default = 0]

*short   [default = 0]

*int     [default = 0]

*long    [default = 0L]

*float   [default = 0.0F]

*double  [default = 0.0D]

*boolean [default = false]

*char    [default = '\u0000']

*String (or any Object)  [default = null]

[NB:- The compiler never assigns a default value to an uninitialized local variable]


text:
Q: single silverlight control in an asp.net mvc website? The main website will be MVC but I have a need for one Silverlight control to allow users to draw on images, just basic shapes, lines, squares, triangles etc.
Also might need Silverlight control to potentially allow users to draw and annotate video clips.
Is this possible?

A: Simple answer, Yes!
Follow the following link to see a demo app developed by some students in the UK. Integrating something similar in your ASP.NET MVC application can be done by using service calls into Controller methods that return JSON, or strongly typed objects.
http://code.msdn.microsoft.com/SilverPaint
Roberto.-


text:
Q: Error in changing Traffic Light State using Veins in OMNET++ I am doing a simulation which when an emergency vehicle is approaching to the intersection the state of traffic light should be changed it phase to green. What I try to do is, EV, will send message to the RSU sending it laneId, then the RSU will trigger traffic light through Traci function. However when the simulation reach the part when it need to trigger the Traci function to change traffic light phase, the simulation said "Simulation has encounter a problem, finished with error". Here is the code for the RSU :-
trafficlightrsu.cc files :
'''
 #include "trafficlightrsu.h"
 #include "veins/modules/application/traci/MyVeinsApp.h"
 #include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"

 using namespace veins;

 Define_Module(veins::trafficlightrsu);

 void trafficlightrsu::onWSA(DemoServiceAdvertisment* wsa)
 {
    // if this RSU receives a WSA for service 42, it will tune to the channel
    if (wsa->getPsid() == 42) {
        mac->changeServiceChannel(static_cast<Channel>(wsa->getTargetChannel()));
     }
 }

 void trafficlightrsu::onWSM(BaseFrame1609_4* frame)
 {
    TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame);

    std:: string laneId = wsm->getDemoData();

    if(laneId == "14617022#0_0"){

        manager->getCommandInterface()->trafficlight("cluster_144084639_252529291_255540900_6503456532").setPhaseIndex(2);

        }
 }

'''
trafficlightrsu.h file :
'''
    #pragma once

    #include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h"
    #include "veins/modules/mobility/traci/TraCIScenarioManager.h"
    #include "veins/modules/mobility/traci/TraCICommandInterface.h"

    using namespace omnetpp;

    namespace veins {

    class VEINS_API trafficlightrsu : public DemoBaseApplLayer {
    protected:
        void onWSM(BaseFrame1609_4* wsm) override;
        void onWSA(DemoServiceAdvertisment* wsa) override;
   //fix by adding this part
        TraCIMobility* mobility;
        TraCICommandInterface* traci;
        TraCICommandInterface::Vehicle* traciVehicle;

        TraCIScenarioManager* manager;
        std::string trafficLightId;

    private:
        void setTraCI();
    };

    }

'''


text:
Q: Wordpress Parent/Child user registration I am trying to evaluate the possibility of creating a plugin for Parent/Child functionality in Wordpress user creation.
What we need to achieve is to allow a Parent to create a sub-user account for his children. This accounts will have limited access but that can be done later with other Wordpress plugins.
What does not exist right now or what I was unable to find, is a plugin which gives the possibility to an existent standard user, to create sub-accounts related to him.
I do not want anything particular except the association between the accounts. The main user should have the possibility of adding or removing his child accounts.
Do you think this is something that is ok to do? Does it open us to any hacking possibility or vulnerability or create problems in the future?
If not, what would be in your opinion the best way to proceed and do this? What would be the best, fastest and most secure flow of operations?
Looking forward to your opinions.
Thanks in advance.
Regards

A: I know this is an old post but here's an option for anyone searching for this in the future.
First, you need to register a new user role. When you register the role, you are free to assign any capability you want. In this case, give the new role the capability to add users.
Then you can create a one-to-many relationship between the new user role and the standard subscriber role. So the new user role can have many subscribers but a subscriber can only belong to one new user role.
This will do what you want. There are several plugins that can do this if you are not comfortable with coding which seems the case per the OP's question. You can try PODS which is free and available in the Wordpress Plugin Directory - https://wordpress.org/plugins/pods/.


text:
Q: Problema com redirect JSF+Primefaces Tenho um menu onde tenho um submenu Cadastro e dentro dele um menuItem Usuários em meu Template, e também tenho um menuItem Sair. O problema é que o sair só funciona na tela Home, que é a tela que é chamada após o login. Quando entro na tela de cadastro e tendo sair o sistema não é redirecionado para pagina principal.
<h:form style="display: inline-block" id="frmPrincipal">
            <p:menubar styleClass="menu-sistema" id="menuBar">

                <p:submenu label="Cadastros" rendered="#{usuarioBean.usuarioLogado.cargo == 'Administrador'}">
                    <p:menuitem value="Usuários" outcome="/usuario/cadastroUsuario" />
                </p:submenu>
                <p:menuitem value="Sair" action="{usuarioBean.sair}" update=":frmPrincipal:menuBar"/>
            </p:menubar>

O método sair é o seguinte:
public String sair() {
        usuarioLogado = null;
        return "Login.xhtml?faces-redirect=true";
    }

A: Mude seu método sair() para :
public void sair() {
        usuarioLogado = null;
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ec.redirect(ec.getRequestContextPath() + "/Login.xhtml");
}

Segue o link do SOen, onde tem outras alternativas.


text:
Q: What is the correct way of releasing nodejs application? What is the correct way of releasing nodejs web application?
My current releasing script is doing following actions:
 Sync(function(){
    var tag = getTag.sync(); //1 - getting the tag to release
    update.sync(null, tag);  //2 - update current project to choosen tag
    archive.sync();          //3 - archive current released project
    stop.sync();             //4 - stop server
    del.sync();              //5 - delete currently released project
    copy.sync();             //6 - copy files from scm folder
    packAssets.sync();       //7 - minify javascript. css, less files
    start.sync();            //8 - start the application
 });

More detailed description - release is run in repository folder on same server (numbers as in comments):

*

*Get tag by proposing last 10 ones and choosing the number or by writing tag name.

*Update current repository to selected tag.

*Archive application folder - copy it to archive folder with unique (data) name.

*Stop the server by calling forever stop pid - from now Nginx will show maintenance mode page.

*Delete current application folder

*Copy files from repository folder to release folder (skip scm folder - in my case .hg)

*Run minifying script for JavaScript, CSS and Less files.

*Start the application by calling forever start server.js in release folder.

Functions (getTag, update, archive, stop, ... ) are declared above Sync call.
Is it correct?

A: Please consider using the following tools to release your JavaScript applications, they may help with SemVer versioning and make release process less error-prone:

*

*Semantic release - a release system that make it easy to perform actions before and after releasing a new version of your software

*Bumped - fully automated package publishing


text:
Q: Function always returns a 0 I'm a bit confused why the addition function always returns 0 no matter what combination of inputs I place. I've already checked if the user inputs are properly placed within the array I made and there are no problem at all within the input. Is the way I structured the function wrong by any means?
Program MathOperation;
uses crt;

type
inputArray = array [1..5] of real;
var
userChoice : integer;
inputValue : inputArray;

procedure userInputValues;
var
counter : integer = 0;
begin
    while counter<5 do
    begin
        write('>> Enter number [', counter + 1, ']: ');
        read(inputValue[counter]);
        counter := counter+1;
    end;
end;

function addOp:real;
var
addCtr : integer = 0;
sum : real = 0;
begin
     while addCtr<5 do
     begin
         sum := sum + inputValue[addCtr];
         addCtr := addCtr+1;
     end
end;

A: Your AddOp function always returns 0 because you never assign a value to its function result.  Somewhere in it, you should have a statement which is guaranteed* to execute and which is like this:
  AddOp := {whatever the correct value is}

Since you are apparently using FreePascal, you can use Result as an alias for the function result, as in
  Result := {whatever the correct value is}

*Actually, this is somewhat of an overstatement, because there may be more than one valid execution path through the code of the function, so the more general rule is that every valid execution path through the function should make the function return a value.


text:
Q: Can't import new definition although old definitions from same file are working Hello I have the file with path project/top_file.py
I have another file with path project/subfolder/model.py
In topfile.py At the moment I have the following code
from subfolder.model import definition_one, definition two

I can use now these two definitions in my topfile.
Now I added a new definition in model.py and called it definition_three
model.py looks this way now
def definition_one(...):
  ...
def defintion_two(...):
  ...
def definition_three(...):
  ...

I wanted to change the code in topfile.py to
from subfolder.model import definition_one, definition_two, definition_three

but I get the Error Import Error: cannot import name 'definition_three'


text:
Q: PHP capitalize first letter of word Hi I am working on simple php code ,where I have to do this :
It needs to take something like:
  $string =  'fiverr.com'
   $string =  'myfiverr.com'
   $string =  'myfiverrgig.com'

and change to:
Fiverr.com

MyFiverr.com

MyFiverrGig.com

so that it should capitalize first letter of real word. Should I use dictionary of all words or is there any php library which I can use ?

A: I would create an array of words you want to replace, and then replace it, like this:
$string = 'myfivvergig.com';

$words =['my','fivver','gig'];

foreach($words as $word){
       $replace = ucfirst($word);
       $string = str_replace($word, $replace, $string);
}

return $string // MyFivverGig.com

A: There is a php function called ucfirst ( string $str ) : string that does the same.
You can find the reference here


text:
Q: Getting indexOutOfBoundException from an endpoint hi guys i am having been struggling to get my head around this, i dont know why i keep getting indexOutBoundsExpection, below are my code structures
service layer
public CompanyExprience getExperience(User user) {

CompanyExpirience model = new CompanyExpirience();

Long teamXp = (user.getTeams() == null ? 0L :
((user.getTeams().get(0).getLevel() * 1000) + user.getTeams().get(0).getExperience()));

Long individualXp = ((user.getLevel() * 1000) + user.getExperience());
        model.setIndividualLevel(user.getLevel());
        model.setTeamLevel(user.getTeams() == null ? 0L : user.getTeams().get(0).getLevel());
        model.setTeamStatus(toStatus(user.getTeams() == null ? 0L : user.getTeams().get(0).getLevel()));
        model.setIndividualStatus(toStatus(user.getLevel()));
        model.setIndividualExperience(((individualXp * 100) / 100000));
        model.setTeamExperience(((teamXp * 100) / 100000));
        model.setTeamExperiencePoint(user.getTeams() == null ? 0L : ((user.getTeams().get(0).getLevel() * 1000) + user.getTeams().get(0).getExperience()));
        model.setIndividualExperiencePoint((user.getLevel() * 1000) + user.getExperience());

        return model;

    }

and below is my  my endpoint
@GET
    @Path("/compexpirience")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public ExperienceModel getExperience() {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User user = (User) auth.getPrincipal();

        return activityService.getExperienceModel(user);
}

can someone try to explain to me why google chrome and eclipse stack trace are giving me indexOutBoundsException, i know what normally cause that error with this one i am struggling


text:
Q: Dotnet Core Web API Versioning I constructed my first dotnet core web api today and found something I can't resolve. I'm hoping someone can see what I'm doing wrong.
Here's code that works as expected.
[Route("api/[controller]")]
public class HelpController : Controller
{
    [HttpGet]
    public string Get()
    {
        return "hello world";
    }
}

However, when I try to apply versioning, I get nothing.
[ApiVersion("1.0")]
[Route("api/{version:apiVersion}/[controller]")]
public class HelpController : Controller
{
    [HttpGet]
    public string Get()
    {
        return "hello world";
    }
}

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddApiVersioning(option =>
    {
       option.ReportApiVersions = true;
       option.DefaultApiVersion = new ApiVersion(1, 0);
       option.AssumeDefaultVersionWhenUnspecified = true;
    });
}

The code compiles as expected, but I get nothing. I think the url should be localhost://.../api/1/help, but that doesn't work. It sends back a 404. I've tried "1," "1.0," "1_0," and "10." Nothing works.
What am I missing?

A: I think, there is a change in the latest 1.1 version of Microsoft.AspNetCore.Mvc.Versioning package.
Try adding app.UseApiVersioning(); in the Configure method.
UPDATE:
In version 1.2.0 the need for app.UseApiVersioning(); is removed.


text:
Q: How to check the winner of Simple Jquery Tic Tac Toe I'm making a super simple Tic Tac Toe game using HTML, JavaScript, and CSS. The game is designed for two players. I'm just wondering how I can check if three dots in a row have the same class for either playerOne or playerTwo.
HTML

Clear

Instructions

CSS
table{
  margin-left:auto;
  margin-right:auto;
  border-spacing:7px;
}
.dot{
  border-radius:50px;
  height:100px;
  width:100px;
  background-color:#A8A8A8;
}
.playerOne{
  border-radius:50px;
  height:100px;
  width:100px;
  background-color:red;
}
.playerTwo{
  border-radius:50px;
  height:100px;
  width:100px;
  background-color:blue;
}
#clear{
  border-radius:50px;
  width:300px;
  padding:10px;
  font-size:30px;
  background-color:#A8A8A8;
  text-align:center;
  margin-right:auto;
  margin-left:auto;
  box-shadow: 2px 2px 2px black;
}
#clear:active{
  box-shadow:none;
}
#instructions{
  border-radius:50px;
  width:300px;
  margin-top:10px;
  padding:10px;
  font-size:30px;
  background-color:#A8A8A8;
  text-align:center;
  margin-right:auto;
  margin-left:auto;
  box-shadow: 2px 2px 2px black;
}
#instructions:active{
  box-shadow:none;
}

JavaScript
$(document).ready(function(){
  $('.dot').click(function() {
    $(this).addClass('playerOne');
  });
  $('.dot').dblclick(function() {
    $(this).addClass('playerTwo');
  });
  $('#clear').click(function(){
    $('.dot').removeClass('playerOne');
  });
  $('#clear').click(function(){
    $('.dot').removeClass('playerTwo');
  });
  $('#instructions').click(function(){
    alert('Hi')
  });
});

A: Tic-Tac-Toe has simple enough win conditions that you could simply check for all of them:
var winSpots = [
  ["dot_1", "dot_2", "dot_3"]
  // More
];

The other way would be to check rows first. and loop over the next two rows.
var rows = ["dot_1", "dot_4", "dot_7"];

for (var i = 0; i < rows; i++) {
  var row = rows[i];

  // Get the next two elements, calculate them off list
}

A cleaner way would be to keep an array of arrays (what you'd think of as a 2D array) and use that to actually hold data, with what is in the HTML only reflecting that.
That would separate game-logic (the board) from presentation (the display) and you could rewrite how the display works without having to change any of the backing code and this is exactly the way I'd solve it.
The process to check for a winning condition wouldn't change, however.  You'd just be checking the array rather than checking the DOM.


text:
Q: Why I cannot do anything on new Rails App?(says mysql gem missing, but I am using default sqlite3) I have been getting this Error when trying to do anything after starting the server in Rails:
Puma caught this error: Error loading the 'mysql2' Active Record adapter. Missing a gem it depends on? mysql2 is not part of the bundle. Add it to your Gemfile. (LoadError)
 .rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/bundler-2.2.7/lib/bundler/rubygems_integration.rb:334:in `block (2 levels) in replace_gem'
    .....

However I am not using mysql adapter in the database.yml file, I have installed rails app with default database settings.
Does it have something to do with the previous application I was working on, we were using docker and mysql2 there.
Gemfile:
ruby '2.6.5'

gem 'rails', '~> 6.0.3', '>= 6.0.3.4'
gem 'sqlite3', '~> 1.4'
gem 'puma', '~> 4.1'
gem 'sass-rails', '>= 6'
gem 'webpacker', '~> 4.0'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.7'
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

A: I had DATABASE_URL env variable set as mysql2 for the last application I was working on, so when i created the new App, rails set my default database to that, further info on the link below.
Found answer here.


text:
Q: Apply different hover effects for canvas in javascript I want to apply different hover colors for each canvas, can anyone tell me how to write hover for canvas.
Here is my code :
<!DOCTYPE html>
<html>
<body>

    <canvas id="myCanvas" width="350" height="200" style="border:1px solid #c3c3c3;"></canvas>
    <script>
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.fillStyle = "#FF0000";
        ctx.fillRect(0,0,150,75);

        var x = c.getContext("2d");
        x.fillStyle = "yellow";
        x.fillRect(175,0,150,75);

        var y = c.getContext("2d");
        y.fillStyle = "green";
        y.fillRect(0,95,150,75);

    </script>
</body>
</html>

A: If you need an idea you can see below Code; It makes a small circle on hover on the points present in Pixel array. You may ask what you need to know in it..
var pixel = [{x:10,y:10}] //Coordinates array
function handleMouse(e){
            var ctx= tooltip.getContext("2d");
            var hit= 0;
            var xMouse = e.pageX;
            var yMouse = e.pageY;
            //console.log(xMouse, yMouse);
            var curleft = curtop = 0;
            var obj = graph;
            if (obj.offsetParent) {
                do {
                    curleft += obj.offsetLeft;
                    curtop += obj.offsetTop;
                    } while (obj = obj.offsetParent);
            }
            //console.log(curleft,curtop);

            for (i=0;i<pixel.length;i++){
                var dx = xMouse - curleft - pixel[i].x;
                var dy = yMouse - curtop - pixel[i].y;

                if(dx*dx + dy*dy <=radiiGraphPoint*radiiGraphPoint ){
                    //console.log("on Circle");
                    tooltip.style.display='block';
                    tooltip.style.left=pixel[i].x+ 'px';
                    tooltip.style.top= pixel[i].y-tooltip.height-10 + "px";
                    ctx.fillStyle="#474747";
                    ctx.fillRect(0,0,tooltip.width,tooltip.height);
                    ctx.fillStyle="#fff";
                    ctx.textAlign="center";
                    ctx.textBaseline="middle";
                    ctx.font="italic 600 8.5pt sans-serif";
                    ctx.fillText(pixel[i].X +","+ pixel[i].Y,tooltip.width/2,tooltip.height/2);

                    c.fillStyle="#79EDED";
                    c.beginPath();
                    c.arc(pixel[i].x,pixel[i].y,radiiGraphPoint+2,0, Math.PI * 2,true);
                    c.fill();
                    hit=1;
                }
            }
            if(hit==0){
                tooltip.style.display='none';
                build_graph();
            }
        }


text:
Q: How do i undo ignoring an error? I was playing Ratchet and Clank 2 on PCSX2 the other night and after clearing the Thugs-4-Less jammer the following cutscene crashed the emulator. i wrongfully hit ignore and while duplicating the issue i didn't get the error message which i would rather.
Is there a way to reset the error message so that the one i ignored is no longer ignored without resetting the entirety of PCSX2


text:
Q: QString exchange in qml through c++ this example is supposed to read the string from TextInput and display it in another Rectangle on click of the mouse. However, it does not. Why?
//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QObject>
#include <QString>

class MainWindow : public QDeclarativeView
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

class Data : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString teamName READ getTeamName WRITE setTeamName NOTIFY nameChanged)

public:
    Data(QObject *parent = 0);
    ~Data();

public:
    QString getTeamName();
    void setTeamName(QString &);

signals:
    void nameChanged();

private:
    QString n_teamName;
};

#endif // MAINWINDOW_H

//mainwindow.cpp
#include "mainwindow.h"
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QString>
#include <QObject>

MainWindow::MainWindow(QWidget *parent)
    : QDeclarativeView(parent)
{

}

MainWindow::~MainWindow()
{

}

Data::Data(QObject *parent) : QObject(parent)
{
    //n_teamName = "Ahoj";
}

Data::~Data(){

}

QString Data::getTeamName(){
    return n_teamName;
}

void Data::setTeamName(QString &newName){
    if(newName != n_teamName){
        n_teamName = newName;
        emit nameChanged();
    }
}

//main.cpp
#include "mainwindow.h"
#include <qdeclarative.h>
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    Data d;
    qmlRegisterType<Data>("NData", 1, 0, "Data");
    w.rootContext()->setContextProperty("data", &d);
    w.setSource(QUrl::fromLocalFile("../klik/Main.qml"));

    w.show();

    return a.exec();
}

//main.qml
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import NData 1.0
Rectangle {
    id: root
    width: 600
    height: 400
    Rectangle{
        id: text
    ...
        TextInput{
            anchors.fill: text
            anchors.margins: 3
            focus: true
         }
    }
    Rectangle{
    ...
        Text{
            id: copyText
            anchors.centerIn: copy
            text: data.setTeamName()
        }
    }
    Rectangle{
        id: klik
        ...
        MouseArea{
        ...
            onClicked: {
                copyText.text = data.teamName
            }
        }
    }
}

It lets out the error: TypeError: Result of expression 'data.setTeamName' [undefined] is not a function.
Main.qml:51: Error: Cannot assign [undefined] to QString

A: teamName is a property of data, so simply use assign operator like data.teamName = 'some text';
Probably you should add id field to your TextInput like
TextInput{
    id: textInput
    anchors.fill: text
    anchors.margins: 3
    focus: true
}

And change onClicked, so
MouseArea{
   ...
    onClicked: {
        data.teamName = textInput.text
        copyText.text = data.teamName // copyText.text = textInput.text is fine too
    }
}

A: I believe your actual exception is due to the following line
text: data.setTeamName()

setTeamName is a private function on your data object, that is not exposed as a slot, and is thus undefined when called and assigned to text.  Nevermind the fact that it makes no sense to call the set when you are performing an assignment. I'm assuming this was supposed to be data.getTeamName().


text:
Q: Find out who deployed database in SSAS? I have this SSAS running:

I see a database deployed and I am trying to check who deployed it, is there a DMV that I can execute somewhere that can retrieve that information?


text:
Q: How can i pass arguments along with an msi when a user downloads the msi from a browser? The only suggestions on how to do this i've found suggest that i can use the arguments (i.e. the values i want to pass) in the name of the msi, then on the client where it's been installed, i can pull the name out of the msi and use them there.  Obviously it's not ideal exposing the values in the name of the msi.
I've looked into using ClickOnce/Wix/standard installer to achieve this but i keep ending up with having to pass my arguments to msiexec, in my mind this means i'm on the server not the client so it'll install the thing on the server which isn't what i want.  Unless i'm fundamentally missing something here?

A: REF: How to Download MSI installer with argument for user-id
As I mentioned in the linked answer you could make per user transforms and give users a ZIP file that contains a CMD/PS1/BAT file to launch the msi with the transform, eg:
msiexec -i c:\temp\The.msi transforms=c:\temp\YourPerso.mst

Alternatively you could "bake" a per user msi on the server, then give the end user a url to download the msi.

if we use msiexec then that'll install on the server because it's server side code.

If you are logged into the server and you execute the msiexec command then yes it will install on the server. What you want to do is either create per-user transforms or bake per user msi's and then give end users a link to download.
Let me know if you have questions or if anything is unclear.

At the end of the day I think a better strategy is to make the user connect to the internet once and give them a unique user id that way. Then store the unique id in the registry (or database, config file, etc) and always check the unqiue id exists before making any external calls using it.


text:
Q: Merging GDML files The GDML manual documents how to setup multiple GDML files as follows.

Now lxml has a facility to parse multiple files as follows
from lxml import etree
parser = etree.XMLParser(resolve_entities=True)
root= etree.parse(filename, parser=parser)

I assume that at least under the covers it must combine the multiple files before parsing.
My question is there some way I can just save the combined files, as I would like to
have the facility to combine and save a LARGE ( > 100 ) number of xml files where they are specified as includes in a gdml file and discard the !ENTITY definitions.
note: I don't want to parse the files as for the large number this takes a long time.
I guess one option would be to code something like
 gdml = etree.tostring('gdml')
 etree.ElementTree(gdml).write('filename')

But have a concern that I might hit a max string size, which I understand would be limited to the maximum addressable.
   import sys
   sys.maxsize

Wondering if there is a better way.


text:
Q: Как получить информацию из команды cat и записать ее в переменную? Пишу программу,которая должна вывести на экран число из файла,который находится в папке,доступная для чтения только из под root и нужно вписать эту информацию в переменную Int(или String).
Вот такие данные имеются в данном файле:
M6Note:/ # cat /dev/block/mmcblk0p50
72151002

Эту информацию нужно считать и записать в переменную.
Каким способом можно это реализовать?

A: Примерно так:
//если приложение имеет root права
FileReader fileReader = new FileReader("/dev/block/mmcblk0p50");
String line = fileReader.readLine());
fileReader.close();
if(line!=null) {
  int i=Integer.parseInt(line); //складываем значение в переменную i
}

Только надо обложиться try-catch


text:
Q: How to submit values from a view? Hi all I have a view with these controls on it
<input type="text" class="radius2" />
<input type="button" value="Place bid" class="bid-btn" />

I want to pass the value in the text box to another view (via an action method) when the button is clicked.  The action method should render the view.
How can this be acheived?
Thanks,
Sachin

A: @using(Html.BeginForm("SubmitAction", "Home", FormMethod.Post))
{

    <input id="radius2" name="radius2" type="text" class="radius2" />
    <input type="submit" value="Place bid" class="bid-btn" />

}
    [HttpPost]
    public ActionResult SubmitAction(string radius2)
    {
       return AnotherView(radius2);
    }

    public ActionResult AnotherView(string value)
    {
       return View();
    }

Written in notepad so might require small syntax changes

A: add name property to the tags so the server can access them
<input name="Name1" type="text" class="radius2" />
<input type="button" value="Place bid" class="bid-btn" />

then when submit your action should be something like this
public ActionResult SubmitAction(string name1)
{
  return View("ViewName" , /* the model here */ )
}


text:
Q: Running callback on the same thread as the caller in iOS I call a method on the native iOS side from Kotlin/Native framework. The method does its work asynchronously and responds back with some data in a different thread than it was called with.
I want a way to call the response function also in the same thread. Below is the code:
func makePostRestRequest(url: String, body: String) {

    let thread1 = Thread.current

    let request = NetworkServiceRequest(url: url,
                                        httpMethod: "POST",
                                        bodyJSON: body)
    NetworkService.processRequest(requestModel: request) { [weak self] (response: Any?, requestStatus: RequestStatus) in
        // This is different thread than "thread1". Need the below code to execute on "thread1"
        if requestStatus.result == .fail {
            knResponseCallback.onError(errorResponse: requestStatus.error)
        } else {
            knResponseCallback.onSuccess(response: response)
        }
    }
}

I have tried to solve this using two ways.
One is to use "semaphores". I just blocked the code execution after the network call and when I got the result back in the callback of network request, I saved it in a variable and signal the semaphore. After that I just call knResponseCallback and use the response variable to return back the response.
Another way I used is to use RunLoops. I got the handle of RunLoop.current, start the runLoop in a mode and in the callback of network request, I just call perform selector on thread with object method of NSObject which dispatches the work to that thread itself.
The problem with both of them is that they are blocking calls. RunLoop.run and semaphore.wait both blocks the thread they are called in.
Is there a way to dispatch some work onto a particular thread from another thread without blocking the particular thread?

A: You need to create a queue to send the request and use that same queue to handle the response. Something like this should work for you:
    let queue = DispatchQueue(label: "my-thread")
        queue.async {
            let request = NetworkServiceRequest(url: url,
                                                httpMethod: "POST",
                                                bodyJSON: body)
            NetworkService.processRequest(requestModel: request) { [weak self] (response: Any?, requestStatus: RequestStatus) in
                queue.async {
                    if requestStatus.result == .fail {
                        knResponseCallback.onError(errorResponse: requestStatus.error)
                    } else {
                        knResponseCallback.onSuccess(response: response)
                    }
                }
            }
        }


text:
Q: Spark Streaming and Sockets I have an application that will be streaming data in from an IRC server in Python. Currently, I'm creating a socket object in Python that connects to the IRC server. Before I can receive the data, I send the socket authentication initially and may have to periodically send other messages throughout the streaming process. The problem is, I want to stream the messages in with Spark.
I've read that you can create CustomReceivers to do something like this, but I can't find any information on creating one in Python.
Now, I have two possible solutions that I could implement, both of which I feel are sub-optimal.
1) Create a Python socket that connects to IRC and parse/save the data directly without using Spark.
2) Create a Python socket that connects to IRC, send that data to another local Python socket, and have Spark connect directly to that socket and stream from there.
Am I trying to solve the wrong problem with the wrong tool or is there a way to send data to a socket in Spark, namely, in Python?


text:
Q: Facebook sharing problem with custom and dynamic data I need to choose an image from a gallery. This image is shown in a modal (using Bootstrap) and under it there's a Facebook sharing button. This button must share the chosen image at full-width, a custom title (always the same), a custom description (always the same) and, when a Facebook user clicks on the shared post, redirect to a custom URL (always the same, not the image one).
I've tried different ways (FB dev docs, http://drib.tech/programming/dynamically-change-facebook-open-graph-meta-data-javascript, different "method", different "action_type" etc) but I always experience different problems.
By following the drib.tech suggestions, here's the situation:

*

*web: it shares the right title, description and custom link but the image is always a thumbnail and it says "John Cats LIKES a link" instead of "John Cats SHARES". That's because I used "action_type": "og.likes", I think, but with any other type (og.shares etc) it shares wrong image, title and description (it takes the custom link data)

*Android (in app): it looks like the web result but then it doesn't close the popup

*iOS: nothing works, I assume it hates popups.

I've tried with iframe instead of popup but it says it's not allowed.
I've also tried with just the Facebook sharer URLs:
https://www.facebook.com/sharer/sharer.php?u=" + url + "&title=" + titolo + "&picture=" + picture
https://www.facebook.com/share.php?u=" + url + "&title=" + titolo + "&picture=" + picture

but the result is wrong image, title, description.
So... I've run out of ideas, my script is a mess and I can't find any other ideas. Any suggestions?

A: The latest updates from the FB API require another structure of the action_properties object.
This is a working example:
FB.ui({
        method: 'share_open_graph',
        action_type: 'og.likes',
        action_properties: JSON.stringify({
            object: {
                "og": {
                    "url": your_url,
                    "title": your_title,
                    "image": {
                        "url": your_image_URL
                    }
                }
            }
        })
    }, function(response){});


text:
Q: phonenumber@vtext.com vs. Twilio, Clickatell, etc? I want to let users interact with my Django app via SMS. Twilio's pricing (for a phone number and the volume of texts I'd be processing) is okay, but why would I do this rather than go through carriers' email gateways?
What do API gateways provide that @vtext.com, etc. addresses don't?

A:
What do API gateways provide that @vtext.com, etc. addresses don't?

Guaranteed delivery.
The email to SMS gateways often drop messages, especially if you're sending quite a few messages through them. They might even block you if you exceed a (undocumented, completely arbitrary) rate. Practically, I wouldn't expect more than a 90% success rate sending emails through a cell providers' email gateway.
Beyond that, to use gateways correctly you'll ask your users for their provider, maintain a database of provider gateway addresses (which have been known to change in the past). Remember also that most of the world has number portability; this means you'll need to constantly monitor for delivery failures (from the gateways that even bother to send 'em) and ask users to update their provider.


text:
Q: Unusable open souce ATI driver on Debian Jessie Background
I'm now forced to use open source proprietary driver (radeon kernel module) since after the last upgrade I got Xorg version 7.7 and fglrx just doesn't support it.
For what concerns the normal desktop usage this driver works fine, even better than fglrx, I even have high resolution frame buffer consoles! ^_^
Issue
But when actual OpenGL capabilities are used i.e. video games or even movie playing with VLC, screen freezes in a while and a number of red or blue pixels appear. Now, if I'm lucky this lasts for some seconds then the monitor loses the signal and suddenly everything restores; if I'm not, I have to reboot...

From what I'm able to see, performances are fine before the crash.
dmesg reports:
[34193.392048] radeon 0000:01:00.0: GPU lockup CP stall for more than 10000msec
[34193.392055] radeon 0000:01:00.0: GPU lockup (waiting for 0x000000000023e95b last fence id 0x000000000023e94d)
[34193.399059] radeon 0000:01:00.0: Saved 471 dwords of commands on ring 0.
[34193.399074] radeon 0000:01:00.0: GPU softreset: 0x00000009
[34193.399078] radeon 0000:01:00.0:   GRBM_STATUS               = 0xF5701828
[34193.399082] radeon 0000:01:00.0:   GRBM_STATUS_SE0           = 0xFC000003
[34193.399086] radeon 0000:01:00.0:   GRBM_STATUS_SE1           = 0x00000007
[34193.399089] radeon 0000:01:00.0:   SRBM_STATUS               = 0x200000C0
[34193.399092] radeon 0000:01:00.0:   SRBM_STATUS2              = 0x00000000
[34193.399096] radeon 0000:01:00.0:   R_008674_CP_STALLED_STAT1 = 0x00000000
[34193.399099] radeon 0000:01:00.0:   R_008678_CP_STALLED_STAT2 = 0x40000000
[34193.399103] radeon 0000:01:00.0:   R_00867C_CP_BUSY_STAT     = 0x00008006
[34193.399106] radeon 0000:01:00.0:   R_008680_CP_STAT          = 0x80228647
[34193.399110] radeon 0000:01:00.0:   R_00D034_DMA_STATUS_REG   = 0x44C83D57
[34193.409161] radeon 0000:01:00.0: GRBM_SOFT_RESET=0x00007F6B
[34193.409216] radeon 0000:01:00.0: SRBM_SOFT_RESET=0x00000100
[34193.410364] radeon 0000:01:00.0:   GRBM_STATUS               = 0x00003828
[34193.410368] radeon 0000:01:00.0:   GRBM_STATUS_SE0           = 0x00000007
[34193.410371] radeon 0000:01:00.0:   GRBM_STATUS_SE1           = 0x00000007
[34193.410375] radeon 0000:01:00.0:   SRBM_STATUS               = 0x200000C0
[34193.410378] radeon 0000:01:00.0:   SRBM_STATUS2              = 0x00000000
[34193.410382] radeon 0000:01:00.0:   R_008674_CP_STALLED_STAT1 = 0x00000000
[34193.410385] radeon 0000:01:00.0:   R_008678_CP_STALLED_STAT2 = 0x00000000
[34193.410388] radeon 0000:01:00.0:   R_00867C_CP_BUSY_STAT     = 0x00000000
[34193.410392] radeon 0000:01:00.0:   R_008680_CP_STAT          = 0x00000000
[34193.410395] radeon 0000:01:00.0:   R_00D034_DMA_STATUS_REG   = 0x44C83D57
[34193.410406] radeon 0000:01:00.0: GPU reset succeeded, trying to resume
[34193.430380] [drm] PCIE GART of 512M enabled (table at 0x0000000000273000).
[34193.430487] radeon 0000:01:00.0: WB enabled
[34193.430491] radeon 0000:01:00.0: fence driver on ring 0 use gpu addr 0x0000000080000c00 and cpu addr 0xffff8800da8b4c00
[34193.430493] radeon 0000:01:00.0: fence driver on ring 3 use gpu addr 0x0000000080000c0c and cpu addr 0xffff8800da8b4c0c
[34193.431938] radeon 0000:01:00.0: fence driver on ring 5 use gpu addr 0x0000000000072118 and cpu addr 0xffffc90002cb2118
[34193.448109] [drm] ring test on 0 succeeded in 2 usecs
[34193.448176] [drm] ring test on 3 succeeded in 1 usecs
[34193.623962] [drm] ring test on 5 succeeded in 1 usecs
[34193.623971] [drm] UVD initialized successfully.
[34193.678291] [drm] ib test on ring 0 succeeded in 0 usecs
[34193.678365] [drm] ib test on ring 3 succeeded in 1 usecs
[34193.828433] [drm:r600_uvd_ib_test] *ERROR* radeon: failed to get create msg (-22).
[34193.828446] [drm:radeon_ib_ring_tests] *ERROR* radeon: failed testing IB on ring 5 (-22).

System information
Distro and kernel:
$ cat /etc/issue
Debian GNU/Linux jessie/sid \n \l
$ uname -a
Linux andrea 3.11-2-amd64 #1 SMP Debian 3.11.8-1 (2013-11-13) x86_64 GNU/Linux

xorg.conf (relevant bits):
Section "Device"
    Identifier "something"
    Driver     "radeon"
    Option     "AccelMethod" "EXA"
    Option     "EXAVSync"    "on"
EndSection

glxinfo (relevant bits):
name of display: :0.0
display: :0  screen: 0
direct rendering: Yes
server glx vendor string: SGI
server glx version string: 1.4

Driver version:
$ apt-cache show xserver-xorg-video-radeon | grep Version
Version: 1:7.2.0-1+b2

A: I finally found a solution in this forum thread.
In short, there's a boot parameter to set (radeon.dpm), so I fixed by editing /etc/default/grub to something like:
GRUB_CMDLINE_LINUX_DEFAULT="quiet radeon.dpm=1"

Then sudo update-grub and reboot.


text:
Q: Cloud Firestore rules issues outside of console I've got this set of Firestore rules :
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents/{path=**} {
     match /mycollections/{item} {
        function isSignedIn() {
          return request.auth != null
            && request.auth.token.firebase.sign_in_provider != 'anonymous';
        }

        function isInRoles(rsc, roles) {
            // return request.auth.uid in request.resource.data.users;
          return rsc != null
          && rsc.data.roles[request.auth.uid] == "owner";
            //&& rsc.data.roles[request.auth.uid] in roles;
        }

        function isOneOfRoles(rsc, array) {
          return isSignedIn() && isInRoles(rsc, array);
        }

        function isValidNewItem() {
          return request.resource.data.roles[request.auth.uid] == 'owner'
             && request.auth.uid in request.resource.data.users;
        }

        function isNewSharedUser() {
            return request.resource.data.roles[getAuthLogin()] == 'writer'
             && request.auth.uid in request.resource.data.users
             && resource.data.shareLink == request.resource.data.shareLink;
        }

        function onlyContentChanged() {
          // Ensure that title and roles are unchanged and that no new
          // fields are added to the document.
          return request.resource.data.title == resource.data.title
            && request.resource.data.roles == resource.data.roles
            && request.resource.data.keys() == resource.data.keys();
        }

        // Split writing into creation, deletion, and updating. Only an
        // owner can create or delete a story but a writer can update
        // story content.
        allow create: if isValidNewItem();
        allow delete: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)), ['owner']);
        allow update: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)), ['owner'])
                      || (isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)), ['writer']) && onlyContentChanged())
                      || isNewSharedUser();
        allow read: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)), ['owner', 'writer', 'reader']);

                // example for permissions
        match /items/{subItem} {
                    allow delete: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)),
                                      ['owner', 'writer']);
            allow update: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)),
                                      ['owner', 'writer']);
          allow read: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)),
                                      ['owner', 'writer', 'reader']);
          allow create: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)),
                                        ['owner', 'writer']);
        }

                // example for permissions
        match /comments/{comment} {
          allow read: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)),
                                      ['owner', 'writer', 'commenter', 'reader']);
          allow create: if isOneOfRoles(get(/databases/$(database)/documents/mycollections/$(item)),
                                        ['owner', 'writer', 'commenter'])
                        && request.resource.data.user == request.auth.uid;
        }
     }
  }
}

With an authenticated user I can insert new list like this,
db.collection('mycollections').add({
  name: 'item ' + Date.now(),
  roles: roles,
  users: [user.uid],
});

With looks like this in Firestore documents explorer
// doc id "CuwoleyStA5O3rY6Q5de"
{
  "roles": {"05CJ88QtXng1NzWQWJkMRB1bkRP2": "owner"}
  "name": "Ma nouvelle liste 1646895620631"
  "users": ["05CJ88QtXng1NzWQWJkMRB1bkRP2"]
}

After that, I can access it trough the Firestore console using the "rules tester"

But in my app, logged in with an authenticated user, I can't access it the collections of this user in /mycollections/*, I always end up with a an error of "Missing or insufficient permissions".
// query
db.collection("mycollections").where('users', 'array-contains', user.uid)
  .onSnapshot((querySnapshot) => { });

=> Error in snapshot listener: FirebaseError: Missing or insufficient permissions.

Where's the rules error? the read access does check that there is a roles for this user which is right, and there is no details to debug the permissions issue.

A: Below is the syntax you can use to allow the authenticated user to read and write their own data as per explained in documentation
service cloud.firestore {
     match /databases/{database}/documents {
       // Make sure the uid of the requesting user matches name of the user
       // document. The wildcard expression {userId} makes the userId variable
       // available in rules.
       match /users/{userId} {
         allow read, update, delete: if request.auth != null && request.auth.uid == userId;
         allow create: if request.auth != null;
       }
     }
   }


text:
Q: randrange python step parameter in minutes In python , i want to generate a random time between two intervals using randrange function and using the step parameter. I want the time to be generated at 5 minute intervals using randrange. Is it possible? Or is there any other function in python which can achieve the same?
import datetime
import time
import random

start = datetime.datetime(2017,4,25,8,0)
end = datetime.datetime(2017,4,25,11,30)
steptime = datetime.datetime(2017,4,25,0,5)
totalnum=10
start_ts = int(time.mktime(start.timetuple()))
end_ts = int(time.mktime(end.timetuple()))
step = int(time.mktime(steptime.timetuple()))
for val in range(totalnum):
    random_ts = random.randrange(start_ts,
 end_ts,step)
RANDOMTIME = datetime.datetime.fromtimestamp(random_ts)
print(RANDOMTIME.strftime("%Y-%m-%d %H:%M"))

As mentioned above im not able to find a way to generate time within 5 minute intervals.
TIA

A: Thanks for the answers. I solved it by providing step as 300 seconds
random_ts = random.randrange(start_ts, end_ts,300)

A: You can start by generating a random datetime between your start and end dates. See Generate a random date between two other dates
Then just round the random date to the nearest 5 minutes. See How to round the minute of a datetime object python

A: I think you're complicating this a bit too much - just subtact the earlier date from the later, get a random second (or millisecond if you want to go very granual) in its range and add it as a datetime.timedelta to the lower datetime, e.g.:
import datetime
import random

def datetime_in_range(low, high, interval):  # interval in seconds
    delta = (high - low).total_seconds()
    return low + datetime.timedelta(seconds=random.randrange(0, int(delta), interval))

# test
start = datetime.datetime(2017, 4, 25, 8, 0)
end = datetime.datetime(2017, 4, 25, 11, 30)

print(datetime_in_range(start, end, 300))  # 2017-04-25 09:25:00
print(datetime_in_range(start, end, 300))  # 2017-04-25 08:30:00
print(datetime_in_range(start, end, 300))  # 2017-04-25 11:10:00

If you want a millisecond precision, just multiply the delta with 1000 and use milliseconds in the datetime.timedelta() construct.


text:
Q: python paho client broker connection My publisher and broker are working on different systems. I am using QOS=2 for delivery of messages.I am using python paho mqtt broker. It is further extension to
MQTT - Is there a way to check if the client is still connected
1) When I publish a message to connected broker, it acknowledge me by calling on_publish() callback. but when I disconnected my broker running on different machine from the network, the publisher stores the publish message on local machine and again when I connect my broker to network it publishes all previous messages to broker. I think these messages stored as inflight messages (not confirmed), if these messages are inflight messages, then  where these messages are stored,is there any limit of these inflight messages as I have not include anything in my code regarding inflight messages.
2)In first case I disconnect my broker from the network, now I shutdown my broker and again connect to network,  my program call on_disconnect() callback says unexpected disconnection, then publishes all unpublished messages to broker.
    a) I am confused why on_disconnect() callback calls only when I shut down by broker not on when I disconnect my broker from my local network.
   b) on_disconnect() method calls only when my broker again connect to network.
      Is there any way if my broker disconnect suddenly, then immediately it will be informed to publisher?
3) I am using mqtt in real time gps tracking, I want to store messages to local db when publisher not connected to broker , but I can't find any way how publisher comes to know immediately when it disconnected from broker.
4) Is using QOS=2 is best way to ensure message delivery to broker or using local db for storage purpose when disconnected to broker and then sync automatically with local db to publish all messages


text:
Q: Difference between "PIXI.Texture.from()" and "new PIXI.Texture()" in pixi.js I am working on getting some textures assigned to an animatedSprite object in Pixi.JS
The below code works as expected:
\\ previously loaded: APP.loader.add("tile_sheet", "img/tile_spritesheet.png");

const texture_base = PIXI.BaseTexture.from(APP.loader.resources["tile_sheet"].url);
const texture_1 = new PIXI.Texture(texture_base);
const component = PIXI.AnimatedSprite.from(texture_1);

However the following throws a "unrecognized source" error.
\\ previously loaded: APP.loader.add("tile_sheet", "img/tile_spritesheet.png");

const texture_base = PIXI.BaseTexture.from(APP.loader.resources["tile_sheet"].url);
const texture_1 = PIXI.Texture.from(texture_base);
const component = PIXI.AnimatedSprite.from(texture_1);

My question is why does the second example [which uses PIXI.Texture.from() rather than "new PIXI.Texture()"] fail? Docs state Texture.from() should be able to accept a base texture as a source. In many of the tutorials the two syntaxes appear (confusingly) to be used interchangeably.


text:
Q: TIdTCPServer OnExecute and prevent constant polling I have a dummy, test server created using TIdTCPServer which I call from a client app using TIdTCPClient.  The OnExecute method of TIdTCPServer is:
procedure TDummySign.OnExecute(AContext: TIdContext);
begin
  Sleep(FDelay);
  // <1>010101<2>060100037908751531342CB30801010801000000000000D69A<3>
  AContext.Connection.IOHandler.Write(#6'01011234'#3#1'010101'#2'060100037908751531342CB30801010801000000000000D69A'#3);

end;

FDelay is set to say 500ms.
What I'm trying to achieve is make multiple requests to this server from my client without re-establishing a connection in between requests.  What is happening is when I attempt to read this reply from my client it (the reply) is constantly growing as the OnExecute is continuously executed once I've sent my first request.
Is there a way to, once I've "finished" with this OnExecute event, tell TidTCPServer to wait again until I send through another request from my client?  Similar to how it operates before any request has been sent from the client.  Some method of some property of TIdTCPServer I could perhaps call?  I've tried debugging through Write and calling ClearWriteBuffer (which is always nil so doesn't do anything) and from the Client side I clear the InputBuffer but to no avail.
For reference, here's my client code to send the request:
FIdTCPClient.IOHandler.Writeln(AString);
FIdTCPClient.IOHandler.InputBuffer.Clear;

TotalTime := 0;
TimedOut := False;
Reply := '';
Result := nil;

ParseInput := CreatePacketParserInput(ProtocolType);
repeat
  if FIdTCPClient.IOHandler.CheckForDataOnSource(Interval) then
  begin
    Reply := Reply + FIdTCPClient.IOHandler.InputBufferAsString;
    ParseInput.Reply := Reply;
    FParser.ParseReply(ParseInput, Result, SignId);
    CanContinue := (Result.ParseReplyResponse = TCommsParseReplyResponse.rrOK) or
      (Result.ParseReplyResponse = TCommsParseReplyResponse.rrStartSessionRetry) or
      (Result.ParseReplyResponse = TCommsParseReplyResponse.rrPacketParseError);
  end
  else
  begin
    TotalTime := TotalTime + Interval;
    if TotalTime > FCommsConfig.ReadTimeOut then
      TimedOut := True;
  end;
until TimedOut or (CanContinue);

A: Your client is using TIdIOHandler.WriteLn() to send a request.  On the server side, call TIdIOHandler.ReadLn() to wait for the request before then calling TIdIOHandler.Write() to send the response:
procedure TDummySign.OnExecute(AContext: TIdContext);
var
  Req: string;
begin
  Req := AContext.Connection.IOHandler.ReadLn;
  ...
  AContext.Connection.IOHandler.Write(#6'01011234'#3#1'010101'#2'060100037908751531342CB30801010801000000000000D69A'#3);
  ...
end;


text:
Q: Convert LaTeX to DAISY book Is there an easy way to convert a LaTeX book into a DAISY book?
BTW: A Daisy book is a talking book for visually challenged users. It has both text and audio. You can directly export a document as a Daisy book from MS-WORD and LibreOffice.


text:
Q: How to archive git status output? I need to archive some changes which are shown by git status command and keep all the paths, so I can copy it, unarchive and commit on my local machine. I know that git archive command exists but how to use it with git status?

A: git-archive is meant to archive the whole project, and works only with a commit/tag id.
What you want to do is:
git diff > patchfile

and
patch -p1 < patchfile

on your local machine.


text:
Q: Regarding instantons in 2D Abelian gauge theory I am trying to understand the analogues of instantons in a $U(1)$ gauge theory in 2D Euclidean spacetime. If we follow the same arguments as the 4D case and say that the the gauge field must tend to pure gauge at infinity, we will get topologically non-trivial configurations. Now, I want an explicit solution for such a configuration. This is where I run into problems. There is no analogue of the self-duality equations in 2 dimensions. If I choose an ansatz for the solution such as $$A_{\theta}=f(r)\big(e^{i\theta}\partial_{\theta}e^{-i\theta}\big)$$ along the with the boundary conditions $f(r=0)=0$ and $f(r \rightarrow \infty)=1$ and try to solve for it using Maxwell's equations, I am not able to get a consistent solution. Can anyone help me in figuring out where I am going wrong? Does such an explicit, analytic solution actually exist?

A: There can't be any such solutions in the pure gauge theory, but if you have  a Higgs field condensate you will get solutions that are the cross sections of Nielsen-Oleson (or Abrikosov) vortex lines.
The 2d euclidean Maxwell equations are the same as those for   $t$ and $z$-independent magnetic fields $B_z=F_{12}$ in 3+1d. You can't have a static  flux lump of  magnetic field  without a current somewhere. To be precise
$$
\partial_x B_z  =-J_y, \quad \partial_y B_z=J_x
$$
so unless $F_{1,2}=B_z$ is to be constant, there has to be a current.


text:
Q: Financial Calculator: How Can I properly store the inputs int N, I/Y, PMT, PV, and FV buttons to later perform a TVM calculation using Numpy? So the regular calculator functions work fine, but I am trying to add a Time Value of Money Calculator to it. Basically, I want to be able to press a number, then store it in one of the buttons (N, I/Y, PMT, PV, FV) and later on use Numpy to compute for the missing value. Any suggestions? If you have any resource suggestions, that would also be very helpful.
from tkinter import *
import numpy as np

operator = ""
nPeriods = ""
rate = ""

def btnClick(numbers):
    global operator
    operator = operator + str(numbers)
    text_input.set(operator)

def btnClearDisplay():
    global operator
    operator = ""
    text_input.set("")

def btnEqualsInput():
    global operator
    sumup = str(eval(operator))
    text_input.set(sumup)
    operator = ""

def btnNClick():
    global nPeriods
    global operator
    nPeriods = text_input.get() #may need to adjust
    text_input.set(nPeriods)
    operator = ""

def btnIYClick():
    global rate
    rate = int(text_input.get()) / 100
    #text_input.set(rate)

calc = Tk()
calc.title("Calculator")

text_input = StringVar()

textDisplay = Entry(calc,font=('arial',20,'bold'), textvariable=text_input, bd=25, insertwidth=10, bg='powder blue', justify='right')
textDisplay.grid(row=0, column=0, columnspan = 4)

#========================================

btn1 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='1', bg='powder blue', command=lambda:btnClick(1))
btn1.grid(row=1,column=0)

btn2 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='2', bg='powder blue', command=lambda:btnClick(2))
btn2.grid(row=1,column=1)

btn3 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='3', bg='powder blue', command=lambda:btnClick(3))
btn3.grid(row=1,column=2)

addition = Button(calc, padx=18, pady=20, fg="black", font=('arial',20,'bold'), text='+', bg='powder blue', command=lambda:btnClick('+'))
addition.grid(row=1,column=3)

#========================================

btn4 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='4', bg='powder blue', command=lambda:btnClick(4))
btn4.grid(row=2,column=0)

btn5 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='5', bg='powder blue', command=lambda:btnClick(5))
btn5.grid(row=2,column=1)

btn6 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='6', bg='powder blue', command=lambda:btnClick(6))
btn6.grid(row=2,column=2)

subtraction = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='-', bg='powder blue', command=lambda:btnClick('-'))
subtraction.grid(row=2,column=3)

#========================================
btn7 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='7', bg='powder blue', command=lambda:btnClick(7))
btn7.grid(row=3,column=0)

btn8 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='8', bg='powder blue', command=lambda:btnClick(8))
btn8.grid(row=3,column=1)

btn9 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='9', bg='powder blue', command=lambda:btnClick(9))
btn9.grid(row=3,column=2)

multiply = Button(calc, padx=19, pady=20, fg="black", font=('arial',20,'bold'), text='*', bg='powder blue', command=lambda:btnClick('*'))
multiply.grid(row=3,column=3)

#========================================
btn0 = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='0', bg='powder blue', command=lambda:btnClick(0))
btn0.grid(row=4,column=0)

btnClear = Button(calc, padx=18.5, pady=20, fg="black", font=('arial',20,'bold'), text='C', bg='powder blue', command=btnClearDisplay)
btnClear.grid(row=4,column=1)

btnEquals = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='=', bg='powder blue', command=btnEqualsInput)
btnEquals.grid(row=4,column=2)

divide = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='/', bg='powder blue', command=lambda:btnClick('/'))
divide.grid(row=4,column=3)

#==========================================
btnN = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='N', bg='powder blue', command=btnNClick)
btnN.grid(row=5,column=0)

btnIY = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='I/Y', bg='powder blue', command=btnIYClick)
btnIY.grid(row=5,column=1)

btnPV = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='PV', bg='powder blue', command=lambda:btnClick(3))
btnPV.grid(row=5,column=2)

btnPMT = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='PMT', bg='powder blue', command=lambda:btnClick(1))
btnPMT.grid(row=6,column=0)

btnFV = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='FV', bg='powder blue', command=lambda:btnClick(2))
btnFV.grid(row=6,column=1)

btnCPT = Button(calc, padx=20, pady=20, fg="black", font=('arial',20,'bold'), text='CPT', bg='powder blue', command=lambda:btnClick(3))
btnCPT.grid(row=6,column=2)

calc.mainloop()


text:
Q: vim sbuffer with fuzzy search I usually have plenty of files opened in different windows and tabs within vim (or neovim). To jump to the window where the file is open I use :sbuffer. For that, I input the begging of the file name and autocomplete with . I would like to find the name of the file in the way fuzzy search does.
How I see this going, I press , I input a part of the file name, until I see the file found by fuzzy search, then I press . If the file is already opened in a window in any tab, vim moves there rather than opening it in the actual window.
Do you know how to achieve this with any fuzzy search plugin? I'm not worried about the behaviour if the file is not open as usually I take manual care of splits when opening files.
Thanks!

A: Fzf is probably one of your best options here.
You'll need both fzf.vim and fzf.
Also, there's a readme for fzf vim in fzf main repo (yeah...).
I can't recall where I found this, but here's a config I copied from Fzf manual somewhere:
let g:fzf_command_prefix = 'Fzf'
let g:fzf_buffers_jump = 1      " [Buffers] to existing split

function! s:build_location_list(lines) abort
    call setloclist(0, map(copy(a:lines), '{ "filename": v:val }'))
    lopen
endfunction

function! s:build_quickfix_list(lines) abort
    call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
    copen
endfunction

" An action can be a reference to a function that processes selected lines
let g:fzf_action = {
            \ 'ctrl-l': function('s:build_quickfix_list'),
            \ 'ctrl-r': function('s:build_location_list'),
            \ 'ctrl-t': 'tab split',
            \ 'ctrl-x': 'split',
            \ 'ctrl-v': 'vsplit'}
" \ 'ctrl-o': '<S-tab>',
" \ 'ctrl-i': 'insert_match',

" function! s:insert_match(lines) abort
"   <c-r>=echo('a:lines')<cr>
" endfunction

nnoremap <leader>ff :FzfFiles $HOME<cr>
nnoremap <leader><c-f> :FzfFiles .<cr>
nnoremap <leader>F :FzfFiles /<cr>
nnoremap <leader>fb :FzfBuffers<cr>
nnoremap <leader>b :FzfBuffers<cr>
nnoremap <leader>fw :FzfWindows<cr>
nnoremap <leader>ft :FzfTags<cr>
nnoremap <leader>f<c-t> :FzfBTags<cr>
nnoremap <leader>fc :FzfCommit<cr>
nnoremap <leader>f<c-c> :FzfBCommit<cr>
nnoremap <leader>fg :FzfGFiles?<cr>
nnoremap <leader>f<c-g> :FzfGFiles<cr>
nnoremap <leader>fl :FzfLines<cr>
nnoremap <leader>f<c-l> :FzfBLines<cr>
nnoremap <leader>f; :FzfHistory:<cr>
nnoremap <leader>f/ :FzfHistory/<cr>
nnoremap <leader>fh :FzfHistory<cr>
nnoremap <leader>fm :FzfHelptags<cr>
nnoremap <leader>fs <esc>:FzfSnippets<cr>
nnoremap <leader>fr <esc>:Rg<cr>
inoremap <c-x><c-s> <c-o>:FzfSnippets<cr>

" Enable per-command history.
" CTRL-N and CTRL-P will be automatically bound to next-history and
" previous-history instead of down and up. If you don't like the change,
" explicitly bind the keys to down and up in your $FZF_DEFAULT_OPTS.
let g:fzf_history_dir = '~/.local/share/fzf-history'

let g:fzf_tags_command = 'ctags -R'
" Border color
let g:fzf_layout = {'up':'~90%', 'window': { 'width': 0.8, 'height': 0.8,'yoffset':0.5,'xoffset': 0.5, 'highlight': 'Todo', 'border': 'rounded' } }

let $FZF_DEFAULT_OPTS = '--layout=reverse --info=inline --bind "ctrl-o:toggle+up,ctrl-space:toggle-preview"'
let $FZF_DEFAULT_COMMAND="rg --files --hidden --glob '!.git/**'"
"-g '!{node_modules,.git}'

" Customize fzf colors to match your color scheme
let g:fzf_colors =
\ { 'fg':      ['fg', 'Normal'],
    \ 'bg':      ['bg', 'Normal'],
    \ 'gutter':  ['bg', 'Normal'],
    \ 'hl':      ['fg', 'Comment'],
    \ 'fg+':     ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
    \ 'bg+':     ['bg', 'Visual', 'CursorColumn'],
    \ 'hl+':     ['fg', 'Statement'],
    \ 'info':    ['fg', 'PreProc'],
    \ 'border':  ['fg', 'vertsplit'],
    \ 'prompt':  ['fg', 'Conditional'],
    \ 'pointer': ['fg', 'Exception'],
    \ 'marker':  ['fg', 'Keyword'],
    \ 'spinner': ['fg', 'Label'],
    \ 'header':  ['fg', 'Comment'] }
    " \ 'border':  ['fg', 'Conditional'],

"Get Files
command! -bang -nargs=? -complete=dir Files
        \ call fzf#vim#files(<q-args>, fzf#vim#with_preview({'options': ['--layout=reverse', '--info=inline']}), <bang>0)

" Get text in files with Rg
command! -bang -nargs=* Rg
    \ call fzf#vim#grep(
    \   "rg --column --line-number --no-heading --color=always --smart-case --glob '!.git/**' ".shellescape(<q-args>), 1,
    \   fzf#vim#with_preview(), <bang>0)

" Ripgrep advanced
function! RipgrepFzf(query, fullscreen) abort
    let command_fmt = 'rg --column --line-number --no-heading --color=always --smart-case %s || true'
    let initial_command = printf(command_fmt, shellescape(a:query))
    let reload_command = printf(command_fmt, '{q}')
    let spec = {'options': ['--phony', '--query', a:query, '--bind', 'change:reload:'.reload_command]}
    call fzf#vim#grep(initial_command, 1, fzf#vim#with_preview(spec), a:fullscreen)
endfunction

command! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)

" Git grep
command! -bang -nargs=* GGrep
    \ call fzf#vim#grep(
    \   'git grep --line-number '.shellescape(<q-args>), 0,
    \   fzf#vim#with_preview({'dir': systemlist('git rev-parse --show-toplevel')[0]}), <bang>0)

I tweaked it only a tad, but with something you'll probably enjoy because it's fzf paradigm to set switchbuf=usetab (or useopen). It lets Vim use a window where the buffer is already opened rather than the current.
let g:fzf_buffers_jump = 1      " [Buffers] to existing split

I hope it helps!

A: I'm personnally using the FZF plugin for all my fuzzy searches.
Here's a piece of code archieving what you ask:
set switchbuf=useopen,usetab
function! HandleFZFSink(filename)
    echo a:filename
    try
        exe "sbuffer " . a:filename
    catch
        exe "edit " . a:filename
    endtry
endfunction
function! FZFTmp()
    let cmd = 'ls --color=never 2> /dev/null'
    silent! exe fzf#run({'source': cmd, 'sink': function('HandleFZFSink'), 'down':'40%'})
endfunction
nnoremap <silent> , :<C-u>call FZFTmp()<CR>


text:
Q: getting version `GLIBC_2.29' not found when installing and configuring envoy 1.24 binary I am working on installing and configuring envoy 1.24 binary on CentOS7 machine.
I download the binary: https://github.com/envoyproxy/envoy/releases/download/v1.24.0/envoy-1.24.0-linux-x86_64 from the envoy releases. Since this is a binary file, I created the following service unit file:
[Unit]
Description=Envoy
[Service]
ExecStart=/opt/envoy/envoy -c /opt/envoy/envoy.yml -path.home /opt/envoy -path.config /opt/envoy -path.logs /var/log/envoy
Restart=always
RestartSec=5
KillMode=mixed
SyslogIdentifier=envoy
LimitNOFILE=640000
[Install]
WantedBy=multi-user.target

I reloaded the system demon so this unit file is reloaded.
I had a very basic envoy.yml in the right folder and executed the command: systemctl start envoy. I am seeing this error:
/lib64/libm.so.6: version `GLIBC_2.29' not found (required by /opt/envoy/envoy)

What am I missing here?
The envoy documentation does not talk about how to use the binary directly.
Also the deployment instructions: https://www.envoyproxy.io/docs/envoy/latest/start/install#install-envoy-on-rpm-based-distros is downloading version 1.18 version instead of 1.24.
Any pointers on resolving the above error?


text:
Q: Aggregrate without reducing dimension of dataframe I am trying to use the aggregate function in R where I want  the dimension of the output data frame to remain unchanged. For example:  Let's say I have the following data frame
Name------Type------    Price
Prod1-----A--------       $1
Prod2----A---------       $5
Prod3----B----------       $7
Prod4-----B---------       $9

After using aggregate function in R by aggregating on Type and function as Sum of price. I get the following result:
Type-------Value
A-----------6
B-----------16

However, I want the dimension of the data frame to remain same. For Example:
Name-----Type----Price----Value
Prod1----A-------$1-------$6
Prod2----A-------$5--------$6
Prod3----B--------$7-------$16
Prod 4----B-------$9--------$16

I do not want to use Loop for this application. Please suggest any other way of doing this.

A: We can use ave from base R
df1$Value <- with(df1, paste0("$", ave(as.numeric(sub("[$]", "", Price)),
                          Type, FUN = sum)))
df1$Value
#[1] "$6"  "$6"  "$16" "$16"

A: Using dplyr,
library(dplyr)
df %>%
  group_by(Type) %>%
  mutate(Value = sum(Price))

or using data.table,
library(data.table)
setDT(df)[, Value := sum(Price), by = Type]

#    Name Type Price Value
#1:   P1    A     1     6
#2:   P1    A     5     6
#3:   P3    B     7    16
#4:   P4    B     9    16


text:
Q: Find duplicates in app engine datastore I've some duplicated elements in my datastore (not the whole row, but most of the fields on it) in App Engine.
What's the best way to find them?
I've both integer and string fields that are duplicated (in case comparing one is faster than the other).
Thanks!

A: An stupid but quick approach would be to take the fields you care about, concatenate them as a long string and store them as the key of an DB_Unique entity that references the original entity. Each time you do DB_Unique.get_or_insert() you should verify the reference is to the correct original entity, otherwise, you have a duplicate. This should probably be done in a map reduce.
Something like:
class DB_Unique(db.Model):
  r = db.ReferenceProperty()

class DB_Obj(db.Model):
  a = db.IntegerProperty()
  b = db.StringProperty()
  c = db.StringProperty()

# executed for each DB_Obj...
def mapreduce(entity):
  key = '%s_%s_%s' % (entity.a,entity.b,entity.c)
  res = DB_Unique.get_or_insert(key, r=entity)
  if DB_Unique.r.get_value_for_datastore(res) != entity.key():
    # we have a possible collision, verify and delete?
    # out two entities are res and entity

There are a couple of edge cases that might creep up, such as if you have two entities with b and c equal to ('a_b', '') and ('a','b_') respectively, so the concatenation is 'a_b_' for both.  so use a character you know is not in your strings instead of '_', or have DB_Unique.r be a list of references and compare all of them.

A: If this is a one time or rarely occurring occasion, you might want to try dumping the whole database into local machine - see uploading and downloading data - load the data into a sqlite3 database and find the duplicate keys with it.
Trying to do this programmatically on the GAE side might turn out quite tedious. With tasks totally doable but not something too easy.


text:
Q: @ManyToMany Hibernate Error: "Target Entity is not defined" + "The attribute type for a collection mapping must be java.util.Collection..." I am trying to create a ManyToMany relation between two Entity-Classes: Produkt.java and Punkt.java. I did it exactly as the hibernate documentation and various tutorials show, and it seems to work, but I get 2 Errors on both of the @ManyToMany-Annontations in both of the Entity-Classes.
The errors are:

*

*"Target entity is not defined"

*"The attribute type for a collection mapping must be
java.util.Collection, java.util.Set, java.util.List or java.util.Map"

And here are the relevant parts of the code:
Produkt.java
@Entity
@Table(name = "produkt")
public class Produkt {

    @Id @GeneratedValue
    @Column(name = "PRODUCT_ID", unique = true, nullable = false)
    long productId;
    .
    .
    .

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "PRODUKT_PUNKT", joinColumns = {
    @JoinColumn(name = "PRODUCT_ID", nullable = false, updatable = false) },
        inverseJoinColumns = { @JoinColumn(name = "PUNKT_ID",
                nullable = false, updatable = false) })
    private List<Punkt>punkte;

    public Produkt() {
    }

    public Produkt(List<Punkt>punkte) {
        this.punkte = punkte;
    }

    public List<Punkt> getPunkte() {
        return punkte;
    }

    public void setPunkte(List<Punkt> punkte) {
        this.punkte = punkte;
    }
}

Punkt.java
@Entity
@Table(name = "punkt")
public class Punkt {

    @Id @GeneratedValue
    @Column(name="PUNKT_ID")
    private long punktId;

    .
    .
    .

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "punkte")
    private List<Produkt>produkte;

    public Punkt() {
    }

    public Punkt(List<Produkt>produkte) {
        this.produkte = produkte;
    }

    public List<Produkt> getProdukte() {
        return produkte;
    }

    public void setProdukte(List<Produkt> produkte) {
        this.produkte = produkte;
    }
}

hibernate.cfg.xml (lies in /src - folder)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
        <session-factory>
            <mapping class="org.duct.ductbased.model.Produkt" />
            <mapping class="org.duct.ductbased.model.Punkt" />
        </session-factory>
</hibernate-configuration>

As mentioned, this whole construct seems to work - I can run the application, I can create instances of both classes, fill them with data and persist to the database. The only problem now seems to be that the two lines with @ManyToMany - Annotations are marked red in eclipse.
Any help would be greatly appreciated! And please let me know, if more information is needed to solve the problem.

A: Ok, after searching and trying things out, I finally got the answers for the both problems:

*

*"The target entity is not defined" was caused by the false name of the second table, as isah already wrote.
But, it was not a coincidence, but a misunderstanding of the fundamental way of working of the entity mapping on my side. All the tutorials use a third table, to link the two tables. I actually thought, that it is what hibernate is doing in the background, when I use the @ManyToMany - Annotation, since I use the internal example database, which gets created and dropped every time I deploy the application.

*"The attribute type for a collection mapping must be java.util.Collection, java.util.Set, java.util.List or java.util.Map" message is an unsolved JBoss bug.
https://issues.jboss.org/browse/JBIDE-16016
It was still there, even when I deleted all the collections and the @ManyToMany parts. It disappeared, when I commented out the constructors. Now I inserted the constructors back again and the errors are not there.

A: @JoinTable(name = "PRODUKT_PUNKT"

While in your Punkt class you have defined
@Table(name = "punkt")
public class Punkt

It should be
@Table(name = "PRODUKT_PUNKT")
public class Punkt

In other words: @JoinTable name param should match the name defined with @Table on the other end.


text:
Q: How to resolve angular lang json file(angular-localization module) from jasmine test case I have angular service method which uses  angular-localization locale service .
I want to write jasmine test cases for  method , which are failing as jasmine is not able to
resolve it. May be it is not waiting till it resolve completely
//service method
$scope.getExcelName = function() {
  var name = locale.getString('export.fileName')
  return name;
}

//lang file
'fileName': 'Status Report'

//Jasmine test case
describe('Service:MyService', function() {
  var myService
  beforeEach(module('app'))

  beforeEach(inject(function($injector) {
    myService = $injector.get('MyService');
  }))

  it('check export name', function() {
    //myService.getExcel giving '' instead of  Status Report
    expect(myService.getExcelName()).toBe('Status Report')
  })
})

How  to resolve above issue ?

A: It seems like you are experiencing a race condition (excerpt from the documentation):

Race conditions
Always use locale.ready() passing in the filename(s)
  in which the token(s) exists in that context, and enclose any other
  relevant calls to locale.getString() within this promise's callback
  function block. Failure to do so may cause unexpected (empty) results
  due to the asynchronous nature of your entire JavaScript application.
You may use locale.getPath() to find the filename for any given token.

So the solution should be to inject the locale service and wrap the expect line inside a locale.ready() call, e.g.:
it('check export name', function(done) {
  locale.ready('export')
    .then(function() {
      expect(myService.getExcelName()).toBe('Status Report');
      done();
    })
    .catch(done.fail);
});

Probably you should also do the same in the service itself to be safe.


text:
Q: RS.EXE not found I have made an application and installing it using installation wizard  in which the application is being installed and in the same process the SSRS installation is called.In which enter image description here
a) Report services not being installed when being called within the installation processes.
b) Report services is being installed once being run from the DVD.
c) RS. exe not found when run through program.
d) RS. exe found when run through DVD.
Snapshot attached

A: You can copy the rs.exe application off the removable media & use it without an SSRS installation or the removable media. Also, are you sure the application is trying to run the rs.exe app from the D drive and not it's local folder?
In my opinion you'd be better packaging this (rs.exe) up with the application, or a few steps further, you can build the reporting services functionality into a C# application without the rs.exe.
Hope that helps


text:
Q: how to give box-shadow in mail I want to create my own mail by html code.
Now I have written the following code

The properties are working properly but the effect of boxshadow is not working in gmail and yahoo but it works properly in other company domain

A: Thats how we did this when no CSS3 was around:

BoxShadows 90s style.

and the CSS:
.overlay {
  background-color: #FFFFFF;
  border: 1px solid #000000;
  color: #000000;
  padding: 0.5em;
}
.shadow {
  background-color: #CCCCCC;
}
.shadow .overlay {
  bottom: 4px;
  position: relative;
  right: 4px;
}

Works by underlaying the content with a slightly displaced gray div.
Look here for the not so fancy result. Example
Another way would be to wrap your table in a table where the outer cells have 2 stretched half transparent pngs and 1 corner png as background. Looks far better, but since most email clients don't show images by default, I would stick to the good old browser safe suggestion with an overlay div.

A: It is only supported in a few email clients. You are better off using images if you want 100% support.

A:

You forgot to add ; check with that if that is the issue.


text: Q: UI no renderiza en la build pero si en el editor unity Tengo un problema con la UI de unity cuando no es "Screen space- Overlay" es decir cuando es "Screen space-Camera" o "World Space" todo parece funcionar perfectamente en el editor pero no aparece nada cuando hago la build