text:
Q: Chat with option to send file I would like to create a simple TCP chat with option to send files.
Sending messages to other clients works, but sending files doesn't work. My chat sends only few bytes of file.
Chat works like: Server starts up and wait for clients, Clients connect to server and they can send messages to other clients through the server. I would like to allow to the same with files.
Server is wrote in C, and Client is wrote in Java (I had guidelines like that).
Server:
    for (i = 0; i < max_clients; i++) {
        sd = client_socket[i];

        memset(buffer, 0, 10000);
        if (FD_ISSET( sd , &readfds)) {
            if ((valread = read( sd , buffer, 1024)) == 0) {
                getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
                printf("Host disconnected , ip %s , port %d \n" ,
                    inet_ntoa(address.sin_addr) , ntohs(address.sin_port));

                close( sd );
                client_socket[i] = 0;
            }
            else {
                // When message "start" arrived download the file and send it back to other clients
                if (strcmp(buffer, "start") == 0) {
                    uint8_t buff[10000];
                    // Read chunks of file
                    while (read( sd , buff, sizeof(buff)) > 0) {

                        // Sending chunks of file to other clients
                        for(j=0; j<max_clients; j++) {
                            int outSock = client_socket[j];
                            if(outSock != master_socket && outSock != sd) {
                                send(outSock , buff , sizeof(buff) , 0 );
                            }
                    }

                    }
                } else {

                    buffer[valread] = '\0';
                    for(j=0; j<max_clients; j++) {
                        int outSock = client_socket[j];
                        if(outSock != master_socket && outSock != sd) {
                            send(outSock , buffer , strlen(buffer) , 0 );
                        }
                    }

                }

            }
        }
    }

Client:
@FXML
void sendFile(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    File file = fileChooser.showOpenDialog(null);

    // Send "start" message to let server know that I'm going to send a file
    out.println("start");
    out.flush();

    try {

        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);

        //Get socket's output stream
        OutputStream os = clientSocket.getOutputStream();

        //Read File Contents into contents array
        byte[] contents;
        long fileLength = file.length();
        long current = 0;

        while(current!=fileLength){
            int size = 10000;
            if(fileLength - current >= size)
                current += size;
            else{
                size = (int)(fileLength - current);
                current = fileLength;
            }
            contents = new byte[size];
            bis.read(contents, 0, size);
            os.write(contents);
            System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
        }

        os.flush();
        System.out.println("File sent successfully!");

    } catch(Exception e) {

    }
}

