text:
Q: Selenium XPATH I am trying to find the checkbox from a table where name is in col 2 and col 3 I have a html table with lots of rows and 3 columns. col1 has a checkbox, col2 has a string text and col 3 has a string text. Using XPath I am trying to locate the checkbox where col 3 has the text "Address" and col 2 has the text "CLEAN_AUDIT"
There is also a row in the table which has "CLEAN_AUDIT" in col2 and col3 has the text "Name"
If i use the following XPATH it will locate all the checkboxes which has "CLEAN_AUDIT" in col2 This is no good for me because I just need to locate "CLEAN_AUDIT" which has "Address"
//table[@id="reporting_add_report_tab_manual_ct_fields_avail"]//div[(text()="CLEAN_AUDIT")]/preceding::td[1]//input

I don't want to use td[1] because the table can change, the data can move to a different place. Also i would like to use text in the xpath somehow because if i wanted to find the checkbox where "CLEAN_AUDIT" is in col2 and "Name" is in col3
The HTML snippet is (Apologies it is a bit long):

    <colgroup>

                            <input type="checkbox" tabindex="-1"/>

                            <input type="checkbox" tabindex="-1"/>

LAST_DATA_CHANGED

                            <input type="checkbox" tabindex="-1"/>

FORENAME_UNN

Name

                            <input type="checkbox" tabindex="-1"/>

SURNAME_UNN

Name

                            <input type="checkbox" tabindex="-1"/>

TITLE

Name

                            <input type="checkbox" tabindex="-1"/>

FORENAME

Name

                            <input type="checkbox" tabindex="-1"/>

SURNAME

Name

                            <input type="checkbox" tabindex="-1"/>

SUFFIX

Name

                            <input type="checkbox" tabindex="-1"/>

GENDER

Name

                            <input type="checkbox" tabindex="-1"/>

SOURCE_FIELDS

Name

                            <input type="checkbox" tabindex="-1"/>

CLEAN_AUDIT

Name

                            <input type="checkbox" tabindex="-1"/>

EXPANDED_CLEAN_AUDIT

Name

                            <input type="checkbox" tabindex="-1"/>

CATEGORY

Name

                            <input type="checkbox" tabindex="-1"/>

SOURCEMAP_ID

Name

                            <input type="checkbox" tabindex="-1"/>

TIME_STAMP

Name

                            <input type="checkbox" tabindex="-1"/>

LAST_SEEN

Name

                            <input type="checkbox" tabindex="-1"/>

STANDARDISED_DATA

Name

                            <input type="checkbox" tabindex="-1"/>

ISRN

Address

                            <input type="checkbox" tabindex="-1"/>

BISRN

Address

                            <input type="checkbox" tabindex="-1"/>

USRN

Address

                            <input type="checkbox" tabindex="-1"/>

ULN

Address

                            <input type="checkbox" tabindex="-1"/>

POBOX

Address

                            <input type="checkbox" tabindex="-1"/>

DEPT

Address

                            <input type="checkbox" tabindex="-1"/>

ORGNAME

Address

                            <input type="checkbox" tabindex="-1"/>

SUBBNAME

Address

                            <input type="checkbox" tabindex="-1"/>

FLOOR

Address

                            <input type="checkbox" tabindex="-1"/>

BLOCK

Address

                            <input type="checkbox" tabindex="-1"/>

BUILDING

Address

                            <input type="checkbox" tabindex="-1"/>

COMPLEX

Address

                            <input type="checkbox" tabindex="-1"/>

BNUM

Address

                            <input type="checkbox" tabindex="-1"/>

SUBSTREET

Address

                            <input type="checkbox" tabindex="-1"/>

STREET

Address

                            <input type="checkbox" tabindex="-1"/>

LOCALITY1

Address

                            <input type="checkbox" tabindex="-1"/>

LOCALITY2

Address

                            <input type="checkbox" tabindex="-1"/>

LOCALITY3

Address

                            <input type="checkbox" tabindex="-1"/>

LOCALITY4

Address

                            <input type="checkbox" tabindex="-1"/>

POSTCODE

Address

                            <input type="checkbox" tabindex="-1"/>

COUNTRY

Address

                            <input type="checkbox" tabindex="-1"/>

X

Address

                            <input type="checkbox" tabindex="-1"/>

Y

Address

                            <input type="checkbox" tabindex="-1"/>

ADDRCL_AUDIT

Address

                            <input type="checkbox" tabindex="-1"/>

XREF

Address

                            <input type="checkbox" tabindex="-1"/>

SOURCE_FIELDS

Address

                            <input type="checkbox" tabindex="-1"/>

CLEAN_AUDIT

Address

Thanks,
Riaz

A: This XPath will select the checkbox of the row that contains "CLEAN_AUDIT" and "Name":
//table[@id="reporting_add_report_tab_manual_ct_fields_avail"]//tr[.//div[text()="CLEAN_AUDIT"] and .//div[text()="Name"]]//input[@type="checkbox"]

A: By your page source, I tried this and found it working:
//td/div[text()='CLEAN_AUDIT']/../following-sibling::td/div[text()='Address']/../../td//input

A: Sorry for it being a little long
//table[@id='reporting_add_report_tab_manual_ct_fields_avail']/descendant::tr[contains(.,'CLEAN_AUDIT') and contains(., 'Address')]/descendant::input[@type='checkbox']


text:
Q: Understanding Dual of $l_1$ norm I am new in vector and Matrix Calculus. I was studying different norm and dual norm of vectors. I found $L_1$ norm as defined as the sum of absolute value of the points in the vector. The dual of that norm is $L_\infty$ norm. I am having hard time to understand that. Particularly, from definition the dual of a norm is the supremum of $x^Ty$ where $||x||\leq1$. So $x$ is normal to the $y$?. If we plot $L_1$ norm than the dual points should be the perpendicular points. But how this produces $L_\infty$ norm?
Thanks

A: You did not understand. Consider the case when the vector space is $E=\mathbb{R}^2$ with the $l_1$ norm $||X||_1=|x_1|+|x_2|$. We consider the dual $E^*=L(E,\mathbb{R})$ and we show that the associated norm $||.||$ is $l_{\infty}$; if $f\in E^*$, then $f(X)=[a_1,a_2]X=a_1x_1+a_2x_2$. Assume that $\sup(|a_1|,|a_2|)=|a_1|$.
Thus $||f||=\sup_{||X||_1=1}|f(X)|=\sup_{|x_1|+|x_2|=1}|a_1x_1+a_2x_2|$. We choose $sign(x_1)=sign(a_1),sign(x_2)=sign(a_2)$; then $|f(X)|=|a_1||x_1|+|a_2|(1-|x_1|)$ and the $\sup$ is obtained for $|x_1|=1$; finally , we obtain the asked result $||f||=|a_1|=||f||_{\infty}$.
Note that $E$ is not euclidean; then, there is no canonical isomorphism between $E$ and $E^*$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python can't find BBIO.GPIO library on Beaglebone I'm using the Beaglebone and I had installed this software:
 http://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/installation
the test works fine (webpage test) but when I'm trying to run my first program it doesn't recognize the library the mistake is:
import BBIO.GPIO as GPIO
File "<stdin>", line 1, in <module>
ImportError: No module named BBIO.GPIO

A: I encountered what might be a similar problem around the same time as you.
The Adafruit library has changed, and the instructions have been updated. It might be worth heading over to http://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black and starting again.
The library's name has been changed as well, so you won't have any collision errors.
Good luck!


