text:
Q: Using abstract formula with emmeans I'm using emmeans to get adjusted means with a log transformation.
But unexpectedly, when I try to call this with a custom function, the behaviour is quite different with no explicit warning (except the one about the log transformation).
Here is a reproducible example:
db = mtcars %>% mutate(cyl=factor(cyl))
m = lm(log(mpg) ~ log(disp) + cyl, data = db)
print(m$call)
emm = emmeans(m, spec = "cyl", type = "response")
as.data.frame(emm)

f = function(formula){
  m = lm(formula, data = db)
  print(m$call)
  emm = emmeans(m, spec = "cyl", type = "response")
  as.data.frame(emm)
}
f(log(mpg) ~ log(disp) + cyl)

Here, the only difference between the models inside and outside the function is the call object (tested with all.equal()). They give exact same results otherwise.
This code is not mine and I'm only trying to automatize it, assuming the "outside function" output is correct.
Why is the output different? How can I automatize an emmeans call?

A: This is a scoping issue (formulas have an associated environment that depends on how/where they are created). You could insert the formula into the lm call by computing on the language:
f = function(formula){
  m = eval(bquote(lm(.(formula), data = db)))
  print(m$call)
  emm = emmeans(m, spec = "cyl", type = "response")
  as.data.frame(emm)
}

A: As described here, this can also be done using do.call.

db = dplyr::mutate(mtcars, cyl=factor(cyl))

f <- function(formula){
  m = do.call(lm, list(formula = formula, data = db))
  print(m$call$formula)
  emm = emmeans::emmeans(m, spec = "cyl", type = "response")
  as.data.frame(emm)}

f(log(mpg) ~ log(disp) + cyl)
#> log(mpg) ~ log(disp) + cyl
#>   cyl response       SE df lower.CL upper.CL
#> 1   4 18.59940 1.847377 28 15.17535 22.79603
#> 2   6 17.71003 1.011478 28 15.75472 19.90802
#> 3   8 17.71054 1.020718 28 15.73839 19.92981

Created on 2021-07-08 by the reprex package (v0.3.0)


text:
Q: The cost price becomes 0 after value of i increases I've been trying to execute the following code.. However, I keep getting the same  wrong results and I don't know why!
MY CODE
int main()
{
        char* sel_items[15]={"apple","ball","keyboard","mouse"};   /*Selling items*/
        float sel_profit[15];         /*Selling Profit*/
        float sel_price[15];          /*Selling Price*/
        float cost_price[15];        /*Original Price*/
        int i;
        for(i=0;i<4;i++)
        {                                                                                printf("\n\t\t\tENTER %s PRICE: ",sel_items[i]);
                scanf("%f",sel_price);                           /*Selling Price input here*/
                printf("\n\t\t\tENTER %s SELLING PROFIT :",sel_items[i]);
                scanf("%f",sel_profit);                          /*Selling Profit input here*/
                cost_price[i]=sel_price[i]*sel_profit[i]/100;        /*Original Price*/
                printf("\n\t\t\t\t\tORIGINAL PRICE : %f",cost_price[i]);
     }
return 0;
}

here is the output of program.

                    *ENTER apple PRICE: 50*

                    ENTER apple SELLING PROFIT :50

                                    ORIGINAL PRICE : 25.000000   /*the loop of first item is coorect*/
                    ENTER ball PRICE: 100

                    ENTER ball SELLING PROFIT :20

                                    ORIGINAL PRICE : 0.000000 /*i dont know what happens in the second loop*/
                    ENTER keyboard PRICE: 56

                    ENTER keyboard SELLING PROFIT :3

                                    ORIGINAL PRICE : -0.000000
                    ENTER mouse PRICE: 244

                    ENTER mouse SELLING PROFIT :4

                                    ORIGINAL PRICE : 0.000000*

help me with loop.When the first loop gets executed the conditions become true all the corresponding instructions are executed,But after the second loop i don't know what happens.Do please help..

A: Your sel_price and sel_profit are arrays and in your loop the way you are accessing them is wrong, you should use indexes to access array elements.
Replace this scanf("%f",sel_price); with this scanf("%f",&sel_price[i]); and the same goes for sel_profit also.
Your for loop should have been like this :-
 for(i=0;i<4;i++)
    {
            printf("\n\t\t\tENTER %s PRICE: ",sel_items[i]);
            scanf("%f",&sel_price[i]);                           /*Selling Price input here*/
            printf("\n\t\t\tENTER %s SELLING PROFIT :",sel_items[i]);
            scanf("%f",&sel_profit[i]);                          /*Selling Profit input here*/
            cost_price[i]=sel_price[i]*sel_profit[i]/100;        /*Original Price*/
            printf("\n\t\t\t\t\tORIGINAL PRICE : %f",cost_price[i]);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Switching to next level doesn't work in pygame I've had very strange problem with my pygame code, that I can't decipher. I've checked the internet, but found nothing usefull. Every time I try to play my game, switching from 2nd to 3rd level won't work. The game just crashes and gives me next error:
 File "C:\Users\Moji podatki\Documents\Python programi\Podmornica\submarine.py", line 883, in naris
screen.blit(mine, (self.x1, self.y1))
pygame.error: display Surface quit

But as I checked this part of code I couldn't understand why this error in the first place, because I checked, if I wrote the part, that switches and I did:
if self.life1 < 0 and self.life2 < 0:
    screen.blit(end, (312, 384))
    pygame.display.flip()
    pygame.time.wait(1000)
    level3()

The error message however points at this part and I have no idea why:
def draw(self):
        if not self.explosion1:
            self.frame1 = (self.x1, self.y1, 84, 196)
            #pygame.draw.rect(screen, (255,125,125), self.frame, 2)
            screen.blit(mine, (self.x1, self.y1))
        else:
            pygame.draw.rect(screen, (0,0,0), self.expl_frame1, 2)
            screen.blit(expl, (self.x1, self.y1))
            explosion.play()
        if not self.explosion2:
            self.frame = (self.x2, self.y2, 84, 196)
            #pygame.draw.rect(screen, (255,125,125), self.frame, 2)
            screen.blit(mine, (self.x2, self.y2))
        else:
            #pygame.draw.rect(screen, (0,0,0), self.expl_frame2, 2)
            screen.blit(expl, (self.x2, self.y2))
            explosion.play()

Can someone please explain where is problem?

A: If it crashed by not responding, it might be because of time.sleep(1000), and if I were you I would add pygame.display.flip() at the end of the main game loop, if you'd like the ending screen to stay there add

frame = 0
# main loop here

# erase all here
# rendering stuff here (make sure they're all here so they get rendered at the back layer)

if dead '''idk, perhaps make a dead var''' and not frame > 100 '''increase the num for it to stay there for a longer period of time''' :
    screen.blit(end, (312, 384))
    frame += 1

display.flip()

I really hope this helps.


text:
Q: get coordinates from JSON from google maps I'm getting my position from an address, I use this website:
I get JSON data, but I dont know how to read it in my Android app.
{
  "name": "plaza mayor 1 madrid España",

  "Status": {

    "code": 200,

    "request": "geocode"

  },

  "Placemark": [ {

    "id": "p1",

    "address": "Plaza Mayor, 1, 28012 Madrid, España",

    "AddressDetails": {

   "Accuracy" : 8,

   "Country" : {

      "AdministrativeArea" : {

         "AdministrativeAreaName" : "Comunidad de Madrid",

         "SubAdministrativeArea" : {

            "Locality" : {

               "LocalityName" : "Madrid",

               "PostalCode" : {

                  "PostalCodeNumber" : "28012"

               },

               "Thoroughfare" : {

                  "ThoroughfareName" : "Plaza Mayor, 1"

               }

            },

            "SubAdministrativeAreaName" : "Madrid"

         }

      },

      "CountryName" : "España",

      "CountryNameCode" : "ES"

   }

},

    "ExtendedData": {

      "LatLonBox": {

        "north": 40.4164186,

        "south": 40.4137207,

        "east": -3.7053139,

        "west": -3.7080118

      }

    },

    "Point": {

      "coordinates": [ -3.7066379, 40.4150359, 0 ]

    }

  } ]

}

How can I read the "coordinates" tag?
Thank you in advance!

A: parse it, to begin with, then access the various elements :
JSONObject response = new JSONObject(responseAsString);
JSONObject point = response.getJSONArray("Placemark").getJSONObject(0).getJSONObject("Point");

double lat = point.getJSONArray("coordinates").getDouble(0);

and so on

A: I would suggest using some sort of framwork to handle your Json data, here's a good aexample. Then you can handle your data as a regular object.
Sending and Parsing JSON Objects
Good luck!


text:
Q: how to add files with same name in different folders of xcode project I want to have two files with the same name in different folders in a xcode project. These files are actually code files and not any resource files. How can I achieve this?
Thanks
Pankaj

A: Well if there .h/.m files you can't have them in the same project, even if they are in different directories.
C does not support namespaces, so every class has to have an unique name.

A: You can add, but when you load it, the system will pick the first one available.
So, really it will not work the way you expect.


text:
Q: Gathering rows to 1 row and adding column Hello I am currently learning programming and I am working on a project of php and mysql, but I have a problem.
What I am doing is I have a table called marks and every time people add a mark to a student, they add a column to the table, the table looks like this:
|------------------|
|  subject | marks |
|------------------|
|   math   |  16   |
|  english |  18   |
|  history |  15   |
|  math    |  14   |
|  english |  20   |
|------------------|

But I want to change it like this when I treat it:
|-------------------------|
|   math   |  16   |  14  |
|  english |  18   |  20  |
|  history |  15   |      |
|-------------------------|

How can I do this with mysql's query, or php if needed?
Well my final goal is to make html table with this but I already know how to do it.
I am sorry if it looked simple, but I am really a beginner at databases and programming and I apologize if the title confuses you guys.

A: You can try
SELECT subject, GROUP_CONCAT(marks ORDER BY marks) marks
  FROM table
 GROUP BY subject
 ORDER BY subject

It will give you two columns, one with a comma-separated list of subjects.
english 18, 20
history 15
math    14, 16


text:
Q: C# xattr file attributes I'm creating a cross-platform software and I want to know if there is any (easy) way to read/write Unix (Mac OSX/Linux) extended file attributes in C#.
I've just read about xattr namespaces, but I haven't found any information about C# implementation or bindings of this feature.
P.S. The only thing I found so far is python-xattr library, but I don't want to use it because:

*

*I don't want to obligate the users to install Python (there is already Mono/.NET dependency to deal with)

*By using Python I will have a performance decrease (C# is compiled, while Python is interpreted)

*I don't want to rely/depend on external tools (if it's possible), because it's not safe

A: You should use the syscalls in Mono.Unix.Native.Syscall.*attr*.
The nuget assembly is called Mono.Posix.NETStandard
Note that the name of the name-value pair is prefixed with a namespace.   According to man 7 xattr

Currently, the security, system, trusted, and user extended attribute
classes are defined as described below.  Additional classes may be
added in the future.

public static void Test()
{
    string path = "/root/Desktop/CppSharp.txt";

    // Mono.Unix.Native.Syscall.getxattr()
    // Mono.Unix.Native.Syscall.fgetxattr()
    // Mono.Unix.Native.Syscall.lgetxattr()

    // Mono.Unix.Native.Syscall.setxattr()
    // Mono.Unix.Native.Syscall.fsetxattr()
    // Mono.Unix.Native.Syscall.lsetxattr

    // Mono.Unix.Native.Syscall.llistxattr()
    // Mono.Unix.Native.Syscall.flistxattr()
    // Mono.Unix.Native.Syscall.llistxattr()

    // Mono.Unix.Native.Syscall.removexattr()
    // Mono.Unix.Native.Syscall.fremovexattr()
    // Mono.Unix.Native.Syscall.lremovexattr()

    if (System.IO.File.Exists(path))
        System.Console.WriteLine("path exists");
    else
        System.Console.WriteLine("path doesn't exists");

    System.Text.Encoding enc = new System.Text.UTF8Encoding(false);
    string[] values = null;

    int setXattrSucceeded = Mono.Unix.Native.Syscall.setxattr(path, "user.foobar",
        enc.GetBytes("Hello World äöüÄÖÜ"), Mono.Unix.Native.XattrFlags.XATTR_CREATE);

    if (setXattrSucceeded == -1)
    {
        Mono.Unix.Native.Errno er = Mono.Unix.Native.Stdlib.GetLastError();
        string message = Mono.Unix.Native.Stdlib.strerror(er);
        // https://stackoverflow.com/questions/12662765/how-can-i-get-error-message-for-errno-value-c-language
        System.Console.WriteLine(message);
    } // End if (setXattrSucceeded == -1)

    byte[] data = null;
    long szLen = Mono.Unix.Native.Syscall.getxattr(path, "user.foobar", out data);

    string value = enc.GetString(data);
    System.Console.WriteLine(value);

    Mono.Unix.Native.Syscall.listxattr(path, System.Text.Encoding.UTF8, out values);
    System.Console.WriteLine(values);

    // https://man7.org/linux/man-pages/man2/getxattr.2.html
} // End Sub TestExtendedAttributes

A: The final solution might be the following, tell me what do you think?
FileAttrsManager is an abstract class, used to create 2 derived classes:

*

*FileAttrsManagerDos: manages advanced attributes using DSOFile.dll*

*FileAttrsManagerUnix: manages advanced attributes using IronPython* and python-xattr**

[ * ] http:\\www.microsoft.com/download/en/details.aspx?displaylang=en&id=8422
[ ** ]  http:\\ironpython.codeplex.com
[ ** * ]  http:\\pypi.python.org/pypi/xatt
Extended attributes operation (such as SetPropery(string key, object value) and GetProperty(string key) etc) will be managed in a static class (FileAttrsProvider) that initializes a FileAttrsManager object to one of two derived types i.e.:
public static class FileAttrProvider
{

    private static FileAttrReader _reader = null;

    public static void Initialize()
    {
        switch (Environment.OSVersion.Platform)
        {
            case PlatformID.MacOSX:
            case PlatformID.Unix:
                _reader = new FileAttrReaderUnix();
                break;
            case PlatformID.Win32NT:
                _reader = new FileAttrReaderDos();
                break;
        }
    }
}

While the derived type depends on the environment, the original type is used in order to ensure an automatic dispatch of all the methods call on _reader object).