public ChatWindowController() {

    try {
        clientSocket = new Socket("127.0.0.1", 54000);
        outToServer = new DataOutputStream(clientSocket.getOutputStream());
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new PrintWriter(clientSocket.getOutputStream(), true);

        thread = new Thread() {
            @Override
            public void run() {
                try {

                    while(isRunning) {
                        if (ta_display != null) {
                            String message = inFromServer.readLine();
                            if (!isDownloadingFile) {
                                System.out.println(message);
                                ta_display.appendText(message + '\n');

                                if (message.equals("start")) {
                                    isDownloadingFile = true;
                                }
                            } else {

                                byte[] contents = new byte[10000];

                                //Initialize the FileOutputStream to the output file's full path.
                                FileOutputStream fos = new FileOutputStream("/example/test.png");
                                BufferedOutputStream bos = new BufferedOutputStream(fos);
                                InputStream is = clientSocket.getInputStream();

                                //No of bytes read in one read() call
                                int bytesRead = 0;

                                while((bytesRead=is.read(contents))!=-1)
                                    bos.write(contents, 0, bytesRead);

                                bos.flush();

                                System.out.println("File saved successfully!");

                            }
                        }

                    }

                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        };

        thread.start();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

When I click button sendFile method is called, then I choose file and I want to send this file, and with other clients download it.

A: Ok, there is a bug on the server when receiving the file:
//client sends 10000 bytes of data in chunks of unknown size

//receive one chunk of unknown size
while (read( sd , buff, sizeof(buff)) > 0) {
    for(j=0; j<max_clients; j++) {
        int outSock = client_socket[j];
        if(outSock != master_socket && outSock != sd) {
            // Send 10000 bytes aka the received chunk and whatever else is in the buffer to all clients
            send(outSock , buff , sizeof(buff) , 0 );
        }
    }

You need to either receive all the data first and then send it to the clients, or only send the size of the chunk many bytes, like in the File writer in the client or as follows:
int chunk = 0;
while ((chunk = read( sd , buff, sizeof(buff))) > 0) {
    ...
    send(outSock , buff , chunk , 0);

Also Im not certain if the Client file writing code works, you should ensure that no following messages are written to file accidently.

A: I have written a similar example for chatting at https://github.com/foreverpersist/socket/blob/master/chatroom.c.
File transferring is implemented by P2P

*

*Server tells <IP:PORT>s of sender and receiver to each other.

*Sender and receiver connect to each other directly.

*Sender sends file to receiver.

*Sender and receiver close the connection.

As what happens in your project, when transferring files with path Sender -> Server -> Receiver, the content of large files may be incomplete if you don't deal carefully. So, I just transfer files with path Sender -> Receiver.


text:
Q: Why was radio and cellphone reception spotty in Jurassic World? Rewatching Jurassic World, I noticed how often they had spotty reception when using radio and cellphone. First when warning Owen Grady and the two park workers examining the Indominus enclosure, later when trying to contact Zach and Gray in their gyrosphere.
Out of universe, that was undoubtedly done to create tension and to further the plot.
But is there an in-universe explanation?

A: The two boys seem to have lost reception very shortly after the announcement was made to evacuate the north side of the island. Presumably the cell towers were overloaded with calls from the other guests contacting their friends and family to complain. Her reception at all other times was impeccable.
As far as radio reception is concerned, it seem to be patchy on the northern side of the island. You can see from this false-colour topological map that the northern paddock is ringed with small hills and a large volcano, all of which would block or refract radio signals.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Composer won't use latest version of openssl ➜  ~ composer diagnose
Checking platform settings: WARNING
The OpenSSL library (0.9.8za) used by PHP does not support TLSv1.2 or TLSv1.1.
If possible you should upgrade OpenSSL to version 1.0.1 or above.

But this doesn't appear to match the version of OpenSSL I've actually got running.
➜  ~ which openssl
/usr/local/opt/openssl/bin/openssl
➜  ~ openssl version
OpenSSL 1.0.2k  26 Jan 2017

I realise there are similar questions but as the most popular answer suggests using the now broken command
brew link --force openssl

which as per the comments doesn't work.


text:
Q: Finding location of specific value in spatial TIFF file using R? I want to find location of specific value in one spatial GIS TIFF file and then compare location to main file in order to find some information.
for example consider this image which is my main image.

For example, I want to find location of values greater than 255 in following image.
I read both image using raster library.
Edit:
by location I mean longitude and latitude.

A: Always a good idea to make a simple test. Here's a 5x6 raster:
> r = raster(matrix(runif(30),5,6))

which has these values:
> r[]
 [1] 0.45825245 0.68935493 0.18918221 0.32181772 0.90459237 0.47537165
 [7] 0.38745306 0.57012344 0.21467928 0.24150341 0.54005789 0.09430709
[13] 0.52352994 0.01489950 0.54890148 0.04762656 0.83931822 0.14997015
[19] 0.02994982 0.89359828 0.22488212 0.55764499 0.30531830 0.13751166
[25] 0.90074801 0.94862034 0.88637761 0.13849934 0.64490219 0.67825152

and its in a (0,1) unit square:
> extent(r)
class      : Extent
xmin       : 0
xmax       : 1
ymin       : 0
ymax       : 1

Now we use the coordinates function which gets the coordinates of the grid points, and subset those that match whatever condition we want. For example, all grid points where the raster is over 0.9:
> coordinates(r)[r[]>0.9,]
              x   y
[1,] 0.75000000 0.9
[2,] 0.08333333 0.1
[3,] 0.25000000 0.1

Alternatively, mask out the condition with NA and convert to Spatial Points:
> r = raster(matrix(runif(30),5,6))
> r[r[] < 0.9] = NA
> (pts = as(r, "SpatialPoints"))
class       : SpatialPoints
features    : 3
extent      : 0.25, 0.9166667, 0.5, 0.7  (xmin, xmax, ymin, ymax)
crs         : NA

That's useful if you want to do further spatial work with the sp package. If you just want the coordinates from that then:
> coordinates(as(r, "SpatialPoints"))
             x   y
[1,] 0.2500000 0.7
[2,] 0.9166667 0.7
[3,] 0.5833333 0.5


text:
Q: Best practices in modelling user constraints in a webapp? I'm building a webapp with role based access control using Acegi (Spring) security. So i have different users with roles: ROLE_ADMIN, ROLE_USER and etc.
However, i need to implement various user constraints.
Let's consider an example:

Suppose, there is a site where users can watch movies online. There are users with roles ROLE_STANDARD_USER and ROLE_VIP_USER. Standard users can watch 3 movies a week and vip users can watch 10 movies a week plus have some other privileges. And there is one user in standard user group to whom i want to give additional 2 movies per week. The number of allowed movies may sometimes change.
  Also, there are various categories of movies: fantasy, comedy, classic, new movies and etc. And i want that some users, regardless of their role, have access only to certain categories. The categories can be created and removed dynamicaly.

Are there any standard practices for implementing such type of user constraints?
Can/should it be done using Spring Security roles and permissions?
Or i need to consider adding a rule based engine to my app?
Thank you.
Edit:
The example above is fictional, my project is concerned with granting remote access to various networking (and other) equipment for students. However, the types of user constrains are likely to be the same.
Unfortunately, the Model for user access & constraints is not complete and stable. In the near future i might be told to implement various additional constraints for users, that are not known now.
So i would like to select a path now that will ease addition or change of new user constraints in future and would not require significant overhaul of internal model or database structure. If that at all possible.
Edit 2
Currently, basic user constraints are hardcoded (leftover from prototyping system). I guess i'll try refactoring it first to some kind of parametrized business services objects first and then think where can i go from there. I will also consider using Spring Security Authorization Decision Managers.
Thank you for all suggestions!

A: I would not expect a declarative role-based security system to give the fine-grained control you are seeking. You have already described quite a few "business rule" based access controls you want to implement and we might expect over time those rules to become more complex. So you need a combination of information from the security sub system (who is the user for this request? what roles do they have? ) but then programatically combine that with business data and rules (this user is entitiled to 2 free movies if today's date is in this range).
A the very least I would define services in which I encapsulate that business logic. The decision as to whether to use a fully fledged rules engine would need further study.

A: Before asking yourself it Acegi (or a rule-engine etc.) is the correct place to do it, I think you need to
analyze your needs precisely and completely.
Considering each topic (for example, limits on movie that can be seen), there is a huge number of ways to implement this, and you need to make functional choices. There can be no correct implementation unless you already decided in details what has to be done!
Example of a Model for your needs:

*

*Limit the number of general movies per week according to the sum of:

*

*role (3 or 10)

*per-user bonus (default 0 if not mentioned)

*Update these numbers as needed

*Restrict the movies to a list of categories:

*

*if a list is specified for the user, use it

*otherwise, use the list that is provided for the role

This example has many implications, that may be correct or unacceptable in your case.
Implications:

*

*after updating a number, the limit is changed immediately.

*there is no memory of the weekly limits, you can't ask this for the past (to make statistics for example)

*...

Supposing this model doesn't fit your needs, you are facing the hard job of creating a model that really fits them. Only once you have it, then think about implementation.

A: If you consider Spring Security, this is one way I see you can implement your solution.  Implement a AccessDecisionVoter to decide on user's access.  Take a look at the reference source here
Also look at the [javadoc][2] for AccessDecisionVoter.  You can implement your rules by implementing the vote method.
int vote(Authentication authentication,
         Object object,
         ConfigAttributeDefinition config)

Let Spring handle the access (Authentication and Authorization).  If the decision making gets complicated use a rule engine might be wise.  Let the vote method call out to a rule engine.  This provide clear separation of duty.  Let Spring Security handle the access, and let the rule engine compute the rules.
[2]: http://static.springsource.org/spring-security/site/apidocs/org/springframework/security/vote/AccessDecisionVoter.html#vote(org.springframework.security.Authentication, java.lang.Object, org.springframework.security.ConfigAttributeDefinition)

A: Starting here: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity.html
Access control intro: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/technical-overview.html#tech-intro-access-control
Authorization:
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/authorization-common.html#d4e1767
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/authorization-common.html#after-invocation-acl-aware
Will take a bit of reading

A: Sounds like you have authentication needs and authorization needs - a lot of times people get the two confused and/or joined.  Thankfully Spring Security delineates the two very well.  You're user will authenticate through the security chain (be it form logj, openID, SSL X509) and then once done with be authorized by your business specific Voters (in your AccessDecisionManagers) as to wether or not they have already seen their allotted number of movies.  If new business logic needs to be added later it's simply a matter of writing new/more voters and injecting them into your Manager.


text:
Q: OAuthSwift & Github - what Authorization callback URL should I use? I want to setup Github client using OAuthSwift. While setting up the app in the GitHub it asks me for Authorization callback URL. What value should I use here ?

A: You should give the url for The URL in your application where users will be sent after authorization.
Check Web Application Flow for the details about redirect url. Specially GitHub redirects back to your site Part where it is described in details with each parameter details you need to supply in callback.
BR


text: Q: Can I reinstall Ubuntu from an ext HDD image after loading Win7 onto the formerly Ubuntu laptop, and get a working dual boot system? If so, how I want to set up a dual-boot Win7 + Ubuntu system on a current Ubuntu Linux DELL laptop  The Windows 7 Ultimate disk I have is a DELL reinstall only disk, so it will wipe any existing OS on the system.  Can I copy the Ubuntu Linux setup as an image to an external HDD, then load Win7 onto the laptop, then copy the Ubuntu image back from the ext HDD, and wind up with a working dual boot system?  If so, are there any specific steps/sequence of steps to follow or specific pitfalls to watch out for?  If there is a better alternate process that has worked for you, I'm open to trying that instead.


text:
Q: Xcode (12.3) Not Responding When Connected To Internet? A few days ago I starting having problems with Xcode hanging. I figured out that disconnecting from wifi fixed the problem and made it run correctly again.
The first day it happened, Xcode was impossible to use while being connected. Since, it's been a bit better, but still hangs often.
I've tried all sorts of things from restarting my computer, to deleting derived data, to reinstalling Xcode. But the issue hasn't resolved.
Please help.


text:
Q: Disallowing setting array properties with TSLint I was wondering if there is a TSLint rule with which I can disallow the following code:
var arr = [1, 2];
//the line below should be disallowed
arr.prop1 = "3";
//because arr now has array elements and object properties

I want to disallow this because it prevents arr from being fully serialized with JSON.stringify, because JSON.stringify will serialize arr into [1, 2].
I have looked at the TSLint rules but wasn't able to find a rule for this.

A: I've implemented a TSLint rule for this, which is available on GitHub and NPM:

*

*https://github.com/leroydev/no-setting-array-properties-rule

*https://www.npmjs.com/package/no-setting-array-properties-rule
It can be used like this:

*

*Install it using npm install no-setting-array-properties-rule --save-dev.

*Add it to your tslint.json, like this:
{
   "rulesDirectory": [
       "../node_modules/no-setting-array-properties-rule/dist/src"
   ],
   "rules": {
       "no-setting-array-properties": true
   }
}

Edit:
It can be implemented by just setting noImplicitAny: true too, for my project this wasn't an acceptable solution, but that's the easy fix.


text:
Q: Long GC pauses in application I am currently running an application which requires a maximum heap size of 16GB.
Currently I use the following flags to handle garbage collection.
-XX\:+UseParNewGC, -XX\:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=50, -XX\:+DisableExplicitGC, -XX\:+PrintGCDateStamps, -XX\:+PrintGCDetails, -Xloggc\:/home/user/logs/gc.log

However, I have noticed that during some garbage collections, the application locks up for a few seconds and then carries on - This is completely unacceptable as it's a game server.
An exert from my garbage collection logs can be found here.
Any advice on what I should change in order to reduce these long pauses would be greatly appreciated.

A:
Any advice on what I should change in order to reduce these long pauses would be greatly appreciated.

The chances are that the CMS GC cannot keep up with the amount of garbage your system is generating.  But the work that the GC has to perform is actually more closely related to the amount of NON-garbage that your system is retaining.
So ...

*

*Try to reduce the actual memory usage of your application; e.g. by not caching so much stuff, or reducing the size of your "world".

*Try to reduce the rate at which your application generates garbage.

*Upgrade to a machine with more cores so that there are more cores available to run the parallel GC threads when necessary.

To Mysticial:
Yes in hindsight, it might have been better to implement the server in C++.  However, we don't know anything about "the game".  If it involves a complicated world model with complicated heterogeneous data structures, then implementing it in C++ could mean that that you replace the "GC pause" problem with the problem that the server crashes all the time due to problems with the way it manages its data structures.

A: Looking at your logs, I don't see any long pauses. But young GC is very frequent. Promotion rate is very low though (most garbage cleared by young GC as it should). At same time your old space utilization is low.
BTW are we talking about minecraft server?
To reduce frequency of young GC you should increase its size. I would suggest start with -XX:NewSize=8G -XX:MaxNewSize=8G
For such large young space, you should also reduce survivor space size -XX:SurvivorRatio=512
GC tuning is a path of trial and errors, so you may need some more iterations and tweaking.
You can find couple of useful articles at mu blog

*

*HotSpot JVM GC options cheatsheet

*Understanding young GC pauses in HotSpot JVM

A: I'm not an expert on Java garbage collection, but it looks like you're doing the right thing by using the concurrent collector (the UseConcMarkSweepGC flag), assuming the server has multiple processors. Follow the suggestions for troubleshooting at http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html#cms. If you already have, let us know what happened when you tried them.

A: Which version of java are you using?http://docs.oracle.com/javase/7/docs/technotes/guides/vm/G1.html
For better try to minimize the use of instance variables in a class.It would be better to perform on local variables than instance varibles .It helps in gaining the performance and safe from synchronization problem.In the end of operation before exit of program  always reset the used variables if  you are using instance variables and set again when it is required. It helps more in enhancing performance.Besides in the version of java a good garbage collection  policy is implemented.It would be better to move to new version if that is fleasible.
Also you can monitor the garbage collector pause time via VisualVm and you can get more idea when it is performing more garbage collection.


text:
Q: Get RadioButtonList value from database & selected I am trying to populate My RadioButtonList values from database. That is working for me. But I am not getting how should I keep one predefined values in database to be selected by default in radiobuttonList. I have list of cities in my db table. One city I want to be selected when page loads. Following is my code
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.PopulateCities()
End Sub

Private Sub PopulateCities()
        Using conn As New MySqlConnection()
            conn.ConnectionString = ConfigurationManager _
                .ConnectionStrings("conio").ConnectionString()
            Using cmd As New MySqlCommand()
                cmd.CommandText = "Select cityName from cities where status = 'active' order by cityName"
                cmd.Connection = conn
                conn.Open()
                Using sdr As MySqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        Dim item As New ListItem()
                        item.Text = sdr("cityName").ToString()
                        item.Value = sdr("cityName").ToString()
                        item.Selected = Convert.ToBoolean(sdr("IsSelected"))
                        locationSelector.Items.Add(item)
                    End While
                End Using
                conn.Close()
            End Using
        End Using

A: If you database cities table contains IsSelected field then you need to change your query like this
Select cityName, IsSelected from cities where status = 'active' order by cityName

Elese you need to update your first list item
locationSelector.Items(0).Selected = True


text:
Q: Get return value of a class method in jupyter notebook? I have a folder called MyModule that contains an __init__.py file with the following contents:
class MyClass(object):
    def __init__(self):
        self.x = 5

    def MyOutput(self):
        return self.x

Next to the MyModule folder I put a jupyter notebook MyNotebook.ipynb which contains the following code in a single cell:
from MyModule import MyClass
myClass = MyClass()
myClass.MyOutput()

Now, I would have expected to see the output 5 below the cell after evaluating it. Instead there just is no output at all. I suspect that I am doing something wrong with the syntax. How should I fix it to have it display the output 5 after evaluating the cell in jupyter notebook?


text:
Q: Django rest framework check if user exist with password The code I'm showing you below its what works for me right now. its not the most secure but does the job but i want to do it using POST method. any ideas how to change it?
I have a serializer.py class
class userLoginSerializer(serializers.ModelSerializer):

class Meta:
    model = users
    fields = ('nick', 'pass_field')

@api_view(['GET'])
def user_login(request,nick,pass_field):

but when i sent the 2 values nick and passfield it says that the nick already exist and returns 404 because it passes it to serializers.errors. I just need to pass the code using POST and validating if it exist and return a success JSON. The code below works but its not the best implementation.
if request.method == 'GET':

    try:

        users.objects.get(nick=nick,pass_field=pass_field)
        json = {}
        json['message'] = 'success'

        return Response(json, status=status.HTTP_201_CREATED)

    except users.DoesNotExist:

        json = {}
        json['message'] = 'error'

        return Response(json, status=status.HTTP_400_BAD_REQUEST)

A: The models is users or User? Why don't you use the Django User model?
The class User has already a check_password method and store it with a hash algoritm: https://docs.djangoproject.com/en/dev/ref/contrib/auth/#methods
Never store a password in plain text, it's very insecure.
Using Django User model (or a class that inherits from it) you can simply check if it's valid this way:
try:
   user = User.objects.get(username=nick)
   if user.check_password(pass_field):
      #TODO: Valid password, insert your code here
   else:
      #TODO: Password not valid, handle it here
      pass
except User.DoesNotExist:
   #TODO: Your error handler goes here
   pass

Another thing you can do is inherits from ApiView and implement your code in post method: http://www.django-rest-framework.org/api-guide/views

A: I implemented a method for Sign In with JWT and what it does is:

*

*Fetches the email and password that is send with the request and
converts it into a string variable

*I check if the email already
exists in the custom user model i made.

*If the user already
exists, i convert the object model to dictionary so that i can get
its particular password.

*In that i match the password
corresponding to user model and the password that is send with the
post request.

*if the email exists in the user model and the password corresponding to that user model matches the password that is sent with the post request i use the pyJWT to make the JWT with my custom data and return the response.

*In all other cases the email and password don't match and i return "No Match"

Suppose the request is   {"email":"xyz@gmail.com", "password":"12345" }

    @api_view(['POST'])
    def signin(request):

    email = list(request.data.values())[0] #gets email value from post request {"email":"xyz@gmail.com", "password":"123"} -> this xyz@gmail.com
    password = list(request.data.values())[1] #gets password value from post request {"email":"xyz@gmail.com", "password":"123"} -> this 123

    usr = User.objects.filter(email=email).exists() #checks if email exists
    if usr:
      dictionary = User.objects.filter(email=email).values()[0] #converts object to dictionary for accessing data like dictionary["password"] dictionary["first_name"] etc
      if usr and dictionary["password"] == password: #check if email and its corresponing password stored matches the password that is sent
        branch = dictionary["branch"]
        id = dictionary["id"]
        encoded_jwt = jwt.encode({'email': email,}, 'secret', algorithm='HS256')
        return Response({'token':encoded_jwt,'email':email,'branch':branch,'id':id})
      else:
        return Response({'No Match'})
    return Response({'No Match'})


text:
Q: How can I by default have all text selected in my lineEdit? I'd like to be able to have all text highlighted in my lineEdit. However, the default selectAll() doesn't seem to do so.
import sys
from PyQt4 import QtCore, QtGui
from gui import Ui_Form

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.lineEdit.setText("Type something here!")
        self.ui.lineEdit.selectAll()
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.ui.textEdit.clear)
        QtCore.QObject.connect(self.ui.lineEdit, QtCore.SIGNAL("returnPressed()"), self.add_entry)

    def add_entry(self):
        self.ui.lineEdit.selectAll()
        self.ui.lineEdit.cut()
        self.ui.textEdit.append("")
        self.ui.textEdit.paste()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

I want to select the text on the lineEdit in the default constructor; however, it doesn't. Any reason for this? What should I be doing instead to accomplish this?


text:
Q: Infinite, never ending, nested ng-repeat I have the following json object:
"comments": [
    {"username": "test", "comment": "This is a comment",
    "child": [
        {"username": "chriscool", "comment": "I replied to the above comment",
        "child": [
            {"username": "Anotherperson", "comment": "But what if I replied again",
            "child": [
                {"username": "ralphy", "comment": "And again?!" }
            ] }
        ] },
        {"username": "ralphy", "comment": "I also replied" }
    ] }
]

As you can see, each comment could have a child comment so it could literally go on forever. I am trying to display all of them but I can't figure out how I would do this.
This is all I have so far (obviously this only gets the first child in each comment):

    {{ comment.comment}}

        {{c.comment}}

A: You could create your own directive that you can call recursively for your case
Markup

Directive
app.directive('myRecursiveDir', function(){
  return {
     templateUrl: 'Recursive.html',
     scope: {
        comments: '=',
     },
     replace: true
  };
});

Recursive.html

    {{c.comment}}

A: What you need is a tree view.
A good way is to print them not all at once, but only the first order comments, and add a button for loading the next ones (subcomments).
You can use a directive to do this, and encapsulate all the comments.
There is a good stackoverflow question for this.

A: You could create a directive that references itself:
angular.directive('myDirective', function() {
  return {
    scope: {
      comment: "="
    },
    templateUrl: "myDirective.html"
  }
})

<my-directive ng-repeat="comment in comments" comment="comment"></my-directive>


text:
Q: Tensor product symbol and convolution The convolution of $f$ and $g$ is sometimes written as $f\ast g$ and sometimes as $f \otimes g$.
Is convolution denoted by both of these symbols because the operations are related, or is it just historically determined? Wikipedia and Google dont know.

A: In the neural networks (e.g. in Tensorflow) there are convolutional layers which use a tensor product. The latter symbol stands for tensor product. It is not applicable in all convolution-scenarios.


text:
Q: Web Blocks in Outsystems I have a screen and it contains 2 web blocks when I click a link in my web block A, I need to show the web block B on the screen. Can I possibly do that? How? I am new to Outsystems and stuck up on this. I am thinking is it possible? Thanks for any help?

A: Enclose your webblock B in an IF binded to a Boolean variable let's say Show.
Then, right click on your webblock A, create a link to a new screen action. Then on your screen action change the value of the Show variable and use an Ajax Refresh to refresh your If created earlier. Don't forget to give a name to the IF so that you can refer in in the Ajax Refresh widget.


text:
Q: Convert Access Attachment data type to file system files I have a lot of files stored as attached files in an Access db. I am going to move data to an SQL server and for that purpose I need to extract the attached files and turn them into file system files.
This snippet works fine for images and pdf files but not for Office documents like Word or Excel. I assume it has something to do with encoding, but I have no clues. Any ideas?
Dim dbs As Database
Dim rs As Recordset
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("table1")
With rs
Do While Not .EOF
    Set rsRec = rs.Fields("AttFiles").Value
    While Not rsRec.EOF
        NameOfFile = "C:\temp\" & rsFil.Fields("FileName")
        Open NameOfFile For Binary Access Write As #1
        Put #1, , rsRec.Fields("FileData").Value
        Close #1
        rsRec.MoveNext
    Wend
    .MoveNext
Loop
End With
rs.Close
dbs.Close

A: If the File is actually an attachment type, then you might as well use the Recordset2 of the Microsoft Access Object Library. Something like,
Public Sub exportDocument(tableName As String, fieldName As String, uniqueID As Long)
On Error GoTo Err_SaveImage
    Dim rsParent As DAO.Recordset2
    Dim rsChild As DAO.Recordset2
    Dim saveAsName As String

    Set rsParent = CurrentDb.OpenRecordset("SELECT " & tableName & ".* " & _
                                           "FROM " & tableName & " WHERE " & tableName & "." & fieldName & " = " & uniqueID)
    Set rsChild = rsParent.Fields("fileData").Value

    If rsChild.RecordCount <> 0 Then
        If Dir(Environ("userprofile") & "\My Documents\tmp\", vbDirectory) <> "." Then MkDir Environ("userprofile") & "\My Documents\tmp\"

        saveAsName = Environ("userprofile") & "\My Documents\tmp\" & rsChild.Fields("FileName")

        rsChild.Fields("fileData").SaveToFile saveAsName

        FollowHyperlink saveAsName
    End If
Exit_SaveImage:
    Set rsChild = Nothing
    Set rsParent = Nothing
    Exit Sub

Err_SaveImage:
    If Err = 3839 Then
        Resume Next
    Else
        MsgBox "Some Other Error occured!" & vbCrLf & vbCrLf & Err.Number & " - " & Err.Description, vbCritical
        Resume Exit_SaveImage
    End If
End Sub

The above code will save the files to a location specified in saveAsName. I have specific unique ID in the WHERE condition. If you want to export all documents, you can alter the code accordingly, but might have to loop through the recordset. I hope this helps !


text:
Q: How do I get pcp to automatically attach nodes to postgres pgpool? I'm using postgres 9.4.9, pgpool 3.5.4 on centos 6.8.
I'm having a major hard time getting pgpool to automatically detect when nodes are up (it often detects the first node but rarely detects the secondary) but if I use pcp_attach_node to tell it what nodes are up, then everything is hunky dory.
So I figured until I could properly sort the issue out, I would write a little script to check the status of the nodes and attach them as appropriate, but I'm having trouble with the password prompt. According to the documentation, I should be able to issue commands like
pcp_attach_node 10 localhost 9898 pgpool mypass 1

but that just complains
pcp_attach_node: Warning: extra command-line argument "localhost" ignored
pcp_attach_node: Warning: extra command-line argument "9898" ignored
pcp_attach_node: Warning: extra command-line argument "pgpool" ignored
pcp_attach_node: Warning: extra command-line argument "mypass" ignored
pcp_attach_node: Warning: extra command-line argument "1" ignored
it'll only work when I use parameters like
pcp_attach_node -U pgpool -h localhost -p 9898 -n 1

and there's no parameter for the password, I have to manually enter it at the prompt.
Any suggestions for sorting this other than using Expect?

A: You have to create PCPPASSFILE. Search pgpool documentation for more info.
Example 1:
create PCPPASSFILE for logged user (vi ~/.pcppass), file content is 127.0.0.1:9897:user:pass (hostname:port:username:password), set file permissions 0600 (chmod 0600 ~/.pcppass)
command should run without asking for password
pcp_attach_node -h 127.0.0.1 -U user -p 9897 -w -n 1
Example 2:
create PCPPASSFILE (vi /usr/local/etc/.pcppass), file content is 127.0.0.1:9897:user:pass (hostname:port:username:password), set file permissions 0600 (chmod 0600 /usr/local/etc/.pcppass), set variable PCPPASSFILE (export PCPPASSFILE=/usr/local/etc/.pcppass)
command should run without asking for password
pcp_attach_node -h 127.0.0.1 -U user -p 9897 -w -n 1
Script for auto attach the node
You can schedule this script with for example crontab.
#!/bin/bash
#pgpool status
#0 - This state is only used during the initialization. PCP will never display it.
#1 - Node is up. No connections yet.
#2 - Node is up. Connections are pooled.
#3 - Node is down.

source $HOME/.bash_profile
export PCPPASSFILE=/appl/scripts/.pcppass
STATUS_0=$(/usr/local/bin/pcp_node_info -h 127.0.0.1 -U postgres -p 9897 -n 0 -w | cut -d " " -f 3)
echo $(date +%Y.%m.%d-%H:%M:%S.%3N)" [INFO] NODE 0 status "$STATUS_0;

if (( $STATUS_0 == 3 ))
then
    echo $(date +%Y.%m.%d-%H:%M:%S.%3N)" [WARN] NODE 0 is down - attaching node"
    TMP=$(/usr/local/bin/pcp_attach_node -h 127.0.0.1 -U postgres -p 9897 -n 0 -w -v)
    echo $(date +%Y.%m.%d-%H:%M:%S.%3N)" [INFO] "$TMP
fi

STATUS_1=$(/usr/local/bin/pcp_node_info -h 127.0.0.1 -U postgres -p 9897 -n 1 -w | cut -d " " -f 3)
echo $(date +%Y.%m.%d-%H:%M:%S.%3N)" [INFO] NODE 1 status "$STATUS_1;

if (( $STATUS_1 == 3 ))
then
    echo $(date +%Y.%m.%d-%H:%M:%S.%3N)" [WARN] NODE 1 is down - attaching node"
    TMP=$(/usr/local/bin/pcp_attach_node -h 127.0.0.1 -U postgres -p 9897 -n 1 -w -v)
    echo $(date +%Y.%m.%d-%H:%M:%S.%3N)" [INFO] "$TMP
fi

exit 0

A: yes you can trigger execution of this command using a customised failover_command (failover.sh in your /etc/pgpool)

A:
Automated way to up your pgpool down node:

*

*copy this script into a file with execute permission to your desired location with postgres ownership into all nodes.

*run crontab -e comamnd under postgres user

*Finally set that script to run every minute at crontab . But to execute it for every second you may create your own
service and run it.

#!/bin/bash
# This script will up all pgpool down node

#************************
#******NODE STATUS*******
#************************

# 0 - This state is only used during the initialization.
# 1 - Node is up. No connection yet.
# 2 - Node is up and connection is pooled.
# 3 - Node is down

#************************
#******SCRIPT*******
#************************
server_node_list=(0 1 2)
for server_node in ${server_node_list[@]}
do
    source $HOME/.bash_profile
    export PCPPASSFILE=/var/lib/pgsql/.pcppass
    node_status=$(pcp_node_info -p 9898 -h localhost -U pgpool  -n $server_node -w | cut -d ' ' -f 3);

    if [[ $node_status == 3 ]]
    then
            pcp_attach_node -n $server_node -U pgpool -p 9898 -w -v
    fi

done


text:
Q: Save video in every 5 second interval while video recoding is ON (Android OS) I want to save the video every 5 seconds while the video recording is ON.
I have tried many solutions but I am facing a Glitch that is, the Last Saved Frame remains in preview for around 300ms.
I think the reason is in MediaRecorder class "Once a recorder has been stopped, it will need to be completely reconfigured and prepared before being restarted."
Thanks

A: I think it's impossible to do that with MediaRecorder. The better approach could be encoding video by using MediaCodec and storing encoded content bt using MediaMuxer.
Grafika is a project on Google Github account which is a dumping ground for Android graphics & media hacks. In this project, you can find good examples of using both MediaCodec and MediaMuxer classes.
I forked the Grafika project and did some modifications to support sequential segmented recording. You can find it here. When you run the application, select Show + capture camera item from the list and then set Output Segment Duration for example to 5 and then press Start recording button.
Please look at VideoEncoderCore and CameraCaptureActivity classes source code to find how it works. You can find here how it segments live camera feed to different files.

A:
"I think the reason is in MediaRecorder class, "Once a recorder has been stopped, it will need to be completely reconfigured and prepared before being restarted"."

You can use multiple mediaMuxer's to encode separate files.

*

*The camera should send data to fill a MediaMuxer object (which itself produces an .mp4 file).

*When needed, you can start writing the Camera data to a second (different) MediaMuxer thus automatically creating a second new .mp4 file (on begin usage of the muxer).

*The first MediaMuxer can then close and save its file. Your first segment is ready...
If needed, try to study this code for a guide on using Camera with mediaMuxer:
https://bigflake.com/mediacodec/CameraToMpegTest.java.txt
So you have a function that handles things when the 5 second interval has passed? In that function, could cycle the recording between two muxers, giving one a chance to close its file, while the other records the next segment and then vice-versa).
Instead of something like below (using MediaRecorder.OutputFormat.MPEG_4):
this.mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

You will instead create a new muxer (with MUXER_OUTPUT_MPEG_4):
//# create a new File to ssave into
File outputFile = new File(OUTPUT_FILENAME_DIR, "/yourFolder/Segment" + "-" + mySegmentNum + ".mp4");
String outputPath = outputFile.toString();
int format = MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4;

try { mMuxer = new MediaMuxer(outputPath, format); }
catch (IOException e) { Log.e(TAG, e.getLocalizedMessage()); }

And you stop a muxer with:
mMuxer1.stop(); mMuxer1.release();

PS:
Another option is to use Threads to run multiple MediaRecorders. It might help your situation. See the Android Background Process guide.


text:
Q: How to change apply setState when onChange happend? This the code:
import React, { Component } from 'react';
import { Select } from 'antd';
import { connect } from "react-redux";

class SelecionarCrypto extends Component {
  constructor(props) {
    super(props);

    this.onChange = this.onChange.bind(this);
    this.onBlur = this.onBlur.bind(this);
    this.onFocus = this.onFocus.bind(this);
    this.onSearch = this.onSearch.bind(this);

    console.log(this.props);

    this.state = {
      ValorState: "nada"
    }

  };

 onChange(value) {
    console.log(`selected ${value}`);
    this.setState({ValorState: value});
    console.log("New value onchange", this.ValorState)

  }

  onBlur() {
    console.log('blur');
  }

  onFocus() {
    console.log('focus');
  }

  onSearch(val) {
    console.log('search:', val);
  }

render(){

const { Option } = Select;

console.log("New value Render", this.ValorState)

return (
  <Select
    showSearch
    style={{ width: 200 }}
    placeholder="Seleciona:"
    optionFilterProp="children"
    onChange={this.onChange}
    onFocus={this.onFocus}
    onBlur={this.onBlur}
    onSearch={this.onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="ETH">ETH</Option>
    <Option value="BTC">BTC</Option>
    <Option value="XRP">XRP</Option>
  </Select>

  );
}

  }

  const mapStateToProps = state => {
    return {
      token: state.token
    };
  };

  export default connect(mapStateToProps)(SelecionarCrypto);

I am trying to change the value of ValorSate when onChange is done.
The error I am obtaining is: TypeError: this.setState is not a function.
I don´t find out the solution even readin about setSate() . I am followinf the same pattern of how-to´s or documentation but I no understanding something.
Now "New value onChange" or "New value Render" is always undefined"
console log:

Thank you.

A: Move those functions outside the render, bind them to the this of your component and reference them with the this keyword:
class SelecionarCrypto extends Component {
  constructor(props) {
     ...
     this.onChange = this.onChange.bind(this)
     // Similar for the rest
  }

  onChange(value) { this.setState({ ValorState: value }) }
  onBlur() {}
  onFocus() {}
  onSearch() {}

  ...

  render(){

  ...
  return
  (
  <Select
    showSearch
    style={{ width: 200 }}
    placeholder="Seleciona:"
    optionFilterProp="children"
    onChange={this.onChange}
    onFocus={this.onFocus}
    onBlur={this.onBlur}
    onSearch={this.onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="ETH">ETH</Option>
    <Option value="BTC">BTC</Option>
    <Option value="XRP">XRP</Option>
  </Select>
  )
}

A: I have modified your code. Please check it and try.
import React, { Component } from 'react';
import { Select } from 'antd';
import { connect } from "react-redux";

class SelecionarCrypto extends Component {
  constructor(props) {
    super(props);

    console.log(this.props);

    this.state = {
      ValorState: 'nada'
    }
  };

onChange = (value) => {
  console.log(`selected ${value}`);
  this.setState({ValorState: 'algo'})
}

onBlur = () => {
  console.log('blur');
}

onFocus = () => {
  console.log('focus');
}

onSearch = (val) => {
  console.log('search:', val);
}
render(){
const { Option } = Select;

return (
  <Select
    showSearch
    style={{ width: 200 }}
    placeholder="Seleciona:"
    optionFilterProp="children"
    onChange={this.onChange}
    onFocus={this.onFocus}
    onBlur={this.onBlur}
    onSearch={this.onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="ETH">ETH</Option>
    <Option value="BTC">BTC</Option>
    <Option value="XRP">XRP</Option>
  </Select>

  );
}

}

const mapStateToProps = state => {
return {
  token: state.token
};
};

export default connect(mapStateToProps)(SelecionarCrypto);

A:

import React, { Component } from 'react';
import { Select } from 'antd';
import { connect } from "react-redux";

class SelecionarCrypto extends Component {
  constructor(props) {
    super(props);

    //this.onChange = this.onChange.bind(this);

    console.log(this.props);

    this.state = {
      ValorState: 'nada'
    }

  };

 onChange=(value)=> {
  console.log(`selected ${value}`);
  this.setState({ValorState: 'algo'})
}

function onBlur() {
  console.log('blur');
}

function onFocus() {
  console.log('focus');
}

function onSearch(val) {
  console.log('search:', val);
}

render(){

const { Option } = Select;

return (
  <Select
    showSearch
    style={{ width: 200 }}
    placeholder="Seleciona:"
    optionFilterProp="children"
    onChange={this.onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="ETH">ETH</Option>
    <Option value="BTC">BTC</Option>
    <Option value="XRP">XRP</Option>
  </Select>

  );
}

  }

  const mapStateToProps = state => {
    return {
      token: state.token
    };
  };

  export default connect(mapStateToProps)(SelecionarCrypto);

function must be a outside from render and bind onchange function otherwise setstate will not effective

A: import React from "react";
import { Select } from "antd";
import { connect } from "react-redux";

class SelecionarCrypto extends React.Component {
    constructor(props) {
        super(props);

    //this.onChange = this.onChange.bind(this);

    console.log(this.props);

    this.state = {
        ValorState: "nada",
    };
}

onChange(value) {
    console.log(`selected ${value}`);
    this.setState({ ValorState: "algo" });
}

onBlur() {
    console.log("blur");
}

onFocus() {
    console.log("focus");
}

onSearch(val) {
    console.log("search:", val);
}

render() {
    const { Option } = Select;

    return (
        <Select
            showSearch
            style={{ width: 200 }}
            placeholder="Seleciona:"
            optionFilterProp="children"
            onChange={this.onChange}
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            onSearch={this.onSearch}
            filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
        >
            <Option value="ETH">ETH</Option>
            <Option value="BTC">BTC</Option>
            <Option value="XRP">XRP</Option>
        </Select>
    );
   }
}

const mapStateToProps = (state) => {
    return {
        token: state.token,
    };
};

export default connect(mapStateToProps)(SelecionarCrypto);


text:
Q: Notebook for Linux/Ubuntu commands Jupyter notebooks are a way of running code interactively while also providing note-taking functionality. While Jupyter supports the Python programming language by default, there are several different kernels available for other languages, like Java for example. I want to create a  Jupyter notebook for running linux terminal commands. If I would use jupyter notebook, I shall be using

!pwd

What is the best way to do this? Are there other applications designed for this use case that are more effective?

A: If I'm understanding your question correctly (that you want to use Jupyter for bash, not write your own notebook software in/for bash), the Jupyter wiki has a section outlining the kernels you can use, including one for bash.


text:
Q: Interpretation of the linear predictor of a OLS model on binomial data If i have some simulated standard normally distributed data:
$$µ_i = β_0 + β_1X_{i1} + β_2X_{i2} +···+β_kX_{ik}$$ where $$Y_i \sim N(\mu_i, 1)$$
Created with function: (with python in this case)
def simulate_normal(dummy, k, n, p, k1, k2, seed):
    # Set seed
    np.random.seed(seed)

    # Simulate regcoef
    P = np.random.randn(k, p)
    Ym = dummy@P
    _, v, _ = PCA(Ym, k)

    # Simulate noise
    # Structured noise
    Esn = np.random.randn(n*k,k)@v.T

    # White noise
    Ewn = np.random.randn(n*k,p)

    # Blend data
    E = k1*Esn + k2*Ewn
    Y = Ym + E
    return Y

where dummy is a dummy matrix of the linear predictors (contrast code), k is number of factor levels, n is number of observations per factor level, p is number of variables, k1 and k2 is the size of the noise of structured and white noise.
And i make it into binomial (bernoulli) data with the logistic function: $$p =\frac{1}{1 + e^{-Y}} = \frac{1}{1 + e^{-(x^T_i + E)}}$$
def make_binomial(Y):
    # Logistic function:
    Y_log = 1/(1 + np.exp(-Y))
    # Random binomial
    Y_bin = np.random.binomial(Y_log)
    return Y_bin

If i then fit two models on the binomial data Y_bin, one with OLS (even though it does not make sense to do) and one with logit link and GLM, i would assume the linear predictors of the glm model $$\eta = β_0 + β_1X_{i1} + β_2X_{i2} +···+β_kX_{ik}$$ are the same as the Ym from the simulate_normal() function.
I would also assume that the linear predictors from the OLS model are the same as the Y_log from the make_binomial() function, or $$µ_i = p_i$$
If i chose  to look at only $β_1X_{i1}$ from the GLM model I would expect to get the same values as $β_1X_{i1}$ from the simulated normally distributed data. (Dependent on the error)
So my question.. :

How would i interpret $β_1X_{i1}$ of the OLS model if i chose to look at the contribution of only one linear predictor?

A: The difference is that OLS is 1) not using a link function and 2) assumes a different distribution of the data.
Fitting a straight line model
OLS works well when you have a linear model for the mean of the distribution and Gaussian distributed data. But even when the distribution would not be Gaussian it would still work reasonable. See for instance in the following example where the data is binomial distributed but the model for the parameter $p$ is linear.

In this case the linear OLS model is a good estimator for the parameter $p$.
Fitting a more complex model
However, OLS works bad in many other cases because the linear fit is often not capturing the underlying model well. Below is an example of a graph where the true underlying model for the parameter $p$ follows a logistic function.

Now the linear fit is not representing the model well and you even get a lot of estimated values above 1 and below 0 which make little sense.
Interpretation of OLS model

How would i interpret $β_1X_{i1}$ of the OLS model if i chose to look at the contribution of only one linear predictor?

If you fit a model that is created with a logistic curve then the values of the coefficients $\beta$ will be different. This is not so much because of the binomial distribution. But it is because of the different scale and you will get distortions because the linear model won't be able to capture the curved model and will only be able to approximate it well in a part of the range.
You might even get that some coefficients will have a different sign in the OLS model. This can occur when the regressor variables are correlated. Then the fit might abuse some of the variables to correct for the wrong slope of the straight line which should not be continuous.
An example is below where we have a model for the parameter $p$ for a Bernoulli variable
$$p = \frac{1}{1+e^{-(\beta_x x+ \beta_z z)} } \qquad \beta_x = 1 \text{ and } \beta_z = 1$$
With the conditions that we created in this example, a linear OLS model will make predictions for the coefficients with $\beta_z$ negative. You see this in the image below. For the true model the red curve associated with $z=1$ is higher than the black curve associated with $z=0$. For the fitted curves/lines this is reversed. The reason that this happens is because in this example most of the values with $z=1$ occur when the value of $x$ is large, and for these values the model has a positive bias. The negative coefficient for $z$ is able to correct for this.

logis = function(x) {
  (1+exp(-x))^-1
}

### data and plot
set.seed(1)
n = 10^4
d = 1+rbinom(n,8,0.5)
x = runif(n,-d,d)
z = rbinom(n,1,prob = logis(x-4))
y = rbinom(n,1,logis(x+z))
plot(x,jitter(y,0.05), pch = 21, col = 1, bg = z*2, cex = 0.7,
     xlab = "x", ylab = "y")

### true model line
xs = seq(-8,8,0.001)
lines(xs,logis(xs), lty = 2, lwd = 2)
lines(xs,logis(xs+1), lty = 2, lwd = 2, col = 2)

### linear model line fit
mod = lm(y~x+z)
mod
## result
# Call:
# lm(formula = y ~ x + z)
#
# Coefficients:
# (Intercept)            x            z
#     0.51526      0.12572     -0.03936

xs = seq(-8,8,0.001)
lines(xs, mod$coefficients[1] + mod$coefficients[2] * xs ,
     col = 1, lty = 1)
lines(xs, mod$coefficients[1] + mod$coefficients[2] * xs + mod$coefficients[3] ,
     col = 2, lty = 1)

### legend
legend(-8.2,0.95, c("data points z=0", "data points z=1",
                      "true model z=0","true model z=1",
                      "linear OLS fit z=0", "linear OLS fit z=1"),
       pch = c(21,21,NA,NA,NA,NA),
       lwd = c(NA,NA,2,2,1,1),
       lty = c(NA,NA,2,2,1,1),
       col = c(1,1,1,2,1,2),
       pt.bg = c(0,2,NA,NA,NA,NA),
       cex = 0.6)

### glm model fit
mod2 = glm(y~x+z, family = binomial)
mod2
## result
# Coefficients:
# (Intercept)            x            z
#     0.06146      1.03038      1.28454


text:
Q: Why won't these class properties display in the view, and why can't breakpoints be set on them? I have a bizarre problem that I can't figure out. I have a domain object similar to the following, with two custom getter properties that (a) do not return any visible value in the view when called, and (b) will not let me set a breakpoint on them to inspect them during execution.
(Note: There are other similar questions regarding setting breakpoints on auto-property setters -- that is NOT my question. My problem is regarding formally declared get{} properties.)
Here's an example of how my domain model looks:
public class Program : IProgram
{
    public string Code { get; set; }
    public string Title { get; set; }
    public string StatusCode { get; set; }
    public DateTime StatusDate { get; set; }

    public bool HasCompleted
    {
        get
        {
            return (StatusCode == "A" || StatusCode == "B");
        }
    }

    public string HumanizedStatus
    {
        get
        {
            switch (StatusCode)
            {
                case "0": return "Text for 0"; break;
                case "1": return "Text for 1"; break;
                case "2": return "Text for 2"; break;
                case "3": return "Text for 3"; break;
                case "4": return "Text for 4"; break;
                case "5": return "Text for 5"; break;
                case "A": return "Text for A"; break;
                case "B": return "Text for B"; break;
                case "C": return "Text for C"; break;
                case "D": return "Text for D"; break;
                case "E": return "Text for E"; break;
                case "W": return "Text for W"; break;
                default : return "UNKNOWN"; break;
            }
        }
    }
}

This model is attached to a ViewModel that is rendered as a set of table rows in the view as follows:
@foreach (var program in Model.Programs)
{

        @program.Code
        @program.Title
        @program.StatusDate
        @program.HumanizedStatus
        @program.HasCompleted

}

In the view I see the displayed text for @program.Code, @program.Title, and @program.StatusDate, but I see nothing in the view for @program.HumanizedStatus or @program.HasCompleted. There are other properties displayed after that in my screen and they show up fine as well.
When I attempt to set a breakpoint on either of those properties (by clicking in the left gutter) I get the red ball as expected, but they are never hit when the view is rendered. I can set other breakpoints just fine, and breakpoints set in methods all execute normally, but here they do not. I can also verify via breakpoint in the controller that the model is properly constructed, but the HumanizedStatus property returns null at that point and the HasCompleted method returns false. So I suspect the debugger is showing default "uninitialized" values for them, but I can't figure out why they aren't called. I even added this to the controller action:
       if (programs[0].HasCompleted)
        {
            //nop
        }

and set a breakpoint on it to inspect the first Program object in the list, and it also returned false for HasCompleted and null for HumanizedStatus. I also tried this answer for manually setting the breakpoint and received an error message "IntelliSense could not find the specified location. Do you still want to set the breakpoint?". Even if I select "Yes" it still never fires.
I could change them to methods, but then AutoMapper throws an error, which I could work around by excluding them from the mapping, but that is jumping through hoops I shouldn't have to jump through.
The properties are declared in the interface. I am using VS2010, MVC 3.
Many thanks in advance for any help!


text:
Q: beautiful soup not to parse nested table data I have a nested table structure. I am using the below code for parsing the data.
for row in table.find_all("tr")[1:][:-1]:
    for td in row.find_all("td")[1:]:
        dataset = td.get_text()

The problem here is when there are nested tables like in my case there are tables inside 	 so these are parsed again after parsing initially as I am using find_all(tr) and find_all(td). So how can I avoid parsing the nested table as it is parsed already?
Input:

   1	2

   3	4

  5

11	22

      6

Expected Output:
1  2
3  4
5
11 22
6

But what I am getting is:
1 2
3 4
5
11 22
11 22
6

That is, the inner table is parsed again.
Specs:
beautifulsoup4==4.6.3
Data order should be preserved and content could be anything including any alphanumeric characters.

A: Using a combinations of bs4 and re, you might achieve what you want.
I am using bs4 4.6.3
from bs4 import BeautifulSoup as bs
import re

html = '''

   1	2

   3	4

  5

11	22

      6

'''

soup = bs(html, 'lxml')

ans = []

for x in soup.findAll('td'):
    if x.findAll('td'):
        for y in re.split('
.*
', str(x)):
            ans += re.findall('\d+', y)
    else:
        ans.append(x.text)
print(ans)

For each td we test if this is a nest td. If so, we split on table and take everything and match with a regex every number.
Note this working only for two depths level, but adaptable to any depths

A: I have tried with findChilden() method and some how managed to produce output.I am not sure if this will help you in any other circumstances.
from bs4 import BeautifulSoup
data='''

   1	2

   3	4

  5

11	22

      6

'''

soup=BeautifulSoup(data,'html.parser')

for child in soup.find('table').findChildren("tr" , recursive=False):
  tdlist = []
  if child.find('table'):
     for td in child.findChildren("td", recursive=False):
         print(td.next_element.strip())
         for td1 in td.findChildren("table", recursive=False):
             for child1 in td1.findChildren("tr", recursive=False):
                 for child2 in child1.findChildren("td", recursive=False):
                     tdlist.append(child2.text)
                 print(' '.join(tdlist))
                 print(child2.next_element.next_element.strip())
  else:

     for td in child.findChildren("td" , recursive=False):
         tdlist.append(td.text)
     print(' '.join(tdlist))

Output:
1 2
3 4
5
11 22
6

EDITED for Explanation
Step 1:
When use findChilden() inside table it first returns 3 records.
for child in soup.find('table').findChildren("tr", recursive=False):
    print(child)

Output:

1	2

3	4

5

11	22

          6

Step 2:
Check that any children has tag
 and do some operation.
 if child.find('table'):

Step 3:
Follow the step 1 and use findChilden() to get  tag.
Once you get the  follow step 1 to get the children again.

Step 4:
for td in child.findChildren("td", recursive=False)
      print(td.next_element.strip())

Next element will return the first text of tag so in that case it will return the value 5.

Step 5
for td in child.findChildren("td", recursive=False):
             print(td.next_element.strip())
             for td1 in td.findChildren("table", recursive=False):
                 for child1 in td1.findChildren("tr", recursive=False):
                     for child2 in child1.findChildren("td", recursive=False):
                         tdlist.append(child2.text)
                     print(' '.join(tdlist))
                     print(child2.next_element.next_element.strip())

If you see here i have just follows step 1 recursively.Yes Again I have used child2.next_element.next_element to get the value of 6 after
 tag.

A: You can check if another table exists inside a td tag, if it exists then simply skip that td, otherwise use it as a regular td.
for row in table.find_all("tr")[1:][:-1]:
    for td in row.find_all("td")[1:]:
        if td.find('table'):  # check if td has nested table
            continue
        dataset = td.get_text()

A: In your example, with bs4 4.7.1 I use :has :not to exclude looping rows with table child
from bs4 import BeautifulSoup as bs

html = '''

        1
        2

        3
        4

                    11
                    22

'''

soup = bs(html, 'lxml')
for tr in soup.select('tr:not(:has(table))'):
    print([td.text for td in tr.select('td')])


text:
Q: How to secure node js API Have create a node JS API application using :
https://github.com/spoonx/wetland
to secure that API I have thought I will assign an API key to every user, but a question stuck to my mind that may be sometime a malicious user get API key of other user and he can use that API.
So my question is how I can secure my API for all this hack?

A: There are multiple ways that you can lock down your API if it is required, bear in mind the more security you add, generally the more difficult it becomes for the end user to use your API.
IP address locking
You can assign an IP address to each one of your users and store it in the database. In your authentication middleware, once the user has succesffuly authenticated with their API key, you will check their requesting ip using request.connection.remoteAddress. If the IPs are matching you allow the connection, otherwise you deny it.
JSON Web Tokens
The second thing you can use is JWT's which are stateless objects that you can use to authenticate your users. It is a more secure way of implementing your API. You can read about it here
Use HTTPS
Using HTTPS will make sure that no one is able to sniff (MiTM) the api keys and any other information sent with the request. Using HTTPS will add an extra layer of security ontop of your app which will make it harder for a malicious actor to gain access to your api keys.
Bear in mind that all these solutions will allow more security for your tokens/api keys, but if one of your users goes and exposes their API key, then you will either need to revoke that API key and generate a new one, or delete that one completely.
So I would recommend storing the API keys alongside the users in the database so that you can easily revoke or regenerate api keys for the specific users. You should also be keeping logs of your api requests so that you can detect abnormal traffic, or traffic originating from an unknown source, if IP address locking is not implemented.


text:
Q: Clear a FireMonkey TListView Is there a preferred way to clear a TListView control or do we just cycle through all items deleting them?
Below is code to clear a TListBox. Is there something similar for TListView that I'm just missing in my searching?
Form1->ListBox2->Clear();

thanks,
russ

A: Use the Items->Clear() method:
ListView1->Items->Clear();


text:
Q: FragmentActivity - Zoom to show streets I'm having some issues using FragmentActivity and SupportMapFragment. The map's zoom is all wonky.
Here's the code:
public class GoogleMapActivity extends FragmentActivity{
Double longitude, latitude;
static LatLng koordinate;
GoogleMap supportMap;
String title, address;

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_googlemaps);
    SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    supportMap = fm.getMap();

    longitude = 13.597651720046997;
    latitude = 45.22456639103469;
    title = "Turistička zajednica Općine Vrsar";
    address = "ul. Rade Končara 46";
    koordinate = new LatLng(longitude, latitude);

    Marker marker = supportMap.addMarker(new MarkerOptions().position(koordinate).title(title).snippet(address)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_star)));
    //supportMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    supportMap.moveCamera(CameraUpdateFactory.newLatLngZoom(koordinate, 15));
    supportMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}}

For some reason, I get following thing in google maps, which is not zoomed enough:
http://imageshack.us/f/812/3yl.png/
When I click on the zoom, the map goes into this state:
http://imageshack.us/f/825/k8np.png/
I need the maps to zoom enough so that the street names are shown.This works just fine in my previous application, but I used regular MapFragment there. For this app, I need SupportMapFragment. Maybe that's causing this issue?

A: Zoom in the Google Map
  googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

OR
 LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
  googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

the maximum zoom allowed is 17 i guess.
i hope this must work...


text:
Q: Build an array of ids of all select boxes I'm trying to convert a bunch of select boxes to be editable using the fantastic jQuery plugin: https://github.com/indrimuska/jquery-editable-select.
The first step is to get the ids of all select boxes. From http://jsfiddle.net/49rk6ph7/69/ I have tried this but I'm not getting:
[s1,s2]

How can I get this working?

var test = [];
test = $("select").each(function() {
  test.push($(this).attr('id'))
});

console.log(test);

  <select id="s1" onchange="this.nextElementSibling.value=this.value">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />

  <select id="s2" onchange="this.nextElementSibling.value=this.value">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />

A: Remove test = before your jQuery call. You're overwriting your original test array.
This is all you need:
var test =  [];

$("select").each(function() {
    test.push($(this).attr("id"));
});

console.log(test);

A: The issue with your code is because you're assigning test to the result of each(), which is a jQuery object, not the array you originally define. Simply remove test = from that statement.
Note that you can also make the logic more succinct by using map() instead of an each() loop and by removing the outdated on* attributes with unobtrusive JS event handlers. Something like this:

var test = $("select").map(function() {
  return this.id
}).get();

console.log(test);

$('#s1, #s2').change(function() {
  $(this).next().val($(this).val());
});

  <select id="s1">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />

  <select id="s2">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />


text:
Q: Добавить/удалить класс к картинке при скролле У меня есть блок с картинками, он находится в контентной части сайта и когда мы докручиваем до него, то к картинкам добавляется класс, и они переворачиваются. Все работает как надо. Но мне нужно чтобы когда мы прошли этот блок, класс удалился, и чтобы он добавлялся каждый раз когда мы будем возвращаться к этому блоку, а то он добавляется только один раз и все. Добавление класса при достижении определенной высоты не предлагать, так как высота может быть разная в зависимости от объема контента. Код приложил ниже:

var a = 0;
$(window).scroll(function() {

  var oTop = $('.exp-wrapper__img').offset().top - window.innerHeight;
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('img').each(function() {
$('img').addClass('exp-animate');
    });
    a = 1;
  }

});
.content{
  float: left;
  height: 500px;
  width: 100%;
}
.exp-wrapper__img{
  float: left;
  width: 100%;
  transform: rotate(0deg);
  transition: 2s;
}
.exp-wrapper__img img{
  width: 100px;
}
.exp-animate{
  transform: rotate(180deg);
  transition: 2s;
}

A: Вот есть хорошее рабочее решение:

$.fn.isInViewport = function() {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();
  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();
  return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
  if ($('.exp-wrapper__img').isInViewport()) {
    $('img').addClass('exp-animate');
  } else {
    $('img').removeClass('exp-animate');
  }
});
.content {
  float: left;
  height: 500px;
  width: 100%;
}

.exp-wrapper__img {
  float: left;
  width: 100%;
  transform: rotate(0deg);
  transition: 2s;
}

.exp-wrapper__img img {
  width: 100px;
}

.exp-animate {
  transform: rotate(180deg);
  transition: 2s;
}


text:
Q: Rotate images from terminal I have a directory with a lots of images but they are in the wrong orientation. I want to rotate the images to correct the orientation (mostly ±90o). Using image (shotwell photo) viewer I can rotate them individually by clicking the rotate button but that's too tedious.
I looked at man shotwell and shotwell --help-all but there's nothing that explains how to invoke the rotate command from the command line.
Is there any way I can invoke the rotate command of shotwell (or any other viewer) from the terminal? Or any other methods to rotate images are welcome too.

A: If you're looking for a pure bash implementation, ImageMagick's convert command is what you're looking for:
for szFile in /path/*.png
do
    convert "$szFile" -rotate 90 /tmp/"$(basename "$szFile")" ;
done

Above will leave existing files intact and copy the newly rotated ones to /tmp so you can move or copy them somewhere else or even replace the existing ones after the conversion and after verification.
(and it'll work on all recent releases of Ubuntu as it's standard software)

A: Here's how I do it:

*

*Install gThumb
 sudo apt-get install gthumb

*Open up nautilus and go to your images directory. Right click on one and choose Open with -> gthumb.

*Under the view menu choose Browser or press the Esc key. This will open the directory browser showing all your images.

*Press Ctrl and select the images you want to rotate or select all of them via Ctrl + A.

*On the toolbar, select Tools and then Rotate Right or Rotate Left depending on your preference.

A: for file in *.JPG; do convert $file -rotate 90 rotated-$file; done

This will copy-rotate-and-rename your files.
If you want to leave the original files untouched just yet, this method may work well for you...
 Note that this is case-sensitive: if your files are named *.jpg replace with lower-case (or *.png ...) accordingly.

A: If you want to overwrite in-place, mogrify from the ImageMagick suite seems to be the easiest way to achieve this:
# counterclockwise:
mogrify -rotate -90 *.jpg

# clockwise:
mogrify -rotate 90 *.jpg

CAVEAT: This isn't a lossless rotation method for JPEG files, https://www.imagemagick.org/discourse-server/viewtopic.php?t=5899.
jpegtran achieves this (untested):
# counterclockwise
ls *.jpg | xargs -n 1 jpegtran -perfect -rotate 270

# clockwise
ls *.jpg | xargs -n 1 jpegtran -perfect -rotate 90

A: As krlmlr notes in their answer, jpegtran (installed on Ubuntu with sudo apt install libjpeg-turbo-progs) is available for lossless rotation, but because it outputs to standard output, the command to use it would be something like this:
$ for img in *.jpg; do jpegtran -rotate 90 -copy all $img > rotated-${img}; done

This command will take each file in the current directory, and produce a rotated version (90° clockwise) copy of each file with the new name rotated-image-name.jpg. The switch -copy all is to copy all metadata to the new file.
For more information see man jpegtran.
An additional piece of information given that the original question referenced Shotwell: according to Shotwell's documentation, Shotwell's rotations and other edits will not actually edit the files on disk:

Shotwell is a non-destructive photo editor. It does not modify your original photographs. That is to say, if you crop a photo or adjust its colors, the photo file on disc remains untouched. Shotwell stores your edits in a database and applies them on the fly as necessary. This means you can undo any alterations you make to a photograph.

A: A nice solution is to make a set of backups (e.g. prefixed backup-), rotate the original files producing a set of new files (prefixed e.g. rotated-), giving you a set of

*

*img-1.png

*backup-img-1.png

*rotated-img-1.png

*img-2.png

*...and so on
The mv/cp tools [bash globbing] can only add prefixes, it's messy to take them away (it'd use parameter expansion, ewww...)
The rename tool allows you to use s/before/after/ substitution syntax (from the sed tool) to swap that safeguard prefix and overwrite the original files, so your overall process for a given set of pictures img-{1..n}.png would be:
for imgf in img-*.png; do mv "$imgf" "backup-$imgf"; done
for imgf in backup-img-*.png; do convert "$imgf" -rotate 90 "rotated-$imgf"; done

Note:

*

*you could use cp rather than mv, but then there's 2 copies of the original lying around (downside is you get concatenation of prefixes, "rotated-backup-...")

*rotation is clockwise (-rotate 270 gets you 90° anti-clockwise)

*to track progress, add echo "Rotating ${imgf#backup-} ... "; after convert calls (before done)

*for a more compact form (e.g. a set of numbered files), use some parameter expansion like echo "$(echo ${imgf#backup-img-} | cut -d\. -f 1)..."; instead
( You can't remove prefix and suffix in the same bash param expansion hence use cut )
Then after verification you've not messed up, delete the pictures by moving them back to the original
rename 's/^rotated-//;' rotated-*
rm backup-img-*

A: You can copy/paste this code, and save it as rotate.sh
#!/bin/bash -e

CUR_DIR=$(pwd)
cd $1
for file in *.jpg
do
    convert $file -rotate 90 $file
done
cd $CUR_DIR

After saving this file, run it from terminal using ./rotate.sh folder_containing_images.

A: How about exiftran - transform digital camera jpeg images
I know it's a bit limiting (jpeg) but it has automatic (using exif orientation tag).
for photo in *.jpg
  do exiftrans -ia $photo
done

About Exiftran,  it is  a command line utility to transform digital camera jpeg images. It can do lossless rotations like jpegtran(1), but unlike jpegtran(1) it cares about the EXIF data: It can rotate images automatically by checking the exif orientation tag; it updates the exif informations if needed (image dimension, orientation); it also rotates the exif thumbnail. It can process multiple images at once

A: If you have ffmpeg and if your images are numbered consecutively starting from zero with 6 digits, you can rotate them with
ffmpeg -pattern_type glob -i '*.jpg' -start_number 0 -vf "transpose=1" -qscale:v 5 %06d.jpg

The digit after qscale:v controls output quality, lower is better.


text:
Q: Run method on server without Refreshing I know how to use UpdatePanels and so on but I would like to know if its possible to run method on the server (after clicking a button) which doesnt change anything in controls on the site but for example updates database.
I know that I can use WebService but is there any way to use simple code behind methods ?
thanks for help

A: Yes you could call a C# function to update the database from say, javascript for example
Heres a link that explains how:
http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx

A: u have writen all ways to do it. There no any way to do it.
1. UpdatePanel (AjaxControl)
2.with javascript(or jQuery. Best to use JQuery) call WebService

A: It's not possible without javascript or ajax because every method which gets hosted in a webenvironment gets only called if the request goes to the server which means postback.

A: Since UpdatePanels and other useful AJAX controls appeared, we, developers, forgot a little bit "How" something is working on the back. I recommend you to use a Script callback, there are plenty of examples on Internet like this: http://msdn.microsoft.com/en-us/magazine/cc163941.aspx
With this you can update database on the server function, and do nothing(return false;) when it succeeds on client success event handling function.
Hope that helps,

A: I would recommend jQuery Ajax including the .ajaxStart() .ajaxStop() to do stuff like display a panel until/while the ajax event is active.
see here for more information: http://api.jquery.com/category/ajax/
EDIT: some complete sample code:
$(document).ready(function()
{
    /***************************************/
    function testLoadTime(jdata)
    {
        $("#timeResult").text(jdata);
    };
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
       {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
            typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "MyProcedure.asmx/GetServerTimeString",
        success: function(msg)
        {
            testLoadTime(msg);
        }
    });

});
server side:
  [WebMethod]
    public static string GetServerTimeString()
    {
        return "Current Server Time: " + DateTime.Now.ToString();
    }


text:
Q: How can you import portfolio projects in react? I'm making a portfolio with react. How can I navigate to my projects through my localhost:3000? They are in my includes folder and the projects aren't made with react. It seems not to be the same as using XAMPP as my sever.
My file structure is:
-src
   -componets
      -sectionB.js
   -imports
     -myproject1
       -index.php
I'm trying to go to my project with an  tag with this code:
import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'

class Card extends Component {
  render() {
    return (

{this.props.projName}

          Technolgies: ({this.props.tech})

{this.props.projdesc}

    )
  }
}

class SectionB extends Component {
  render() {
    return (

        <Card projdesc={...} img={...} tech="..." projName="..." href="./imports/calendar2/index.php"/>

    )
  }
}

export default SectionB;

Why is this not directing the url to my project?

A: I think you're supposed to be using Link from react-router-dom. That may be a place to start. And what happens when you change:
<Card projdesc={...} img={...} tech="..." projName="..." href="./imports/calendar2/index.php"/>

to
<Card projdesc={...} img={...} tech="..." projName="..." href="../imports/calendar2/index.php"/>


text:
Q: Como chamar a aplicação de "ligar número" em uma webview? Eu tenho uma parte no meu aplicativo que é uma webview, como fazer para que ao clicar no telefone da webview, abrir a intent de chamadas?

A: Não precisa necessariamente chamar um Intent, você pode usar o "tel URI scheme", desta maneira:
Chamar

Ou com javascript:
window.location = "tel:0110000000";


text:
Q: How to get the HTTP_REFERER from a Yahoo or Gmail I have an e-mailer script that send messages to Yahoo or Gmail with a link on it, a link that will return back to my website when it is clicked.
I need to get the HTTP_REFERER from Yahoo or Gmail. in my site I have

echo $_SERVER["HTTP_REFERER"];

expecting something to return on it. but its empty.

A: This seems to be by design. It is possible to remove the header using Javascript shenanigans. From Google's docs on GMail privacy:

Minimized "referrer" header information. When you click on links in messages, the web browser that loads contains a referrer header. When you click on links in Gmail, Google takes steps to eliminate this referrer header, preventing others from knowing that you clicked on a link from an email.

A: You have no control over HTTP_REFERER. What you see is what the client passed.

A: The browser might not provide HTTP_REFERER so you cannot rely on it -
Secondly, some software firewalls (like Norton Internet Security) have
features to strip out such information...


text:
Q: Android Studio 4.0 shortcuts changed This week I updated to Android Studio 4.0, and one of the first things I noticed was that some of my favorite shortcuts like CMD+W has changed to CMD+F4 (which the touchbar wont actually show the F keys anymore), and also CMD+O changed to CMD+N.  Is there any way to get them back to what they were to set to in Android Studio 3?

A: Fixed, it happen because Android Studio 4.0 by default use Intellij Keymap, fixed by change back to MacOs keymap. Android Studio > Preferences > Keymap > macOS

A: Method 1:
Go to this location :
C:\Users\<user_name>\.AndroidStudio3.0\config\keymaps

And copy the file present inside that (Usually Default Proper Redo.xml) and paste it inside
C:\Users\<user_name>\.AndroidStudio4.0\config\keymaps

It will bring back all old shortcuts or alternatively
Method 2:
go to settings and search for keymap this window will come up

and search for the keystroke you want or navigate around those

Right-click on the shortcut you want to change and a window will come up just press the new keystroke that you want to assign

If the same keystroke is applied to some other actions it will show a dailog just confirm it by removing old keystrokes ...
You can relate to MacOS ...

A: For Mac users:
I went to:
~/Library/Preferences/Android Studio 4.0/options
and deleted keymap.xml, which I noticed was not present on the previous version folder.
It seems to have the shortcuts working as expected.

A: It happened to me too after upgrading to Android Studio 4.0, it was fixed after I went to Android Studio > Preferences > Keymap then choice MacOS:

A: To open the keymap settings, choose File > Settings (on Mac, Android Studio > Preferences) and navigate to the Keymap pane.
Select the short cut you want to modify then add/assign new keys to short cut.
See for more info

A: For MacOS you can use :
"macOS Keymap" plugin by JetBrains
Restart IDE then select macOS in Keymap preferences


text:
Q: Coq: Cannot infer an internal placeholder of type "nat" in environment: ev : nat -> Prop I am trying to execute IndProp.v of Software Foundation classes, but I am immediately greeted with error
Set Warnings "-notation-overridden,-parsing,-deprecated-hint-without-locality".
From LF Require Export Logic.
From Coq Require Import Lia.

...

Inductive ev : nat -> Prop :=s
  | ev_0 : ev 0
  | ev_SS (n : nat) (H : ev n) : ev (S (S n)).
===============================================

Cannot infer an internal placeholder of type "nat" in environment:
ev : nat -> Prop

I ve had some errors with core types being shadowed by those defined in the book before, but haven't seen this error before?
Previous chapters compile correctly.
denis@dgecko:~/books/Volume1_LogicalFoundations> coqc --version
The Coq Proof Assistant, version 8.14.0
compiled with OCaml 4.13.1

A: There is a spurious "s" after the := sign.


text:
Q: Can I somehow pass TInput/TOutput pages to a function as one parameter in Inno Setup? I wonder if I can somehow pass TInputQueryWizardPage, TInputOptionWizardPage, TInputDirWizardPage, TInputFileWizardPage, TOutputMsgWizardPage, TOutputMsgMemoWizardPage, TOutputProgressWizardPage pages to a function as one parameter?
The reason I need this is because depending on the situation I have to pass one of those pages to a function that has the case statement inside that decides what changes must be done to a particular page and I don't want to pass 7 parameters.
Here's an example:
procedure SetPropertiesForPages(InputOptionWP: TInputOptionWizardPage; TextWP: TOutputMsgWizardPage; SelectDirWP: TInputDirWizardPage; InputQueryWP: TInputQueryWizardPage; Mode: String; AWordWrap: Boolean; AWidth, AHeight, ALeft, ATop: Integer);
begin
  case Lowercase(Mode) of
    'text':
      begin
         biLeftSideImage := CreateBitmapImage(TextWP, ExpandConstant('{tmp}\LefthandsideImg.bmp'), True, 0, 0);
         with TextWP do
           begin
             MsgLabel.WordWrap := AWordWrap;
             MsgLabel.Width := AWidth;
             MsgLabel.Height := AHeight;
             MsgLabel.Left := ALeft;
           end;
      end;
    'inputoption1':
      begin
        biLeftSideImage := CreateBitmapImage(InputOptionWP, ExpandConstant('{tmp}\LefthandsideImg.bmp'), True, 0, 0);
        with InputOptionWP do
           begin
             SubCaptionLabel.WordWrap := AWordWrap;
             SubCaptionLabel.Width := AWidth;
             SubCaptionLabel.Left := ALeft;
             SubCaptionLabel.Top := ATop;
             CheckListBox.Width := AWidth;
             CheckListBox.Height := AHeight;
             CheckListBox.Left := ALeft;
             CheckListBox.Top := ATop + SubCaptionLabel.Height + ScaleY(20);
           end;
      end;
    'inputoption2':
      begin
        biLeftSideImage := CreateBitmapImage(InputOptionWP, ExpandConstant('{tmp}\LefthandsideImg.bmp'), True, 0, 0);
        with InputOptionWP do
          begin
            SubCaptionLabel.WordWrap := AWordWrap;
            SubCaptionLabel.Width := AWidth;
            SubCaptionLabel.Height := 6 * AHeight + ScaleY(5);
            SubCaptionLabel.Left := ALeft;
            SubCaptionLabel.Top := ATop;
            CheckListBox.Width := AWidth;
            CheckListBox.Height := AHeight + ScaleY(40);
            CheckListBox.Left := ALeft;
            CheckListBox.Top := ATop + SubCaptionLabel.Height + ScaleY(5);
          end;
      end;
    'selectdir':
      begin
        biLeftSideImage := CreateBitmapImage(SelectDirWP, ExpandConstant('{tmp}\LefthandsideImg.bmp'), True, 0, 0);
        with SelectDirWP do
          begin
            Edits[0].ReadOnly := True;
            Edits[1].ReadOnly := True;
            Edits[0].Left := ALeft;
            Edits[1].Left := ALeft;
            Edits[0].Width := AWidth - ScaleX(70);
            Edits[1].Width := AWidth - ScaleX(70);
            Buttons[0].Left := Edits[0].Left + Edits[0].Width + ScaleX(10);
            Buttons[1].Left := Edits[1].Left + Edits[1].Width + ScaleX(10);
            PromptLabels[0].Left := ALeft;
            PromptLabels[1].Left := ALeft;
            SubCaptionLabel.WordWrap := AWordWrap;
            SubCaptionLabel.Width := AWidth;
            SubCaptionLabel.Left := ALeft;
            SubCaptionLabel.Top := ATop;
          end;
      end;
    'inputquery':
      begin
        biLeftSideImage := CreateBitmapImage(InputQueryWP, ExpandConstant('{tmp}\LefthandsideImg.bmp'), True, 0, 0);
        with InputQueryWP do
          begin
            Edits[0].Left := ALeft;
            Edits[0].Width := AWidth - ScaleX(75);
            PromptLabels[0].Left := ALeft;
            SubCaptionLabel.WordWrap := AWordWrap;
            SubCaptionLabel.Width := AWidth;
            SubCaptionLabel.Height := AHeight;
            SubCaptionLabel.Left := ALeft;
            SubCaptionLabel.Top := ATop;
          end;
      end;
  end;
end;

So, as you can I seen I need to change different things for different types of pages, but I don't want to pass so many parameters.

A: If you want the function to operate over any of those pages, if must use only their common API/functionality. Their common API/functionality is their base class, the TWizardPage:
procedure DoSomethingWithAnyCustomPage(WizardPage: TWizardPage);
begin
  // ...
end;

If many cases you can also implement the common functionality by using the same/shared implementation of pages events.


text:
Q: How to create vuetify toolbar link dropdown menu? Go to https://vuetifyjs.com/en/components/toolbars
On the top left toolbar we see links: store, support, ecosystem, version, locate
How do I create this style of toolbar button link (with dropdown items)?
(I am unable to find an example)

A: It's a simple plain menu component.
Click on the example button (dropdown) and on "support"
and you will see, that they behave the same.
If you inspect the "support" button with your browser (Firefox, Chrome Shortcut F12 for both),
you can see thats a "v-menu"(menu component) and you can see the CSS used for it.

A: <template>
<div>
        <v-toolbar rounded tile>
        <v-app-bar-nav-icon> </v-app-bar-nav-icon>
        <v-app-bar-title>
            <route-link to="/" tag style="cursor:pointer">ProjectName</route-link>
        </v-app-bar-title>
        <v-spacer></v-spacer>
        <v-toolbar-items>
            <v-btn flat to="/">
                Home
            </v-btn>
            <v-menu :rounded="rounded" open-on-hover offset-y transition="slide-x-transition" bottom right>
                <template v-slot:activator="{ on, attrs }">
                    <v-btn flat v-bind="attrs" v-on="on">
                        Services
                    </v-btn>
                </template>
                <v-list dense>
                    <v-list-item v-for="(item, index) in services" :key="index" router :to="item.link">
                       <v-list-item-action>
                            <v-list-item-title>{{ item.title }}</v-list-item-title>
                        </v-list-item-action>
                    </v-list-item>
                </v-list>
            </v-menu>
            <v-btn to="/about" flat>
                About Us
            </v-btn>
            <v-btn to="/contact" flat>
                Contact Us
            </v-btn>
        </v-toolbar-items>
        <v-spacer></v-spacer>
        <v-toolbar-items class="hidden-sm-and-down">
            <v-btn to="/signup" flat>Sign Up </v-btn>
            <v-btn to="/login" flat>login</v-btn>
        </v-toolbar-items>
        <v-menu open-on-hover transition="slide-x-transition" bottom right offset-y>
            <template v-slot:activator="{ on, attrs }">
                <v-btn icon v-bind="attrs" v-on="on">
                    <v-icon>mdi-dots-vertical</v-icon>
                </v-btn>
            </template>
            <v-card class="mx-auto" max-width="300" tile>
                <v-list dense>
                    <v-subheader>THEMES</v-subheader>
                    <v-list-item-group v-model="theme" color="primary">
                        <v-list-item v-for="(item, i) in themes" :key="i" router :to="item.link">
                            <v-list-item-action>
                                <v-icon v-text="item.icon"></v-icon>
                            </v-list-item-action>
                            <v-list-item-action>
                                <v-list-item-title v-text="item.text"></v-list-item-title>
                            </v-list-item-action>
                        </v-list-item>
                    </v-list-item-group>
                </v-list>
            </v-card>
        </v-menu>
    </v-toolbar>
</div>
</template>

<script>
export default {
    data: () => ({
        activate: true,
        theme: 1,
        themes: [{
                text: "Dark",
                icon: "mdi-clock"
            },
            {
                text: "Light",
                icon: "mdi-account"
            }
        ],
        mini: true,
        services: [{
                icon: "mdi-domain",
                title: "Media Monitoring",
                link: "/mmrservices"
            },
            {
                icon: "mdi-message-text",
                title: "Audience Measurement",
                link: "/amrservices"
            },
            {
                icon: "mdi-flag",
                title: "Integration Analysis"
            }
        ]
    })
};
</script>


text:
Q: how to insert values from list/menu into mysql i want to insert the grades into the mysql database. my list/menu as follow
  <select name="grade" size="1" id="select">
        <option value="" selected="selected">--- Select ---</option>
        <option value="">A</option>
        <option value="A-">A-</option>
        <option value="B+">B+</option>
        <option value="B">B</option>
        <option value="B-">B-</option>
  </select>

i used this code but grades didn't insert in the database and error message appeared
     <?php
$grade = mysql_real_escape_string($_POST['grade']);

$sql3 = "INSERT  (enrollment_id, stud_id, code, grade, date_enrolled) VALUES ('','','','$_POST[grade]','')";
$result = mysql_query($sql3);

if(mysql_query($sql3))
{
    echo 'User information saved successfully.';
}else
{
    echo 'Error: We encountered an error while inserting the new record.';
}
mysql_close($con_mark_entry);
?>

A: Like MySQL would say, "you have an error in your syntax". I think this should work:
$sql3 = "INSERT INTO your_sql_table (enrollment_id, stud_id, code, grade, date_enrolled) VALUES ('','','','$grade','')";
I would suggest adding echo mysql_error() after your "We encountered an error" message for debugging purposes.

A: Your query is wrong. It should be
INSERT INTO Table Name (COL1, COL2) VALUES (VAL1,VAL2)