text:
Q: Closing Cursor in function that returns Cursor I have a problem with closing Cursor in my SQLite class. When I'll close the Cursor and SQLiteDatabase in finally block (in DBHelper) then i can't read data in my other class (Can't reopen closed Cursor error) but when I do not close Cursor and SQLiteDatabase then i have memory leak errors.
DHHelper.java :
//...
public Cursor selectData(String selectVal, String tabName){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = null;
    try {
        String areaTyp = "SELECT " + selectVal + "  FROM " + tabName;
        c = db.rawQuery(areaTyp, null);
        return c;
    } finally {
        c.close();
        db.close();
    }
}
//...

UserMenager.java
    public List<UserModel> getUsersList(){
    List<UserModel> allUsers = new ArrayList<UserModel>();

    final DBHelper db = new DBHelper(appStatic.CONTEX);
    Cursor c = db.selectData("*","User");
    if (c.moveToFirst()) {
        while (!c.isAfterLast()) {

            allUsers.add(new UserModel(c.getString(c.getColumnIndex("cms_id")),
                    c.getString(c.getColumnIndex("login")),
                            c.getString(c.getColumnIndex("name")),
                                    c.getString(c.getColumnIndex("active")),
                                            c.getString(c.getColumnIndex("avatar")),
                                                    c.getString(c.getColumnIndex("gtoken"))));

            c.moveToNext();
        }
    }
    c.close();
    db.close();

    return allUsers;
}

Maybe I should do this in other way and the function that returns Cursor is a bad idea?
EDIT:
When i run app, i have error:

java.lang.IllegalStateException: attempt to re-open an already-closed
  object: SQLiteQuery: SELECT *  FROM User

In UserMenager.java, line
if (c.moveToFirst()) {

A: I'd suggest returning what you want as an end result, that is an ArrayList, from the selectData class. You can then close the Cursor and the Database in the selectData method as soon as they are done with.
e.g. :-
public ArrayList<UserModel> selectData(String selectVal, String tabName){
    SQLiteDatabase db = this.getWritableDatabase(); //<<<< getReadable will most likely return a writeable database anyway
    ArrayList<UserModel> rv = new ArrayList<>();
    Cursor c = db.query(
            tabName,
            new String[]{selectVal},
            null,
            null,
            null,
            null,
            null
    );
    while (c.moveToNext()) {
        rv.add(new UserModel(
                c.getString(c.getColumnIndex("cms_id")),
                c.getString(c.getColumnIndex("login")),
                c.getString(c.getColumnIndex("name")),
                c.getString(c.getColumnIndex("active")),
                c.getString(c.getColumnIndex("avatar")),
                c.getString(c.getColumnIndex("gtoken"))
        ));
    }
    c.close();
    db.close();
    return rv;
}

Along with :-
public List<UserModel> getUsersList(){
    List<UserModel> allUsers = new ArrayList<UserModel>();

    final DBHelper db = new DBHelper(appStatic.CONTEX);
    return selectData("*","Users");
}

*

*Wrapping try/catch around SQLiteDatabase methods tends to cause more frustration and confusion than would otherwise be caused.

*Generally the convenience methods are recommended over the use of the rawQuery and execSQL methods (in this case query is the convenience method).

*Ideally selectVal should be a String[] of the columns rather than just a String to suit the query convenience method.

*As commented getReadableDatabase rarely gets a read only database as per

*

*Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk,
  requires the database to be opened read-only. In that case, a
  read-only database object will be returned. If the problem is fixed, a
  future call to getWritableDatabase() may succeed, in which case the
  read-only database object will be closed and the read/write object
  will be returned in the future.
  SQLiteDatabase getReadableDatabase


text:
Q: LEFT JOIN SUBQUERY Olá, estou com uma pequena dúvida sobre SQL já que não entendo nada sobre isso.Tenho uma tabela onde estou fazendo um select para ver as atualizações com uma subquery e faço um LEFT JOIN qui está o código:
SELECT a.id, a.nome,
(SELECT COUNT(c.id) FROM postagens as c WHERE c.data_cadastro >
b.data_acesso AND c.id_categoria = a.id AND deletado = 0) as atualizacoes
FROM postagens_categorias as a
LEFT JOIN postagens_categorias_view as b ON a.id = b.id_categoria
WHERE a.deletado =0 AND a.id != 3 ORDER BY a.nome DESC

E dá este resultado aqui:

Os dados que eu gostaria seria:
Projetos   25
Estágios   24
Divulgação 21

Acredito que deveria usar um GROUP BY em algum lugar, se eu usar o DISTINCT no começo ele continua duplicando os valores só que no lugar de NULL, 0.
Aqui está a tabela de postagens_categorias:

Postagens_categorias_view:

Postagens:

Como faço essa parte?

A: Pelo que eu entendi do seu problema, a solução é a seguinte:
SELECT a.id, a.nome, count(d.id_categoria) as atualizacoes
FROM postagens_categorias as a
    LEFT JOIN (SELECT id_categoria from postagens_categorias_view b
                INNER JOIN postagens c
                    ON c.id_categoria = b.id_categoria
                WHERE c.deletado = 0 AND
                    c.data_cadastro > b.data_acesso
              ) d
        ON a.id = d.id_categoria
WHERE a.deletado = 0 AND
    a.id != 3
GROUP BY a.id, a.nome
ORDER BY a.nome DESC

A: Tente usar Isnull (quando for null substitui zero) se não der certo, coloca CASE
SELECT a.id, a.nome, isnull(count(*),0) atualizacoes
FROM postagens_categorias as a
    LEFT JOIN postagens_categorias_view as b ON a.id = b.id_categoria
    LEFT JOIN postagens as c on c.id_categoria = a.id
WHERE a.deletado = 0 AND
    c.deletado = 0 AND
    a.id != 3 AND
    c.data_cadastro > b.data_acesso
GROUP BY a.id, a.nome
ORDER BY a.nome DESC

A: Se o filtro do seu select estiver certo, o código pode ser esse aqui:
SELECT T.ID,
       T.NOME,
       T.ATUALIZACOES
FROM (
SELECT A.ID,
       A.NOME,
       (SELECT COUNT(C.ID)
        FROM   POSTAGENS AS C
        WHERE  C.DATA_CADASTRO > B.DATA_ACESSO
        AND    C.ID_CATEGORIA = A.ID
        AND    DELETADO = 0) AS ATUALIZACOES
FROM   POSTAGENS_CATEGORIAS AS A
LEFT   JOIN POSTAGENS_CATEGORIAS_VIEW AS B
ON     A.ID = B.ID_CATEGORIA
WHERE  A.DELETADO = 0
AND    A.ID != 3
GROUP BY A.ID,
         A.NOME) T
ORDER BY T.NOME DESC


text:
Q: Properly disposing of variable. Are using statements enough? I have a class that contains methods that calls stored procedures. Some of these stored procedures return data structures others do not. Here is an example of one of the methods.
public DataTable GetProductData(int productID)
{
  DataTable dataTable = new DataTable();
  using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
  {
    using (SqlConnection sqlConn = new SqlConnection("CONNECTIONSTRING"))
    {
      using (SqlCommand sqlCmd = new SqlCommand("getProductData", sqlConn))
      {
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.AddWithValue("@ID", productID);
        sqlConn.Open();
        sqlDataAdapter.Fill(dataTable);
      }
    }
  }
  return dataTable;
}

This method is used by another program when data access is required. Here is an example of a method that makes use of the above method ...
public DataTable GetProductInfoFromDatabase(int productID)
{
  DataLibrary dl = new DataLibrary();
  return dl.GetProductData(productID);
}

What I am wondering is how I should dispose of the dl variable once I have retrieved the data. Will the garbage collection take care of it or should I implement IDisposable in the class where the GetProductData method is defined? Are the using statements enough?

A: Unless your class is holding onto unmanaged resources or otherwise IDisposable objects; no, you do not need to implement IDisposable yourself. An empty Dispose method buys you nothing.
In the code you provided, the using statements are sufficient. The DataLibrary object created in GetProductInfoFromDatabase will be collected by the GC as you expect.


text:
Q: How do I fork a process that doesn't die when shell exits? If I run emacs from the shell:
$ emacs foo &

and then kill that shell, emacs dies.
How can I run a command so that it will not die when the shell dies?
I found references to nohup, but that does not seem to help:
$ nohup emacs foo &

still kills emacs when shell dies.

A: Check you shell settings. You can also try screen instead of nohup.

A: The most reliable method appears to be:
(setsid emacs &)

This uses ( &) to fork to background, and setsid to detach from the controlling tty.
You can put this in a shell function:
fork() { (setsid "$@" &); }

fork emacs

The possibilities are:

*

*The disown builtin command:
emacs &
disown $!

& acts as command separator, and disown will default to the most recent job, so this can be shortened to:
emacs & disown

*Double-fork():
(emacs &)

Commands inside parentheses ( ) are run in a separate shell process.

*setsid, as suggested by Rich, might be the best choice, because it unsets the controlling TTY of the process by creating a new session:
setsid emacs

However, it is also a little unpredictable - it will only fork() to background if it is the leader of a process group (which won't happen if setsid is used in a sh script, for example; in such occassions it will merely become resistant to Ctrl-C.)

A: You do not mention if this is running as an X app or a console app.
If it's as a console app, of course it needs to close.  You got rid of it's input/output, more technically the (pseudo) tty it was on.  It's very unlikely this is what you meant, so let's assume you're talking about an X app.
nohup should work, not sure why it isn't.  When the shell closes, it sends SIGHUP to all processes in its process group.  nohup tells the command to ignore SIGHUP.
You can also try setsid, which disconnects the process from the process group
alias emacs='setsid emacs'

Or add disown after &


text:
Q: Probability - find the number of balls in a box There are $20\%$ less white than black balls in a box. Two balls are randomly chosen. If the probability that at least one chosen ball is white is $12/17$, how many black balls are in a box?
If $w$ is the number of white balls, and $b$ is the number of black balls, then:
$$w=b-b/5=4b/5$$
Total number of balls in a box is $t=9w/4$ or $t=9b/5$.
How can we find the total number of black balls after two are randomly chosen?

A: Hint
\begin{align}
P( \text{at least } 1 \text{white ball} ) &=1-P(\text{both balls are black}) \\
&=1-\frac{b}{t}\frac{b-1}{t-1} \\
&= 1- \frac59 \left( \frac{b-1}{\frac{9b}{5}-1} \right)
\end{align}
equate this to $\frac{12}{17}$, solve for $b$.


text:
Q: Force automatic linq to sql classes to have pascal case properties? My SQL database has column names in camel case.
I'm using Linq to SQL with C#.
Is there a way to force auto-generation of properties to be in pascal case?
The camel case properties do not conform to the C# standards, and it's a pain to do it manually each time I need to re-create the classes.

A: If your database is really big and renaming entities manually is time consuming, then:

*

*Download LINQ to SQL templates for T4 and add two files to your project CSharpDataClasses.tt and L2ST4.ttinclude.

*Rename `CSharpDataClasses.tt to match your dbml file name (e.g. Northwind.tt)

*Select dmbl file (e.g. Northwind.dbml) and remove MSLinqToSQLGenerator from Custom Tool property.

*Open L2ST4.ttinclude and change it as described further

*Select Northwind.tt file and press Ctrl+S (this will run LINQ 2 SQL classes generation).

L2ST4.ttinclude file changes:
Find definition of class Data (at the top of file) and paste this code before it:
class Lazy
{
   public static string FirstLetterToUpper(string str)
   {
       return Char.ToUpper(str[0]) + str.Substring(1);
   }
}

Then find definition of class Table and in constructor replace Member property initialization with
Member = Lazy.FirstLetterToUpper((String)xe.Attribute("Member"));

Find class Class and in constructor replace Name property initialization with
Name = Lazy.FirstLetterToUpper((String) xe.Attribute("Name"));

And last, find class Association and in its constructor set
typeName = Lazy.FirstLetterToUpper((String) xe.Attribute("Type"));

PS If you really lazy, then use this L2ST4.ttinclude file already changed by me :)

A: I suggest LINQ to SQL templates for T4 project l2st4.codeplex.com. You can customize it as you wish.


text:
Q: LINQ: Compare List A and B, if in B, select item in A I have a list of tags (List A), and a list of tags matched to topics (List B). I want to parse all items in List B and if it's there, have it select the item in List A. I've tried to do a two line and one line statement to do this, but I run into the same problem no matter what I try. Here's my one line attempt of code:
var tags = db.Tags.Where(x=>x.TagID == db.TagLink.Where(y => y.TopicID == incomingTopicID)).ToList();

List A and B have a common column of Tag ID.
Any suggestions?
Update
The structure of db.TagLink are these columns: TagLinkID(Key), TopicID, TagID.
The structure of db.Tags are these columns: TagID, TagName, IsTagScored.

A: There are several ways you could go about it. Here's one approach:
var tags = db.Tags
    .Where(x=>db.TagLink
        .Any(y => y.TagId == x.TagId && y.TopicID == incomingTopicID))
    .ToList();

A: You could use Join, like this:
var tags = db.TagLink.Where(x => x.TopicID == incomingTopicID)
                     .Join(db.Tag, x => x.TagId, y => y.TagId, (x, y) => y)
                     .ToList();


text:
Q: Django Wagtail sitemap I have an existing Django site for which i've added Wagtail. I would like to have a sitemap for both Django and Wagtail urls.
My current sitemap.py:
class StaticSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = "weekly"
    protocol = "https"

    def items(self):
        return ["public:index", "other pages etc..."]

    def location(self, item):
        return reverse(item)

My current urls.py:
sitemaps = {"static": StaticSitemap}
path(
    "sitemap.xml",
    sitemap,
    {"sitemaps": sitemaps},
    name="django.contrib.sitemaps.views.sitemap",
),

The above works correctly for a standard Django sitemap. How do I include Wagtail urls?

A: I assume your sitemap view comes from wagtail.contrib.sitemaps.views (if you're using Django's view, you should switch to Wagtail's.
Then the only thing you need to do is add Wagtail's Sitemap on your sitemaps dictionary:
from wagtail.contrib.sitemaps.sitemap_generator import Sitemap

sitemaps = {"static": StaticSitemap, "wagtail": Sitemap}


text:
Q: gdb-mutiarch can't connect JLinkGDBServer on Cortex-A55
*

*JLinkExe can connect to cortex-a55.Cortex-A55 identified.connect to device.png

*After device connected,"Regs" command seems to work fine."Regs" works fine.png

*"Mem32" command seems to work fine(dump rom memory)."Mem32 works fine.png"

*Use JLinkGDBServerExe to connect to device, and waiting for gdb connection.(J-Link connected,Device connected,waiting for gdb)JLinkGDBServer looks fine.png

*Now, Use gdb-mutiarch to connect JLinkGDBServercan't connect jlinkgdbserver.png

*

*set architecure aarch64

*tar rem:2331

*can't connect.Could not fetch register "PC"; remote failure reply 'E01'.

*I set arch to armv7 in gdb(aka aarch32,which is not right for my situation.In the connect to device.png,now my device is in el3&aarch64), connection succeeded?aarch32 connection succeeded???.png

*

*set architecure armv7

*tar rem:2331

*connection succeeded?!

*info registers, but dump regs in the aarch32 way.

Is there something wrong with my operations?
Or can anyone tell me how to debug baremetal cortex-a55?
By the way, JLink sw version is V7.64c, JLink hw is EDU V11. gdb-mutiarch version is GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2.


text:
Q: C problems when going through list elements I'm stuck with one problem in my little program in C and I really, really need your help. The 90% of the code works perfectly, because I checked multiple times, the problem is in the last lines and I can't figure out how to fix it. I'm still only a beginner so there's probably a really basic mistake somewhere.
My program puts all the words from txt file on a list [checked, works fine]. The user types the keyword. In the keyword instead some letters it can be used '?' meaning any random letter, '*' meaning any random amount of letters at the end and [x,y,z] meaning the letter could be x or y or z, then the program checks if any of words from the list match. The function that checks all these conditions works very good as well [I checked it on some random words], but somehow I fail when trying to make it check all the words from the list and printf the ones that match. I'd be very grateful if someone can help me fix this problem.
Here's the code:
typedef struct bazaslowek                                    // structure
    {
        char *wordlist;
        struct bazaslowek* next;
    } baza;

int MatchWord(char *Word, char *Sequence)    //function, here works everything

{int i = 0;
int j = 0;
int k = 0;
int LastChar = 0;
int CharMatch = 0;
char SpecifiedChars[20];

while(Word[i]!='\0' && Sequence[j]!='\0')
{if(isalpha(Sequence[j]))
    {if(Word[i]!=Sequence[j])
        {return 0;}
    i++;
    j++;
    }
if(Sequence[j] == '?')
    {i++;
    j++;}
if(Sequence[j] == '[')
    {j++;
    while(Sequence[j]!= ']')
        {if(isalpha(Sequence[j]))
            {SpecifiedChars[LastChar] = Sequence[j];
            LastChar++;
            j++;}
        else
            { j++;}
        }
    j++;
    for(k = 0 ; k <= LastChar ;k++)
        {if(SpecifiedChars[k]==Word[i])
            {CharMatch = 1;}
        SpecifiedChars[k] = ' ';}
        SpecifiedChars[0] = '\0';
        LastChar = 0;
        if(!CharMatch)
            {return 0;}
        i++;
    }
    if(Sequence[j] == '*')
    { j++;
    while(Word[i]!='\0')
        { i++;}
    }
}
return 1;
}

int main()

{    //============================== txt file -> list, works fine

baza *head = NULL;
char wordlist[30];
FILE *fp;
if ((fp = fopen("bazaslow.txt", "r"))==NULL)
    {printf("Error while opening!");
    exit(EXIT_FAILURE);}
else
    {
    while(!feof(fp))
        {
        fscanf(fp,"%s\n", wordlist);
        baza *wsk = head;
        baza *new = malloc (sizeof(baza));
        new -> next = NULL;
        new -> wordlist = strdup(wordlist);
        if(wsk == NULL)
            {
            new -> next = head;
            head = new;
            }
        else
            {
            while(wsk -> next != NULL)
            wsk = wsk -> next;
            wsk -> next = new;
            }
        }
    }
fclose(fp);

//=============================HERE THE PROBLEM STARTS

char word[30], keyword[30];
printf("Type the keyword: \n");
scanf("%s", keyword);
baza *wskx = head;
while (wskx != NULL)
    {wskx->wordlist=word;
    printf("%s\n", wskx->wordlist);
    if(MatchWord(word,keyword))
        {printf("\n%s", wskx->wordlist);}
    wskx=wskx->next;}
return 0;
}

With this code it printfs me a lot of lines of some random letters and characters that are not even on list, every time they're different. I'm really, really in need of your help, I'm trying to figure out this problem for a long time already, but every time I fail.

A: You are assignment is wrong. Instead of
wskx->wordlist=word;

you should do
word=wskx->wordlist;

A: It should be like this:
char keyword[30];
printf("Type the keyword: \n");
scanf("%s", keyword);
baza *wskx = head;
while (wskx != NULL)
{
    if(MatchWord(wskx->wordlist,keyword))
        printf("\n%s", wskx->wordlist);
    wskx=wskx->next;
}


text:
Q: How to convert TSQL aggregate function to Postgresql I am having difficulty converting a view from T-SQL to Postgresql as it relates to the aggregate functions.
Here is my original SQL query:
SELECT TOP (100) PERCENT
    thread_id,
    MIN(message_id) AS message_id,
    MIN(parent_message_id) AS parent_message_id,
    MIN(created_at) AS initialResponse
FROM
    dbo.bi_linear_thread
WHERE
    LEFT([subject], 5) LIKE '%RE:%' AND parent_message_id IS NOT NULL
GROUP BY
    thread_id
ORDER BY
    thread_id

I have attempted to utilize the window function of:
first_value(message_id) OVER (Partition BY message_id ORDER BY messageid)

but continue to get incorrect returns.
Thoughts?
Edit for more context
-- after the answer provided.  Hopeful this is helpful to others.
Needed to read the first line in a group that excluded the first record in a hierarchal order of threads to replies.
thread_id represents the thread.
message_id represents any message type whether a reply/original message. parent_message_id represents the original message in the thread.
"RE:" is a specified format for replies regardless whether nested or not in the subject field.

A: SELECT thread_id
      ,MIN(message_id) AS message_id
      ,MIN(parent_message_id) AS parent_message_id
      ,MIN(created_at) AS initialResponse
FROM   dbo.bi_linear_thread
WHERE  left(subject, 5) LIKE '%RE:%'
AND    parent_message_id IS NOT NULL
GROUP  BY thread_id
ORDER  BY thread_id;

Except for removing the illegal brackets from [subject] and also removing TOP (100) PERCENT, which is just noise anyway, the query should work.
You might want ILIKE instead of LIKE for case-insensitive pattern-matching.
left() was introduced with Postgres 9.1.
If you want CaMeL-case identifiers you need to double-quote: "initialResponse". Else they are lower-cased automatically. My advice is to use lower-case identifiers exclusively.
Educated guess
If you actually want the row with the earliest created_at per thread_id, which you cunningly kept a secret, your query is incorrect, tSQL or PostgreSQL alike.
You could use DISTINCT ON for that.
You probably don't have a schema named dbo in Postgres either, and that's an artifact from SQL Server, so I removed that, too.
I use ILIKE as explained above.
SELECT DISTINCT ON (thread_id)
       thread_id, message_id, parent_message_id, created_at AS initial_response
FROM   bi_linear_thread
WHERE  left(subject, 5) ILIKE '%RE:%'
AND    parent_message_id IS NOT NULL
ORDER  BY thread_id, created_at;

Information on DISTINCT ON:
Select first row in each GROUP BY group?
For perfomance, a trigram GIN index on the expression left(subject, 5) might help quite a bit. More info:
PostgreSQL LIKE query performance variations

A: This was the closest I came on my own... better answer above.
SELECT DISTINCT
 thread_id
,first_value(message_id) OVER (Partition BY thread_id ORDER BY message_id) AS message_id
,first_value(parent_message_id) OVER (Partition BY thread_id ORDER BY parent_message_id) AS parent_message_id
,first_value(created_at) OVER (Partition BY thread_id ORDER BY created_at) AS initialResponse
FROM bi_linear_thread
WHERE parent_message_id IS NOT NULL AND subject ~* '.*RE:.*'
GROUP BY message_id, thread_id, parent_message_id, created_at
ORDER BY thread_id desc


text:
Q: Getting a weird HTTP ERROR 500 on running query on a specific database table I have tried doing this
$query = "SELECT * FROM policies";
$policies = DB::select($query);

And also this
    $policies = Policy::all();
Whenever I try to do this, this happens
here is my controller function
public function getPremiumCollectionReport (Request $request) {
    $policies = Policy::all();
    echo $policies;
}

Other queries run perfectly well for other models and tables. And if I run the raw query in the sql server, it runs perfectly as well.
Can anyone help me find a solution? I don't have a clue.

A: I just found out that there were too many policies in that table for the server to handle. If I run the query for a smaller number of policies, the query runs successfully. It only happens when I try to select a large number of policies.


text:
Q: stacktrace E/UncaughtException: java.lang.IndexOutOfBoundsException: Invalid index 1 i am developing a android app with firebase leaderboard, it working well, but crash when i click on leaderboard,
here is stack trace logs,
 i am getting 2 error:
E/UncaughtException: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
E/AndroidRuntime: FATAL EXCEPTION: main
12-02 01:05:53.969 3508-3508/com.example.myapp E/UncaughtException: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
                                                                            at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                            at java.util.ArrayList.get(ArrayList.java:308)
                                                                            at com.example.myapp.activity.LeaderboardActivity$4.onChildAdded(LeaderboardActivity.java:167)
                                                                            at com.google.android.gms.internal.zzaer.zza(Unknown Source)
                                                                            at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
                                                                            at com.google.android.gms.internal.zzags$1.run(Unknown Source)
                                                                            at android.os.Handler.handleCallback(Handler.java:739)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
12-02 01:05:54.215 3508-3508/com.example.myapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.example.myapp, PID: 3508
                                                                     java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
                                                                         at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                         at java.util.ArrayList.get(ArrayList.java:308)
                                                                         at com.examle.myapp.activity.LeaderboardActivity$4.onChildAdded(LeaderboardActivity.java:167)
                                                                         at com.google.android.gms.internal.zzaer.zza(Unknown Source)
                                                                         at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
                                                                         at com.google.android.gms.internal.zzags$1.run(Unknown Source)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:135)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

both blue lines indicate error on this line in leaderboardactivity.java
if (leaderboards.get(1).getName().equalsIgnoreCase(displayName)) {

here is code snippet from leaderboardactivity.java
private void getLeaderboard() {

        databaseLeaderboard.orderByChild("score").limitToLast((int) totalValue).addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
                Leaderboard leaderboard = dataSnapshot.getValue(Leaderboard.class);
                leaderboards.add(leaderboard);

                if (leaderboards.size() >= (int) totalValue) {
                    Collections.reverse(leaderboards);
                    leaderboardAdapterNew.notifyDataSetChanged();
                }

                if (leaderboards.size() == totalValue) {

                    if (leaderboards.get(0).getName().equalsIgnoreCase(displayName)) {
                        txtUname1.setText("Me");
                    } else {
                        txtUname1.setText(leaderboards.get(0).getName());
                    }
                    if (leaderboards.get(1).getName().equalsIgnoreCase(displayName)) {
                        txtUname2.setText("Me");
                    } else {
                        txtUname2.setText(leaderboards.get(1).getName());
                    }
                    if (leaderboards.get(2).getName().equalsIgnoreCase(displayName)) {
                        txtUname3.setText("Me");
                    } else {
                        txtUname3.setText(leaderboards.get(2).getName());
                    }

can someone tell me where is my fault?

A: Yes, you are trying to access an index that doesn't exist:
Change this :
if (leaderboards.size() == totalValue) {

To this:
if (leaderboards.size() == totalValue && totalValue > 2) {


text:
Q: Modify footline in Beamer - R Markdown I'm actually using the CambridgeUS theme for my Beamer using RMarkdown.
output:
  beamer_presentation:
    theme: "CambridgeUS"
header-includes:
  - \usepackage{color}
  - \usepackage{amsmath}
  - \setbeamertemplate{navigation symbols}{}

I wanna know how to delete the date in the footline and how to change the value taken as the full name (author) to only take last name.
It's possible using only tex as here but I don't succeed using RMarkdown.
Do you already face this issue ?

A: To remove the date from the footline, you could specify en empty optional argument in \date[]{\today}.
To show only the last name in the footline, define a short version for the author: \author[Smith]{Jack Smith}

\documentclass{beamer}

\usetheme{CambridgeUS}

\date[]{\today}
\author[Smith]{Jack Smith}

\begin{document}

\begin{frame}
    abc
\end{frame}

\end{document}

The identical code also works in rmarkdown:
---
output:
  beamer_presentation:
    theme: "CambridgeUS"
header-includes:
  - \setbeamertemplate{navigation symbols}{}
  - \date[]{\today}
  - \author[Smith]{Jack Smith}
---

test


text:
Q: RatingBar incorrectly selected <LinearLayout>
    ...
    <androidx.appcompat.widget.AppCompatRatingBar
        android:id="@+id/starRatingBar"
        style="@style/yellowStarRatingBar"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/dp_10"
        android:layout_weight="0.5"
        android:numStars="5"
        android:rating="0"
        android:stepSize="1" />
    ...
</LinearLayout>

When I click on the right half of the , the next  is also selected. Do any of you know what is going on?

A: Additionally, if you set a layout_weight, this supersedes the numStars attribute.
  <RatingBar
                android:id="@+id/starRatingBar"
                style="@style/yellowStarRatingBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                style="?android:attr/ratingBarStyleSmall"
                android:numStars="5"
                android:rating="0"
                android:stepSize="1" />


text:
Q: FLASH AS3 spme External streams urls not working from my server Some external streaming urls working from my server, some streams urls not working , what is the reason ?I am using as3 flash 9player. external urls like this http://38.96.174.38:9568 this is not working .
Please let me know.
thanks

A: Problem (and solution) : getURL() in a Flash projector fails in Firefox
http://probertson.com/articles/2006/10/11/geturl-flash-projector-firefox-problem/

A: It's dead simple: if the given server grants your player permission to access its contents via the default policy file (called /crossdomain.xml), then it works. If there is no default policy file, then it doesn't.


text:
Q: How to run a PDO/ODBC/PHP query with double quote in it? When I run the following simple query inside Microsoft Access:
select * from movie where moviename like 'batman'

it works.
Also using double quotes around the string works:
select * from movie where moviename like "batman"

I have a website where the user can type in any select query which PHP will then run and returning the record results to the user. I use PDO/ODBC to connect to the Access database. If the user types in query 1 it works, but query 2 fails with:

[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (SQLExecute[-3010] at ext\pdo_odbc\odbc_stmt.c:254)

The documentation says about quote() function:

"Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead."

but I can't use prepared statement as I don't know what query the user will type in. Sometimes they use '...' around a string and sometimes "...".
To reproduce you only need an Access (.mdb/.accdb) database with at least one table called 'film' and a column 'titel'. Put some records in it. At least 1 with 'Batman'. Use the following testscript:
//also using a older Access version of the database "film.mdb" didn't work
//be sure to use full/absolute pathname
$dbnameFile="C:\\wamp\\www\\elearning2\\databases\\film.accdb";
$username="";
$password="";
$accessdriver="{Microsoft Access Driver (*.mdb, *.accdb)}";
$dbDB = new PDO("odbc:Driver=$accessdriver;Dbq=$dbnameFile", $username, $password,
                array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

//Testcases, comment all but one
//Testcase 1: works
$sql="select * from film where titel like 'Batman'";

//Testcase 2: works
$sql='select * from film where titel like \'Batman\'';

//Testcase 3: COUNT field incorrect: -3010 [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
$sql="select * from film where titel like \"Batman\"";

//Testcase 4: COUNT field incorrect: -3010 [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
$sql='select * from film where titel like "Batman"';

//Testcase 5: Syntax error (missing operator) in query expression 'titel like \[Batman\]
$sql='select * from film where titel like \"Batman\"';

//Testcase 6: Syntax error (missing operator) in query expression 'titel like []Batman[]
$sql='select * from film where titel like ""Batman""';

$result=$dbDB->query($sql);
$rows=$result->fetchAll(PDO::FETCH_ASSOC);
$result->closeCursor();

foreach($rows as $row) {
  echo $row["TITEL"]."\n";
  echo "<br>";
}

$dbDB=null;

How can I properly escape a user given SQL query for PHP/PDO/ODBC/Access? Or is it just not possible to use a "..." string delimiter, despite working in Access?
I also find the error messages for testcase 5 and 6 odd. It looks like the double quote is changed into a [ or ]??
I can't use bind parameters, prepared statements or rewrite the query because the query is totally unknown and given by the user and can also contain syntax error(s). I can't modify this user query and just want it to be executed by PDO/ODBC but how?
I use Apache 2.4.9 and PHP 5.5.12 running locally on a Windows 7 SP1 machine.
I posted an official PHP bug report
Here's proof that query 1 and 2 both work in Access:


text:
Q: HL7 extract an entire segment/ segments/content between each repeating segment I have a HL7 message that contains one MSH segment and multiple PIV segments.
Using Java REGEX, I need to do these:
1) extract the entire MSH segment
2) find each occurence of PV1 segment.
3) extract the entire content/segments that exists between each PV1 segment - including the PV1 segment.
How do I accomplish the above?
Below is the sample HL7 msg:
MSH|^~\&|OADD|${FACILITY}|HELIX||201012010910||ORU^R01|20101720000042|T|2.2
PID|||PX65^^^MRENTR||Mayer^Ronny
PV1||I||2|||9898^Jackson^Burt^T|||||||||||IP||||||||||||||||||||||||||201012010840
OBX|1|NM|NA^Sodium^0|1.1|140^3|mmol/L|137-146||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)
OBX|2|NM|K^Potassium^0|1.1|4.5|mmol/L|3.5-5.0||||F|||201012010905|IM^|8035^COX^CATHERINE
(IM)
OBX|3|CE|CL^Chloride^0|1.1|100|mmol/L|98-109||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)
PV1||I||2|||9898^Jackson^Burt^T|||||||||||IP||||||||||||||||||||||||||201012010840
OBX|1|NM|NA^Sodium^0|1.1|140^3|mmol/L|137-146||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)
PV1||I||2|||9898^Jackson^Burt^T|||||||||||IP||||||||||||||||||||||||||201012010840
OBX|1|NM|NA^Sodium^0|1.1|140^3|mmol/L|137-146||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)

So the final goal is to have a msg like this - to have the extracted MSH segment before each PV1 segment. Then create a new HL7 message object that contains each of such HL7 message. In my example, 3 hl7 message will be created - each ofthem will be passed to HAPI parser.
MSH|^~\&|OADD|${FACILITY}|HELIX||201012010910||ORU^R01|20101720000042|T|2.2
PID|||PX65^^^MRENTR||Mayer^Ronny
PV1||I||2|||9898^Jackson^Burt^T|||||||||||IP||||||||||||||||||||||||||201012010840
OBX|1|NM|NA^Sodium^0|1.1|140^3|mmol/L|137-146||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)
OBX|2|NM|K^Potassium^0|1.1|4.5|mmol/L|3.5-5.0||||F|||201012010905|IM^|8035^COX^CATHERINE
(IM)
OBX|3|CE|CL^Chloride^0|1.1|100|mmol/L|98-109||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)
MSH|^~\&|OADD|${FACILITY}|HELIX||201012010910||ORU^R01|20101720000042|T|2.2
PV1||I||2|||9898^Jackson^Burt^T|||||||||||IP||||||||||||||||||||||||||201012010840
OBX|1|NM|NA^Sodium^0|1.1|140^3|mmol/L|137-146||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)
MSH|^~\&|OADD|${FACILITY}|HELIX||201012010910||ORU^R01|20101720000042|T|2.2
PV1||I||2|||9898^Jackson^Burt^T|||||||||||IP||||||||||||||||||||||||||201012010840
OBX|1|NM|NA^Sodium^0|1.1|140^3|mmol/L|137-146||||F|||201012010905|IM^|8035^COX^CATHERINE(IM)

A: You can use the library jar: hapi-base.2.0.jar
With the class ca.uhn.hl7v2.util.Terser you can get the segments that you want of the report.
public Message processMessage(Message theIn) throws ApplicationException,
            HL7Exception {

        theIn = (ORU_R01) new PipeParser(new CanonicalModelClassFactory("2.3"))
                .parse(theIn.encode());

        System.out.println(theIn.printStructure());//for debug better
        Terser menssageParsed = new Terser(theIn);
        String sResp = menssageParsed.get("/.RESPONSE/ORDER_OBSERVATION/OBR-3-1");
}

But if you like to create new segments in the report or edit. You can use this classes
ca.uhn.hl7v2.model.Message;
ca.uhn.hl7v2.model.Structure;


text:
Q: Existence of EditText data prior to int activity? There is activity, activity. I enter the text in EditText of A, click the button, move to B, do other activities, and come back to A. At this time, I hope the text remains in A's EditText. What should I do? Attempted startActivityForResult, but onActivityResult() is not invoked. Is this the wrong way?

A: Since Activity A is destroyed when you move to B, in order to restore the data you had in the EditText you first have to store it somewhere. To do this you can use the onSaveInstanceState() method from Activity which will be called right before the Activity is destroyed.
You can then restore the data by using either onRestoreInstanceState(savedInstanceState: Bundle?) or directly in onCreate(savedInstanceState: Bundle?)
For example:
const val TEXT_KEY = "editText_text"

override fun onSaveInstanceState(outState: Bundle) {
  super.onSaveInstanceState(outState)
  outState.putInt(TEXT_KEY, yourEditText.text)
}

override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
  super.onRestoreInstanceState(savedInstanceState)

  savedInstanceState?.run {
    yourEditText.text = getString(TEXT_KEY)
  }
}

Note: you should only save simple, lightweight data using onSaveInstanceState.


text:
Q: Bootstrap slider in ASP.NET MVC from SQL Server database I tried to make Bootstrap carousel slider for news from SQL Server database
I want the slider to look like this: https://www.w3schools.com/bootstrap/bootstrap_carousel.asp
But the role said

The .active class needs to be added to one of the slides. Otherwise, the carousel will not be visible.

but I did not know how to use .active class to one of my news because it is foreach loop.
All of my news has been under each other also, the left and right controls not working
Here is a screenshot of news slider result now
The code now:
HomeController.cs
public ActionResult Index()
{
     return View(db.News.ToList());
}

Index.cshtml
@model IEnumerable<Project.Models.News>
    @{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@Scripts.Render("~/bundles/bootstrap")

        @foreach (var item in Model)
        {

 //My mistake is here, how to make first news of class active?

                        @{ string imageBase64 = Convert.ToBase64String(item.newImg);
                            string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);

                        }

@item.newName

                            Read More
                            @*<button type="button" class="btn btn-default">Read More</button>*@

        }

            Previous

            Next

Any help?

A: To add class="active" to the first element in the list you can either:
@{int v = 0;}
@foreach (var item in Model)
{

            @item.newName

    v++;
}

Or:
@foreach (var item in Model.Select((value, i) => new { i, value }))
{

            @item.value.newName

}


text:
Q: Reading the medusa_s3_credentials not work on medusa Describe the bug
Python rises an error during the initialization of medusa container
Environment:
```
apiVersion: v1
kind: Secret
metadata:
 name: medusa-bucket-key
type: Opaque
stringData:

 medusa_s3_credentials: |-
   [default]
   aws_access_key_id = xxxxxx
   aws_secret_access_key = xxxxxxxx
```

*

*medusa-operator version:
0.12.2

*Helm charts version info
apiVersion: v2
name: k8ssandra
type: application
version: 1.6.0-SNAPSHOT
dependencies:
  * name: cass-operator
    version: 0.35.2
  * name: reaper-operator
    version: 0.32.3
  * name: medusa-operator
    version: 0.32.0
  * name: k8ssandra-common
    version: 0.28.4

*Kubernetes version information:
v1.23.1

*Kubernetes cluster kind:
EKS

*Operator logs:
MEDUSA_MODE = GRPC sleeping for 0 sec Starting Medusa gRPC service INFO:root:Init service [2022-05-10 12:56:28,368] INFO: Init service DEBUG:root:Loading storage_provider: s3 [2022-05-10 12:56:28,368] DEBUG: Loading storage_provider: s3 DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 169.254.169.254:80 [2022-05-10 12:56:28,371] DEBUG: Starting new HTTP connection (1): 169.254.169.254:80 DEBUG:urllib3.connectionpool:http://169.254.169.254:80 "PUT /latest/api/token HTTP/1.1" 200 56 [2022-05-10 12:56:28,373] DEBUG: http://169.254.169.254:80 "PUT /latest/api/token HTTP/1.1" 200 56 DEBUG:root:Reading AWS credentials from /etc/medusa-secrets/medusa_s3_credentials [2022-05-10 12:56:28,373] DEBUG: Reading AWS credentials from /etc/medusa-secrets/medusa_s3_credentials Traceback (most recent call last): File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main "**main**", mod_spec) File "/usr/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/cassandra/medusa/service/grpc/server.py", line 297, in <module> server.serve() File "/home/cassandra/medusa/service/grpc/server.py", line 60, in serve medusa_pb2_grpc.add_MedusaServicer_to_server(MedusaService(config), self.grpc_server) File "/home/cassandra/medusa/service/grpc/server.py", line 99, in **init** self.storage = Storage(config=self.config.storage) File "/home/cassandra/medusa/storage/**init**.py", line 72, in **init** self.storage_driver = self._connect_storage() File "/home/cassandra/medusa/storage/**init**.py", line 92, in _connect_storage s3_storage = S3Storage(self._config) File "/home/cassandra/medusa/storage/s3_storage.py", line 40, in **init** super().**init**(config) File "/home/cassandra/medusa/storage/abstract_storage.py", line 39, in **init** self.driver = self.connect_storage() File "/home/cassandra/medusa/storage/s3_storage.py", line 78, in connect_storage profile = aws_config[aws_profile] File "/usr/lib/python3.6/configparser.py", line 959, in **getitem** raise KeyError(key) KeyError: 'default'
Which could be the problem?
thanks
Cristian


text:
Q: Can someone explain this php function to me? I'm trying to understand everything this PHP function does. A game has this code and I'm trying to determine how much XP it takes to level for each level.
function xpToNextLevel($level){

    if($level == 0){
        return 200;
    }

    $s = 500;
    $m = 0xFFFF * ($level / 98);
    $xp = floor((($m - $s) * ($level / 98)) + $s);

    return $xp;
}

Thanks!

A: So, let's simplify the formula mathematically. Following formulas are not a PHP code, but pure mathematics!
xp = ((65535 * (level / 98)) - 500) * (level / 98) + 500

... which simplifies to ...
xp = (65535 / 98^2) * level^2 - (500 / 98) * level + 500

... which is approximately equivalent to ...
xp = 6.8 * level^2 - 5.1 * level + 500

As You can see, the amount of experience needed for next level grows quadratically along the formula above.

A: I think it's great to look over other people's code (open-source or with permission that is) to better understand the language. While I understand the down-voting, as google would have been a good resource to figure this out, I'll try to explain it the best I can.
To help explain it, I have rewritten a bit of your code for you.
function xpToNextLevel($level){

        if($level == 0){
            return 200;
        }

        $d = $level / 98;
        $s = 500;
        $m = 65535 * $d; /* 65535 is equivalent to 0xFFFF */
        $k = $m - $s; /* takes (0xFFFF * ($level / 98)) - $s */
        $dk = $k * $d; /* takes ($m - $s) * ($level/98) */
        $unroundedXP = $dk + $s; /* adds (($m-$s) * ($level/98)) to $s */
        $xp = floor($unroundedXP); /* rounds the experience down. */

        return $xp;
}

so, I know in your comment you asked about the level 4. Let's trace through that!
4 != 0 // thus we continue.
4/98 = 2/49 /*which is roughly ~0.04082, but for the sake of accuracy, I'll leave it as 2/49 */
65535 * (2/49) = ~2674.89795
2674.89795 - 500 = 2174.89795
2174.89795 * 2/49 = ~88.771345
88.771344 + 500 = 588.771344 //This is the unrounded experience
Experience = 588

The floor function basically rounds to the lowest integer. In positive numbers, this means we take the number and toss out everything behind the decimal point. So the number returned is roughly 588. I say roughly because a computer would be more exact about it.
By the way, I believe this is most comparable to a "Arithmetic Series." More information about that can be found here: http://mathworld.wolfram.com/ArithmeticSeries.html


text:
Q: Structuremap, AutoFac, or Ninject, which one is great for a large scale web app? I have some experience in working by Structuremap. And now I'm creating a big and large scale web app (really a social networking site) using ASP.NET MVC 3, Entity Framework 4.1 code-first, SqlServer 2008, via C#.NET 4. Which one of Structuremap, AutoFac, and Ninject would you suggest me to use in this case? Performance and easy-of-use is important. Thanks to any help, idea and suggestion.

A: This article has a good summary of most popular IoC frameworks and discusses their performance as well as ease of use. All in all a great read!
http://philipm.at/2011/di_speed.html
& a follow-up at http://philipm.at/2011/di_speed_redux.html

A: I've only really looked at / used Ninject and simply haven't bothered looking at any others. The simplicity in usage & it's low learning curve fit my last couple of projects very well. IMO, it is a great IoC container for projects large and small.

A: I've used Unity (some time ago), AutoFac and StructureMap and prefer StructureMap, specifically for its AssertConfigurationIsValid method which I use in unit tests to, well, assert that my StructureMap configuration is valid (relevant if you're using constructor-based DI).
As far as I'm aware only StructureMap offers this facility.
When using ASP.NET MVC, I also like how the StructureMap NuGet package wires things up for you nicely.

A: I think there is no differences between them! Its associated on your-self. Every body has some favorites, and you too. I use StructureMap and its good enough for large and/or small scale applications.
UPDATE:
Well, a few months ago I met with Simple Injector which is really really simple, and actually fast. I've used it in several projects with different scales, and it really works perfectly.

A: If you are interested in HOW they are used in large scale web apps, one good one to look at is OrchardCMS; it uses Autofac.


text:
Q: Send data between activities with custom variable How can I send data, using a custom variable type I created, between activities?
I have checked and the "putExtra/putExtras" option does not allow me to send my custom made variable, it only allows string/boolean/int/....

A: Use a Bundle and make your custom variable Serializable.
Bundle bundle = new Bundle();
bundle.putSerializable("key", CustomVariableObject());
intent.putExtras(bundle);

A: you need to serialize your object
intent.putExtra("MyData", data);

getIntent().getSerializableExtra("MyData");

you can see more informations in this post
How to pass an object from one activity to another on Android


text:
Q: ASP.NET MVC 2 Calling html helper inside if conditional statement I'm having a problem getting the syntax correct.  The html helper returns true or false.
<% if (<%= Html.SecurityTrim("Admin")%>) { %>
            Only for accounting
    <% } %>

What do I need to change to get this to compile correctly?

A: Supposing that Html.SecurityTrim() returns bool,
<% if ( Html.SecurityTrim("Admin") ) { %>
    Only for accounting
<% } %>

A: Sounds like your Html.SecurityTrim() returns a bool.
In this case, then no need to escape out of code, just use it as your condition to test.
<% if (Html.SecurityTrim("Admin")) { %>
            Only for accounting
  <% } %>


text:
Q: SQLite group by localtime date I am storing dates with a timezone offset and I would like to use group by queries to group by the local time, and not UTC. Here is an example of how the dates are stored:
sqlite> CREATE TABLE t1 (datecol TEXT);
sqlite>
sqlite> INSERT INTO t1 (datecol) VALUES ('2022-01-24T22:00:00-07:00');
sqlite> INSERT INTO t1 (datecol) VALUES ('2022-01-24T23:00:00-07:00');
sqlite> INSERT INTO t1 (datecol) VALUES ('2022-01-25T00:00:00-07:00');
sqlite> INSERT INTO t1 (datecol) VALUES ('2022-01-25T01:00:00-07:00');
sqlite>
sqlite> SELECT DATE(datecol),COUNT(*) FROM t1 GROUP BY DATE(datecol);
2022-01-25|4

What I want to see is:
sqlite> SELECT DATE(datecol),COUNT(*) FROM t1 GROUP BY DATE(datecol);
2022-01-24|2
2022-01-25|2

I realize that one way to do this would be to manually subtract the timezone offset (in this case 7 hours). But that would have the weakness that it wouldn't work for daylight savings time.
sqlite> SELECT DATE(datecol,'-7 hours'),COUNT(*) FROM t1 GROUP BY DATE(datecol,'-7 hours');

A: You can add the localtime modifier to the date function:
SELECT date(datecol, 'localtime') AS localdate, count(*)
FROM t1 GROUP BY localdate;

See https://www.sqlite.org/lang_datefunc.html for details, including the "Caveats And Bugs" part.
But it is usually recommended to always store timestamps as UTC in SQLite, because it's the default, and makes things easier.
So you could convert your current timestamps to UTC with
UPDATE t1 SET datecol=datetime(datecol);


text:
Q: Adding account features via AccountManager There are several APIs which take a String[] of features to be used to filter accounts on the device by, but no obvious way of adding a feature to an account.
How do you add a new feature to a new or existing account?


text:
Q: does react native release mode must have hosted api / db? im quite new on react native and i want to build this app so it can run remotely on device  , on debug everything went fine, it uses api and xampp mysql for db
when i try to build apk release and run npx react-native run-android --variant=Release the build is successful but when i open the app it instantly crashed
im wondering if it because my api and db still not hosted yet , must it hosted first and only then u can release it ? i kinda want to try it on device before hosting my db and api
i try adb logcat *:E and this is what i got
https://drive.google.com/file/d/1lv4X2U4QjMyeNMlNTo5jDe243pUMALbl/view

A: I've fixed it , it just need to use axios https instead of axios http
and i import usestate wrong , bcs its automatic
i've actually tried this before but i think i've tried this fix separately and i already reverted one of them with git , so i thought 2 of these things is not the solution
tried 2 of them again today bcs of desperate  and thankfully it worked


text:
Q: Intellisense works only when the module folder is in current workspace I made a module recently, for data management. Then I decided to split it into several submodules. However, when I import the module, the auto-complete doesn't work, even though the module itself works perfectly. I found out, that if I keep the module in my workspace, the auto-complete works.
Sample import: from module.core.client import Client
The structure of my module directory:
module
  module
    core
      __init__.py
      client.py
    extra
      __init__.py
      municipality.py
    modules
      __init__.py
      generic.py
      timetable.py
    __init__.py
    utils.py
  ...
  setup.py

If there's any issue with my module set-up, please let me know.
Thank you.

A: I found out it was caused by python setup.py install --user installing the package as egg. For it to work, I had to do pip install . --user from the directory containing setup.py


text:
Q: jdbc connection mysql8.0 data format problem 100 becomes 100.0 when I connect to mysql8 via JDBC for float data, but 100 when I use navicat or mysql command
enter image description here
enter image description here

A: Change the type of f variable from float to int
and
use
f = rs.getInt("f");
It will work


text:
Q: AJAX request does not work (POST) I have a little problem with a POST request using AJAX. The data just doesn't seem to get stored in the database. When I used GET instead of POST it worked, but the problem is that it sends a huge amount of data since it is imagedata from a canvas on the page. I tried to print out the size of the data that is sent to make sure it actually is correct before it is sent (it was about 10500 characthers long).
Here's the Javascript/AJAX-code:
if(type == "DrawingData" && Drawer)
{
    var CanvasData = canvas.toDataURL("image/png");
    var url = "DB_Com.php";
    var params = "DrawingData="+CanvasData;

    xmlhttp.open("POST", url, true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.send(params);
}

And here is the PHP-code:
if(isset($_POST['DrawingData']))
{
    $Image = mysql_real_escape_string($_POST['DrawingData']);

    $query = "UPDATE BlackboardDrawing SET Data = '$Image'";
    mysql_query($query) or die(mysql_error());
}

Any help is is highly appreciated.
Thanks!

A: Your Ajax looks fine, but you need to POST the row id that you are updating. :
if(type == "DrawingData" && Drawer)
{
    var CanvasData = canvas.toDataURL("image/png");
    var url = "DB_Com.php";
    var rowid = 'your_row_id';
    var params = "DrawingData="+CanvasData+"rowid="+rowid;

    xmlhttp.open("POST", url, true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.send(params);
}

And change your PHP script:
if(isset($_POST['DrawingData']))
{
    $Image = mysql_real_escape_string($_POST['DrawingData']);
    $rowid = (int)$_POST['rowid'];
    $query = "UPDATE BlackboardDrawing SET Data = '$Image' WHERE id='$rowid'";
    mysql_query($query) or die(mysql_error());
}


text:
Q: Assignment is treated as initialization I've written the following and expected a to be initilized with 4 rvalue. But it didn't:
struct A
{
    const int a;

    A() //ctor-initializer is not specified, therefore no initialization for a is performed
    {
        a = 4; //initialization
    }
};

A a;

What's wrong? Why does compiler complain?


text:
Q: Receiving a file with sockets I'd like to receive a file over sockets in my c program, for which I made a function recvfile_all. It receives the file in chunks based on the parameter data.
struct filedata is defined as
struct filedata {
    struct stat st;
    char filename[FILENAME_MAX];
};

The code for my function is-
// Receive a file based on filedata. Return the number of bytes
// left to receive in case of error
size_t recvfile_all(int sock, const struct filedata *data) {
    size_t to_recv = data->st.st_size;     // total data to receive for a file
    size_t recv;                           // length of data to receive once
    char *buffer = malloc(0);              // buffer to hold chunk
    size_t chunk_s = data->st.st_blksize;  // chunk size to receive file in
    size_t supp_to_recv;

    FILE *file = fopen(data->filename, "w");
    if (file == NULL) return to_recv;

    while (to_recv) {
        // receive a chunk if we have more to receive than the size of a
        // single chunk, otherwise receive whatever is left
        recv = to_recv > chunk_s ? chunk_s : to_recv;
        supp_to_recv = recv;
        buffer = realloc(buffer, recv);
        recvall(sock, (char *)buffer, &recv);

        if (recv < supp_to_recv)
            return to_recv - recv;  // return how much is left to receive

        fwrite(buffer, 1, recv, file);  // write what was received to file
        to_recv -= recv;
    }
    fclose(file);
    return to_recv;
}

The function recv_all is a function that's similar to send_all from Beej's Guide to Network Programming. It simply receives a number of bytes from a socket. I've tested it multiple times and it has worked fine, I don't think the error is in this function. It's defined as-
int recvall(int s, char *buf, size_t *len) {
    size_t total = 0;         // how many bytes we've recveived
    size_t bytesleft = *len;  // how many we have left to receive
    size_t n;

    while (total < *len) {
        n = recv(s, buf + total, bytesleft, 0);
        if (n == -1 || n == 0) {
            break;
        }
        total += n;
        bytesleft -= n;
    }

    *len = total;  // return number actually sent here

    return n == -1 ? -1 : 0;  // return -1 onm failure, 0 on success
}

My function doesn't seem to work. Any ideas why?
Also, the error is definitely not in the code that sends the file, I've already tested that multiple times.

A: Turns out the function works fine, I was using a linked list to send the files, and because of a previous mistake, the server receives the header of the files that the client is about to sent in reverse order, rectifying that fixed the problem


text:
Q: jQuery on keypress trigger button I have two buttons:
$('#prev').click(function() {
   // some code
});

$('#next').click(function() {
  // some other code
});

what I now want to do is adding a .keypress() handler to the site which triggers on arrow-left the #prev click and for arrow-right it triggers #next. Problem is how can I add this handler?

A: You can check the keydown event and catch the left/right arrow key code.
If left/right arrow are pressed trigger the according button, arrow codes:

37 - left
38 - up
39 - right
40 - down

Code:
$('#prev').click(function () {
    alert('prev');
});

$('#next').click(function () {
    alert('next');
});

$(document).keydown(function (e) {
    if (e.keyCode == 37) {
        $('#prev').click();
        return false;
    }
    if (e.keyCode == 39) {
        $('#next').click();
    }
});

Demo: http://jsfiddle.net/IrvinDominin/6CYXH/


text:
Q: Обьединить два массива в один, но с одним условием Здравствуйте , у меня такая вот задача:
есть два массивы, в этих массивах есть слова. Слова в этих массивах записаны в рандомном порядке. Нужно эти 2 массива объединить в один , так чтобы в новом массиве шли сначала слова которые имеют парное количество гласных букв, а потом все остальные слова.
Например: есть массив: $str = 'лама, мама, конь' И есть 2 массив $str2 = 'клас, бабушка , клава'. Нужно чтобы такой массив получился такой: (лама, мама, клава, конь, бабушка)
ЧТо я придумал:
<?php

$str = 'Mother,  Fther';
$strTwo = 'sister,  brother';

$result = str_split($str);
$resultTwo = str_split($strTwo);

if(...) {

 $test = array_merge($result , $resultTwo);
}

?>

Ка вообще реализовать такую задачу, что нужно использовать, какие методы, можно как то сделать без регулярок эту задачу?? Буду благодарен за любую помощь. Спасибо!

A: Зачем здесь применять регулярки - я не знаю, возможно "специалисты" и сделают. А мы обойдемся и без них. Вот к примеру так выглядит функция, которая подсчитывает кол-во гласных в слове:
function count_letter($x) {
    $c = 0;
    for ($i = 0; $i < strlen($x); $i++) {
        if (strpos('euoaiy', $x[$i]) > -1) {
            $c+=1;
        }
    }
    return $c;
}

Там конечно латинские буквы, но это дело житейское. Сам код построен просто - проходим по всем буквам слова и проверяем есть ли эта буква в специальном слове с одних гласных. Можно конечно было написать длинющий if и проверять каждую букву, но оставим это индусам и гореоптимизаторам.
Теперь сам алгоритм решения задачи. Пробегаем по каждому слову и если там четное кол-во гласных - пишем в массив четных, иначе - в массив для нечетных. Потом это же проделываем и со вторым массивом. И в самом конце эти два массива просто "складываем".
Как же проверить, что кол-во гласных четно? очень просто - с помощью взятия модуля - a % 2 будет равно 0, если число четно. А дальше самостоятельно:)

A: Если без использования 2-х массивов (мин. версия PHP 5.4.0), то функцию для получения количества гласных букв уже описали, дальше можно сделать так:
$words1 = ['Mother', 'Grandfather', 'Brother', 'Sister'];
$words2 = ['Uncle', 'Father', 'Grandmother'];

$words = [];

array_map(function ($word) use (&$words) {

    if (count_letter($word) % 2 === 0) { // если количество гласных букв - парное
        array_unshift($words, $word); // добавляем слово в начало массива
    } else {
        $words[] = $word;
    }

}, array_merge($words1, $words2));

print_r($words);

A: Можно рассуждать иначе.

*

*С точки зрения конечного результата массивы неупорядочены, и последующая их сортировка неизбежна. Поэтому сразу сливаем их в один (функция array_merge().

*Обмениваем местами ключи и значения общего массива (функция array_flip()).

*Заменяем номер элемента на_массив, состоящий из этого номера и бита чётности от числа гласных в слове (функция array_walk()).
Число гласных букв в слове подсчитывает регистронезависимая функция str_ireplace() с дополнительным параметром $count или её "регулярный аналог" (благодарность KoVadim).
Бит чётности - это(count & 1)

*Сортируем функцией uasort() с учётом исходного порядка и бита чётности.

*Готовый массив ключей 'отрезаем" функцией array_keys().

Программа:
$array1 = array("Father", "Mother", "Sister", "Grandfather");
$array2 = array("Grandmother", "Brother", "Aunt");

$array12= array_merge($array1, $array2);
var_dump($array12);

$flip = array_flip($array12);
array_walk($flip, function(&$item,$key) {
    // str_ireplace(array("a","e","i","o","u","y"), "", $key, $count);
    preg_replace("/[aeiouy]/i", "", $key, -1, $count);
    $item = array($item, $count & 1);
});

uasort($flip, function($a,$b){
    if(end($a)==end($b))    return reset($a)-reset($b);
    else                    return end($a) - end($b);
});

$result = array_keys($flip);
var_dump($result);

Результаты (массив после слияния и готовый массив):

array (size=7)
  0 => string 'Father' (length=6)
  1 => string 'Mother' (length=6)
  2 => string 'Sister' (length=6)
  3 => string 'Grandfather' (length=11)
  4 => string 'Grandmother' (length=11)
  5 => string 'Brother' (length=7)
  6 => string 'Aunt' (length=4)
array (size=7)
  0 => string 'Father' (length=6)
  1 => string 'Mother' (length=6)
  2 => string 'Sister' (length=6)
  3 => string 'Brother' (length=7)
  4 => string 'Aunt' (length=4)
  5 => string 'Grandfather' (length=11)
  6 => string 'Grandmother' (length=11)


text:
Q: Concrete5: How to create custom navigation for multilingual site? I need to create multilingual site with Concrete5 (v 5.7).
I've a custom theme and my page layout would be:
Home
|-en
|--Frontpage
|--Contatcs
|-<language2>
|--<Frontpage>
|--<Contacts>

With current navigation implementation:
<nav class="nav">
<?php
$bt_main = BlockType::getByHandle('autonav');
$bt_main->controller->displayPages = 'top';
$bt_main->controller->orderBy = 'display_asc';
$bt_main->controller->displaySubPages = 'none';
$bt_main->render('templates/level1');
?>
</nav>

I get the result where in the navigation there is only | EN | <language2>|
Can't find any proper document how to fix or use multilingual settings.

A: With Concrete5 version 5.7.x.x you can use Global areas. Global areas can be setup differently for each language.
When using a global area, you can add an autonav block on one language and show pages below  and in the other language you can add an autonav block which shows pages below  .
Another advantage of working with a global area is the templates. Hardcoded blocks are known to always show the default template (view.php, view.css).
If you do not want anyone else (except the superuser) to be able to edit the global area, you can use this code:
$u = new User();
$areaNav = new GlobalArea('Navigation');
if(!$u->isSuperUser()){
  $areaNav->disableControls();
}
$areaNav->display($c);

If you really want to work with a hardcoded block, you can still check for the language and load a different (hardcoded) block for each language.
$lang = Localization::activeLanguage();
if($lang == 'en'){
  //hardcoded block for english language
}else if($lang == 'fr'){
  //hardcoded block for french language
}


text:
Q: Query for count and distinct I should make a report in T-SQL from several table.
I can join all the table needed but after I don't know excatly how to get my information.
Explanation :
I've got the following table :
Tbl_User (UserId, Username)
Tbl_Customer (CustomeriD, CustomerName)
Tbl_DocA (DocId, CustomerID, DateCreate, DateAdd, UseriD)
Tbl_DocB (DocId, CustomerID, DateCreate, DateAdd, UseriD)
Tbl_DocC (DocId, CustomerID, DateCreate, DateAdd, UseriD)

I am trying to get a report like this :

After I can get this, the idea is to have a filter with the date in SQL reporting.

A: You can union all the document tables together and join users and customers on it.
SELECT Customer.CustomerID
      ,Customer.CustomerName
      ,COUNT(CASE WHEN DocType = 'A' THEN 1 END) AS doc_a_total
      ,COUNT(CASE WHEN DocType = 'B' THEN 1 END) AS doc_b_total
      ,COUNT(CASE WHEN DocType = 'C' THEN 1 END) AS doc_c_total
      ,COUNT(CASE WHEN DocType = 'A' AND user.username ='azerty' THEN 1 END) AS doc_a_made_by_azerty
      ,COUNT(CASE WHEN DocType = 'B' AND user.username ='azerty' THEN 1 END) AS doc_b_made_by_azerty
      ,COUNT(CASE WHEN DocType = 'C' AND user.username ='azerty' THEN 1 END) AS doc_c_made_by_azerty

FROM (
(SELECT 'A' AS DocType, * FROM Tbl_DocA)
UNION ALL
(SELECT 'B' AS DocType, * FROM Tbl_DocB)
UNION ALL
(SELECT 'C' AS DocType, * FROM Tbl_DocC)
) AS docs
JOIN Tbl_User AS user ON user.UserId = docs.UseriD
JOIN Tbl_Customer AS Customer ON Customer.CustomeriD = docs.CustomeriD
GROUP BY Customer.CustomerID , Customer.CustomerName

A: You can use common table expressions to get the count for each report type per customer, with conditional aggregation for reports made by a specific user, and join them to the customers table.
Something like this should get you the desired results:
DECLARE @UserId int = 1; -- or whatever the id of the user you need
WITH CTEDocA AS
(
    SELECT CustomerID
         , COUNT(DocId) As NumberOfReports
         , COUNT(CASE WHEN UserId = @UserId THEN 1 END) As NumberOfReportsByUserAzerty
    FROM Tbl_DocA
    GROUP BY CustomerID
), CTEDocB AS
(
    SELECT CustomerID
         , COUNT(DocId) As NumberOfReports
         , COUNT(CASE WHEN UserId = @UserId THEN 1 END) As NumberOfReportsByUserAzerty
    FROM Tbl_DocB
    GROUP BY CustomerID
), CTEDocC AS
(
    SELECT CustomerID
         , COUNT(DocId) As NumberOfReports
         , COUNT(CASE WHEN UserId = @UserId THEN 1 END) As NumberOfReportsByUserAzerty
    FROM Tbl_DocC
    GROUP BY CustomerID
)

SELECT cust.CustomeriD
      ,cust.CustomerName
      ,ISNULL(a.NumberOfReports, 0) As NumberOfDocA
      ,ISNULL(a.NumberOfReportsByUserAzerty, 0) As NumberOfDocAByAzerty
      ,ISNULL(b.NumberOfReports, 0) As NumberOfDocB
      ,ISNULL(b.NumberOfReportsByUserAzerty, 0) As NumberOfDocBByAzerty
      ,ISNULL(c.NumberOfReports, 0) As NumberOfDocC
      ,ISNULL(c.NumberOfReportsByUserAzerty, 0) As NumberOfDocCByAzerty
FROM Tbl_Customer cust
LEFT JOIN CTEDocA As a
    ON cust.CustomeriD = a.CustomerID
LEFT JOIN CTEDocA As b
    ON cust.CustomeriD = b.CustomerID
LEFT JOIN CTEDocA As c
    ON cust.CustomeriD = c.CustomerID

To filter by date you can add a where clause to each common table expresstion.
BTW, The fact that you have three identical tables for three document types suggest a bad database design.
If these tables are identical you should consider replacing them with a single table and add a column to that table describing the document type.

A: There are several ways to do this. One key feature needed is to count a particular user apart from the others. This is done with conditional aggregation. E.g.:
select
  customerid,
  count(*),
  count(case when userid = <particular user ID here> then 1 end)
from tbl_doca
group by customerid;

Here is one possible query using a cross join to get the user in question once and cross apply to get the numbers.
select
  c.customerid,
  c.customername,
  doca.total  as doc_a_total,
  doca.az     as doc_a_by_azerty,
  docb.total  as doc_b_total,
  docb.az     as doc_b_by_azerty,
  docc.total  as doc_c_total,
  docc.az     as doc_c_by_azerty
from tbl_customer c
cross join
(
  select userid from tbl_user where username = 'Azerty'
) azerty
cross apply
(
  select
    count(*) as total,
    count(case when da.userid = azerty.userid then 1 end)n as az
  from tbl_doca da
  where da.customerid = c.customerid
) doca
cross apply
(
  select
    count(*) as total,
    count(case when db.userid = azerty.userid then 1 end)n as az
  from tbl_docb db
  where db.customerid = c.customerid
) docb
cross apply
(
  select
    count(*) as total,
    count(case when dc.userid = azerty.userid then 1 end)n as az
  from tbl_docc dc
  where dc.customerid = c.customerid
) docc
order by c.customerid;

Other options would be to replace the cross apply with left outer join and non-correlated subqueries or to put subqueries into the select clause.

A: Combining the totals for the documents is another method.
Then use conditional aggregation for the counts.
untested notepad scribble:
;WITH SPECIFICUSER AS
(
  SELECT UseriD
  FROM Tbl_User
  WHERE UserName = 'azerty'
),
DOCTOTALS (
   SELECT CustomeriD, UseriD, 'DocA' AS Src, COUNT(DocId) AS Total
   FROM Tbl_DocA
   GROUP BY CustomeriD, UseriD

   UNION ALL

   SELECT CustomeriD, UseriD, 'DocB', COUNT(DocId)
   FROM Tbl_DocB
   GROUP BY CustomeriD, UseriD

   UNION ALL

   SELECT CustomeriD, UseriD, 'DocC', COUNT(DocId)
   FROM Tbl_DocC
   GROUP BY CustomeriD, UseriD
)
SELECT
 docs.CustomeriD,
 cust.CustomerName,

 SUM(CASE WHEN usrX.UseriD is not null AND docs.Src = 'DocA' THEN docs.Total ELSE 0 END) AS Total_DocA_userX,
 SUM(CASE WHEN Src = 'DocA' THEN docs.Total ELSE 0 END) AS Total_DocA,

 SUM(CASE WHEN usrX.UseriD is not null AND docs.Src = 'DocB' THEN docs.Total ELSE 0 END) AS Total_DocB_userX,
 SUM(CASE WHEN Src = 'DocB' THEN docs.Total ELSE 0 END) AS Total_DocB,

 SUM(CASE WHEN usrX.UseriD is not null AND docs.Src = 'DocC' THEN docs.Total ELSE 0 END) AS Total_DocC_userX,
 SUM(CASE WHEN Src = 'DocC' THEN docs.Total ELSE 0 END) AS Total_DocC

FROM DOCTOTALS docs
LEFT JOIN Tbl_Customer cust ON cust.CustomeriD = docs.CustomeriD
LEFT JOIN Tbl_User usr ON usr.UseriD = docs.UseriD
LEFT JOIN SPECIFICUSER usrX ON usrX.UseriD = docs.UseriD
GROUP BY docs.CustomeriD, cust.CustomerName
ORDER BY docs.CustomeriD

Those long column names could be set on the report side


text:
Q: Database Design column naming convention; Primary and Foreign Keys As a common convention, i ask since i'm not entirelly sure;
Normaly in column naming; id_* referes to pk's and *id to fk's?
So multiple id* would imply the id_* 's  forming a multicolumn pk?

A: A field named FOO_BAR_ID would suggest to me some sort of bridge or map table, not a relationship to a composite primary key which is what I believe you are suggesting, below is a demonstration of how I tend to name fields, personally I avoid using composite primary keys because they break second normal form and tbh I have never seen a logical rational for using them
  + a normal table
-----------------------------------------------------
| DEPARTMENT_SID | NAME | DESCRIPTION | ADDRESS_SID |
-----------------------------------------------------
  ^ pk                                  ^ fk

  + another normal table
--------------------------------------------------
| ADDRESS_SID | NUMBER | STREET | TOWN | POSTCODE |
--------------------------------------------------
  ^ pk

  + yet another normal table
-----------------------------------------------------------------------
| EMPLOYEE_SID | FIRST_NAME | LAST_NAME | DATE_OF_BIRTH | ADDRESS_SID |
-----------------------------------------------------------------------
  ^ pk                                                    ^ fk

  + bridge table as an employee can belong to many departments
  + uses a composite key rather then defining a single primary key
---------------------------------
! EMPLOYEE_SID ! DEPARTMENT_SID |
---------------------------------
  ^ cpk / fk     ^ cpk / fk

  + bridge table defining a single primary key
-----------------------------------------------------------
| EMPLOYEE_DEPARTMENT_SID ! EMPLOYEE_SID | DEPARTMENT_SID |
-----------------------------------------------------------
  ^ pk                      ^ fk           ^ fk

  + a table with a foreign key to the bridge table
------------------------------------------------------
! SHIFT_SID | EMPLOYEE_DEPARTMENT_SID | HOURS_WORKED |
------------------------------------------------------
  ^ pk        ^ fk

pk = PRIMARY KEY, fk = FOREIGN KEY, cpk = COMPOSITE PRIMARY KEY


text:
Q: How to tell GCC that input file is assembler even if it's really .c? I have an unusual situation: I have an assembler file, which has .c extension and I cannot change build scripts, where this file is defined as "C" type. However, I can build it with the same GCC options if I rename it into .asm or *.s.
Is there any standard method to make GCC to think an input file is Assembler even if it has .c extension?
I can't change build script! I can only change the .c file. So, maybe there is a way to set command-line option '-x assembler' using preprocessor?

A: This sounds a bit complicated, but if you use bash or anything similar you can alias gcc to a script you'll write and in this script when it gets the file you want to change behavior use the -x assembler parameter with gcc and act normally in otherfiles.


text:
Q: Display an icon based on post type I have a defined set of seven different post types and would like to display an icon for each one in the search results list.
I've got the following code to display the post type but have no idea how to extend it into an if
<?php $post_type = get_post_type_object( get_post_type($post) );
echo $post_type->label ; ?>

Any help appreciated.

A: <?php
   $post_type = get_post_type($post);
   switch ($post_type) {
       case "type1":
           echo "";
           break;
       case "type2":
           echo "";
           break;
   }
?>

A: You could also do this with CSS. If you're using post_class() in the search results it will have the post-type available within each post's classes for styling each type differently.
Then you just apply a different background image as an icon for each post type class.


text:
Q: Html/CSS login system does not work properly I am trying to use this code I found on internet from codepen.io. But when I implement the html and css I do get some errors. The code isn't perfect right but in the compiler of codepen it does work properly.
I know you can't place a div inside a label tag but I tried diffrence thinks like instead of using div tag using the spand tag. This didn't work propperly either.
Here is the original link to the code https://codepen.io/robcampo/pen/ZGgGow.
This is the code html code:
<!DOCTYPE html>

<title>

</title>

<input type="checkbox" id="navcheck" role="button" title="menu">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" />

<link rel = "stylesheet" href = "style.css">
<form>

<input type="text" required />

First name

<input type="text" required />

Last name

<button>Submit</button>
</form>

sorry I wasn't clear about the errors I did get, let me provide them to you.
When I do run this code I get: div cannot be nested inside label. Furthermore the placement in my screen isn't right everythink is cropped up in the left upper corner. And there are not any textfield where I could put in some test. Hope this provide the right errors
Hope you could help me with this "log in system"
Thanks in adavance
hope this works it says I am not allowed to add images
enter image description here

A: As discussed in the comments, the OP had targeted the elements by the element names, which were being mixed up for two different purposes. Targeting the elements by classes or IDs seems to provide the solution.


text:
Q: Django comments framework, set default form values I defined a custom comment form in forms.py as fallow

class CommentFormWithReply(CommentForm):
    reply_to = forms.ModelChoiceField(queryset=CommentWithReply.objects.all(),
            widget=forms.HiddenInput(), required=False)

    def get_comment_model(self):
        # Use our custom comment model instead of the built-in one.
        return CommentWithReply

    def get_comment_create_data(self):
        # Use the data of the superclass, and add in the title field
        data = super(CommentFormWithReply, self).get_comment_create_data()
        return data

what should I do to render this form with the current user information as default values (name, email, webpage ).

A: may be this:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#initial
if request.method == 'POST':
    form = CommentFormWithReply(request.POST)
    .........................................

if request.method == 'GET':
    default_data = {'name': 'Alexey', 'email': 'smt@email.smt', 'webpage': 'http://example.com'}
    form = CommentFormWithReply(default_data)


text: Q: RFC2047 Conversion Issue I am making a GMail add-on in Google Apps Scripts and I come across an issue with emails not in ASCII encoding. I tried converting the portions that look like =?us-ascii?Q?a*data=3DBaUd8g06EDNqzYX7LSepWIJnDYVzU7yu?= using Utilities.newBlob(rawCont).getDataAsString("us-ascii")); however, this provides no avail. Is there a native Javascript way to do this or a way to do this in Google Apps Scripts?


text:
Q: Using jQuery to display a value to 2 decimal places in an input box while retaining more precision
Possible Duplicate:
JavaScript: formatting number with exactly two decimals

Maybe I'm going about this the wrong way, but I have some javascript which is filling up some text inputs with numbers like 12.434234234. I want the text input to only display 12.43, but I'd like it's value to remain as 12.434234234.
Is this even possible? If not, what would be the best work-around?
Thanks!
John.
--
Although there were some very good answers here, I was looking for something like 'why don't you just use this clever one liner thing..' - hence I've ticked the most basic approach which is to just use an extra field. Thanks though! Marked up all answers.

A: You can store the fine-grained values in hidden fields, and trim the ones displayed for the user.

A: You could store the value of the input as data of the input (using jQuery), format it onload and then replace the value during submit like so:
http://jsfiddle.net/magicaj/8cdRs/1/
HTML:
<form id="form">
    <input type="text" class="formatted-number-input" value="12.434234234" />
</form>

JS:
$(".formatted-number-input").each(function() {
   var value = $(this).val();
   $(this).data("originalValue", value);
   var roundedValue = value.toFixed(2);
   $(this).val(roundedValue);
});

$("#form").submit(function() {
    var formattedInput = $(".formatted-number-input");
    formattedInput.each(function() {
        var originalValue = $(this).data("originalValue");
        $(this).val(originalValue);
    });
});

A: num = 12.434234234;
result = num.toFixed(2); // returns 12.43

A: There are multiple ways to solve this problem:
 1. Create hidden field, store 12.434234234 in it and display formatted value in textfield.
 2. Store original 12.434234234 using jquery.data() and display formatted value in textfield.


text:
Q: Make image center without display block My html:

Some text

I want to move image to center without making it block. With block link goes clickable in all width.
Tried:
img{
    margin:0 auto;
    display:inline-block;
}

but it doesn't work.
Fiddle.
Fiddle with centered image but wrong link.
Image width can be different.
Any idea how to make image center and leave clickable area only on image?

A: try this

Some text

#imgPara{
text-align: center;
}

http://jsfiddle.net/Shashi0812/YAusb/

A: You can set this CSS for the a tag:
a{
  margin:0 auto;
  display:table;
}

The demo http://jsfiddle.net/9653Y/4/

A: Align parent of img to center.
HTML:

CSS:
.center{text-align:center;}

Here is the updated fiddle.

A: change margin to 50%
 img{
        margin:0 50%;
        display:inline-block;
    }


text:
Q: Elasticsearch gives [function_score] malformed query, expected [END_OBJECT] but found [FIELD_NAME] I have a query as follows to use function_score but it gives an error that the query is malformed  and [END_OBJECT] is expected but found [FIELD_NAME]. I have checked the documentation and couldn't find what is incorrect or inconsistent with this. I haven't added any script in script_score here but even when I tried with adding script it gave the same problem.
{
  "from": 0,
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "filter": [
            {
              "bool": {
                "should": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match": {
                            "address.area.area.raw": "Durbarmarg"
                          }
                        },
                        {
                          "match": {
                            "address.area.city.raw": "Kathmandu"
                          }
                        },
                        {
                          "match": {
                            "address.area.district.raw": "Kathmandu"
                          }
                        },
                        {
                          "match": {
                            "address.area.state.raw": "State-3"
                          }
                        },
                        {
                          "match": {
                            "address.area.country.raw": "Nepal"
                          }
                        }
                      ]
                    }
                  },
                  {
                    "nested": {
                      "inner_hits": {},
                      "path": "branchAddress",
                      "query": {
                        "bool": {
                          "must": [
                            {
                              "match": {
                                "branchAddress.area.area.raw": "Durbarmarg"
                              }
                            },
                            {
                              "match": {
                                "branchAddress.area.city.raw": "Kathmandu"
                              }
                            },
                            {
                              "match": {
                                "branchAddress.area.district.raw": "Kathmandu"
                              }
                            },
                            {
                              "match": {
                                "branchAddress.area.state.raw": "State-3"
                              }
                            },
                            {
                              "match": {
                                "branchAddress.area.country.raw": "Nepal"
                              }
                            }
                          ]
                        }
                      }
                    }
                  }
                ]
              }
            }
          ],
          "must": [
            {
              "term": {
                "sub_categories.raw": "Restaurant"
              }
            }
          ],
          "must_not": [],
          "should": []
        }
      }
    },
    "script_score": {}
  },
  "size": 10
}

The error is as bellow:
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', '[function_score] malformed query, expected [END_OBJECT] but found [FIELD_NAME]')

A: The script_score section is not at the right place, it needs to be a sibling of the inner query:
{
  "from": 0,
  "query": {
    "function_score": {
      "query": {
        ...
      },
      "script_score": {}       <--- script_score goes here
    }
  },
  "size": 10
}


text:
Q: How to provide a 'real time' update in Table View Xcode I've created a Tableview that shows players (bees) and their attributes. You can level up the players too, however this upgrade isn't shown in real time. I have to scroll all the way down on the TableView, then scroll back up to see the updated value. Anyone know a fix?
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var beeslevel: [Int] {
        return [beelevel, wasplevel, bumblebeelevel]
    }
    var beelevel = 0
    var wasplevel = 0
    var bumblebeelevel = 0
    let bees = ["bee", "wasp", "bumblebee"]

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return(bees.count)
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

        cell.beeimage.image = UIImage(named: bees[indexPath.row] + ".png")
        cell.beelabel.text = bees[indexPath.row]
        cell.beelevel.text = "lvl \(beeslevel[indexPath.row])"

        return(cell)
    }

    @IBAction func beelevelup(_ sender: Any) {
        beelevelup()
    }

    func beelevelup() {
        beelevel += 1
        score -= 50
    }

A: If I have got the question correctly, you actually want a row of a TableView which contains player's information, to be updated whenever it levels up.
You need to reload the cell by writing the following code:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var players:[String]?
    var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        players = ["Ronaldo", "Ronaldinho", "Messi", "Suarez", "Neymar", "Pogba", "Pele", "Rooney", "Ozil"]

        tableView = UITableView()
        tableView?.frame = CGRect.init(x: 10, y: 20, width: 200, height: 500)
        tableView?.dataSource = self
        tableView?.delegate  = self
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        view.addSubview(tableView!)

        let button = UIButton.init(type: UIButtonType.system)
        button.setTitle("Update Data", for: UIControlState.normal)
        button.frame = CGRect.init(x: 10, y: tableView!.frame.origin.y + tableView!.frame.size.height+20, width: tableView!.frame.width, height: 50)
        button.addTarget(self, action: #selector(onRowUpdate), for: UIControlEvents.touchUpInside)
button.backgroundColor = UIColor.brown
        view.addSubview(button)

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (players?.count)!
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = players?[indexPath.row]
        return cell
    }

    func onRowUpdate() {
        let index = NSIndexPath.init(item: 2, section: 0)
        players?[index.row] = "Traxido"
        tableView!.reloadRows(at: [index as IndexPath], with: UITableViewRowAnimation.automatic)
    }

}