text:
Q: Binary files: write with C++, read with MATLAB I could use your support on this. Here is my issue:
I've got a 2D buffer of floats (in a data object) in a C++ code, that I write in a binary file using:
ptrToFile.write(reinterpret_cast<char *>(&data->array[0][0]), nbOfEltsInArray * sizeof(float));

The data contains 8192 floats, and I (correctly ?) get a 32 kbytes (8192 * 4 bytes) file out of this line of code.
Now I want to read that binary file using MATLAB. The code is:
hdr_binaryfile = fopen(str_binaryfile_path,'r');
res2_raw = fread(hdr_binaryfile, 'float');
res2 = reshape(res2_raw, int_sizel, int_sizec);

But it's not happening as I expect it to happen. If I print the array of data in the C++ code using std::cout, I get:
pCarte_bin->m_size = 8192
pCarte_bin->m_sizel = 64
pCarte_bin->m_sizec = 128
pCarte_bin->m_p[0][0] = 1014.97
pCarte_bin->m_p[0][1] = 566946
pCarte_bin->m_p[0][2] = 423177
pCarte_bin->m_p[0][3] = 497375
pCarte_bin->m_p[0][4] = 624860
pCarte_bin->m_p[0][5] = 478834
pCarte_bin->m_p[1][0] = 2652.25
pCarte_bin->m_p[2][0] = 642077
pCarte_bin->m_p[3][0] = 5.33649e+006
pCarte_bin->m_p[4][0] = 3.80922e+006
pCarte_bin->m_p[5][0] = 568725

And on the MATLAB side, after I read the file using the little block of code above:
size(res2) = 64  128
res2(1,1) = 1014.9659
res2(1,2) = 323288.4063
res2(1,3) = 2652.2515
res2(1,4) = 457593.375
res2(1,5) = 642076.6875
res2(1,6) = 581674.625
res2(2,1) = 566946.1875
res2(3,1) = 423177.1563
res2(4,1) = 497374.6563
res2(5,1) = 624860.0625
res2(6,1) = 478833.7188

The size (lines, columns) is OK, as well as the very first item ([0][0] in C++ == [1][1] in MATLAB). But:

*

*I'm reading the C++ line elements along the columns: [0][1] in C++ == [1][2] in MATLAB (remember that indexing starts at 1 in MATLAB), etc.

*I'm reading one correct element out of two along the other dimension: [1][0] in C++ == [1][3] in MATLAB, [2][0] == [1][5], etc.

Any idea about this ?
Thanks!
bye

A: Leaving aside the fact there seems to be some precision difference (likely the display settings in MATLAB) the issue here is likely the difference between row major and column major ordering of data. Without more details it will be hard to be certain. In particular MATLAB is column major meaning that contiguous memory on disk is interpreted as detailing sequential elements in a column rather than a row.
The likely solution is to reverse the two sizes in your reshape, and access the elements with indices reversed. That is, swap the int_size1 and int_size2, and then read elements expecting
pCarte_bin->m_p[0][0] = res2(1,1)
pCarte_bin->m_p[0][1] = res2(2,1)
pCarte_bin->m_p[0][2] = res2(3,1)
pCarte_bin->m_p[0][3] = res2(4,1)
pCarte_bin->m_p[1][0] = res2(1,2)

etc.
You could also transpose the array in MATLAB after read, but for a large array that could be costly in itself


text:
Q: Anchor links in a React app work on desktop and all android browsers, but not iOS devices I load some HTML via a HTTP call and display it on site. The structure is very simple, for example

Introduction

  ...

...

1.  Introduction

Clicking the anchor redirects to a page looking like
      website.com/terms-and-conditions#intro
The links work as expected on desktop Firefox and Chrome, on a Galaxy S8 and S9 on Firefox and Chrome, but do not work on an iPhone 7 or an iPad pro on either Chrome or Safari. The page does not move, but the link is still pushed on to the browsers history, i.e., pressing the back button will navigate back and you will still be in the same place.
I have tried swapping the id attribute to a name attribute and also having both, which does not work.
Any help would be appreciated. Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change gContextMenu flags in Firefox extension In my extension I need, under certain circumstances, to display the context menu as if it had been clicked on a different element. E.g: I right-click on a certain element on a page, but the context menu should be displayed as if under the cursor there wasn't the element above, but rather a different element I specify.
I tried doing this in the popupshowing handler this by:
window.addEventListener( "load", function() {
    var contextMenu = document.getElementById("contentAreaContextMenu");
    if (contextMenu) {
        contextMenu.addEventListener("popupshowing", function(event) {
            if (document.popupNode !== newElement) {
                event.preventDefault();
                synthesizeMouse(newElement, 2, 2, { type: "contextmenu", button: 2 }, newElement.ownerDocument.defaultView);
            }
        }, false);
    }
}, false );

newElement is the element that should be "clicked on", and synthesizeMouse is defined here. Unfortunately, it doesn't work (if I actually click on newElement the context menu is shown correctly, if I click anywhere else the context menu is not shown at all). Can anybody see why this isn't working?

A: Why not set document.popupNode to your element, call gContextMenu.init(contextMenu, gBrowser); and then clear document.popupNode again?

A: This is just a bit of a wild guess, but because you're doing this while the context menu from the first event is already opening, maybe this is is blocking the context menu from opening again. Try sending the event 10ms later, so that the original context menu has already closed.


text:
Q: Expanding a multi-linear polynomial in the "correct" way Let's say I have the formula
fmla = x1^2 + (x1 + 1) (x2 + 2)

If I Expand it, I get:
In[1]:=  Expand[fmla]
Out[1]:= 2 + 2 x1 + x1^2 + x2 + x1 x2

How can I expand it, so as to get the typical expansion (all linear terms, followed by all quadratic terms, followed by all cubic terms, ..., followed by all interactions)?  That is, I want to get:
In[1]:=  MyExpand[fmla]
Out[1]:= 2 + 2 x1 + x2 + x1^2 + x1 x2

Any ideas?