A: I think Mono.Unix.Native.Syscall.setxattr would be a better solution, which is in Mono.Posix module.


text:
Q: Python: printing a dictionary with a numpy array inside I am trying to save dictionaries to a stream so that it can be loaded up later. The issue is that when I print the dictionary with a numpy array inside, it prints with the string "array" in front of the numpy array. Example:
import numpy as np
import pprint

a = {"hi":"greeting","celeryman":np.array([4,3,3])}

print(a)

pprint.pprint(a)

The above produces the output
{'celeryman': array([4, 3, 3]), 'hi': 'greeting'}
{'celeryman': array([4, 3, 3]), 'hi': 'greeting'}

The desired output is
{'celeryman': [4, 3, 3], 'hi': 'greeting'}

which I am hoping can be read without issue by using json.load.
Do I have to write my own printer for this?

A: you will have to assign the numpy array as list by-
a = {"hi":"greeting","celeryman":list(np.array([4,3,3]))}

and if you again want to initialise the list attached as value to the key 'celeryman' as a numpy array then-
a=json.load('yourfile.json')
newnplist=np.array(a['celeryman'])


text:
Q: Logoff button IIS6 ASP.NET Basic Authentication I have a requirement for an explicit logout button for users in a ASP.NET web app. I am using IIS6 with Basic Authentication (SSL). I can redirect to another web page but the browser keeps the session alive. I have googled around and found a way to do it by enabling an active x control to communicate with IIS and kill the session. I am in a restricted environment that does not allow forms authentication and active x controls are not forbidden as well. Has anyone else had this requirement and how have you handled it?
Okay that is what I was afraid of. I have seen similar answers on the net and I was hoping someone would have a way of doing it. Thanks for your time though. I guess I can use  javascript to prevent the back button like the history.back()

A: I was struggling with this myself for a few days.
Using the IE specific 'document.execCommand('ClearAuthenticationCache');' is not for everyone a good option:
1) it flushes all credentials, meaning that the user will for example also get logged out from his gmail or any other website where he's currently authenticated
2) it's IE only ;)
I tried using Session.Abandon() and then redirecting to my Default.aspx. This alone is not sufficient.
You need to explicitly tell the browser that the request which was made is not authorized. You can do this by using something like:
response.StatusCode = 401;
response.Status = "401 Unauthorized";
response.AddHeader("WWW-Authenticate", "BASIC Realm=my application name");
resp.End();

This will result in the following: the user clicks the logout button ==> he will get the basic login window. HOWEVER: if he presses escape (the login dialog disappears) and hits refresh, the browser automagically sends the credentials again, causing the user to get logged in, although he might think he's logged out.
The trick to solve this is to always spit out a unique 'realm'. Then the browser does NOT resend the credentials in the case described above. I chose to spit out the current date and time.
response.StatusCode = 401;
response.Status = "401 Unauthorized";
string realm = "my application name";
response.AddHeader("WWW-Authenticate", string.Format(@"BASIC Realm={0} ({1})", realm, DateTimeUtils.ConvertToUIDateTime(DateTime.Now)));
resp.End();

Another thing that you need to do is tell the browser not to cache the page:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.MinValue);
Response.Cache.SetNoStore();

With all these things in place it works (for me) in IE, but until now I still wasn't able to prevent firefox from logging in the user when the user first presses escape (hides the basic login dialog) and then refresh (F5) or the browsers back button.

A: The Session.Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.

A: Have you tried calling Session.Abandon in response to the button click?
Edit:
It would seem this is a classic back button issue.
There is very little you can do about the back button.  Imagine the user has just opened the current page in a new window then clicked the logOut button, that page appears to log out but it will not immediately affect the content of the other window.
Only when they attempt to navigate somewhere in that window will it become apparent that their session is gone.
Many browsers implement the back button in a similar (although not identical) way.  Going back to the previous page is not necessarily a navigation for a HTML/HTTP point of view.

A: This is a solution for this problem that works in IE6 and higher.
<asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="logout();">LinkButton</asp:LinkButton>

<script>

    function logout()
    {
    document.execCommand("ClearAuthenticationCache",false);
    }
 </script>

Found this from
http://msdn.microsoft.com/en-us/library/bb250510%28VS.85%29.aspx
Web Team in Short
Your Credentials, Please
Q: Jerry B. writes, "After the user has validated and processed his request, I now want to invalidate him. Assuming this machine is in an open environment where anyone could walk up and us it, I want to throw a new challenge each time a user accesses a particular module on the Web."
A: This is a frequently requested feature of the Internet Explorer team and the good people over there have given us a way to do it in Internet Explorer 6.0 SP1. All you need to do is call the execCommand method on the document, passing in ClearAuthenticationCache as the command parameter, like this:
document.execCommand("ClearAuthenticationCache");

This command flushes all credentials in the cache, such that if the user requests a resource that needs authentication, the prompt for authentication occurs again.
I put this on my logout link button and it works in IE6 sp1 and higher:
OnClientClick="document.execCommand('ClearAuthenticationCache');"


text:
Q: reCaptcha, .NET, Chrome: not working combination I faced a problem that I wanna share with you, both for documentation and for finding a proper explanation. The issue: reCaptcha stops showing (and thus working), but only on Chrome.
environment
It's a web site build with .NET 3.5, WebForms, and the official reCaptcha library Recaptcha.web.dll.
implementation
<%@ Register Namespace="Recaptcha.Web.UI.Controls" Assembly="Recaptcha.Web" TagPrefix="cc1" %>
<cc1:Recaptcha id="RecaptchaControl" runat="server" />

then, at submit, I check the control using a CustomValidator control.
output
A recaptcha box is shown in every browser BUT Chrome, in which a blank space is left. If I try to submit the form, a .NET server error is shown, saying:

Recaptcha challenge field cannot be empty.

furher analisys
Going deep in debug, I got how the dll is actually working: it injects a <script> tag referring to http://www.google.com/recaptcha/api/challenge?k=MY_PUBLIC_KEY. Thus, is seems the core problem is something between Chrome and xss or script injection. Searching google about it, I can't find anything. Even more, the Chrome console doesn't show any error/wanring/info about it.

A: my lucky, loose solution
After I got frustrated about the issue, I did something both trivial and stupid: I hard-coded a <script> tag referring to the http://www.google.com/recaptcha/api/challenge?k=MY_PUBLIC_KEY I found out during debug. Directly in page. It works as expected: it displays a reCaptcha control in the exact position I put the <script> tag. But here's the funny part: after I removed the hard-coded <script>, the entire page is working fine, and on other's machines too!
That's all folks, I hope it helps someone else. And, If you can explain me what actually happened, you're welcome ;