A: Since summation is commutative, Mathematica arranges the terms alphabetically.
You can define a function to return a $k^{th}$ degree term and print them individually (for one's personal visual preference).
I did it like this:
fmla = x1^2 + (x1 + 1) (x2 + 2) // Expand

(* The following Module takes the vector components of {x1,x2,x3,...} \
in powers of {i1,i2,i3,...} and multiplies them. *)
M[exp_, x_, i_] :=
 Module[{exp0 = exp, x0 = x, i0 = i},
  If[Length[x] == 0, Return[exp0], exp0 = exp x[[1]]^i[[1]]];
  x0 = Delete[x, 1]; i0 = Delete[i, 1]; Return[M[exp0, x0, i0]]]

(* The following Module returns the part of the expression which is \
of order k. *)
ORD[func_, k_] := Module[{exp = 0},
  Do[exp =
    exp + If[Total[c[[1]]] == k, c[[2]] M[1, Variables[func], c[[1]]],
       0], {c, CoefficientRules[func]}];
  Return[exp]]

(* The maximum degree of polynomial: *)
DG = Exponent[fmla /. Table[xi -> x, {xi, VR}], x];

(* The following line prints different parts of the polynomial up to \
the maximum degree. *)
Do[Print["Degree #", i, ": ", ORD[fmla, i]], {i, 0, DG, 1}];

The output of the preceding code is:
2 + 2 x1 + x1^2 + x2 + x1 x2
Degree #1: 2
Degree #2: 2 x1 + x2
Degree #3: x1^2 + x1 x2

If desired, you can always use ORD[fmla,k] as a regular expression (derive, integrate, whatever). You can even add several different degrees and use them (keep up to order 2, for example), however, it'll still be arranged alphabetically.
Anyway, Mathematica doesn't care about the order of terms and does its job pretty well.


text:
Q: AWS Cognito user's attributes differ between CognitoUser object and CognitoUserSession sub-object Dev Console showing CognitoUser object obtained from amplify's Auth.currentAuthenticatedUser()
In there, you can see the CognitoUser object shows two different values for the same user attribute. The "{}" is the previous value. The value in the CognitoUserSession is correct.
Also, the user actually has another value that is not showing up anywhere here:
Actual User attributes in AWS
When I call adminGetUserAttributes on the backend, everything shows up correctly.
Can anyone explain why there is a mismatch here and possibly how to correct it?


text:
Q: SQL Application Role access-control I have been researching the use of Application Roles within Microsoft SQL Server and was wondering if there is a way to limit a user to only be able to set specific application roles. As I understand, any user of the database with sys.sp_setapprole execute permissions can set any application role they choose, as long as they provide the application role name and password. To me this seems like a trade-off in security.
For example, let's say John works in Accounting and uses an application named Accounting.exe, which is hard-coded to set the Accounting_appRole once connected to the AdventureWorks Database. Bill works in Finance and uses an application named Finance.exe, which is hard-coded to set the Finance_appRole once connected to the AdventureWorks Database.
Both John and Bill must, at a minimum, have execute permissions for the sys.sp_setapprole stored procedure of the AdventureWorks Database. Therefore, if John from accounting e-mails the Accounting.exe application to Bill in finance, Bill can execute the Accounting.exe application without issue, which is undesired.
I think there should be a way to limit who can set a specific application role, does anyone know of a way? All I can come up with is modifying the sp_setapprole stored procedure to use SUSER_SNAME() to limit the value(s) of @rolename that can be used.

A: I wouldn't recommend messing with the system stored procs.  You could wrap the sp_setapprole call in a stored proc and have your app call that proc instead.  The wrapper proc would have the password hard-coded and use EXECUTE AS to impersonate a user who can use sp_setapprole.  Then you could limit access to the wrapper proc.  Another advantage to this approach is that the password doesn't go out across the network, nor is it included in your .exe file.
EDIT:
My mistake, you can't wrap the call directly.  But you can wrap a modified version of the T-SQL that it runs.  Looking at the version in my 2008r2 server, I see that the proc calls SETUSER intead of EXECUTE AS.  Sad to see deprecated code in system stored procs.  For yours, you may want to use EXECUTE AS instead.
You could also grant rights on whatever your app needs to function to a SQL user who can't login, give certain users rights to impersonate that user, and have your app EXECUTE AS the login-less user.  This route still requires cookie handling to set the context back.  In fact, it's very similar to a customized version of sp_setapprole, since both require some sort of impersonation.
Or, you could also create a database role and grant the role to authorized users.  This seems like it might be more like what you want.  Application roles are designed for app-defined rights.  It seems like you really want user-defined rights.

A: The idea of an application role is that the privileges and the secret are given to the application that the user is using.  The user only potentially gains those privileges because they're using that application.  Any access-control decisions among users are now the responsibility of the application, not the database.  Which is the problem as you have described it.
So you need to think more deeply about what privileges you want the application to have, (contingent upon the ability of the CONNECT and EXECUTE permissions granted to the user who owns the connection).
There are probably not very many privileges in the database which you'll deny to a user, but wish to allow to the application which the user is using, despite the user themselves not having such access.
A good example is access to OAuth tokens.  In the OAuth scheme, the tokens are issued to a 'piece of software' (called the client in OAuth terminology).  These data are truly the property of the 'piece of software' itself, and not really the property of 'the users of the software'.
Consider application-roles a way for the application to keep application-private-state in the database, which is only accessible to users when they're using that application.  Don't consider application-roles as a technique to apply access-control policies which need to distinguish among users.
Then you won't encounter the scenario you described, at all.


text:
Q: Function Time Complexity hi read in a book that calling subroutines is considered to be a constant time operation, even if the subroutines itself does not execute in constant time, but depends on the input size.
Then if i have the following piece of code:
void func(int m){
int n = 10;
    subrout(m);//function which complexity depends on m
    subrout2(n);//function which complexity depends on n
}

i suppose i can consider func() to be a constant time function, e.g. O(1)?
and what if i have this:
void func(){
    int n = 10;
    Type object;
    object.member_method(n);/*member function which time complexity depends upon n*/
}

can i still consider func() a constant time function?
is there some case in which this rule falls ?
thanks!

A: No, you cannot consider func(int m) to have a constant time complexity. Its time complexity is O(T1(m) + T2(10)), where T1 and T2 are functions describing the time complexity of subrout and subrout2, respectively.
In the second case, the time complexity, technically, is constant.
As a general comment, the point of specifying time complexity with asymptotic notation is to describe how the number of operations increases as a function of input size.

A: What the book probably meant to say is that time complexity of the calling function T_func is T_call + T_callee. Here T_call is the time operation of passing parameters and setting up the environment for the callee and T_callee is the time spent inside the subroutine. The book says is that it is safe to assume T_call is constant, while no such assumptions are made regarding T_callee.
To clarify assume we have a function func that calls one subroutine callee.
  func(s){
      callee(s);
  }

then T_func(s) = T_call + T_callee(s). If size(s) = n and T_callee = O(f(n)) then it is safe to say that T_func = O(f(n)).


text:
Q: how to iterate arraylist five times but not the same numbers? I try to simulate a powerball numbers pick up program.
I can get random numbers in range but how to make it random 5 times?
looks the for loop only print result 5 times but won't go random loop once again.
here is the code
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class lottery {
    public static void main(String[] args) {
        List<Integer> whiteBalls = new ArrayList<>();
        Random rand = new Random();
        Random randi = new Random();
        //non duplicate numbers 1-69
        for(int i=0; i<5; i++){
            while(true){
                int whiteBall = rand.nextInt(69)+1;
                if(!whiteBalls.contains(whiteBall)){
                    whiteBalls.add(whiteBall);
                    break;
                }
            }
        }
        int redBall = randi.nextInt(26)+1;  //special 1-26
        for(int i=0; i<5; i++){
        System.out.println(whiteBalls + " " + redBall);
        }
    }
}

A: You are printing your results at the end 5 times. Instead of once for each element in the list. The ArrayList has a built-in toString() method that can let you print it. To fix your problem, however, you need to run your same code 5 times over instead of just printing the list 5 times as each time you print it it's still the same as the last time and has not been regenerated with 5 new values. You can simplify this task by wrapping your code in a function then simply calling that function 5 times through a for loop. Check out the code I pasted below and see if that's what you were looking for.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class lottery {
    public static void main(String[] args) {
        Random randi = new Random();
        for(int i = 0; i < 5; i++)
        {
            int redBall = randi.nextInt(26)+1;  //special 1-26
            System.out.println("Whiteball: " + generateWhiteBalls());
            System.out.println("Redball: " + redBall);
        }
    }

    public static List<Integer> generateWhiteBalls()
    {
        List<Integer> whiteBalls = new ArrayList<>();
        Random rand = new Random();
        //non duplicate numbers 1-69
        for(int i=0; i<5; i++){
            while(true){
                int whiteBall = rand.nextInt(69)+1;
                if(!whiteBalls.contains(whiteBall)){
                    whiteBalls.add(whiteBall);
                    break;
                }
            }
        }

        return whiteBalls;
    }
}


text:
Q: Reducing the spin bordism group to its Pontryagin dual of the torsion subgroup The spin bordism group for the classifying space $BG$ of group $G$ is denoted as $\Omega^{Spin}_d(BG)$. $\Omega^{Spin}_d(pt)$ are computed by Anderson-Brown-Peterson (D. W. Anderson, E. H. Brown, Jr. and F. P. Peterson, The structure of the Spin cobordism ring, Ann. of Math. 86, 271-298 (1967).).

Would you be able to illuminate the following statement, in the similar context: If a bordism group contains a free part, its Pontryagin dual has a U(1) factor. If we can ignore such continuous parameters, this is equivalent to only
  considering the torsion subgroup of $\Omega^{Spin}_d(pt)$. They are the elements of the Pontryagin dual of the torsion subgroup of $\Omega^{Spin}_d(pt)$.

Can one work on these statements explicitly to see what has been gone through and what has been thrown away, by reducing "$\Omega^{Spin}_d(pt)$" to "the Pontryagin dual of the torsion subgroup of $\Omega^{Spin}_d(pt)$"?


text:
Q: `gcloud compute instances create-with-container` is logging to stackdriver, but not including memory information? I'm spinning up a g1-small with the create-with-container command. I am able to see CPU, Network Traffic, and I/O, but not the memory. Am I missing something?

A: Here are the metrics for compute:
https://cloud.google.com/monitoring/api/metrics_gcp#gcp-compute
If you CTRL-F on "memory", there are 2 'types':

*

*/guest/memory

*/instance/memory -- these are only for e2 family (not g1-small)

For the /guest/ metrics, you should follow this guidance:
https://cloud.google.com/container-optimized-os/docs/how-to/monitoring
And then you should be able to observe e.g. guest/memory/bytes_used
You can hack your way to a solution by ssh'ing into your VM, running node-problem-detector manually and then using metrics explorer with e.g. bytes_used:

*

*gcloud compute ssh instance ...

*sudo systemctl start node-problem-detector

*sudo journalctl --unit=node-problem-detector
And:


text:
Q: Multi-Threading Tkinter Python I am trying to create an instrumental cluster using the OBDII and the tkinter as the GUI.
The problem is that, the GUI is non responsive and the draw time is very bad as I have only 1 thread.
I am new to python and the OOP concepts and is the reason I am not sure how to proceed here.
This is what I want to do, I want two threads one for the drawing while other too process the data.
Also can I use multiple threads to draw the objects too?
Any help is appreciated
import tkinter as tk
from PIL import ImageTk
from PIL import Image
import datetime
import obd

class SimpleApp(object):
    def __init__(self, master, **kwargs):
        self.master = master
        self.canvas = tk.Canvas(width=1400, height=800)
        self.canvas.pack()
        self.update = self.draw().__next__
        master.after(1, self.update)

    def draw(self):
        image_bk = Image.open("img/1.png")
        image = Image.open("img/2.png")
        image1 = Image.open("img/3.png")
        image_prnd = Image.open("img/4.png")
        angle = 2  # 0 -> 270
        angle1 = 0  # 0 -> 89
        Speed = 0
        RPM = 0
        Fuel = 0
        Temp = 0
        Time = ' '
        tkimage_bk = ImageTk.PhotoImage(image_bk)
        self.canvas.create_image(700, 400, image=tkimage_bk)
        self.canvas.create_text(100, 770, fill="white", font="BatmanForeverOutline 20 bold", text=" 70 F")
        tkimage_prnd = ImageTk.PhotoImage(image_prnd)

        while True:

            tkimage = ImageTk.PhotoImage(image.rotate(angle))
            tkimage1 = ImageTk.PhotoImage(image1.rotate(angle1))

            canvas_obj = self.canvas.create_image(690, 400, image=tkimage)
            canvas_obj1 = self.canvas.create_image(700, 400, image=tkimage1)
            self.canvas.create_image(700, 400, image=tkimage_prnd)
            self.canvas.create_text(700, 350, fill="white", font="BatmanForeverAlternate 20 bold ", text="MPH")
            self.canvas.create_text(700, 525, fill="white", font="BatmanForeverAlternate 20 bold ", text="RPM")
            self.canvas.create_text(700, 655, fill="white", font="BatmanForeverOutline 22 bold  ",  text="P  R  N      S")
            self.canvas.create_text(760, 655, fill='white', font="BatmanForeverAlternate 45  ", text="D")
            speed = self.canvas.create_text(700, 290, fill="white", font="Beyond 80  ", text=str(Speed))
            rpm = self.canvas.create_text(700, 465, fill="white", font="Beyond 65  ", text=str(RPM))
            temp = self.canvas.create_text(1250, 240, fill="white", font="BatmanForeverOutline 22   ",text=str(Temp) + " F")
            fuel = self.canvas.create_text(1250, 470, fill='white', font="BatmanForeverOutline 22  ", text=str(Fuel) + " %")
            time1 = self.canvas.create_text(1000, 770, fill="white", font="BatmanForeverOutline 20 bold", text=datetime.datetime.now().strftime("%a, %d %B"))
            time2 = self.canvas.create_text(1250, 770, fill="white", font="BatmanForeverOutline 20 bold", text=datetime.datetime.now().strftime("%I : %M : %S"))
            run_time = self.canvas.create_text(500, 770, fill="white", font="BatmanForeverOutline 20 bold",text=str(Time))
            self.master.after_idle(self.update)

            yield
            self.canvas.delete(time1)
            self.canvas.delete(canvas_obj)
            self.canvas.delete(canvas_obj1)
            self.canvas.delete(time1)
            self.canvas.delete(time2)
            self.canvas.delete(run_time)
            self.canvas.delete(temp)
            self.canvas.delete(fuel)
            self.canvas.delete(speed)
            self.canvas.delete(rpm)

            RPM = str(connection.query(cmd).value)
            RPM = RPM.split()
            RPM = int(RPM[ 0 ])

            Speed = str(connection.query(cmd1).value)
            Speed = Speed.split()
            Speed = int(Speed[ 0 ] / 1.60934)

            Temp = str(connection.query(cmd2).value)
            Temp = float(Temp.split()[ 0 ])

            Time = str(connection.query(cmd3).value)
            Time = int(Time.split()[ 0 ])

            Fuel = str(connection.query(cmd4).value)
            Fuel = int(float(Fuel.split()[ 0 ]))

            if (Speed > -1 and Speed < 21):
                angle = (Speed * 0.75)
                angle = 360 - angle
            else:
                angle = ((20 * 0.75) + ((Speed - 20) * 1.5))
                angle = 360 - angle

            if (RPM > -1 and RPM < 1000):
                angle1 = 0.016 * RPM

            else:
                angle1 = 16 + (RPM - 1000) * 0.0296

connection = obd.OBD()

cmd = obd.commands.RPM
cmd1 = obd.commands.SPEED
cmd2 = obd.commands.COOLANT_TEMP
cmd3 = obd.commands.RUN_TIME
cmd4 = obd.commands.FUEL_LEVEL

root = tk.Tk()
app = SimpleApp(root)

root.mainloop()

A: As far as I remember, tkinter incorrectly processes changes to the gui not from the main thread. But you can perform calculations in other threads and transfer to the main one.
Pay attention to the tkinter after method. Using it, you can check the data in streams at some intervals.


text:
Q: Wxpython. Выполнить скрипт в собственном браузере Почему скрипт не может работать полностью (скрипт работает в обычном браузере)? Помечен комментарием "no".
И SVG не отображается на странице.
Мне нужно через Python определить размер svg-элемента "text".
Можно как-то решить эту проблему?
import wx
import wx.html2
html_string = """
<!DOCTYPE htm>
<html>
    <head>
       <title>Hello World!</title>
    </head>
    <body>
        <svg viewBox="0 0 192 192" xmlns="http://www.w3.org/2000/svg" id="svg" height="100%" width="100%">
          <rect transform="translate(64,128)" width="27" height="64" stroke-width=".5" fill="#ff0" stroke="#000" id="rect"/>
          <text font-family="monospace" font-size="16" transform="translate(64,141)" id="tsvg">Test Text</text>
        </svg>
        <script type="text/javascript">
            var text = document.getElementById('tsvg');
            alert(text); // ok
            var tw = text.getComputedTextLength();
            alert(tw); // no
            var box = text.getBBox();
            var w = box.width;
            var h = box.height;
            alert(w+" "+ h); // no
        </script>
    </body>
</html>
"""
class MyBrowser(wx.Dialog):
  def __init__(self, *args, **kwds):
    wx.Dialog.__init__(self, *args, **kwds)
    sizer = wx.BoxSizer(wx.VERTICAL)
    self.browser = wx.html2.WebView.New(self)
    sizer.Add(self.browser, 1, wx.EXPAND, 10)
    self.SetSizer(sizer)
    self.SetSize((700, 700))
if __name__ == '__main__':
  app = wx.App()
  dialog = MyBrowser(None, -1)
  dialog.browser.SetPage(html_string, '')
  dialog.Show()
  app.MainLoop()

A: Решение: библиотека "cefpython3".
Позволяет вставлять свой браузер (chromium) в GUI на wxPython.


text:
Q: Perl remove unwanted lines from a String I am writing a perl script. I want to filter out lines that do not match a given regex. The problem is that I can not do that.
I have the following lines:
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/SeverityLevelCounter"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/FilterSet"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/util/Locale"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/CheckstyleException"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/PackageObjectFactory"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/DefaultContext"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/AutomaticBean"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/FileSetCheck"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/Filter"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/AuditListener"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/lang/StringBuilder"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/lang/Exception"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/io/File"

And I want to remove all those that do not start with com/puppycrawl/tools/checkstyle/ after the ->
So far my script looks like:
#! /usr/bin/perl -s

use File::Find;

our ($roll);

$dir = shift or die("Folder missing\n");
$prefix = shift;

$command = "javap -v";
$extension = "class";
$temp_file = "temp.tmp";

find(\&wanted, $dir);
sub wanted
{
    if ($_ =~ /\.$extension$/)
    {
        push (@class_files, $File::Find::name);
    }
}

print "digraph G\n{\n";
    print "node [shape=box]\n";

    foreach $class (@class_files) {
        $class=~ s/(.*)\..*/$1/;
        $_result= `$command $class | grep " = class"`;
        $_result=~ s/.*\/\/ */\"$class\" -> /g;

        $_line.=$_result;
    }

    $_line=~ s/"$dir\//"/g;
    $_line=~ s/\[[A-Z]?//g;
    $_line=~ s/\;//g;
    $_line=~ s/->\s*(.*)/-> \"$1\"/g;

A: Something like this maybe?
   perl -ne 'print unless /->\s+"com\/puppycrawl\/tools\/checkstyle"/' filename.txt

A: At the end of your script you can add the following line:
$_line = join("\n", grep { $_ !~ m{->\s+"com/puppycrawl/tools/checkstyle} }
                       split(/\n/, $_line) );

This (from the back to the front)
a.) splits $_line into separate lines
b.) filters out the unwanted lines with grep
c.) joins the lines again into $_line

A: Do this after you create your @class_spec list (which you can do with my @class_spec = split(/\n/, @class_files);:
# only keep the class specifiations that match the desired pattern
@class_spec = grep {
    m# -> com/puppycrawl/tools/checkstyle/#;
} @class_spec;

A: You know that you don't have to use forward slashes for the regex operator. Right?
foreach my $line (@list) {
   print "$line" if ($line =~ m(->\s+com/puppycrawl/tools/checkstyle));
}

You can use any character you want after the m:
foreach my $line (@list) {
   print "$line" if ($line =~ m#->\s+"com/puppycrawl/tools/checkstyle#);
}

or
foreach my $line (@list) {
   print "$line" unless ($line =~ m@->\s+com/puppycrawl/tools/checkstyle@);
}

etc.
That makes it a lot easier to work with regular expressions that contain slashes.
BTW, you can read in a whole file at once into an array:
open (MY_FILE, "file.txt") or die qq(A slow and painful death\n);
my @list = <MY_FILE>;
close (MY_FILE);    #No longer needed. It's in @list.

Also, I hate File::Find because it breaks every rule in module writing. I wrote my own which doesn't require you to put your whole program in a wanted subroutine or use global variables: http://db.tt/SSAw1x3.

A: perhaps something like this could help
use strict;
use warnings;

# the desired string
my $to_match = 'com/puppycrawl/tools/checkstyle/';

my $pattern = qr/   # compile the regex
    ->      # start matching from the arrow ->
    \s+     # which is followed by a space
    "       # and then a "
    $to_match   # finally the desired string
    /x;

while (my $line = <DATA>) {
    chomp $line;
    next if $line =~ /^\s*$/;
    next unless $line =~ /$pattern/;
    print $line, "\n";
}

__DATA__
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/SeverityLevelCounter"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/FilterSet"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/util/Locale"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/CheckstyleException"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/PackageObjectFactory"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/DefaultContext"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/AutomaticBean"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/FileSetCheck"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/Filter"
"com/puppycrawl/tools/checkstyle/Checker" -> "com/puppycrawl/tools/checkstyle/api/AuditListener"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/lang/StringBuilder"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/lang/Exception"
"com/puppycrawl/tools/checkstyle/Checker" -> "java/io/File"

A: Using backticks in a scalar context gives you the program output in a single string, along with the headaches about what characters can match a newline and whether a greedy regex will gobble up multiple lines. Maybe your code would be clearer if you used backticks in a list context:
foreach $class (@class_files) {
    $class=~ s/(.*)\..*/$1/;
    my @_result = `$command $class | grep " = class"`;
    s{.*// *}{"$class" -> }g foreach @_result;
    $line .= join'', @_result;
}


text:
Q: PHP curl API request works. Using explode to make array, not giving key value pairs desired Like the title says I am getting the API response just fine. I've cleaned the response data up several different ways. When attempting to use explode, I cannot get it to assign the string as the key and value pairs needed. I'll post some of the data below. If I need to delimit the data differently for ease, I will. Tried dozens of examples over the last fourteen hours. Please help!
# Find the part of the string after the description
$mysearchstring = 'color';

# Minus one keeps the quote mark in front of color
$position = (stripos($response, $mysearchstring)-1);

#This selects the text after the description to the end of the file
$after_descrip = substr($response, $position);

echo "
__________Show the data after the description________________
";
echo $after_descrip;

echo "
__________Show the cleaned data________________
";
$cleaned = $after_descrip;
$cleaned1 = str_replace('{', "", $cleaned);
$cleaned2 = str_replace('}', "", $cleaned1);
$cleaned3 = str_replace('[', "", $cleaned2);
$cleaned4 = str_replace(']', "", $cleaned3);
$cleaned5 = str_replace('https://', "", $cleaned4);
$cleaned6 = str_replace('"', "", $cleaned5);

echo $cleaned6;

echo "
__________Explode is next________________
";

#Turn the string into an array but not the array I want
$last_half = explode(':', $cleaned6);
print_r($last_half);

}
The cleaned data looks like this:
color:#3C3C3D,iconType:vector,iconUrl:cdn.coinranking.com/rk4RKHOuW/eth.svg,websiteUrl:www.ethereum.org,socials:name:ethereum,url:twitter.com/ethereum,type:twitter,name:ethereum,url:www.reddit.com/r/ethereum/
The resulting array looks like this:
Array ( [0] => color [1] => #3C3C3D,iconType [2] => vector,iconUrl [3] => cdn.coinranking.com/rk4RKHOuW/eth.svg,websiteUrl [4] => www.ethereum.org,socials [5] => name [6] => ethereum,url [7] => twitter.com/ethereum,type [8] => twitter,name [9] => ethereum,url [10] => www.reddit.com/r/ethereum/,type [11] => reddit,name [12] => ethtrader,url [13] =>
Color should be the first key, #3C3C3D should be the first value. The rest of the data should follow that format.
What do you think is the best way to go? Thank you.
-Rusty

A: You should use json_decode function. https://www.php.net/manual/en/function.json-decode.php
This function can decode json to array and object

A: So you want an array where "color" -> "#3C3C3D" ?
Thats the way:
$last_half = explode(',', $last_half);
$new_array = [];
foreach ($last_half as $item) {
    [$key, $value] = explode(':', $item, 2);
    $new_array[$key] = $value;
}

Now new array should be like you want :)
But wait, just noticed that initially you have json, so you should always go with native functions and use that to parse this string. (as the other answer says)
Best,
intxcc

A: Just one more step...
$last_half = explode(',', $cleaned6);
foreach($last_half as $item){
    list($k, $v) = explode(':', $item);
    $result[$k] = $v;
}
print_r($result);


text:
Q: How to share a library in client and server packages I am developing a full stack application with expressjs on the server and react on the front end.
Currently my code structure looks like this
project
--client
----src/
----package.json
----tsconfig.json

--server
----src/
----package.json
----tsconfig.json

I want to create a new library that holds all the common interfaces between client and server into a separate third package.
What is the right way to create this package? I tried using npm link and path references but both times I got errors.

A: you can try separately into client directory and open command line and excute "npm i package Name"


text:
Q: Node.js download and execute external script I am building a simple http client using Node.js.
I wonder how to execute a JS script downloaded from a Web server (browser mimicking):
my JS code - already tested on FF3.6 - contains both Web Workers and XMLHttpRequest Level 2.
Is Node.js capable of processing such code ?

A: You will find this in the VM module which is part of the standard library. You will find JSDOM to be useful as well.


text:
Q: Publishing Google Sheets Addon - site verification I've built a Google Sheets script that queries my company's API and outputs the data from my platform into a spreadsheet. It takes the username and password using a form and then runs an API call to output the results to Google Sheets.
When I tried to publish the addon, I received feedback that I needed to comply with Google OAuth verification. To get this verification, I need to prove that the domain is mine; although I have access to GA for our site (which isn't working for the verification), I am not the domain owner. So, I was wondering, is there a way to publish this Google addon for my company account and what are the next steps to complying with Google OAuth?


text:
Q: Installing from Github onto Kubuntu here's the question: Usually when I download programs, it's done via the Terminal using sudo apt-get or in the software center. But I want to install a screenshot saver distributed through a remote git repository
In the Readme file, I saw no instructions on how to install it. I downloaded the zip file but now I don't know what to do.

PS What I want to achieve is:
each time I press PrtSc or ctrl+prsc I save a file named
screenshot_todaysdate
to
/Dropbox/folder
and then the URL is pasted to my clipboard.

A: If you extract the files in the zip, you will find a directory named:
Scrot-and-imgur-zenity-GUI-master/src
In this directory (scr) there are 2 .sh files.
If you execute the zscreen.sh script you will get questions what kind of screenshot you will make, and if you want to upload it.
if you look into this zscreen.sh file, you will see it will store its screenshots in $HOME/Screenshots. Here you can also change the filename to something you like more.
I am not sure how to upload the screenshots to dropbox (I don't have dropbox so I'm not sure), and it gives an error that it can't find zimgur.sh.
You have to edit the zimgur.sh file and make a list/replace zimgur for uploading :)


text:
Q: Triggering Javascript Code from PHP Laravel Controller I'm using OAuth for login in my Laravel Controller. Its working fine but the thing is when the user is registered for the first time, I wanna trigger the HTML 5 geolocation API to fetch the user's current location and do some mixpanel stuff. Earlier I was using AJAX in the JS for the login so there was no such problem but now that I've implemented a complete server side solution, I'm stuck with this one problem.
The Laravel Controller code looks something like this :
       function callback(){
          \\ fetch the access token and graph data
          if($res = \Auth::mjAuthenticate('facebook', $fbData)){
                $user = \Auth::scope()->getUser();

                return \Redirect::to('events');
            }
            if (\Auth::mjRegister('facebook', $fbData)) {

                $user = \Auth::scope()->getUser();

                return \Redirect::to('events');
            }

            return $this->handleFailure('Some Problem Occured');
        }

The Earlier JS Code was  :
             ajax
                .post('auth/login', {
                    data: {
                        oauth_provider: 'facebook',
                        oauth_token: accessToken
                    },
                    cache: false
                })
                .done(function(data) {

                    mixpanel.track('User Logged In', {
                        id: data.resource.id,
                        provider: 'Facebook',
                        email: data.resource.email,
                        first_name: data.resource.first_name,
                        last_name: data.resource.last_name
                    });
                    if (data.msg == 'Resource registered') {
                      if(navigator.geolocation){
                      // Prompt for Allow Deny Geolocation popup.
                      }
                    }
                 });


text:
Q: Whats the fastest way to translate sqlite data to Google Chart format? I have a sqlite database with the following scheme
CREATE TABLE `sensor` (
    `id`    TEXT NOT NULL UNIQUE,
    `description`   TEXT
);
CREATE TABLE `temperature` (
    `time`  INTEGER NOT NULL,
    `sensor`    TEXT NOT NULL,
    `value` REAL,
    FOREIGN KEY(`sensor`) REFERENCES sensor(id)
);

with temperature values from different sensors in it. One Entry looks like
unixtimestamp|sensor-id|temperature
1459802024|sensor1|22.0

I want to plot the data with the google Chart library (line plot). The javascript ajax-calls the following php-script:
<?php

ini_set("display_errors", 1);
//header('Content-Type: application/json');
$db = new SQLite3('/file/to/sqlite/db');

$result = $db->query('SELECT * FROM sensor');
$sensors = array();
$dataTable = array();

$interval = filter_input(INPUT_GET,'interval',FILTER_VALIDATE_INT, array("options"=>array("default" => time(),"min_range"=>0)));
$starttime = time() - $interval;

while($row = $result->fetchArray(SQLITE3_ASSOC)){
    $sensors[$row['id']] = $row['description'];
}

$et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "
get available sensors: $et
";

$dataTable['cols'][] = array('id' => 'time_axis', 'label' => 'Time', 'type' => 'datetime');
$offset = 0;
foreach($sensors as $id => $description) {
    //Add Line for Sensor
    $new_column = array('id' => $id, 'label' => "$description ($id)", 'type' => 'number');
    $dataTable['cols'][] = $new_column;
    // Define your SQL statement //
    $stm = $db->prepare('SELECT time, value FROM temperature WHERE sensor=:sensor AND time >= :starttime ORDER BY time');
    $stm->bindValue(':sensor',$id,SQLITE3_TEXT);
    $stm->bindValue(':starttime',$starttime,SQLITE3_INTEGER);

    $result = $stm->execute();
    $et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
    echo "
sql sensor $offset: $et
";

    while($row = $result->fetchArray(SQLITE3_ASSOC)){
        $date = $row['time']*1000;
        $temp = $row['value'];
            $cell = array();
            $cell[] = array('v' => "Date($date)");
            for ($i = 1; $i <= $offset; $i++) {
                $cell[] = array('v' => null);
            }
            $cell[] = array('v' => $temp);
            $dataTable['rows'][]['c'] = $cell;
        }
    $et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
    echo "
complete sensor $offset: $et
";
        $offset++;
}
$json =  json_encode($dataTable);
$et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "
done: $et
";
?>

I observed that iterating through the rows takes up to 1 seconds. There are ~7k entries total and the code runs on a raspberry pi.
get available sensors: 0.0048329830169678
sql sensor 0: 0.067873001098633
complete sensor 0: 1.0311329364777
sql sensor 1: 1.0555880069733
complete sensor 1: 1.2514669895172
done: 1.4120419025421

Is there anything i could do to reduce computation time significantly ?
Reference for the data format:
https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file
https://developers.google.com/chart/interactive/docs/reference#dataparam


text:
Q: Jenkins Blue Ocean set default language? After install blue ocean , the default language is depend on browser language setting.
How can i set the default language to en_us ?
I find a way that work on Jenkins classic mode with plugin Locale Plugin,but not work on blue ocean.
second way is set url with paramter like: https://ci.jenkins-ci.org/blue/pipelines/?language=en , but it's not my best soulction.


text:
Q: Exact difference between overriding and hiding Can anybody tell the working of overriding and hiding in terms of memory and references.
class A
{
    public virtual void Test1() { //Impl 1}
    public virtual void Test2() { //Impl 2}
}
class B  : A
{
    public override void Test1() { //Impl 3}
    public new void Test2() { Impl 4}
}

static Main()
{
    A aa=new B() //This will give memory to B
    aa.Test1(); //What happens in terms of memory when this executes
    aa.Test2(); //-----------------------SAME------------------------
}

Here memory is with class B but in the second statement aa.Test2 class A's method will be called. Why is it? If B has memory then B's method should be called (in my point of view).
Any link / exercise that describes this fundamental very deeply and completely will be a big help.

A: To add to @Rawling's answer, practical examples could be shown using an example such as this:
class Base
{
    // base property
    public virtual string Name
    {
        get { return "Base"; }
    }
}

class Overriden : Base
{
    // overriden property
    public override string Name
    {
        get { return "Overriden"; }
    }
}

class New : Base
{
    // new property, hides the base property
    public new string Name
    {
        get { return "New"; }
    }
}

1. Overriding
In case of the overriden property, base class' virtual method's slot is replaced by a different implementation. Compiler sees the method as virtual, and must resolve its implementation during run-time using the object's virtual table.
{
    Base b = new Base();
    Console.WriteLine(b.Name); // prints "Base"

    b = new Overriden();
    // Base.Name is virtual, so the vtable determines its implementation
    Console.WriteLine(b.Name); // prints "Overriden"

    Overriden o = new Overriden();
    // Overriden.Name is virtual, so the vtable determines its implementation
    Console.WriteLine(o.Name); // prints "Overriden"
}

2. Hiding
When a method or a property is hidden using the new keyword, the compiler creates a new non-virtual method for the derived class only; base class' method remains untouched.
If the type of the variable is Base (i.e. only contains the virtual method), its implementation will be resolved through the vtable. If the type of the variable is New, then the non-virtual method or property will be invoked.
{
    Base b = new Base();
    Console.WriteLine(b.Name); // prints "Base"

    b = new New();
    // type of `b` variable is `Base`, and `Base.Name` is virtual,
    // so compiler resolves its implementation through the virtual table
    Console.WriteLine(b.Name); // prints "Base"

    New n = new New();
    // type of `n` variable is `New`, and `New.Name` is not virtual,
    // so compiler sees `n.Name` as a completely different property
    Console.WriteLine(n.Name); // prints "New"
}

3. Summary
If a part of your code accepts the base type, it will always use the virtual table during run-time. For most OOP scenarios, this means that marking a method as new is very similar to giving it a completely different name.
4. Object sizes after instantiation
Note that instantiating any of these types doesn't create a copy of the virtual table. Each .NET object has a couple of bytes of header and a pointer to the virtual table of table of its type (class).
Regarding the new property (the one which is not virtual), it is basically compiled as a static method with thiscall semantics, meaning that it also doesn't add anything to the size of the instance in memory.

A: Take a look at this answer to a different question by Eric Lippert.
To paraphrase (to the limits of my comprehension), these methods go into "slots". A has two slots: one for Test1 and one for Test2.
Since A.Test1 is marked as virtual and B.Test1 is marked as override, B's implementation of Test1 does not create its own slot but overwrites A's implementation. Whether you treat an instance of B as a B or cast it to an A, the same implementation is in that slot, so you always get the result of B.Test1.
By contrast, since B.Test2 is marked new, it creates its own new slot. (As it would if it wasn't marked new but was given a different name.) A's implementation of Test2 is still "there" in its own slot; it's been hidden rather than overwritten. If you treat an instance of B as a B, you get B.Test2; if you cast it to an A, you can't see the new slot, and A.Test2 gets called.

A: Already answered at here
Overriding is the definition of multiple possible implementations of the same method signature, such that the implementation is determined by the runtime type of the zeroth argument (generally identified by the name this in C#).
Hiding is the definition of a method in a derived type with a signature identical to that in one of its base types without overriding.
The practical difference between overriding and hiding is as follows:
Hiding is for all other members (static methods , instance members, static members). It is based on the early binding . More clearly , the method or member to be called or used is decided during compile time.
•If a method is overridden, the implementation to call is based on the run-time type of the argument this.
•If a method is simply hidden, the implementation to call is based on the compile-time type of the argument this.
Here are some samples : Example # 1. and Example # 2

A: Test1() method in class A and test1() method in class B will executes according to MethdOverriding.
Test2() method in class A and test2() method in class B will executes according to Method Hiding.
In method Overriding the child class members will execute, and in Method Hiding the Parent class members will execute.

A: Deducting from the code provided you should have B:A.
You can hide a method in case when you want create your own implementation of the (say) method of the base class, which can not be overriden, cause, say, it's not virtual.
In my expirience, I used hiding  mostly for debug purposes.
For example when I don't know who sets the property of some 3rd prt component, whom code is not available to me. So what I do is:

*

*create a child class from the component

*hide the property of interest with new keyword

*put the breakpoint in set

*and wait when it will be hit.

Sometimes, very useful and helps me get information in fast way, especially in first stage when you're learning new components, frameworks, libraries.. whatever.

A: Put simply when overriding a method or property the override method must have the same signature as the base method. When hiding this is not required, the new object can take any form as shown below
// base
    public int GrossAmount { get; set; }

    // hiding base
    public new string GrossAmount
    {
        get;
        set;
    }

A: By hiding a method or a property you are simply stating that you want to stop such method being polymorphic when you have an object of that type. Additionally hidden methods are called in a non polymorphic way so to call these method type has to be know at compile time, as it was a simply non virtual method.

A:  public class BaseClass
    {
      public void PrintMethod()
      {
       Console.WriteLine("Calling base class method");
      }
     }
     public class ChildClass
     {
      public new void PrintMethod()
      {
       Console.WriteLine("Calling the child or derived class method");
       }
      }
      class Program
      {
       static void Main()
       {
        BaseClass bc = new ChildClass();
        bc.PrintMethod();
        }
       }

Method Hiding is that when Base Class reference variable pointing to a child class object. It will invoke the hidden method in base Class.
Where as, When We declare virtual method in the base class. We override that method in the derived or child class. Then Base Class reference variable will call the derived class method. This is called Method Overriding.

A: class Base {
    int a;
    public void Addition() {
        Console.WriteLine("Addition Base");
    }
    public virtual void Multiply()
    {
        Console.WriteLine("Multiply Base");
    }
    public void Divide() {
        Console.WriteLine("Divide Base");
    }
}

class Child : Base
{
    new public void Addition()
    {
        Console.WriteLine("Addition Child");
    }
    public override void Multiply()
    {
        Console.WriteLine("Multiply Child");
    }
    new public void Divide()
    {
        Console.WriteLine("Divide Child");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Child c = new Child();
        c.Addition();
        c.Multiply();
        c.Divide();

        Base b = new Child();
        b.Addition();
        b.Multiply();
        b.Divide();

        b = new Base();
        b.Addition();
        b.Multiply();
        b.Divide();
    }
}

Output : -
Addition Child
Multiply Child
Divide Child
Addition Base
Multiply Child
Divide Base
Addition Base
Multiply Base
Divide Base
At the time of overriding the compiler checks the object of the class but in
in hiding compiler only checks the reference of the class


text:
Q: C Syntax related to fgetc() and ungetc() In my code I am trying to accomplish something like this (written in pseudocode):
While not at EOF:
    Get line
    Write line to different file
    Skip 30 bytes

Currently, the best way I can think of to do this is something like this:
int c;
while((c = fgetc(stream)) != EOF){
     ungetc(c,stream);
     REST OF CODE

Is there a better way to check if I am at the EOF but still use the character that I am currently reading?

A: You might want to call fgetc outside of the loop conditional:
int c = fgetc(stream);
while(c != EOF){
    ....
    c = fgetc(stream);
}

A: You can use fgetc like this:
while ((c = fgetc(fp)) != EOF) {
    ...
}

OR, since you want to read lines (as your pseudocode says), you can use fgets:
char *fgets(char *s, int size, FILE *stream);

And you would use it as:
char *buffer = malloc(500);

while (fgets(buffer,500, fp)) {
    // treat line here
}

From the manual:

fgets() reads in at most one less than size characters from stream
         and stores them into the buffer pointed to by s.  Reading stops after
         an EOF or a newline.  If a newline is read, it is stored into the
         buffer.  A terminating null byte ('\0') is stored after the last
         character in the buffer.

And the return:

fgets() returns s on success, and NULL on error or when end of file
         occurs while no characters have been read.

This means the return of the fgets function can be used as the condition for the while loop (so you don't need to do the != EOF).

EDIT (bonus): As for you pseudocode of skip 30 bytes, you may want to take a look at the fseek function manual.


text:
Q: Custom Filter in cPanel to Auto-Delete Emails with Russian Characters I get a lot of spam to my email account from Russia. The emails themselves (name, subject, body) are in Russian and I was hoping to create a custom filter in cPanel (not in SpamAssassin but in cPanel itself) to catch these emails and delete them before they hit my inbox. I've tried setting up rules to flag emails with these characters but they still are getting through. This leads me to believe that there is an encoding issue at play here. Unfortunately I do not know how to overcome this. Ideas?
I already have Spamassassin configured to delete emails with a .ru TLD. These emails have other TLDs like .com, etc.

A: s/a has a setting for languages,  there is usually comments in the s/a folder - user prefs file, add this
ok_locales en          (only allow English)
see-
http://spamassassin.apache.org/full/3.1.x/doc/Mail_SpamAssassin_Conf.html
(user prefs)
will/dallas


text:
Q: Reading csv file and want to skip first two columns I am trying to read a CSV file in Python. Further I want to read my whole file but just don't want first two columns. Also I don't have columns name so that I can easily drop or skip it.
What code do I need to read the file without reading first two columns?
I have tried below code:
with open("data2.csv", "r") as file:
    lines = [line.split() for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))

I am just reading file line by line from above code. But how to skip first two columns and then read the file? I don't have names of the columns.

A: You should use the csv module in the standard library. You might need to pass additional kwargs (keyword arguments) depending on the format of your csv file.
import csv

with open('my_csv_file', 'r') as fin:
    reader = csv.reader(fin)
    for line in reader:
        print(line[2:])
        # do something with rest of columns...

A: if the lines list does getting the data you want you can use slicing to get rid of the columns you don't want:
getting rid of first two:
lines[2:]
getting rid of last two:
lines[:-2]
with open("data2.csv", "r") as file:
    lines = [line.split()[2:] for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))


text:
Q: How to set the permission right of static files on the site? I have a special web page for members.
I am publishing with IIS 10 on Windows server 2016.
Through the website, members upload their private documents to the site.
For example:
http://mywebpage.com/upload/xuser/a.jpg
http://mywebpage.com/upload/xuser/b.pdf
http://mywebpage.com/upload/yuser/c.pdf
http://mywebpage.com/upload/yuser/abc/d.pdf

I use these files in html tags with classic asp. For example;
yuser transcript

Profile

But I want these files to be accessible only by *.asp files under "http://mywebpage.com".
The possibility that users can access it by typing the link directly into the address bar annoys me very much.
For this, I used the following ways. But I still don't feel safe.

*

*Disallow all files in /upload/ directory with robots.txt.

*Prevent browsing to /upload/ with web.config.

*Using a complex directory name and complex filenames with the user id and not the yuser. /upload/ASDASD12djd829D2/DUJA811220.jpg
But these are still not the solution I want. Is it possible to say that no one can read these static files except just http://mywebpage.com/*.asp pages? What path should I follow?


text:
Q: Working on getting GPS to start when a widget is pressed After following a tutorial on SO I found a way to get GPS to enable after a person goes into my app. The issue being is that I have the code set up to change the display for lat and lon to change as the user changes position. I know it works because I have my first GPS running smooth. Right now I am trying to implement it on my existing code.
Aside the point when I run the code the GPS Icon flashes like it working but when I go into the app nothing changes.
Here is the code I was using:
    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    sendBroadcast(intent);

Any tips on getting this to fully function please do tell!

A: A better solution to your problem is to ask user to enable GPS himself. Doing it without user's permission can be pretty harmful, imagine that a device's battery is almost empty and enabling GPS will kill the battery right away. To ask user to enable GPS you can fire an AlertDialog, create an Intent with the ACTION_LOCATION_SOURCE_SETTINGS to open the device's Settings menu, where the user will be able to enable GPS. Hope this helps.


text:
Q: Android - How to reopen an app few seconds after it is minimized by the home button? I need my application (minimized by the home button) to be active again on the screen after 10 seconds.
The idea is to always keep the application on the screen. If the user needs to leave my app (by home button), the app will quickly return to the screen.
Is it possible to show an application minimized by the user programmatically?

A: Since you control the environment, Android has APIs for this use case:
https://developer.android.com/work/dpc/dedicated-devices/lock-task-mode?hl=en


text:
Q: How to replace double/more letters to a single letter? I need to convert any letter that occur twice or more within a word with a single letter of itself.
For example:
School -> Schol
Google -> Gogle
Gooooogle -> Gogle
VooDoo -> Vodo

I tried the following, but stuck at the second parameter in eregi_replace.
$word = 'Goooogle';
$word2 = eregi_replace("([a-z]{2,})", "?", $word);

If I use \\\1 to replace ?, it would display the exact match.
How do I make it single letter?
Can anyone help? Thanks

A: Not only are you capturing the entire thing (instead of just the first character), but {2,} rematching [a-z] (not the original match). It should work if you use:
$word2 = eregi_replace("(\w)\1+", "\\1", $word);

Which backreferences the original match. You can replace \w with [a-z] if you wish.
The + is required for your Goooogle example (for the JS regex engine, anyway), but I'm not sure why.
Remember that you will need to use the "global" flag ("g").

A: See regular expression to replace two (or more) consecutive characters by only one?
By the way: you should use the preg_* (PCRE) functions instead of the deprecated ereg_* functions (POSIX).
Richard Szalay's answer leads the right way:
$word = 'Goooogle';
$word2 = preg_replace('/(\w)\1+/', '$1', $word);

A: Try this:
$string = "thhhhiiiissssss hasss sooo mannnny letterss";
$string = preg_replace('/([a-zA-Z])\1+/', '$1', $string);

How this works:
/ ... /    # Marks the start and end of the expression.
([a-zA-Z]) # Match any single a-z character lowercase or uppercase.
\1+        # One or more occurrence of the single character we matched previously.

$1
\1+        # The same single character we matched previously.


text:
Q: Making lists from a dict of lists I have this dict:
{'Hours Outside Sprint': [5.25, 5.0, 0.0],
 'Sprint End': ['2017-02-14', '2017-02-14', '2017-02-14'],
 'Sprint Start': ['2017-01-31', '2017-01-31', '2017-01-31'],
 'Status': ['done', 'done', 'done'],
 'Story': ['SPGC-14075', 'SPGC-9456', 'SPGC-9445'],
 'Story Actual (Hrs)': [11.0, 12.75, 0.0],
 'Story Estimate (Hrs)': [16.0, 12.0, 0.0]}

I think this is a fairly simple task but the solution is not apparent at the moment. What I want to do is iterate through this dict and make the following:
[[done, 2017-02-14, SPGC-14075, 16.0, 5.25, 2017-01-31, 11.0], ... ]

So all the 1st elements of each list go together, all the 2nd, and so on until I have a list of lists. How do I do this?
EDIT:
Here is what the pandas dataframe looks liek that produced the above dict:
Story Status  Story Estimate (Hrs)  Story Actual (Hrs)  Hours Outside Sprint Sprint Start  Sprint End
0  SPGC-14075   done                  16.0               11.00                  5.25   2017-01-31  2017-02-14
1   SPGC-9456   done                  12.0               12.75                  5.00   2017-01-31  2017-02-14
2   SPGC-9445   done                   0.0                0.00                  0.00   2017-01-31  2017-02-14

Would iterrows work?

A: Here's how I would do this in Python:
df_dict = {'Status': [u'done', u'done', u'done'], 'Sprint End': ['2017-02-14', '2017-02-14', '2017-02-14'], 'Story': [u'SPGC-14075', u'SPGC-9456', u'SPGC-9445'], 'Story Estimate (Hrs)': [16.0, 12.0, 0.0], 'Hours Outside Sprint': [5.25, 5.0, 0.0], 'Sprint Start': ['2017-01-31', '2017-01-31', '2017-01-31'], 'Story Actual (Hrs)': [11.0, 12.75, 0.0]}

result = []
lengthOfFirstArrInDict = len(df_dict[df_dict.keys()[0]])

for i in range(0, lengthOfFirstArrInDict):
    nestedList = []

    for key in df_dict.keys():
        nestedList.append(df_dict[key][i])

    result.append(nestedList)

print(result)

And here's the output:
[['done', '2017-02-14', 'SPGC-14075', 16.0, 5.25, '2017-01-31', 11.0], ['done', '2017-02-14', 'SPGC-9456', 12.0, 5.0, '2017-01-31', 12.75], ['done', '2017-02-14', 'SPGC-9445', 0.0, 0.0, '2017-01-31', 0.0]]

A: df.iterrows makes a pretty neat solution. Make sure to slice out the row index: (i[0] = row_index; i[1] = row_values)
df = pd.DataFrame(df_dict)

#re-order columns (may not be necessary depending on your original df)
df = df[['Status','Sprint End','Story','Story Estimate (Hrs)','Hours Outside Sprint','Sprint Start','Story Actual (Hrs)']]
values = [i[1].tolist() for i in df.iterrows()]

A: Whenever you need to combine successive elements from two or more sequences in Python, think zip():
from pprint import pprint

data = {'Hours Outside Sprint': [5.25, 5.0, 0.0],
        'Sprint End': ['2017-02-14', '2017-02-14', '2017-02-14'],
        'Sprint Start': ['2017-01-31', '2017-01-31', '2017-01-31'],
        'Status': ['done', 'done', 'done'],
        'Story': ['SPGC-14075', 'SPGC-9456', 'SPGC-9445'],
        'Story Actual (Hrs)': [11.0, 12.75, 0.0],
        'Story Estimate (Hrs)': [16.0, 12.0, 0.0]}

# desired order of items in the result
key_order = ('Status', 'Sprint End', 'Story', 'Story Estimate (Hrs)',
             'Hours Outside Sprint', 'Sprint Start', 'Story Actual (Hrs)')
pprint([x[0] for x in zip(data[k] for k in key_order)])

Output:
[['done', 'done', 'done'],
 ['2017-02-14', '2017-02-14', '2017-02-14'],
 ['SPGC-14075', 'SPGC-9456', 'SPGC-9445'],
 [16.0, 12.0, 0.0],
 [5.25, 5.0, 0.0],
 ['2017-01-31', '2017-01-31', '2017-01-31'],
 [11.0, 12.75, 0.0]]

A: map(lambda x: list(x),zip(*map(lambda (k,v): v, df_dict.iteritems())))

or
map(lambda x: list(x),zip(*df_dict.values()))

you could strip absolving method call one by one to see what you got each step
It's no more than transforming of your data.
*df_dict.values() means you could pass a list as parameters for a function that needs arguments likes this:
def fun(arg1, arg2, arg3 ...)

A: You can try this:
df_dict = {'Status': [u'done', u'done', u'done'], 'Sprint End': ['2017-02-14', '2017-02-14', '2017-02-14'], 'Story': [u'SPGC-14075', u'SPGC-9456', u'SPGC-9445'], 'Story Estimate (Hrs)': [16.0, 12.0, 0.0], 'Hours Outside Sprint': [5.25, 5.0, 0.0], 'Sprint Start': ['2017-01-31', '2017-01-31', '2017-01-31'], 'Story Actual (Hrs)': [11.0, 12.75, 0.0]}

vals = df_dict.values()

final_data = list(map(list, zip(*vals)))

print(final_data)

Output:
[[16.0, 5.25, 11.0, '2017-02-14', 'done', 'SPGC-14075', '2017-01-31'], [12.0, 5.0, 12.75, '2017-02-14', 'done', 'SPGC-9456', '2017-01-31'], [0.0, 0.0, 0.0, '2017-02-14', 'done', 'SPGC-9445', '2017-01-31']]


text:
Q: ie6 hover and jquery error Can anyone see why this would not work in IE6. The hover image is not displaying at all nor is if I substitute for background-color. I have tried absolute and relative paths. I would be grateful if someone could point out my error. Thank you.
CSS
.buttonMailTrue:hover {
    width:290px;
    height: 44px;
    background: url('http://localhost/sample/users/images/mail_icon_strip_hover.png') no-repeat;
    background-repeat: no-repeat;
}

JS

HTML

    $subject;

        $rowdate

    span style="font-weight:bold;margin-top:50px;">$from

A: Try this:

*

*Change ".buttonMailTrue:hover" to ".hover"

*Add a "<" to the start of your SPAN tag.

*Remove "background-repeat: no-repeat;" from your CSS as you're declaring it twice.

*Add in some background position values to your CSS.


text:
Q: Algolia: Filter if attribute exists For the below data
[
  {
    "name": "iPhone XR Black 64GB",
    "color": "red"
  },
  {
    "name": "iPhone XS Gold 64GB",
    "color": "blue"
  },
  {
    "name": "Galaxy Note9 Ocean Blue 128GB",
  },
  {
    "name": "G7 ThinQ™ Platinum Gray 64GB",
  },
  {
    "name": "Moto E5 Play 16GB",
  }
]

If I filter color:red it should return the records matching the following criterias.

*

*If the color attribute exists it should be red.

*If the color attribute doesn't exist.

Output would be
[
  {
    "name": "iPhone XR Black 64GB",
    "color": "red"
  },
  {
    "name": "Galaxy Note9 Ocean Blue 128GB",
  },
  {
    "name": "G7 ThinQ™ Platinum Gray 64GB",
  },
  {
    "name": "Moto E5 Play 16GB",
  }
]

Click here for flow chart

A: Algolia is a search engine, meaning that it returns matching records as is. It doesn't perform any transformations, and you can't inject logic into the engine's behavior.
With your above dataset, if you run an empty search ('') with a filter "color:red", Algolia will only return the following record:
{
  "name": "iPhone XR Black 64GB",
  "color": "red"
}

If you want all records (in the limit of 1,000 records), you need to perform an empty query with no filters.


text:
Q: Handling an automatically uploaded file I have a simple ASP.NET page that users can browse to, select a file from their machine and upload it to my server.  My remote users wish to automate uploading of files (using CURL) at their end.
As there is no user to click a button I need to do something to handle this, but what?
What changes do I need to make to have my web page handle the file upload without clicking a button?
Code Page...
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace FileUpload
{
    public partial class _Default : System.Web.UI.Page
    {
        string UploadTo_Path = ConfigurationManager.AppSettings.Get("UploadTo_Path");
        protected System.Web.UI.HtmlControls.HtmlInputFile File1;
        protected void Page_Load(object sender, EventArgs e){ }
        protected void Button1_Click(object sender, EventArgs e)
        {
            UploadFile();
        }
        private void UploadFile()
        {
            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                UploadTo_Path += "\\" + fn;
                File1.PostedFile.SaveAs(UploadTo_Path);
                Response.Write("The file has been uploaded.");
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }
        }
    }
}

Front End...
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUpload._Default" Trace="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>File Upload</title>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
        <input type="file" id="File1" name="File1" runat="server" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>

A: I'd do this differently.
I'd check if the page was accessed using POST and then run UploadFile(), I wouldn't use button with a click handler.
On the client side the form would just do a normal form submit (a POST) to the page.
This then lets CURL also access the page directly, without the need to do anything clever with JavaScript (which could be disabled and CURL doesn't do).

A: You can fire with javascript for example on load of page or another event of your choice
"document.getElementById(' " + FileUpload1.ClientID+ "').click()"

A: If it were me, I'd set up a web service with authentication.   I'm thinking you are opening up the ability to allow anyone to jam files into your server without a HttpHandler validating the files being uploaded.


text:
Q: How to declare get and set accessors of a List property of a class I have a Teacher class  which has a property
class Teacher:Employee
    {
        //private List<string> SubjectTaughtList = new List<string>();

        public string SubjectTaught { get; set; }

        public string Qualification{ get; set; }

        public Teacher() { }

        public Teacher(string id,string title, string fn,string ln, DateTime dob,
                       string gender,string houseno,string street,string city,string county,
                       string phone,string workPhone, string email,string workEmail,DateTime doj,
                       string status,decimal sal,List<string> subject,string qualification)
            : base(id, title, fn,ln, dob, gender,houseno,street,city,county, phone,
                   workPhone, email, workEmail, doj, status, sal)
        {
            SubjectTaught = subject;
            Qualification = qualification;
        }
    }

I want to create a list for SubjectTaught as it will have more than one value. I am creating a checkedListbox in windows form but I don't know how to get and set the property.
I think it should be read-only as I already have the values for the list for eg Art,Law,etc or may be I am wrong as I the list will be created as per the checked listbox.
I am new to C# so I am at beginner level so very confused as to how  it will work. Please advise

A: For .NET 3.5
Even if you have readonly property of type List, it can be modified from outside of the object, because it is reference type. For better encapsulation use IEnumerable if you don't need indexer and Count. Such object cannot be modified from the outside of the class, except items, these can be modified even it is IEnumerable. IEnumerable can be hacked by casting back to the List and then modified.
public IEnumerable<string> SubjectTaught  { get; }

Or you can use ReadOnlyCollection. This will provide you Count property + indexer, which is not included in IEnumerable. All changes of ReadOnlyCollection apply to the wrapper not to the original collection, it means the encapsulation goes even far.
private List<string> _subjectTaught;

public ReadOnlyCollection<string> SubjectTaught
{
   get{ _subjectTaught.AsReadOnly();}
}

For .NET 4.5
In NET Framework 4.5 you can use IReadOnlyCollection which is implemented by List and by ReadOnlyCollection as well. Usage of AsReadOnly + IReadOnlyCollection prevent caller from modifying the IReadOnlyCollection after casting IReadOnlyCollection back to List, because all changes are made to AsReadOnly wrapper, not the collection itself.
private List<string> _subjectTaught;

public IReadOnlyCollection<string> SubjectTaught
{
   get{ _subjectTaught.AsReadOnly();}
}

Returning only IReadOnlyCollection as interface of List doesn't provide the readonly wrapper and thus enable a hack by casting the property back to List and modifying the original collection:
private List<string> _subjectTaught;

public IReadOnlyCollection<string> SubjectTaught
{
   get{ _subjectTaught;}
}

See comparing IReadOnlyCollection and ReadOnlyCollection.
For better understanding try this example:
public class MyClass
{
    private List<string> _list = new List<string>();

    public MyClass()
    {
        _list.Add("banana");
        _list.Add("orange");
        _list.Add("apple");
    }

    public IReadOnlyCollection<string> ReadOnly
    {
        get { return _list; }
    }

    public IReadOnlyCollection<string> ReadOnlyWithWrapper
    {
        get { return _list.AsReadOnly(); }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass my = new MyClass();

        //modify by hack
        ((List<string>)my.ReadOnly).Add("Cherries");

        Console.WriteLine("no wrapper");

        foreach (var item in my.ReadOnly)
        {
            Console.WriteLine(item); //will include cherries
        }

        Console.WriteLine("with wrapper");

        MyClass my2 = new MyClass();

        //cannot be modify by hack, unless reflection is used
        //throw InvalidCastException
        ((List<string>)my2.ReadOnlyWithWrapper).Add("cherries");
    }
}

NOTES:
Thanks to Scott Chamberlain's comment about IReadOnlyCollection in .NET 4.5


text:
Q: Why does hardware encoding in FFMPEG result in lower quality when using CRF, which is supposed to be quality-based? I've recently been encoding videos using FFMPEG through the Shutter Encoder GUI. I've been using CRF as a quality indicator, since I don't care about filesize as long as it is encoded as efficiently as possible. The H.264 encoding guide says to "Consider 17 or 18 to be visually lossless or nearly so", but when I use hardware acceleration, it results in a significant drop in quality, even though the CRF hasn't changed. I understand that GPUs require a higher bitrate to achieve the same quality, but CRF controls quality, so I would've expected the quality to remain the same while the file size increases.

A: Because hardware encoding uses fixed function blocks which are far less versatile and adaptable than software encoders.
Hardware encoders will always be worse than software encoders, unless they are specifically tuned to produce high quality results which would result in them having far higher complexity and therefore cost in terms of both silicon real estate and development time.
It might be the only job a hardware encoder can do, but it requires a massive amount of real-estate to achieve the same level of complexity as a full-featured software encoder. It will have shortcuts and trade-offs in order to keep complexity down.
As a result the software encoder will get better results 99 times out of 100.
The hardware encoder in your graphics card is enough to do the job, to do it quickly. It is a great choice where speed is key and where quality loss for a given bandwidth (or greater bandwidth for given quality) is acceptable.
If you need a high quality hardware encoder then you will be paying more for it.
You'll find more information at Hardware vs. Software Encoders for Live Streaming: Your Options Explained [2021 Update]

A: To add upon the answer by @Mokubai:
H.264 is a video encoding norm, and there exists different encoders (or codecs) that can produce H.264 video streams. The most widely known is x264, which is the default encoder in ffmpeg. It runs on CPU only. There exist also H.264 encoders that run on GPU, and they are generally provided by the GPU vendors: QSV for Intel integrated GPUs, nvenc for Nvidia GPUs, etc...
Using the "hardware acceleration" is definitely not using the same encoder ported to a GPU (or to any other hardware accelerator), it's actually using fully different encoder (since you are on a Mac I'm not sure which one is selected by your software, I know that Apple provides its own encoder). And the point is that not only the algorithms are different, but also the parameters do not match between them: e.g. the crf parameter in an encoder does not necessarily have the same effect in another encoder, and the same value can result in completely different effective quality (the parameters and their scales are not standardized).


text:
Q: How does activerecord change model associations in rails? I at one point had a simple model where a recipe had many photos, yet I was only creating Recipe objects by setting one photo through carrierwave on the recipe.photo attribute rather than through recipe.photos.
This was in part because I didn't realize I had specified has_many. I was creating Recipe objects through rails_admin gem by assigning to the recipe.photo attribute rather than recipe.photos.
class Recipe < ActiveRecord::Base
  validates :title, :content, presence: true
  belongs_to :category
  has_many :photos, class_name: 'RecipePhoto', dependent: :destroy
  mount_uploader :photo, RecipePhotoUploader
  accepts_nested_attributes_for :photos, allow_destroy: :true
end

class RecipePhoto < ActiveRecord::Base
  belongs_to :recipe
  mount_uploader :photo, RecipePhotoUploader
end

So my question is when I began assigning to recipe.photos and then were to access a recipe instances photos via recipe.photos
I would only see photos that were created onto recipe.photos, and not recipe.photo.
Why is this? Shouldn't ActiveRecord access ALL associated photos to the recipe with notation recipe.photos?
Why does it treat it as recipe.photo were assigned via a has_one relationship even though it was has_many the whole time?
Shouldn't ActiveRecord be robust to changing relationships? Like if it at a later date and wanted to change it to has_one, etc.


text:
Q: Manual Elmah Logging dosnt work properly in MVC I used ELAMH 1.2 to log errors in MVC 5. It work well for 404 500... HTTP errors and in controller's catch blocks.
public ActionResult Index()
    {
        Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("test"));
        try
        {
            var a = 0;
            var b = 1 / a;
        }
        catch(Exception e)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(e);
        }
        return View();
    }

i get two log for this code.
but it dosent work in a static class like below. i dont get any exception while running ErrorSignal.FromCurrentContext().Raise(e);.
public static class FileUtility
{
    public static string SaveSampleFile(HttpPostedFileBase file)
    {
        try
        {

            var b = 0;
            var  a = 1/b;
        }
        catch (Exception e)
        {
            ErrorSignal.FromCurrentContext().Raise(e);
            return null;
        }
    }

}

no error log nothing happen!

A: I have also seen this problem when calling ELMAH logger without any HttpContext in class library projects.
I used the old manual way to get around this:
Elmah.ErrorLog.GetDefault(null).Log(new Error(ex));


text:
Q: In iPhone, is it guaranteed that viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear are always called? I'm using viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear of UIViewController.
And I use UINavigationController to navigate view controllers.
For example, I create NSTimer or register notifications in viewWillAppear or viewDidAppear. And I invalidate the timer or remove notifications in viewWillDisappear or viewDidDisappear.
But if those 4 methods (viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear) are not called, the program will crash or retain cycle will happen.
I couldn't find the documentation saying that it is guaranteed that viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear are always called.
Till now, they seem to be always called and my program works as I expected.
But are there cases that the 4 methods are not called?
Or is it possible the 4 methods are usually called but sometimes not called randomly with no reason?

A: I can say than viewWillAppear and viewDidAppear methods are always called in your view.
viewWillDisappear and viewDidDisappear methods are called when you change your view with another one or close it. If you have some scrolling views for example, these methods won't be called.

A: Yes, they are always called. Just make sure to call the superclass implementation if you subclass one of your view controllers.

A: I think you can trust those methods, still, viewDidLoad and dealloc for me never failed.
You can register and remove notifications there. But, I don't know all of your app specifications and what I recommend might not be viable.

A: Yes the View events always fire, however to override the behaviour you must declare them.
According to apple documentation viewDidUnload is deprecated.
Look at this link for the official apple class reference for UIViewController
UIViewController Reference
It states:
The UIViewController class provides specific methods that are called when these events occur. Subclasses can override these methods to implement specific behaviors.

A: Here are the same thread in which same thing asked m any times
you can view these here
here the first link
here the second one

A: Aside from bugs when some of the methods may not get called and/or called twice (e.g. dismissing/popping several controllers at once), with iOS 7, if you initiate the swipe-to-back gesture, partially revealing the previous controller in the navigation stack, and then cancel the swipe-to-back, so that no popping occurs, you will observe that not all of the methods get called on both of the controllers.


text:
Q: Randomising arrays to form an highly entropic grid I am attempting to make a 5x5 grid using arrays with the following limitations

*

*Should not exceed more than 4 check marks per grid

*Should not have 2 consecutive check marks

This is what I have come up with so far, I would appreciate if someone could help me figure out how would I achieve the latter condition
 let emoji = {
            0: '✅',
            1: '❓',
   }
    let grid = []
        let checkmarks = 0
        for (let i = 0; i < 5; i++) {
            let row = []
            for (let j = 0; j < 5; j++) {
                let random = crypto.randomInt(0, 1000) % 2
                if (random == 0) {
                    if(checkmarks < 4) {
                    row.push(emoji[0])
                    checkmarks++
                    }
                    else {
                        row.push(emoji[1])
                    }
                } else {
                    row.push(emoji[1])
                }
            }
            grid.push(row)
        }

I am attempting to make it as random as possible.

A: Instead of randomly determining if a cell should be a checkmark I would rather randomly find cells that should be a checkmark.
Your current solution decreases the chance of getting a checkmark with each cell.
Created some example code for you:

const emojis = ['✅', '❓']

const size = 5
const checkmarks = []

for (let i = 0; i < 4; i += 1) {
  while (true) {
    // get random x and y
    const x = Math.random() * size | 0
    const y = Math.random() * size | 0
    // check if x and y are far enough from existing checkmarks
    const areNeighbours = checkmarks.some(c => {
      if (c.x === x) {
        return Math.abs(c.y - y) <= 1
      }
      if (c.y === y) {
        return Math.abs(c.x - x) <= 1
      }
      return false
    })

    if (!areNeighbours) {
      checkmarks.push({
        x,
        y
      })
      break
    }
  }
}

const grid = []

for (let y = 0; y < size; y += 1) {
  grid.push([])
  for (let x = 0; x < size; x += 1) {
    const checkmark = checkmarks.find(c => c.x === x && c.y === y)
    grid[y][x] = checkmark ? emojis[0] : emojis[1]
  }
}

console.log(grid.map(row => row.join('')).join('\n'))

A: Imagine a 5x5 board initially filled by ❓.
Next you toss 4 coins at once, each coin will landed in one cell, head or tail.
If head, place a ✅ in the cell.
Now check if non-consecutive ✅ condition is met. If not start over.
Solution:

const emojis = ['✅', '❓'];

function randomInt(min, max) {
  return min + Math.floor(Math.random() * (max - min));
}

function tossCoins(checkmarkLimit, size) {
  const positions = Array.from({ length: checkmarkLimit }, () => {
    const pos = randomInt(0, size * size);
    const tail = Math.random() > 0.5;
    if (tail) return null;
    const x = pos % 5;
    const y = (pos - x) / 5;
    return [x, y];
  })

  return positions.filter(Boolean);
}

function checkNonConsecutive(positions) {
  for (let i = 0; i < positions.length; i++) {
    const p = positions[i];
    for (let j = 0; j < positions.length; j++) {
      if (i == j) continue;
      const o = positions[j];
      const distance = Math.abs(p[0] - o[0]) + Math.abs(p[1] - o[1])
      if (distance <= 1) {
        return false;
      }
    }
  }
  return true;
}

function main() {
  const checkmarkLimit = 4;
  const size = 5;
  const grid = Array.from({ length: size }, () => Array.from({ length: size }, () => emojis[1]));

  let positions = tossCoins(checkmarkLimit, size);
  while (!checkNonConsecutive(positions)) {
    positions = tossCoins(checkmarkLimit, size);
  }

  positions.forEach(([x, y]) => {
    grid[y][x] = emojis[0];
  });

  return grid;
}

for (let n=0; n < 10; n++) {
  console.log('round: ' + n);
  console.log(main().map(row => row.join('')).join('\n'));
}

A: I'm posting this answer because the accepted answer doesn't seem to produce a consistent result. I agree with most of the approach, but result just wasn't always returning 4 checkmarks (because it seems to reset after each iteration, which can increase the maximum number of loops needed).
But ultimately, the idea is to fill the 5x5 array with the ❓ character first, randomly select a location, verify the surrounding blocks are not ✅, and then place a ✅ if these conditions are met. If not, I instead just select a new position but keep the existing results until the needed number of ✅ have been set.

let grid = [],
    rows = 5,
    cols = 5,
    maxChecks = 4,
    totalChecks = 0,
    emoji = {
      0: '✅',
      1: '❓',
   };

const _RandomChecks = () => {
  grid = [];
  totalChecks = 0;
  for(let i = 0; i < rows; i++) {
    grid[i] = [];
    for(let j = 0; j < cols; j++) {
      grid[i] = [...grid[i], emoji[1]];
    }
  }

  while(totalChecks < maxChecks) {
    let rndRow = parseInt(crypto.randomUUID().replace(/[^0-9]/g, "").substr(-8)) % rows,
    rndCol = parseInt(crypto.randomUUID().replace(/[^0-9]/g, "").substr(-8)) % cols,
    valid = (grid[rndRow][rndCol] == emoji[1]) ? true : false;

    if(grid[rndRow-1]?.[rndCol] && valid) valid = (grid[rndRow-1]?.[rndCol] == emoji[1]) ? true : false;
    if(grid[rndRow+1]?.[rndCol] && valid) valid = (grid[rndRow+1]?.[rndCol] == emoji[1]) ? true : false;
    if(grid[rndRow][rndCol-1] && valid) valid = (grid[rndRow][rndCol-1] == emoji[1]) ? true : false;
    if(grid[rndRow][rndCol+1] && valid) valid = (grid[rndRow][rndCol+1] == emoji[1]) ? true : false;

    if(valid) {
      grid[rndRow][rndCol] = emoji[0];
      totalChecks++;
    }
  }
  console.log(grid.map(row => row.join('')).join('\n'));
}

_RandomChecks();


text:
Q: SFML cannot load image file no matter what I try I am trying a simple SFML project and it is giving me an error saying that it cannot load the image file. Here is my code:
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace sf;

int main() {
RenderWindow window(VideoMode(600, 600), "Chess");

system("dir");

Texture texture;
texture.loadFromFile("board.png");

Sprite s(texture);

while (window.isOpen()) {
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    //draw
    window.clear();
    window.draw(s);
    window.display();
}
}

I have tried every guide and fix for this problem I could find and not a single one of them has worked. Would anyone be able to help me? And yes, my image files are in the project directory. If it helps, I am using VS 2013.


text:
Q: Mocha/Chai tests hanging at .should.be.deep.equal despite result existing I'm running some tests using Mocha and chai. One of the tests is hanging at a .should.be.deep.equal call.
Here's the test code:
// Make the fake connection before running tests
before(function(done) {
    mongoose.connect('mongodb://fake.test/TestingDB', function(err) {
        done(err);
    });
});

// Test Cases
describe('Testing the functions that deal with users and locations:', function() {
    // Test Setup
    var req = {};
    beforeEach(function(done) {
        mockgoose.reset()
        async.parallel([function(callback){
            sensors.create(testData.deviceData, function(err, model) {
                    if (err) {console.log(err)}
                    callback();
                });
        }, function(callback) {
            locations.create(testData.locationData, function(err, model) {
                    if (err) {console.log(err)}
                    callback();
                });
            }], function(err) {
                done();
            });
    });

    afterEach(function(done) {
        mockgoose.reset();
        done();
    });
    // Tests
    describe('function locationList', function() {
        it('should list the test location', function(done) {
            dbFunctions.locationList(req, function(result) {
                console.log(result) //Prints the whole result
                console.log(testData.locationList)
                result.should.exist; //This doesn't cause it to hang
                result.should.be.deep.equal(testData.locationList) //hangs here
                done(result);
            });
        })
    })
});

And here's the function it's testing:
exports.locationList = function(req, callback) {
listLocations().then(
    function(data) {
        callback(data);
    },
    function(err) {
        console.log('Error Retrieving Location Information: ' + err);
        callback(err);
    });
};

As I note in the comments, the results object exists and gets printed to the console. results.should.exist; doesn't throw an exception and if I comment out everything but it the test works fine. For some weird reason, despite both the testData.locationList and result object existing, the test times out. I have 14 other tests that use the exact same syntax without any problems. Does anyone know what could be causing this to happen for this specific test?
Here's the output from the tests:
Testing the functions that deal with users and locations:
    function locationList
        [ { devices: {},
            address: '123 Fake St, Waterloo, On',
            location: 'Unittest',
            owner: 'unit@test.com',
            _id: '-1' } ]
        [ { devices: {},
            address: '123 Fake St, Waterloo, On',
            location: 'Unittest',
            owner: 'unit@test.com',
            _id: '-1' } ]

            1) should list the test location
0 passing (2s)
1 failing
1) Testing the functions that deal with users and locations: function locationList should list the test location:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
    at null.<anonymous> (C:\Users\My Name\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:189:19)

Extending the timeout doesn't work. Nor does putting something random (ie. the integer 1 in the .should.be.deep.equal() function.

A: My guess is that the callback in exports.locationList is called synchronously, and that your test case is actually failing, throwing an exception, which never gets caught because the callback is (synchronously) called from within a promise handler (more info here).
Try and see if this works better:
dbFunctions.locationList(req, function(result) {
  setImmediate(function() {
    console.log(result) //Prints the whole result
    console.log(testData.locationList)
    result.should.exist; //This doesn't cause it to hang
    result.should.be.deep.equal(testData.locationList) //hangs here
    done(result);
  });
});
// or use a module like dezalgo (https://github.com/npm/dezalgo)

The underlying cause may be mockgoose.
Also, you're not using the proper Node.js conventions where the first argument to a callback function is "reserved" for errors. In other words, your code should look similar to this:
if (err) {
  callback(err);
} else {
  callback(null, data);
}

You're now passing both errors and data as the first argument.

A: A guess: Maybe the issue lies with mongoose decorating the result with it's own functions/members, and one of them somehow getting stuck in an infinite loop when chai tries to enumerate them all to perform a deep comparison.


text:
Q: What to do if KNN has K+ matches We run a 3-NN classifier.
We are looking at a case in which a point has 5 points (or something greater than K, which is 3 at the moment) of equal distance.
What can we do in this case?

A: There is no "correct" answer to this question. Two options are: (1) have a tie-breaking rule; or (2) just use all of them (in your example, all 5). There might be other options. I'd suggest that you try different options and see what works best for your particular application.


text:
Q: Resolving WiFi interference 2.4GHz/5GHz Set-up:
iPad user connects to WiFi via Airport Express. A printer is attached to Airport Express for (Airprint) printing facility.
Problem:
I am using the above set-up with the permission of IT (I am an external staff person who is not on their payroll). Recently IT has reached out to me saying that I need to remove my Airport Express because it is causing  interference to their devices and making them slow. Since Airport express broadcasts both on 2.4GHz and 5GHz, I was thinking as a possible solution I configure Airport Express to 5GHz only (less crowded spectrum). I think there is no possibility to restrict Airport Express to broadcast 5GHz network only (it will broadcast both 2.4GHz & 5GHz) therefore I was thinking to get a good value router/WiFi base station which has the capability broadcast only 5Ghz WiFi. I have looked up on internet and couldn't find any good value router which could serve the above purpose. My questions are
1) Will the above proposed solution (5GHz network only) could resolve my interference woes?
2) Please suggest an alternative (with specs) to Airport Express which could be roughly of same value and has the printer attachment capability and could broadcast 5GHz WiFi only.
Caveat: I have already scanned the WiFi Spectrum 2.4GHz is very crowded therefore changing the channel wouldn't resolve it plus frequencies are overlapping, 5GHz spectrum is less crowded (only 1 more SSID other than mine is residing there, hence I want to broadcast only 5GHz radio frequency so that IT doesn't blame me that my device is interfering/crowding their 2.4 GHz spectrum)
Thank you!

A: There is an app, WiFi Explorer, which shows all the networks your computer can see. It also shows the relative strengths and channel number of them. You could use this to determine that the problem is indeed 5 GHz. Maybe changing Airport channel will help. The app is not free and is available from the App Store.


text:
Q: ScrollViewer border moves out when HorizontalScrollBarVisibility set to "Auto" or "Visible" In XAML I have a ScrollView and a ListView inside.
<ScrollViewer Margin="0, 0, 0, 2" HorizontalScrollBarVisibility="Visible">
      <ListView  BorderBrush="Red" BorderThickness="3" Name="listAnswers">

...
/>

So, when I remove the HorizontalScrollBarVisibility tag,
my border is unmovable while scrolling, but if I set HorizontalScrollBarVisibility
to "Auto" or "Visible" vertical Red border moves out and disappears.
How to enable scrollbar and set its border unmovable?
Pictures:
alt text http://www.freeimagehosting.net/uploads/f2446d54ab.jpg
alt text http://www.freeimagehosting.net/uploads/a5bfe72b5e.jpg

A: You can use padding instead of border:
<ScrollViewer Margin="0, 0, 0, 2" HorizontalScrollBarVisibility="Visible" Padding="3" Background="Red">
    <ListView Name="listAnswers" MinWidth="300"/>