text:
Q: subset lists based on a condition in r I have a data frame which looks like:
df = read.table(text="S00001    S00002  S00003  S00004  S00005  S00006
GG  AA  GG  AA  GG  AG
CC  TT  TT  TC  TC  TT
TT  CC  CC  TT  TT  TT
AA  AA  GG  AA  AG  AA
TT  CC  CC  TT  TC  TT
GG  GG  GG  AA  GG  GG", header=T, stringsAsFactors=F)

I would like to count the number of character strings with the same letters (i.e. "AA", "CC", "GG", or "TT") for each row. What I did is to use table() function to count all elements and generated another list based on if the names of lists are "homo". I tried to subset the lists but it didn't work. Here is my scripts:
A <- apply(df,1, function(x) table(x))
B <- apply(df,1, function(x) (names(table(x)) %in% c("AA","CC","GG","TT")))
A[B] ## this didn't work

I expect a data frame would be generated:
2 3
1 3
2 4
4 1
2 3
1 5

appreciate any helps.

A: Try mapply. It will take each element of the lists sequentially for evaluation. The header names are auto-generated, you can change them as you see fit:
t(mapply('[', A, B))
     AA GG
[1,]  2  3
[2,]  1  3
[3,]  2  4
[4,]  4  1
[5,]  2  3
[6,]  1  5

As mentioned by CathG, you can avoid calculating B with:
t(sapply(A, function(x){x[grepl("([A-Z])\\1", names(x))]}))

A: I don't like apply due to matrix conversion and especially apply(df, 1,...) due to by row operations.
Alternatively, I would suggest and helper function that uses sapply combined with rowSums (which will operate on sapply matrix output)
f <- function(x, y) rowSums(sapply(x, `%in%`, y))

then you could do (without calculating A and B)
cbind(f(df, c("AA", "CC")),
      f(df, c("GG", "TT")))
#      [,1] [,2]
# [1,]    2    3
# [2,]    1    3
# [3,]    2    4
# [4,]    4    1
# [5,]    2    3
# [6,]    1    5

Or just (depends on what you looking for)
f(df, c("AA", "CC", "GG", "TT"))
# [1] 5 4 6 5 5 6

A: We could do this with a single apply
t(apply(df, 1, function(x) {tbl <- table(x)
        tbl[names(tbl) %in% c("AA", "CC", "GG", "TT")]}))
#      [,1] [,2]
#[1,]    2    3
#[2,]    1    3
#[3,]    2    4
#[4,]    4    1
#[5,]    2    3
#[6,]    1    5


text:
Q: Pull screen down to refresh data in qml On my Application I need to apply a feature like when I pull the screen down then the current page get refresh. For that I have done this
Sample Code
      Page {
height: 460
width: 300
id: app
property var refreshFlik: ""
Flickable {
    id:flick
    anchors.fill: parent
    contentHeight : rect.height
    Rectangle{
        id:rect
      color: "#fffff1"
        height: 540
        width: 300
    Text{
        id:text
       anchors.centerIn: parent
        text:"Hello World"
    }
    }
    onFlickStarted: {
         refreshFlik = atYBeginning
        busy.running=true
     }
    onFlickEnded: {
         if ( atYBeginning && refreshFlik )
         {
          //   updateDataFromServer();   // it's a function to update the data from server
             console.log("After getting the updated data refresh the page");
             // here after getting the data from server I need to refresh the whole page
             busy.running=false
         }
     }
}
BusyIndicator{
        id:busy
        anchors.centerIn: parent
        running: false
    }
}

So This code is working fine, but one thing which i'm lacking at is not able to refresh the data on the screen. Suppose on Screen It shows "Hello world", but after I pull down the screen after getting the data from my server that text changes to something else according to the data i get from server.

A: If you want to reload the whole thing I think its better you use a Component and loader as below
   Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Component{
        id:toLoad
        Page {

            height: 460
            width: 300
            id: app
            signal reloadComponent()
            property var refreshFlik: ""

            Flickable {
                id:flick
                anchors.fill: parent
                contentHeight : rect.height
                Rectangle{
                    id:rect
                    color: "#55ff00ff"
                    height: 540
                    width: 300
                    Text{
                        id:text
                        anchors.centerIn: parent
                        text:"Hello World"
                    }
                }
                onFlickStarted: {
                    refreshFlik = atYBeginning
                    busy.running=true
                }
                onFlickEnded: {
                    if ( atYBeginning && refreshFlik )
                    {
                        //   updateDataFromServer();   // it's a function to update the data from server
                        console.log("After getting the updated data refresh the page");
                        // here after getting the data from server I need to refresh the whole page
                        busy.running=false
                    }
                    reloadComponent()
                }
            }
            BusyIndicator{
                id:busy
                anchors.centerIn: parent
                running: false
            }

            Component.onCompleted:{
                console.log("loaded")
            }
        }

    }

    Loader{
        id:ldr
        sourceComponent: toLoad

        Connections{
            target:ldr.item
            onReloadComponent:{
                console.log("reloading")
                ldr.sourceComponent=undefined
                ldr.sourceComponent=toLoad
            }
        }

    }

}


text:
Q: Almost all trees have non-trivial automorphism group In their paper Asymmetric Graphs Erdős and Rényi proved that almost all trees have non-trivial automorphism group. More specifically they showed that almost all trees contain at least one so-called cherry, i.e. three vertices $i, j, k$ where $i, j$ are leaves, $k$ has degree $3$ and $(i,k)$ and $(j,k)$ are edges.
Unfortunately I'm having some trouble understanding their proof. I can follow the counting argument but fail to understand the following bits, in particular the part where Chebyshev's inequality is used.
I would be very grateful if someone could explain to me the steps in the proof in more detail or point me to some other reference for this result. I haven't found this in any graph theory book.
I have linked the original paper above. The relevant bit starts on page 18 of the pdf.


text:
Q: How do I highlight the entire quote with both quotes given that a keyword is found using RegEx? Forgive me, just got started with regex today. What I've come up with so far to my understanding is \".*\bkeyword\b.*\". I'm not too sure how to handle special characters such as / or ; . So some help please?
What I need to detect is goes something like this.
"Mozilla/5.0   (X11;   Ubuntu;   Linux   x86_64;   rv:31.0)
 Gecko/20100101 Firefox/31.0"

If I type the word Mozilla, the quotes and text in between will be highlighted. And look sorta like this.

A: You may use
"[^"]*\bMozilla\b[^"]*"

See the regex demo
Details

*

*" - a double quote

*[^"]* - a negated character class that matches any char other than " zero or more times (due to the * quantifier)

*\b - a word boundary

*Mozilla - any keyword consisting of word chars (letters, digits or/and _)

*\b - a word boundary

*[^"]* - a negated character class that matches any char other than " zero or more times.

When declaring the regex inside double quoted string literals, you may have to escape " (=> "\"") and \b (=> \\b) once. There are ways to avoid using (too many) backslashes, but that depends on what language and notation you are using.


text:
Q: How to remove white space from masonry image gallery You can check JSFIDDLE

HTML

JS
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  columnWidth: 1,
  itemSelector: '.item',
  gutter: 10
});

A: Just got this working while defining .item as columnWidth in masonry js. And adding some style to .item
SEE THIS FIDDLE
JS
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  columnWidth: '.item',
  itemSelector: '.item'
});

CSS
.item {
    width: 19.8%;
    height: auto;
    margin:0.1%;
}
.item img {
    width: 100%;
    height: auto;
}

A: How about trying this: (beautiful cats :p)

JSFIDDLE

A: That's just the nature of the plugin; since your code doesn't have any items small enough to fill the space, it skips past it. If you can make the items smaller, even 90% of the current size, it'll be easier for the to fill the given space – think peas in a jar as compared to sand in a jar.
Beyond that, increasing gutter space might make that big gap look less intense, but not fix everything.


text:
Q: Play WAV file using Audioplayer I am trying to write a short program to play a wave sound in Java, but I seeing many exceptions. Maybe someone can help me?
import java.io.*;
import sun.audio.*;
import sun.audio.AudioPlayer;

@SuppressWarnings("restriction")
public class Main {
    public static void main(String[] args) throws IOException {
        String wav_file = "C:/Users/Patrick/workspace/WaveFreq/zelda_01.wav";
        InputStream in = new FileInputStream(wav_file);
        AudioStream audio = new AudioStream(in);

        AudioPlayer.player.start(audio);
    }
}

And this is the exception:

Exception in thread "main" java.io.IOException: could not create audio stream from input stream
      at sun.audio.AudioStream.(Unknown Source)
      at Main.main(Main.java:16)

A: Hope this helps:
import java.io.File;
import javax.sound.sampled.*;
import javax.sound.sampled.DataLine.Info;

public class AudioFilePlayer {
    public static void main(String[] args) {
        try {
            String filePath = "C:/Users/Patrick/workspace/WaveFreq/zelda_01.wav";
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(filePath));
            AudioFormat format = inputStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip) AudioSystem.getLine(info);

            clip.open(inputStream);
            clip.start();
        } catch (Exception e) {
            System.out.println("Error with playing sound.");
            e.printStackTrace( );
        }
    }
}


text:
Q: Convert adjacency matrix to graph Is there any online service that can provide possible graphs (the simplest one) when I give a sequence of integers (node degrees) as input (or reject the input) -based on Erdős-Gallai formula?
Thanks in advance for your help.

A: Presumably you'r after a graph that realizes a degree sequence (if possible), since this is what the Erdős–Gallai Theorem is about.  These graphs can be constructed by the Havel-Hakimi algorithm (a description is on the Wikipedia page for degree).
It's straightforward:  Each vertex is labeled by its remaining degree (starting off with the specified degree sequence).  In each iteration, we take a vertex $v$ of maximum degree $d$, and connect it to $d$ vertices that have the maximum remaining degree.  This drops the remaining degree of $v$ to $0$ and each of its new neighbors' remaining degrees by $1$.
Moreover, the algorithm fails if and only if the degree sequence is not realizable.


text:
Q: Creating regular expressions for input validation I want to do field validation to see if the value matches a pattern but am having trouble understanding the necessary regular expression.  Is there a tool where you can enter a pattern and have it tell you the regular expression that will match it?  Or is anyone willing to take a shot at the formula?
The patterns I need to match are (the capital letters are literal, 'a' is a character from A-Z or 0-9 and 'n' is a character from 0-9):
    Aaaaaannn
    Tnnnnnnnnnnnnn
    Snnnnn
Fortunately these are all in separate fields, but if anyone can tell me how to validate any of these patterns in the same field, that would be helpful.
Thanks!

A: I didn't test any of these.
Separately:
/\AA[A-Z0-9]{5}\d{3}\z/
/\AT\d{14}\z/
/\AS\d{5}\z/

Together:
/\AA[A-Z0-9]{5}\d{3} T\d{14} S\d{5}\z/

A:
Is there a tool where you can enter a pattern and have it tell you the regular expression that will match it?

I use RegEx Buddy. It isn't free but very good. Will create the required source and help you build the regex.
http://www.regexbuddy.com/
A free online version is:
http://www.regextester.com/

(the capital letters are literal, 'a' is a character from A-Z or 0-9 and 'n' is a character from 0-9): Aaaaaannn Tnnnnnnnnnnnnn Snnnnn

A[A-Z,0-9]{5}[0-9]{3} T[0-9]{13} S[0-9]{5}

Probably a number of ways to write it though.

A: On Sourceforge you will find The Regulator It is a Windows app that helped me a lot. And yes among the Query languages Regex are the beast, second only to advanced XPath.


text:
Q: Multithreading 4-Tier Mixed Producer Consumer Pattern - Threads Not Alternating Properly Here is the problem I am trying to model: I have an incoming call center (no outbound calls). There are 3 employee levels - Freshers, Technical Lead, Project Manager. In our call center there is only one TL, one PM and multiple Freshers. Calls that the Freshers cannot handle are escalated to the TL, and calls that the TL cannot handle are escalated to the PM.
I need to take an OO C# approach.
Here is my current attempt: I used C# ConcurrentQueue since I thought it would take care of the 'locks'. I want FIFO for call center. I made a queue for each level.
I have a producer (callers) adding calls to the first queue. Mixed prod/consumer freshers check the call (take or escalate to the next queue). Mixed prod/consumer tl, then a pure consumer project manager.
The output is not what I expect. Only the first fresher runs and the project manager does not run at all. I expect a lot more alternation as the calls are added to the queue.
My code is below. Does anyone have a better approach to this problem or is there something wrong with my code?
The CallCenter Class is where most of the action takes place.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Concurrent;
namespace CallCenterThreaded
{
/// <summary>
///
/// MIXED CONSUMER/PRODUCER TYPE
/// </summary>
class Fresher
{
    // add a class variable for the number of Employee objects instantiated
    private static int fresherNum = 0;
    private int fresherId;
    private ConcurrentQueue<Call> incommingCalls;
    private ConcurrentQueue<Call> outgoingCalls;

    public Fresher(ConcurrentQueue<Call> calls, ConcurrentQueue<Call> outcalls)
    {
        fresherId = ++fresherNum;
        incommingCalls = calls;
        outgoingCalls = outcalls;
        //start the producer thread
        Thread thread = new Thread(new ThreadStart(HandleCalls));
        thread.Start();
    }

    public int ID
    {
        get { return fresherId; }
    }

    /// <summary>
    ///
    /// </summary>
    public void HandleCalls()
    {

        while (incommingCalls.Count > 0)
        {

            Call call;
            incommingCalls.TryDequeue(out call);

            if (call != null)
            {
                if (call.EscalationLevel == 0)
                {
                    TakeCalls(call);
                }
                else
                {
                    TransferCalls(call);
                }
            }

        }

    }

    /// <summary>
    /// Transfer to the TL
    /// </summary>
    public void TransferCalls(Call call)
    {
        outgoingCalls.Enqueue(call);
        Console.WriteLine(".......Fresher {0} escalated call {1}", ID, call.CallID);
    }

    /// <summary>
    /// Consume the calls
    /// </summary>
    public void TakeCalls(Call call)
    {
        Console.WriteLine("Fresher {0} handled call {1}", ID, call.CallID);
    }

}
}
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Collections.Concurrent;
   namespace CallCenterThreaded
    {
    /// <summary>
    /// MIXED CONSUMER/PRODUCER TYPE
    /// </summary>
    class TechnicalLead
    {

    // add a class variable for the number of Employee objects instantiated
    private static int tlNum = 0;
    private int tlId;

    private ConcurrentQueue<Call> incommingCalls;
    private ConcurrentQueue<Call> outgoingCalls;

    public TechnicalLead(ConcurrentQueue<Call> calls, ConcurrentQueue<Call> outcalls)
    {
        tlId = ++tlNum;
        incommingCalls = calls;
        outgoingCalls = outcalls;
        //start the producer thread
        Thread thread = new Thread(new ThreadStart(HandleCalls));
        thread.Start();
    }

    public int ID
    {
        get { return tlId; }
    }

    /// <summary>
    ///
    /// </summary>
    public void HandleCalls()
    {

        while (incommingCalls.Count > 0)
        {

            Call call;
            incommingCalls.TryDequeue(out call);

            if (call != null)
            {
                if (call.EscalationLevel == 1)
                {
                    TakeCalls(call);
                }
                else
                {
                    TransferCalls(call);
                }
            }

        }

    }
    /// <summary>
    /// Transfer to the PM
    /// </summary>
    public void TransferCalls(Call call)
    {
        //Console.WriteLine(".......Technical Lead {0} escalated call {1}", ID, call.CallID);
        outgoingCalls.Enqueue(call);
    }

    /// <summary>
    /// Consume the calls
    /// </summary>
    public void TakeCalls(Call call)
    {
        Console.WriteLine("Technical Lead {0} handled call {1}", ID, call.CallID);
    }
}
}
    using System;
   using System.Collections.Generic;
 using System.Linq;
 using System.Text;
   namespace CallCenterThreaded
   {
class Call
{
    private static int numberCalls = 0;
    private int callno;

    private int esclataion;

    public Call()
    {
        callno = ++numberCalls;
        esclataion = 0;
        if(callno % 3 == 0)
        {
            esclataion = 1;
        }
        if(callno % 5 == 0)
        {
            esclataion = 2;
        }

    }

    public int CallID { get { return callno; } }
    public int EscalationLevel { get { return esclataion; } }
}
}
 using System;
 using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Concurrent;
namespace CallCenterThreaded
{
/// <summary>
///
/// </summary>
class CallCenter
{

    private ConcurrentQueue<Call> fresherCalls;
    private ConcurrentQueue<Call> tlCalls;
    private ConcurrentQueue<Call> pmCalls;

    private List<Caller> myCallers;
    private List<Fresher> myFreshers;

    private TechnicalLead tl;
    private ProjectManager pm;

    public CallCenter()
    {
        //initial incomming calls to the fresher queue
        fresherCalls = new ConcurrentQueue<Call>();
        tlCalls = new ConcurrentQueue<Call>();
        pmCalls = new ConcurrentQueue<Call>();

        myFreshers = new List<Fresher>();
        myCallers = new List<Caller>();

        generate_callers();
        generate_freshers();

        tl = new TechnicalLead(tlCalls, pmCalls);
        pm = new ProjectManager(pmCalls);
    }

    /// <summary>
    ///
    /// </summary>
    private void generate_freshers()
    {
        for (int i = 0; i < 5; i++ )
        {
            myFreshers.Add(new Fresher(fresherCalls, tlCalls));
        }
    }

    /// <summary>
    ///
    /// </summary>
    private void generate_callers()
    {
        for (int i = 0; i < 5; i++ )
        {
            myCallers.Add(new Caller(fresherCalls));
        }
    }

   }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Concurrent;
namespace CallCenterThreaded
{
/// <summary>
/// PURE CONSUMER
/// </summary>
class ProjectManager
{

     // add a class variable for the number of Employee objects instantiated
    private static int pmNum = 0;
    private int pmId;

    private ConcurrentQueue<Call> incommingCalls;

    public ProjectManager(ConcurrentQueue<Call> calls)
    {
        pmId = ++pmNum;
        incommingCalls = calls;

        //start the producer thread
        Thread thread = new Thread(new ThreadStart(HandleCalls));
        thread.Start();
    }

    public int ID
    {
        get { return pmId; }
    }

    /// <summary>
    ///
    /// </summary>
    public void HandleCalls()
    {

        while (incommingCalls.Count > 0)
        {

            Call call;
            incommingCalls.TryDequeue(out call);

            if (call != null && call.EscalationLevel == 2)
            {
                TakeCalls(call);
            }

        }

    }
    /// <summary>
    /// Consume the calls
    /// </summary>
    public void TakeCalls(Call call)
    {
        Console.WriteLine("Project Manager {0} handled call {1}", ID, call.CallID);
    }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Concurrent;
namespace CallCenterThreaded
{
class MainClass
{
    static void Main(string[] args)
    {

        CallCenter myCenter = new CallCenter();

        Console.ReadLine();
    }
}
}
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;
namespace CallCenterThreaded
{
/// <summary>
/// This is a producer. It produces calls and adds them to the queue.
/// PURE PRODUCER TYPE
/// </summary>
class Caller
{

    private ConcurrentQueue<Call> incommingCalls;

    public Caller(ConcurrentQueue<Call> calls)
    {
        incommingCalls = calls;
        //start the producer thread
        Thread thread = new Thread(new ThreadStart(placeCalls));
        thread.Start();
    }

    public void placeCalls()
    {

        //place 10 calls
        for (int callno = 0; callno < 4; callno++)
        {
            //Console.WriteLine("Call {0} was added to the queue", callno);
            incommingCalls.Enqueue(new Call());
        }

    }

}
}

A: The problem is in the HandleCalls() methods:
public void HandleCalls()
{
    while (incommingCalls.Count > 0)
    {
        …
    }
}

What this code does is to check incomingCalls and if there are none, it immediately exits the thread. It's as if the worker came to work, looked at his queue of calls, found nothing there (because he came to work at the same time as the freshers who are supposed to redirect the calls) and so he left and went home.
What you need to do is to wait if there is no work at the moment. Probably the best way to do that is to use BlockingCollection instead of ConcurrentQueue.
Also, your design doesn't seem to that good. For example, there is lots of repeated code.


text:
Q: What is wrong with my stored procedure? please This is my stored procedure:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PROC_AgregarUsuario]
    @Email VARCHAR(100),
    @SALT VARCHAR(100),
    @PASS VARCHAR(100),
    @PASSWORDECRYPT VARCHAR(100),
    @Nuevo INT
AS
BEGIN
    DECLARE @USERID UNIQUEIDENTIFIER,
            @MensajeRegreso VARCHAR(8000),
            @CantidadContactosEmpresa INT,
            @EmpresaRFC char(13)

    SET @USERID = (SELECT [UserId]
                   FROM [dbo].[aspnet_Users]
                   WHERE [UserName] = @Email)

    IF @Nuevo IN (1, 2)
    BEGIN
        SET @CantidadContactosEmpresa =
            (SELECT COUNT(*)
             FROM [dbo].[EmpresaUser]
             WHERE [EmpresaUser_Empresa] IN (SELECT [EmpresaUser_Empresa]
                                             FROM [dbo].[EmpresaUser]
                                             WHERE [EmpresaUser_Email] = @Email))
        IF @USERID IS NULL
        BEGIN
            INSERT INTO dbo.aspnet_Users(ApplicationId, UserId, UserName, LoweredUserName,
                                         MobileAlias, IsAnonymous, LastActivityDate)
                SELECT TOP 1
                    ApplicationId, -- ApplicationId - uniqueidentifier
                    NEWID() , -- UserId - uniqueidentifier
                    @Email , -- UserName - nvarchar(256)
                    LOWER(@Email) , -- LoweredUserName - nvarchar(256)
                    NULL , -- MobileAlias - nvarchar(16)
                    0 , -- IsAnonymous - bit
                    GETDATE()  -- LastActivityDate - datetime
                FROM
                    dbo.aspnet_Applications

            SET @USERID = (SELECT UserId FROM dbo.aspnet_Users
                           WHERE UserName = @Email)