</ScrollViewer>


text:
Q: Read Excel Cell And Set Row Colour I am using Com Interop and C#.  I have to iterate through an Excel file looking for certain values in each of the rows (always in column 2).  For some values I need to set the background colour of the row to red.
I am having trouble:

*

*Reading the value in cell [i][2] for row i, and

*Setting the background colour of this row.

Basically I am looking for something like this (which is the best I can find after much Googling):
// ws is the worksheet
for (int i = 1; i <= ws.Rows.Count; i++)
{
    Range range = ws.Cells[i][2];
    int count = Convert.ToInt32(range.Value2.ToString());
    if (count >= 3)
    {
        Range chronic = ws.UsedRange.Rows[i];
        chronic.EntireRow.Cells.Interior.Color = 0xFF0000;
    }
}

Of course this doesn't work.  I can't get past the first hurdle of just reading the cell.  Any advice is appreciated.

A: Try this. The code assumes that the value in the column 2 cell is a number.
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

Missing noValue = Missing.Value;
Excel.Range conditionalCell;
foreach (Excel.Range usedRange in ws.UsedRange.Rows)
{
    conditionalCell = usedRange.Cells[noValue, 2] as Excel.Range;
    if (Convert.ToInt32(conditionalCell.Value2) >= 3)
    {
        usedRange.Cells.Interior.Color = Excel.XlRgbColor.rgbRed;
    }
}