            INSERT INTO dbo.aspnet_Membership (ApplicationId, UserId, Password, PasswordFormat, PasswordSalt,
                                               MobilePIN, Email, LoweredEmail,
                                               PasswordQuestion, PasswordAnswer,
                                               IsApproved, IsLockedOut,
                                               CreateDate, LastLoginDate,
                                               LastPasswordChangedDate,
                                               LastLockoutDate,
                                               FailedPasswordAttemptCount ,
                                               FailedPasswordAttemptWindowStart,
                                               FailedPasswordAnswerAttemptCount,
                                               FailedPasswordAnswerAttemptWindowStart,
                                              Comment)
                SELECT
                    ApplicationId , -- ApplicationId - uniqueidentifier
                    @USERID , -- UserId - uniqueidentifier
                    @PASSWORDECRYPT , -- Password - nvarchar(128)
                    1 , -- PasswordFormat - int
                    @SALT , -- PasswordSalt - nvarchar(128)
                    NULL , -- MobilePIN - nvarchar(16)
                    @Email , -- Email - nvarchar(256)
                    LOWER(@Email) , -- LoweredEmail - nvarchar(256)
                    'Pregunta' , -- PasswordQuestion - nvarchar(256)
                    @PASSWORDECRYPT , -- PasswordAnswer - nvarchar(128)
                    1 , -- IsApproved - bit
                    0 , -- IsLockedOut - bit
                    GETDATE() , -- CreateDate - datetime
                    GETDATE() , -- LastLoginDate - datetime
                    GETDATE() , -- LastPasswordChangedDate - datetime
                    '18990101' , -- LastLockoutDate - datetime
                    0 , -- FailedPasswordAttemptCount - int
                    '18990101' , -- FailedPasswordAttemptWindowStart - datetime
                    0 , -- FailedPasswordAnswerAttemptCount - int
                    '18990101', -- FailedPasswordAnswerAttemptWindowStart - datetime
                    @PASS  -- Comment - ntext
                FROM
                    dbo.[aspnet_Applications]

        /*Rol Empresa*/

            INSERT INTO dbo.aspnet_UsersInRoles
                    ( UserId, RoleId )
            SELECT @USERID, -- UserId - uniqueidentifier
                      RoleId -- RoleId - uniqueidentifier
                  FROM dbo.aspnet_Roles WHERE RoleName IN ('Empresas')

        IF EXISTS (SELECT NULL FROM [dbo].[Empresa] WHERE [EMP_RFC] IN (SELECT [EmpresaUser_Empresa] FROM [dbo].[EmpresaUser] WHERE [EmpresaUser_Email] = @Email))
        BEGIN
            INSERT INTO dbo.aspnet_UsersInRoles
                    ( UserId, RoleId )
            SELECT @USERID, -- UserId - uniqueidentifier
                      RoleId -- RoleId - uniqueidentifier
                  FROM dbo.aspnet_Roles WHERE RoleName IN ('Empresas')
        END

            IF @CantidadContactosEmpresa = 1
            BEGIN
                INSERT INTO dbo.aspnet_UsersInRoles
                        ( UserId, RoleId )
                SELECT @USERID, -- UserId - uniqueidentifier
                          RoleId -- RoleId - uniqueidentifier
                      FROM dbo.aspnet_Roles WHERE RoleName IN ('Empresas')
            END
            SET @MensajeRegreso = 'Creo que funcionó ...'
    END
    ELSE
    BEGIN
        INSERT INTO dbo.aspnet_Users
                    ( ApplicationId ,
                      UserId ,
                      UserName ,
                      LoweredUserName ,
                      MobileAlias ,
                      IsAnonymous ,
                      LastActivityDate
                    )
            SELECT TOP 1 ApplicationId , -- ApplicationId - uniqueidentifier
                      NEWID() , -- UserId - uniqueidentifier
                      @Email , -- UserName - nvarchar(256)
                      LOWER(@Email) , -- LoweredUserName - nvarchar(256)
                      NULL , -- MobileAlias - nvarchar(16)
                      0 , -- IsAnonymous - bit
                      GETDATE()  -- LastActivityDate - datetime
                    FROM dbo.aspnet_Applications

            SET @USERID = (SELECT UserId FROM dbo.aspnet_Users WHERE UserName = @Email)

            INSERT INTO dbo.aspnet_Membership
                    ( ApplicationId ,
                      UserId ,
                      Password ,
                      PasswordFormat ,
                      PasswordSalt ,
                      MobilePIN ,
                      Email ,
                      LoweredEmail ,
                      PasswordQuestion ,
                      PasswordAnswer ,
                      IsApproved ,
                      IsLockedOut ,
                      CreateDate ,
                      LastLoginDate ,
                      LastPasswordChangedDate ,
                      LastLockoutDate ,
                      FailedPasswordAttemptCount ,
                      FailedPasswordAttemptWindowStart ,
                      FailedPasswordAnswerAttemptCount ,
                      FailedPasswordAnswerAttemptWindowStart ,
                      Comment
                    )
            SELECT ApplicationId , -- ApplicationId - uniqueidentifier
                      @USERID , -- UserId - uniqueidentifier
                      @PASSWORDECRYPT , -- Password - nvarchar(128)
                      1 , -- PasswordFormat - int
                      @SALT , -- PasswordSalt - nvarchar(128)
                      NULL , -- MobilePIN - nvarchar(16)
                      @Email , -- Email - nvarchar(256)
                      LOWER(@Email) , -- LoweredEmail - nvarchar(256)
                      'Pregunta' , -- PasswordQuestion - nvarchar(256)
                      @PASSWORDECRYPT , -- PasswordAnswer - nvarchar(128)
                      1 , -- IsApproved - bit
                      0 , -- IsLockedOut - bit
                      GETDATE() , -- CreateDate - datetime
                      GETDATE() , -- LastLoginDate - datetime
                      GETDATE() , -- LastPasswordChangedDate - datetime
                      '18990101' , -- LastLockoutDate - datetime
                      0 , -- FailedPasswordAttemptCount - int
                      '18990101' , -- FailedPasswordAttemptWindowStart - datetime
                      0 , -- FailedPasswordAnswerAttemptCount - int
                      '18990101', -- FailedPasswordAnswerAttemptWindowStart - datetime
                      @PASS  -- Comment - ntext
                    FROM dbo.[aspnet_Applications]

        /*Rol Empresa*/

            INSERT INTO dbo.aspnet_UsersInRoles
                    ( UserId, RoleId )
            SELECT @USERID, -- UserId - uniqueidentifier
                      RoleId -- RoleId - uniqueidentifier
                  FROM dbo.aspnet_Roles WHERE RoleName IN ('Empresas')

        IF EXISTS (SELECT NULL FROM [dbo].[Empresa] WHERE [EMP_RFC] IN (SELECT [EmpresaUser_Empresa] FROM [dbo].[EmpresaUser] WHERE [EmpresaUser_Email] = @Email))
        BEGIN
            INSERT INTO dbo.aspnet_UsersInRoles
                    ( UserId, RoleId )
            SELECT @USERID, -- UserId - uniqueidentifier
                      RoleId -- RoleId - uniqueidentifier
                  FROM dbo.aspnet_Roles WHERE RoleName IN ('Empresas')
        END

        SET @PASS = (SELECT TOP 1 [EmpresaUser_Password] FROM [dbo].[EmpresaUser] WHERE [EmpresaUser_Email] = @Email ORDER BY [EmpresaUser_Email])

        UPDATE [dbo].[EmpresaUser] SET [EmpresaUser_Password] = @PASS WHERE [EmpresaUser_Email] = @Email

        SET @MensajeRegreso = 'No creo que funcione ...'
    END

END
IF @Nuevo IN (0, 1)
BEGIN
    SELECT @MensajeRegreso AS Mensaje
END
END

I get this error every time I insert email & password:

Cannot insert duplicate key row in object 'dbo.aspnet_Users' with unique index 'aspnet_Users_Index'. The duplicate key value is (f12020b5-6b40-488a-bc55-2bb4708986b2, ). Violation of PRIMARY KEY constraint 'PK__aspnet_M__1788CC4DA6E8A466'. Cannot insert duplicate key in object 'dbo.aspnet_Membership'. The duplicate key value is (556ba324-9720-4081-a4be-89fbb38902fc). Violation of PRIMARY KEY constraint 'PK__aspnet_U__AF2760AD5013D67A'. Cannot insert duplicate key in object 'dbo.aspnet_UsersInRoles'. The duplicate key value is (556ba324-9720-4081-a4be-89fbb38902fc, 084b9f2d-08d4-4e74-911e-ac5ae50dfaf9). The statement has been terminated. The statement has been terminated. The statement has been terminated.

A: add distinct to the select statment
  SELECT DISTINCT  @USERID, -- UserId - uniqueidentifier
                   RoleId -- RoleId - uniqueidentifier
  FROM dbo.aspnet_Roles WHERE RoleName IN ('Empresas')

A: You check if @USERID IS NULL which is great. But then in ELSE (that is @USERID is not null) part you try to insert again. this is your violation of PK.


text:
Q: Storing values in a struct in a linked list I'm wondering how I would go about storing a value into a struct that is part of a linked list of structs. I have:
struct polynomial
{
    polynomial(string newCoefficient, string newPower, polynomial *nextPtr);
    string coefficient;
    string power;
    polynomial *next;
};

class linkedList
{
public:
    void createList();

private:
    polynomial *head;
};

For this assignment, we need to do some parsing when gathering input values. For example, we are to input two numbers separated by a space (ex. 7 9 or 10 8). Therefore, in void createList(), I want to read in a line using string, convert it to a char array to strip down the values, then store that value into polynomial.coefficient and polynomial.power, for each node in the linked list.
Or, I was searching some information up, and I was thinking maybe I can input two int values and then use stringstream to convert them into strings and them store into coefficient and power.
Either way, can you help introduce me to the concept of storing a value into a linked listed struct?
EDIT: I have added the overloaded constructor:
polynomial:: polynomial ( string newCoefficient, string newPower, polynomial *nextPtr )
{
    coefficient = newCoefficient;
    power = newPower;
    next = nextPtr;

};

A: You are mixing C-style practice with C++ practice.
In C++, you generally separate the data from the container.  Look at how std::list works.
Even if you don't want to get into templating, you can still do this:
struct polynomial {
   string coefficient;
   string power;
};

struct listnode {
   polynomial data;
   listnode *next;
};

If you really want to have the head concept, you can either keep a 'dummy head' where you store one listnode that has nothing in it.
Alternatively, if you really want the next pointer in polynomial and you want a way to copy over an existing element without nuking the pointer, just make a setter function:
void polynomial::set( const string& inCoeff, const string & inPower );

A: I tested the following code which may help you out:
struct Polynomial {
        string coefficient;
        string power;
        Polynomial* next;

        Polynomial(const string& coeff, const string& pow) : coefficient(coeff), power(pow), next(NULL) {}
};

// linked-list of Polynomials
struct LinkedList {
    Polynomial* head;

    LinkedList() : head(NULL) {}

    // add to end of list
    void add(const string& coeff, const string& pow) {
        if(head == NULL)
            head = new Polynomial(coeff, pow);
        else {
            Polynomial* n;
            for(n = head; n->next != NULL; n = n->next);
            n->next = new Polynomial(coeff, pow);
        }
    }

    // check if results are correct
    void print() {
        for(Polynomial* n = head; n != NULL; n = n->next)
            cout << n->coefficient << " " << n->power << endl;
    }
};

// somewhere in main()
LinkedList ll;
...
// read input values
ll.add(coeff1, pow1);
ll.add(coeff2, pow2);
ll.add(coeff3, pow3);
// check results
ll.print();

Note your Polynomial struct members need not be strings. Instead you could just parse your input and store cofficient as float and power as int (All polynomial exponents are integers).


text:
Q: Remove Orphaned Windows 2000 Server Domain Controller (VerifyEnterpriseReferences test failed) I have a Windows Server 2003 machine that is our domain controller.  It is the only domain controller (I know bad practice).  It is having some hardware issues so I want to move the domain controller to a Windows Server 2012 machine.  I ran the following dcdiag command just to make sure the domain was healthy before migrating the DC:
Dcdiag /v /c /d /e /s:SERVER001 >c:\dcdiag.log

Looking through the log, all the tests passed except for the VerifyEnterpriseReferences test.  I am receiving the following:
  Starting test: VerifyEnterpriseReferences
     The following problems were found while verifying various important DN
     references.  Note, that  these problems can be reported because of
     latency in replication.  So follow up to resolve the following
     problems, only if the same problem is reported on all DCs for a given
     domain or if  the problem persists after replication has had
     reasonable time to replicate changes.
        [1] Problem: Missing Expected Value
         Base Object:
        CN=AMPNT1,CN=Domain System Volume (SYSVOL share),CN=File Replication Service,CN=System,DC=Ampdomain,DC=com
         Base Object Description: "SYSVOL FRS Member Object"
         Value Object Attribute Name: frsComputerReference
         Value Object Description: "DC Account Object"
         Recommended Action: Check if this server is deleted, and if so
        clean up this DCs SYSVOL FRS Member Object.  Also see Knowledge
        Base Article:  Q312862

        [2] Problem: Missing Expected Value
         Base Object:
        CN=AMPNT1,CN=Domain System Volume (SYSVOL share),CN=File Replication Service,CN=System,DC=Ampdomain,DC=com
         Base Object Description: "SYSVOL FRS Member Object"
         Value Object Attribute Name: serverReference
         Value Object Description: "DSA Object"
         Recommended Action: Check if this server is deleted, and if so
        clean up this DCs SYSVOL FRS Member Object.  Also see Knowledge
        Base Article  Q312862

     ......................... SERVER001 failed test VerifyEnterpriseReferences

AMPNT1 just happens to be an old Windows 2000 Server machine.  A while back I had the DC functionality moved from it to the SERVER001 machine.  I am guessing it did not get demoted properly.
Looking at the Q312862 article referenced above in the log file I noticed it is for recovering missing objects.  I am thinking I don't need to recover the objects, but rather completely remove them.  So with a little searching I found How to remove completely orphaned Domain Controller.
I was working through the steps and I am getting stuck on step 13.  I am not seeing an entry for server AMPNT1.  Here is what I am getting:

What might I be doing wrong?  How do I go about fixing the VerifyEnterpriseReferences failed test?  Am I moving in the right direction?  Does this need to be corrected before moving the DC functionality to the Windows Server 2012 machine?
You can see in the following screenshots AMPNT1 is not found in The Domain Controllers object of Active Directory Users and Computers nor under the Servers node of Active Directory Sites and Services:

A: A better article for what you're trying to do is: How to remove data in Active Directory after an unsuccessful domain controller demotion.
Based on your screenshot of the ntfsutil command you just need to continue with the procedure. Your next step is a select site 0, followed by a list servers in site and a select server x (where x is the ordinal returned for the server you want to remove). Then you'll quit and remove selected server.
Edit:
Pardon me for doing a poor job reading.
It looks like the old AMPNT1 server has been removed from the Active Directory Sites and Services, so you're all done with ntdsutil.
To get rid of the "VerifyEnterpriseReferences" failure in the dcdiag output, use adisedit (from the Windows Support Tools) to navigate to the "Domain System Volume (SYSVOL share)" subcontainer in the "File Replication Service" container under the "System" container of the "Domain" partition of the directory. You'll find an "AMPNT1" object there. Delete that object to remove the reference that's appearing in the "VerifyEnterpriseReferences" output.
It's don't believe it's strictly necessary to clean this up before deploying a Windows Server 2012 DC, but I certainly would.


text:
Q: showing app logo on toolbar i want to put my logo an actionbar so i put an relativelayout inside toolbar which contain an image view but i got no result when its running.
(its not a icon ,so i cant use seticon() method )
<RelativeLayout
    android:layout_width="182dp"
    android:layout_height="53dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="@+id/toolbar2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.655"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/toolbar2"
    app:layout_constraintVertical_bias="0.307">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="162dp"
        android:layout_height="45dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/fragment"
        app:layout_constraintHorizontal_bias="0.443"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.016" />
</RelativeLayout>

one more thing is i have set the resource in java file
and i got error whenever i use toollbar methods (seticon,setlogo...)

java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details

A: Ok  You Have Options
1- use Toolbar with it`s material Design like this

then you need to use this code
 toolbar = (Toolbar) findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
 getSupportActionBar().setDisplayShowHomeEnabled(true);
 getSupportActionBar().setHomeButtonEnabled(true);
 toolbar.setLogo(icon);

2- deal with Tool bar as A View  Just Like Any other View If you want to change position
of the Image And texts

A: You can create a custom toolbar and add it into your activity
  getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
  getSupportActionBar().setCustomView(R.layout.custom_toolbar);
  Imageview mView = (ImageView) findViewById(R.id.title)
  mView.setImageResource(enter image here);


text:
Q: how to correctly assign the through attribute in django? I was just looking the documentation to be able to change the intermediate table but when I implement it, I get into trouble:
https://docs.djangoproject.com/en/2.0/topics/db/models/#extra-fields-on-many-to-many-relationships
The problem as such is that, although I can migrate the database and run the application, when I enter the administrator I do not visualize correctly the relationship of my models through the trough attribute (especially a field of my model called Tested).
Why does this happen and how can it be corrected?

A: This is by design. Django cannot automatically generate the widget for ManyToMany relations that use a through table because of the extra data needed (tested in your case). From Django docs:

When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.
However, we still want to be able to edit that information inline. Fortunately, this is easy to do with inline admin models.

Your best bet is to create an inline admin model as explained in the docs.


text:
Q: Handling contents of Embed tag in selenium python How can I access embedded part from web page and contents using selenium and python
<embed src="RainPastDailyMonth.php" width="100%" height="100%">

Embedded part has input button elements which I need to access using selenium but getting
Message: no such element: Unable to locate element:

{"method":"xpath","selector":"/html/body/center/b/input"}

for below code
driver.find_element(By.XPATH, '/html/body/center/b/input')

where '/html/body/center/b/input' is XPATH for input button

A: I am able to access the elements in an <embed> block by switching frame to <embed> element.
driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, 'body > embed'))

Here, 'body > embed' is selector for <embed> element.

A: You cannot.
The <embed> element creates an embedded panel in which a third-party
application can run. In other words: it is outside of the DOM. Selenium is able to operate only on items in the browser's DOM.
You will need to access this third-party application using some other means. AutoIT or Sikuli are popular options.


text:
Q: fetch data from array and save it in database I had this code
echo "
";
print_r($data);
echo "
";

through which i got the following data
Spreadsheet_Excel_Reader Object
    (
        [sheets] => Array
            (
                [0] => Array
                    (
                        [maxrow] => 0
                        [maxcol] => 0
                        [numRows] => 2
                        [numCols] => 5
                        [cells] => Array
                            (
                                [1] => Array
                                    (
                                        [1] => sno
                                        [2] => candidta name
                                        [3] => email
                                        [4] => ctc
                                        [5] => location
                                    )
                            )
                    )
            )
    )

I needed numCols so i used the following code
echo $data->sheets[0]['numCols'];

and got the result 5
Now i wish to fetch the following values
[1] => sno
[2] => candidta name
[3] => email
[4] => ctc
[5] => location

and store them in the table like this
id  value
1   sno
2   candidta name
3   email
4   ctc
5   location

Can anyone please tell how it can be done

A: $Data = array();
foreach($data->sheets[0]['cells']['1'] as $key=>$value):
    $Data[] = "('".$key."','".$value."')";
endforeach;
mysql_query("INSERT INTO tbl_name(`id`,`value`) VALUES".implode(",",$Data)) or die (mysql_error());

A: $newarray = $data->sheets[0]['cells'][1];
for ( $i=1; $i < count($newarray); $i++)
    {
        echo $newarray[$i];

        $sql= "INSERT INTO `tablename` (value) VALUES ('$newarray[$i]')";
        if(!mysqli_query($con,$sql))
            {
                echo "Error: " . $sql. "
" . mysqli_error($con);
            }
    }


text:
Q: Python: select packages to import in runtype [dynamically] I have APIs [port.py] with the same interface for two different hardware platforms: mips and powerpc. By the same interface I mean that classes are the same, thier methods are the same, but implementation differs.
mips/port.py
powerpc/port.py

A program that uses these APIs should be decoupled from the specific platform and the code looks exactly the same except importing packages. How is it possible to dynamically select the platform, something like the code below, where platform is a global setting (mips or powerpc) or whatever like this:
from [platform].port import PortCli

I tried importing with if, but it looks nasty and doesn't scale well since I may need to add a different platform.
Thank you
Update after discussion with Eduard:
The code below is actually an analogue of import mips.port:
import importlib
platform = 'mips'
myModule = importlib.import_module(platform + '.port')
myModule.Port().PrintMe()

It's fine, but I need to add myModule everywhere. Is it possible to have a similar substitute for from mips.port import Port?

A: Based on post of Python Core Developer Andrey Svetlov.
I can suggest you to add platform/hardware specific Python modules in separate directories and append this modules to sys.path in runtime.
For example:
We have a package

*

*package

*

*__init__.py

*a.py

*x86_64

*

*b.py

*i386

*

*b.py

__init__.py will contain something like this:
import sys
import platform
from os.path import join, dirname
__path__.append(join(dirname(__file__), platform.machine()))

With this approach common code is located in package while platform specific distributed in subdirectories.
Take attention that x86_64 and i368 do not have __init__.py module.
Import required module b
from package import b


text:
Q: Progress line in perl I would like to create a very simple progressbar for my script. So far I've got this, and it works. However, I cannot get it to be a percentage out of 100. My code is the following and it produces basically a dot for every 5 entries in @entries.
my $total_entries = @entries;
my $count = 0;
my $count_tens = $total_entries/0.2;
$count_tens = sprintf ('%d',$count_tens);

foreach (@entries){

    # do some stuff #

    for (1 .. $total_entries){
        if ($count == $count_tens){
            print ".";
            $count = 0;
        }
    $count++;
    }
}

I would like to have something that produces always a fixed amount of dots, regardless of the total number of entries in @entries.

A: Let's say we want 80 dots. Then:
my $number_of_dots = 80;
my @items = 0 .. 20; # or something
my $items_per_dot = @items / $number_of_dots;

STDOUT->autoflush(1);  # print everything out immediately

for my $i (0 .. $#items) {
    my $dots = $i / $items_per_dot;
    print "\r", "." x $dots;
    sleep 1; # do something
}
print "\n";

Note that we avoid rounding errors by calculating the number of dots per item anew on each iteration. The \r will move the cursor to the start of the line, so the existing dots will be overwritten each time. You can easily skip the printing if the $dots value doesn't change between iterations.

A: Rather than rewriting the wheel, you may want to use existing code that has already been written, tested and debugged.
http://metacpan.org/pod/Term::ProgressBar


text:
Q: Error installing ionic cordova
$ npm install -g cordova ionic
npm ERR! Unexpected end of input at 1:172390
npm ERR! version":"3.20.2","dependencies":
{"basic-auth":"1.0.0","connect":"2.2

npm ERR!

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Inspiron 15\AppData\Roaming\npm-cache\_logs\2017-08-
01T08_02_19_789Z-debug.log

I'm keep getting this error while trying to install cordova ionic. I've already installed node js latest version to my computer.

A: Try :
sudo apt-get install nodejs nodejs-legacy npm

And then :
sudo npm install -g cordova


text:
Q: gcc generates 32bit code on sparc I have a Solaris sparc machine and when i build my programs, it generates 32bit code which should be 64bit. How to check the cause?
$uname -a
SunOS sol 5.10 Generic_118833-33 sun4u sparc SUNW,Sun-Fire-V240
$/usr/sfw/bin/gcc --version
gcc (GCC) 3.4.3 (csl-sol210-3_4-branch+sol_rpath)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$/usr/sfw/bin/gcc test.c
$file a.out
a.out:          ELF 32-bit MSB executable SPARC Version 1, dynamically linked, not    stripped, no debugging information available
$

A: You should be able to force a 64-bit build using the -m64 option.
If that fails, you can download and install a prebuilt GCC package with 64-bit SPARC support for Solaris 10 from SunFreeware.com (download, gunzip, install with pkgadd -d gcc-...-sparc-local) which will run from /usr/local/bin/gcc.

A: OSNews - SPARC Optimizations With GCC

The creation of 64-bit code requires using the -m64 flag (-m32 for 32-bit code is implied by default).

(Yes, this is different than GCC for x86_64, which defaults to -m64 unless overridden with -m32.)


text:
Q: Truncating Text to 2 Lines with Javascript Below I've written some code that takes some content in a table cell and truncates it to two lines if it runs over. When trying to find the correct content length that is close to 2 full lines (but does not go over!) I take a logarithmic approach (I think). I first cut the content in half. I then check the content again and either add or subtract a quarter (half of the half). Etc.
Requirements:

*

*Ellipsis (...) at the end of truncated text.

*Responsive, strategy should work for dynamic width cells

Questions:

*

*In the snippet, I've included an example that results in 3 lines. How can I guarantee I land at 2 lines while getting reasonably close to 2 full lines?

*I did the logarithmic approach so I wouldn't have to do something like pop a word, retest, pop a word, retest, etc. This still seems too expensive, how can I improve this?

document.querySelectorAll('.expand').forEach(td => {

  // get cell styles
  let styles = window.getComputedStyle(td);
  let lineHeight = parseInt(styles.lineHeight, 10);

  // create test element, mostly because td doesn't support max-height
  let el = document.createElement('div');
  el.innerHTML = td.innerHTML;
  el.style.maxHeight = (lineHeight * 2) + 'px';
  el.style.overflow = 'hidden';
  td.appendChild(el);

  // if scrollHeight is greater than clientHeight, we need to do some expand-y stuff
  if (el.scrollHeight > el.clientHeight) {

    // store content
    let content = el.innerHTML.trim(),
        len = content.length;
    for (let i=Math.round(len*.5);; i=Math.round(i*.5)) {
      let over = el.scrollHeight > el.clientHeight;

      // if over 2 lines, cut by half
      // else increase by half
      over ? (len-=i) : (len+=i);

      // update innerHTML with updated content
      el.innerHTML = content.slice(0, len);

      console.log(i, len);

      // break if within margin of 10 and we landed under
      if (i<10 && !over) break;
    }

    td.innerHTML = `

${el.innerHTML.slice(0, -3).trim()}...

${content}

      <button type="button">Toggle</button>`;

    td.querySelector('button').addEventListener('click', e => td.classList.toggle('expanded'))
  }
});
html {
  font-size: 14px;
  line-height: 24px;
  font-family: Helvetica, Arial, sans-serif;
}

table {
  border-collapse: collapse;
}

td {
  white-space: nowrap;
  padding: 1rem;
}

.expand {
  white-space: normal;
}

.expand:not(.expanded) .show-expanded,
.expand.expanded .hide-expanded {
  display: none;
}

      This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content. This is some content.

A: This github repo was the best (and most terse) solution I could find. I have adapted a solution from it.
https://github.com/dollarshaveclub/shave/blob/master/src/shave.js
export default function shave(target, maxHeight, opts) {
  if (!maxHeight) throw Error('maxHeight is required');
  let els = typeof target === 'string' ? document.querySelectorAll(target) : target;
  if (!('length' in els)) els = [els];

  const defaults = {
    character: '…',
    classname: 'js-shave',
    spaces: true,
  };
  const character = opts && opts.character || defaults.character;
  const classname = opts && opts.classname || defaults.classname;
  const spaces = opts && opts.spaces === false ? false : defaults.spaces;
  const charHtml = `<span class="js-shave-char">${character}</span>`;

  for (let i = 0; i < els.length; i++) {
    const el = els[i];
    const span = el.querySelector(`.${classname}`);

    // If element text has already been shaved
    if (span) {
      // Remove the ellipsis to recapture the original text
      el.removeChild(el.querySelector('.js-shave-char'));
      el.textContent = el.textContent; // nuke span, recombine text
    }

    // If already short enough, we're done
    if (el.offsetHeight < maxHeight) continue;

    const fullText = el.textContent;
    const words = spaces ? fullText.split(' ') : fullText;

    // If 0 or 1 words, we're done
    if (words.length < 2) continue;

    // Binary search for number of words which can fit in allotted height
    let max = words.length - 1;
    let min = 0;
    let pivot;
    while (min < max) {
      pivot = (min + max + 1) >> 1;
      el.textContent = spaces ? words.slice(0, pivot).join(' ') : words.slice(0, pivot);
      el.insertAdjacentHTML('beforeend', charHtml);
      if (el.offsetHeight > maxHeight) max = spaces ? pivot - 1 : pivot - 2;
      else min = pivot;
    }

    el.textContent = spaces ? words.slice(0, max).join(' ') : words.slice(0, max);
    el.insertAdjacentHTML('beforeend', charHtml);
    const diff = spaces ? words.slice(max + 1).join(' ') : words.slice(max);

    el.insertAdjacentHTML('beforeend',
      `<span class="${classname}" style="display:none;">${diff}</span>`);
  }
}


text:
Q: Why in vuejs app prefer-const rule in vuejs app is not disabled? In  @vue/cli app I got error eslint error :
  117:11  error  'resArray' is never reassigned. Use 'const' instead     prefer-const

  pointing at line :
      let resArray = []

I disabled this error with adding rule prefer-const = 0 in package.json :
{
  "name": "yt3",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.20.0-0",
    "core-js": "^3.6.5",
    "mitt": "^2.1.0",
    "moment-timezone": "^0.5.31",
    "node-sass": "^4.12.0",
    "sass-loader": "^10.0.4",
    "vee-validate": "^3.1.0",
    "vue": "^3.0.0",
    "vue-router": "^4.0.0-rc.1",
    "vuex": "^4.0.0-rc.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-standard": "^5.1.2",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "eslint-plugin-vue": "^7.0.0-0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {
      "semi": [
        2,
        "never"
      ],
      "promise/param-names": [
        0
      ],
      "dot-notation": [
        0
      ],
      "no-trailing-spaces": [
        0
      ],
      "prefer-const": [
        0
      ]
    }
  }
}

and run command :
yarn run serve

I expected that last condition with 0 value will disable this erorr, but failed.
Which is valid syntax?
I have file : .eslintrc.js with lines :
module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/vue3-essential',
    '@vue/standard'
  ],
  parserOptions: {
    parser: 'babel-eslint'
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  }
}

Have I to edit it? How it works ?
Thanks!

A: If you already have a .eslintrc.js file I would suggest moving all your eslint config into there to prevent any conflicts with the package.json file.
You should be able to add 'prefer-const': 'off' to your rules to disable that error.
Although if you are only using resArray with array operations e.g. .push(), .pop(), .splice() etc and are not going to reassign the value e.g resArray = [] then you can use const resArray = [] instead without needing to remove the prefer-const rule.


text:
Q: varied input items in php mysql I created a html form with html and had inputs of item, comment and visible. What i would like to do is to be able to input these variables to sql by creating a code that cycles through with these protocols:
     if all fields are blank, all are filled or only one or two are filled so it can only add said filled data to mysql table.
     Example of one of the codes i used was
            if($nitem != ' ' and $comment != ' ')
{$query = "UPDATE shop.titem  SET
item = '$nitem', comment = '$comment', visible = $visible
WHERE titem.item ='$item'";
$sqlhandle = mysql_query($query, $connection);}
if (!$sqlhandle){echo 'create all failed' . mysql_error();
}else{break;}

I used the break but it keeps cycling through ALL the queries done and thats where i need help. As usual, i'm a total noob in this so i'd appreciate it if you have patience and understanding with me. Thank you.
UPDATE: i did an echo to generate sql and it returns a statement where all the codes wher run, i.e if only the item field had been edited with to eg: milk, it gives me item as milk, comment as blank and visible as 1 (i set default values as blank and visible as 1 if fields weren't filled with anything)
full code
    $item = $_POST['item'];
$nitem = $_POST['nitem'];
$comment = $_POST['comment'];
if(!isset($_POST['visible']))
{$visible = 1;}
else
{$visible = $_POST['visible'];}

     //for when all is true
if($nitem != ' ' and $comment != ' ')
{$query = "UPDATE shop.titem  SET
item = '$nitem', comment = '$comment', visible = $visible
WHERE titem.item ='$item'";
$sqlhandle = mysql_query($query, $connection);}
if (!$sqlhandle){echo 'create all failed' . mysql_error();
}else{break;}

//for when all is false
if($nitem = ' ' and $comment = ' ' )
{echo 'please go back and edit a field.';
}else{break;}

//for when nitem and comment is true
if($nitem != ' ' and $comment != ' ')
{$query = "UPDATE shop.titem SET item = $nitem, comment = $comment
WHERE item = $item";
$sqlhandle = mysql_query($query, $connection);}
if (!$sqlhandle){echo 'item and comment write failed' . mysql_error();
}else{break;}

//for when nitem only is true
if($nitem !=' ' and $comment = ' ')
{$query = "UPDATE shop.titem SET item = $nitem
WHERE item = $item";
$sqlhandle = mysql_query($query, $connection);}
if (!$sqlhandle){echo 'item write failed' . mysql_error();
}else{break;}

//for where comment only is true
if($comment != ' ' and $nitem = ' ')
{$query = "UPDATE shop.titem SET
        comment = $comment WHERE titem.item = $item";
$sqlhandle = mysql_query($query, $connection);}
if(!$sqlhandle){echo 'comment write failed' . mysql_error();
}

A: I think most of your validation checks for a space and some of them assigning spaces instead of validating (you had "=" instead of "==") , I have minimised and fixed some stuff from your code you posted and came up with following,
    $item   = $_POST['item'];
    $nitem  = $_POST['nitem'];
    $comment= $_POST['comment'];

   if(!isset($_POST['visible'])){
        $visible = 1;
   }else{
        $visible = $_POST['visible'];
   }

     //for when all is true
   if(trim($nitem)!= '' and trim($comment) != ''){
           $query = " item = '".$nitem."', comment = '".$comment."', visible = $visible ";
   }else{
           $message = 'please go back and edit a field.';
   }

   //for when nitem and comment is true
   if(trim($nitem)!= '' and trim($comment) != ''){
       $query = " item = '".$nitem."', comment = '".$comment."' ";
   }

   //for when nitem only is true
   if(trim($nitem) != '' and trim($comment) == ''){
       $query = " item = '".$nitem ."' ";
   }

   //for where comment only is true
   if(trim($comment) != '' and trim($nitem) == ''){
       $query = " comment ='". $comment ."' " ;
   }

    $mainquery = "UPDATE shop.titem  SET ". $query ." WHERE titem.item = '".$item."'";
    $sqlhandle = mysql_query($mainquery, $connection);

   if(!$sqlhandle){
      echo $message . mysql_error();
   }

If I were you, and I had this requirement I would take a different approach, but I didn't want to change your concept which will confuse you. Also I dont know whats the full requirement is.  Anyway try to adapt my code and see how it goes, I have removed all the breaks and there is only one place that sql queries get execute.
Think this will help you to fix the issue...
P.S : Always try to write readable code, it will help you in future :)


text:
Q: How can I replicate a google docs default document? I want to replicate this google docs format. Those who have a degree in latex programming please please please please please please please please please please please please please please help me.

*

*The fonts are different even though I call the usepackage function with times as the argument

*The bolding is different for the sections.

Google docs
https://docs.google.com/document/d/15AXu65Itz5TxXLLxGOKg4AZsQs6bQX_TkV7GFIImtfQ/edit

Latex
\documentclass[12pt]{article}
\usepackage{times}
\usepackage[margin=1in]{geometry}

\begin{document}

\noindent
{\large Title} \\
{\large Name (Email)} \\
\hline

\section*{Introduction}
\section*{Research Question}
\section*{Methodology}

\end{document}

A: In order to change the appearance of the sections, you can use titlesec. And I think you really want a page header. So you could do
\documentclass[12pt]{article}
\usepackage{times}
\usepackage[margin=1in,top=1.6in,headheight=1in]{geometry}
\usepackage{titlesec}
\titleformat{\section}{\Huge}{\thesection}{2em}{}
\usepackage{fancyhdr}
\renewcommand{\headrulewidth}{0.6pt}%
\pagestyle{fancy}
\lhead{\large Title\\
Name (Email)}
\begin{document}

\section*{Introduction}
Some text for the introduction.

\section*{Research Question}
Some text for the research.

\section*{Methodology}
Some text for the methodology.

\end{document}

This seems to be closer to the target output.


text:
Q: jQuery Accordion - set active panel on load depending on previous link I'm trying to figure out how to set up an accordion so that a different active panel is displayed depending which link is used to open the page.
If you look at the page I'm working on - http://testing.xenongroupadmin.com/lms/admin/index.html - you can see a navigation bar at the top. If you hover on a selection, a drop down box appears.
The first menu item, 'Course Materials' shows three options - 'Workshops', 'Distance Learning' and 'Learning Resources'. Click on any of these links and the target page opens, featuring a jQuery accordion. The titles on this accordion correlate with the three options in the nav bar.
So, to get to the point, what I want is for the appropriate accordion tab to be open depending on which link is clicked. So if I were to click 'Distance Learning' in the navigation menu, the 'materials' page would load with the Distance Learning accordion tab open.
If the 'Course Materials' link is clicked without choosing an option from the sub-menu, all accordion tabs should be closed.
Can anyone help? My server is set up for use with PHP if any server-side scripting is necessary. Also happy to use Ajax if necessary.
Thanks!

A: You can use accordions option 'active':
$('#accordion').accordion({
    active : 0
});

-1 for closed, 0 for Workshops, 1 for Distance Learning and 2 for Learning Resources

A: Have your sub menu link to materials.html with a hash tag indicating the panel to open. Like 'materials.html#workshop-slides', then use Javascript to parse location.hash on document ready and open the appropriate panel.

A: A way to do this in javascript. Pass the active tab reference in the url as #tab-0 (where the number is going to be the index of the tab). Here is a crude implementation to get you started:
$(document).ready(function() {
    var a =0;
    if(location.href.indexOf("#tab-1")) a = 1;
    if(location.href.indexOf("#tab-2")) a = 2;
    $('#accordion').accordion({collapsible : true, active : a});
});

If you want to do it from php, then you have to replace the 'none' value with the proper tab index to be opened.


text:
Q: Voice recognition based on signal/spectrum analysis I'm working on a solution to recognize an audio word by comparing the signal and spectrum.
To decode audio, I use libavcodec and libavformat and I use 1 reference word and compare to other.
Example:
# Must return true
./vrecog --file_ref chocolat.wav --file_cmp chocolat_2.wav
# Must return false
./vrecog --file_ref chocolat.wav --file_cmp banana.wav

My step:

*

*I put the signal in a std::vector

*I transform the signal into spectrum with Fast Fourier Transform

*I calculate the [min, max, average, std_deviation, variance] of my spectrum

*I use the values in step 3 to calculate a correlation coefficient
Is the reasoning correct ? The coefficient is always neer to 1 and I don't know what can I use to efficiently comparing data to says if the words is the same or not.
These are my plots:
Signals (chocolat, chocolat_2 and banana):

Spectrum (chocolat, chocolat_2 and banana):

We can easily see that the signal and spectrum seems near for both "chocolat" words, but I'm not able to get a percentage of similarity.

A: For signals, this is typically done via the cross-correlation function (of two signals) which is very similar to convolution. As such, it can be mathematically done via the FFT, which is specifically designed to be efficient. Once you take the correlation function, you can decide what threshold you want to be a "match", etc. For more information I'd read up at: http://www.aip.de/groups/soe/local/numres/bookcpdf/c13-2.pdf since what we're talking about is pretty math heavy and was taught across a few weeks in one of my college courses.


text:
Q: Enterprise batch processing of application-generated emails Here is what I perceive is our problem.
In our corporate environment, we have developed over 40 custom .Net applications (and growing). A good many of these send email notifications in some fashion. A few of these send "real time" notifications -- the user takes some action on the front end, which triggers an email sent. But most of the applications queue these notifications in a database table. A separate console app will then process these emails periodically. Note that each application has its own little console app which processes these emails. So we probably have a good 25+ little separate console apps that run all day, hitting tables in their respective application databases, using the .Net libraries to send mail.
This isn't the most horrible of things in and of itself but some applications send a TON of email -- to the tune of 100k+ per day. And if something goes wonky, we have to look at some console app to see what's the problem.
So the problem is two-fold: a) volume, and b) maintenance.
What I envision is, rather than some user action storing a mail record in the application database to be processed later by its own console app, that this action would queue it up in a central location (either send some web service request or MQ, whatever) for some central, dedicated application to process.
Basically, I think I want some optimized, centralized, enterprise email sending service where I can just hand it jillions of emails from any app. Not a email marketing software per se (although this may fall into that category) because that is more like defining templates, logging into a UI and emailing people on a list. Rather, I want to queue up mail dynamically for this thing to send. (As a bonus, other groups in our org could use this.)
I'd prefer some OTS, supported product, and not have to write it myself.
Anybody have any experience with something like this?
Thanks!
Tom


text:
Q: Parsing XML Inner XML tags Objective-C I would like to create an NSDictionary or (NSArray) full of NSDictionary objects for each station in the following XML:
<stations lastUpdate="1328986911319" version="2.0">
    <station>
        <id>1</id>
        <name>River Street , Clerkenwell</name>
        <terminalName>001023</terminalName>
        <lat>51.52916347</lat>
        <long>-0.109970527</long>
        <installed>true</installed>
        <locked>false</locked>
        <installDate>1278947280000</installDate>
        <removalDate/>
        <temporary>false</temporary>
        <nbBikes>12</nbBikes>
        <nbEmptyDocks>7</nbEmptyDocks>
        <nbDocks>19</nbDocks>
    </station>

    ... more...

    <station>
        <id>260</id>
        <name>Broadwick Street, Soho</name>
        <terminalName>003489</terminalName>
        <lat>51.5136846</lat>
        <long>-0.135580879</long>
        <installed>true</installed>
        <locked>false</locked>
        <installDate>1279711020000</installDate>
        <removalDate/>
        <temporary>false</temporary>
        <nbBikes>12</nbBikes>
        <nbEmptyDocks>4</nbEmptyDocks>
        <nbDocks>18</nbDocks>
    </station>

    ...

 </stations>

What's the best way to achieve this? Right now I have an NSDictionary with one object and one key - "stations", but I want the NSDictionary (or NSArray) of NSDictionarys.
I'm using an XML parser by Troy Brant - http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
I'm guessing it's going to involve some looping of some sort but I'm not really sure how to approach this problem. Any help or pointers in the right direction would be much appreciated.
Thanks.

A: I also use the XMLReader it is very easy to understand
I have looked at your xml, and I am assuming you wanted to use the array of station tags.
Here is my solution:
NSDictionary *dictXML= [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
NSArray *arrStation = [[dictXML objectForKey:@"stations"] objectForKey:@"station"];//this would return the array of station dictionaries

Now that you have the array of station tags you can do what you want for example displaying all id:
for(int i=0;i<[arrStation count];i++){
   NSDictionary *aStation = [arrStation objectAtIndex:i];
   NSLog(@"id = %@",[aStation objectForKey:@"id"]);
}

also you can write less code using the fast enumeration loop:
for(NSDictionary *aStation in arrStation){
  NSLog(@"id = %@",[aStation objectForKey:@"id"]);
}

hope that helps :)

A: The best way would be to create subclasses of NSObject that map to each tag. That would be way more cleaner than using Dictionaries and Arrays.


text:
Q: I am stuck with an attribute error in Brownie Python I wrote a simple code in brownie python but getting an Attribute error
from brownie import accounts
def deploy_simple_storage():
    account=accounts[0]
    print(account)
    pass

    def main():
        deploy_simple_storage()

        if _name_=="_main_":
            main()

above is the code and below is the terminal's message
INFO: Could not find files for the given pattern(s).
Brownie v1.19.1 - Python development framework for Ethereum

BrownieSimpleStorageProject is the active project.

Launching 'ganache-cli.cmd --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...
  File "C:\Users\Lenovo\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\_cli\run.py", line 51, in main
    return_value, frame = run(
  File "C:\Users\Lenovo\.local\pipx\venvs\eth-brownie\lib\site-<br>packages\brownie\project\scripts.py", line 65, in run
    raise AttributeError(f"Module '{name}' has
 no method '{method_name}'")
AttributeError: Module 'scripts.deploy' has no method 'main'
Terminating local RPC client...
PS C:\brownie_simple_storage>