Q:

Are there disadvantages to contained databases?

SQL Server 2012 introduced the concept of "contained" databases, where everything (well, mostly everything) the database needs is contained within the database itself. This offers big advantages when moving databases between servers. I would like to know, then, if this should be my default strategy when designing a new database.
MSDN lists several disadvantages to contained databases, and the big ones are a lack of support for change tracking and replication. Are there others? If I'm not going to use these features, is there any reason not to use contained databases?

A:

The primary purpose of contained databases is to make it easier to port your database to a new server without a lot of scaffolding around it. With that in mind, I'll treat a few potential issues that will make this migration more difficult - and most revolve around the fact that contained databases are only partially contained in SQL Server 2012 (containment is not actually enforced).

Connection strings
Connection strings to a contained database must explicitly specify the database in the connection string. You can no longer rely on the login's default database to establish a connection; if you don't specify a database, SQL Server is not going to step through all the contained databases and try to find any database where your credentials may match.

Cross-db queries
Even if you create the same user with the same password in two different contained databases on the same server, your application will not be able to perform cross-database queries. The usernames and passwords may be the same, but they're not the same user. The reason for this? If you have contained databases on a hosted server, you shouldn't be prevented from having the same contained user as someone else who happens to be using the same hosted server. When full containment arrives (likely in the version after SQL Server 2012 never), cross-database queries will absolutely be prohibited anyway. I highly, highly, highly recommend that you don't create server-level logins with the same name as contained database users, and try to avoid creating the same contained user name across contained databases. If you need to run queries that hit multiple contained databases, do so using a server-level login that has appropriate privileges (you might think this is sysadmin, but for read-only queries, this is CONNECT ANY DATABASE and SELECT ALL USER SECURABLES).

Synonyms
Most 3- and 4-part names are easy to identify, and appear in a DMV. However if you create a synonym that points to a 3- or 4-part name, these do not show up in the DMV. So if you make heavy use of synonyms, it is possible that you will miss some external dependencies, and this can cause problems at the point where you migrate the database to a different server. I complained about this issue, but it was closed as "by design" and didn't survive the migration to the new feedback system. Note that the DMV will also miss 3- and 4-part names that are constructed via dynamic SQL.

Password policy
If you have created a contained database user on a system without a password policy in place, you may find it hard to create the same user on a different system that does have a password policy in place. This is because the CREATE USER syntax does not support bypassing the password policy. I filed a bug about this problem, and it remains open (and it also didn't survive the move when Connect was retired). And it seems strange to me that on a system with a password policy in place, you can create a server-level login that easily bypasses the policy, but you can't create a database user that does so - even though this user is inherently less of a security risk.

Collation
Since we can no longer rely on the collation of tempdb, you may need to change any code that currently uses explicit collation or DATABASE_DEFAULT to use CATALOG_DEFAULT instead. See this BOL article for some potential issues.

IntelliSense
If you connect to a contained database as a contained user, SSMS will not fully support IntelliSense. You'll get basic underlining for syntax errors, but no auto-complete lists or tooltips and all the fun stuff. I filed a bug about this issue, and it remains open - and one more that did not survive the move.

SQL Server Data Tools
If you are planning to use SSDT for database development, there currently isn't full support for contained databases. Which really just means that building the project won't fail if you use some feature or syntax that breaks containment, since SSDT currently doesn't know what containment is and what might break it.

ALTER DATABASE
When running an ALTER DATABASE command from within the context of a contained database, rRather than ALTER DATABASE foo you will need to use ALTER DATABASE CURRENT - this is so that if the database is moved, renamed, etc. these commands don't need to know anything about their external context or reference.

A few others
Some things you probably shouldn't still be using but nonetheless should be mentioned in the list of things that aren't supported or are deprecated and shouldn't be used in contained databases:

numbered procedures
temporary procedures
collation changes in bound objects
change data capture
change tracking
replication

That all said, these aren't necessarily disadvantages to using contained databases, they're just issues you should be aware of and aren't all explicitly disclosed in the official documentation.
You'll also need to be sure that if a contained database is going to be migrated, or is part of an availability group or is being mirrored, that all potential destination servers have the sp_configure option contained database authentication set to 1.
You may find this blog post useful, as well as this one, even though they pre-date RTM.

A:

For those who are interested in getting more details about contained databases, I can recommend them to read this article http://www.sqlshack.com/contained-databases-in-sql-server/
The article pinpoints main advantages/disadvantages of using contained databases.
Disadvantages
Partially contained databases cannot use features like replication, change data capture, change tracking, schema-bound objects that depend on built-in functions with collation changes.
Advantages
On the other hand, as already mentioned, there are some benefits of using contained DBs, such as:

It is quite easy to move the database from one server to another,
as there won’t be orphaned user issues
Metadata is stored on contained databases so it is easier and    more portable
It is possible to have both SQL Server and Windows    authentication for contained DB users

Article also helps with:

creating a new contained database (by making containment type as    Partial in the Options page in SQL Server, and using T-SQL query to    create a database afterwards)
connecting to the contained DB using SQL Server Management Studio (it is needed to specify contained DB name in the connection    parameter)
converting existing database to a contained database
working on a contained database and listing all logins that are of contained user type

A:

One disadvantage is that a contained database user cannot be forced to change their own password like logins could (MUST_CHANGE). Users cannot manage their own password unless you grant them an alter user permission and tell them how to change it using a SQL statement. There is nowhere easy for them to manage it via user interfaces or at least I don't know how.
Additional note is that, I found the unexpected and undocumented metadata usage in "PIVOT" AND "UNPIVOT" clause which I thought it should be only in the system catalog only (sys.tables/sys.columns/etc). As documented in msdn :

In a contained database, the catalog collation Latin1_General_100_CI_AS_WS_KS_SC. This collation is the same for all contained databases on all instances of SQL Server and cannot be changed.

But they didn't mention that the "PIVOT" AND "UNPIVOT" clause also use the system catalogs as an execution mechanism. so it produce a collation conflicted error everywhere near the use of "PIVOT" AND "UNPIVOT" clause during the migration. here is some repro:
/*step1 create a table belongs to a contained database and populate some data*/
create  table dbo.test1 (col1 varchar(100),col2 varchar(100))
insert  dbo.test1 values('a','x')
insert  dbo.test1 values('b','y')
insert  dbo.test1 values('c','z')

/*step2 lets see its collation you will see it is correctly as same as its (contained) database */
select name,collation_name from sys.columns where object_name(object_id) = 'test1'

/*step3 reproduce an unpivoted column*/
select * into dbo.test2
from (select * from dbo.test1) a unpivot (val for col in (col1,col2)) a

/*step4 lets check its collation you will see the column specified at "FOR" clause is created as Latin1_General_100_CI_AS_KS_WS_SC */
select name,collation_name from sys.columns where object_name(object_id) = 'test2'

/*step5 make use of the unpivoted table without awareness will cause an error*/
select val + ' = ' + col from dbo.test2

/*step6 clean up*/
drop table dbo.test1
drop table dbo.test2

you can also see that the articles about contained database are mostly incomplete. so deciding to use it needs a very good improvisation.


Q:

Why does returning partial view affect my styles from being applied to my partial view?

So,
I have bools for when to display a certain partial view and I noticed for one of my partial views, it displays correctly with the correct CSS styles and classes.
However, my other partial view does not display correctly (I get no errors in console too) and I have narrowed it down to this line of code seeing how this makes the difference:
 @Html.ActionLink(@Culture.GetString("ResetPasswordViaQuestionAnswer"), "GetUserName", "Account", new { style = "color:black; background: none;" })

OR
    @Culture.GetString("ResetPasswordViaQuestionAnswer")

Whenever I use @Html.ActionLink or @Url.Action to call my action to return my partial view, the CSS style breaks. None of my classes get properly added to my inputs and form elements.
The above calls this action:
        [AllowAnonymous]
        public ActionResult GetUserName()
        {
            LoginModel loginModel = new LoginModel();
            GetUserName getUserName = new GetUserName();
            loginModel.getUserName = getUserName;
            loginModel.DisplayResetPasswordDialog = true;
            return PartialView("Login", loginModel);
        }

Which then goes to my Login partialview which inside a div contains:
@if(Model.DisplayChangePasswordDialog == true){
                    @Html.Partial("PasswordExp",new ViewModels.PasswordChangeViewModel())
               }else if (Model.DisplayResetPasswordDialog == true){
                    @Html.Partial("ResetUserPassword", new ViewModels.GetUserName())
               }else{
                     @Html.Partial("_login", Model)
            }

Something in what I have done above is breaking the CSS styles and classes from being attached to my inputs. The view is loaded but the view is loaded incorrectly. No styles or classes are applied.
Why?

A:

You can't (or shouldn't) redirect to a partial view because you're not going to be getting your _Layout file that contains your css and js.
Instead you should redirect to a view containing your partial view. That view should have a reference to your layout file.


Q:

How to deploy a custom JavaScript file to Style Library from SharePoint Apps?

I want to do some java-script operation on a custom list in SharePoint 2013 Online version. So I am creating a separate java-script file and deploying to Style Library manually.
Does anybody know how to deploy java-script file into Style Library of a site collection automatically in Sharpoint 2013 App for online ? Also where the app.js file from SharePoint App Solution is deployed?

A:

I'll start out by defining two terms, the Host Web and the App Web. The SharePoint site where you install an App is called the Host Web. The SharePoint site where the SharePoint-Hosted App lives is called the App Web. The App Web is a child site of the Host Web.
A SharePoint-Hosted App can automatically deploy files inside the App Web using a Module element but it cannot automatically deploy files to the Host Web or the Site Collection containing the Host Web. To do what you want to do you would deploy the JavaScript file to the App Web and then use code to read it and add it to the Style Library in the Host Web's Site Collection root.
This blog post shows how to deploy a master page from an App to the Master Page Gallery. You can use the same technique to deploy a JavaScript file to the Style Library.
http://www.sharepointnutsandbolts.com/2013/05/sp2013-host-web-apps-provisioning-files.html


Q:

Can rabbits fart?

It is an uncontested fact that rabbits are physically incapable of vomiting.  Rabbit health is primarily dependent on digestion, moving large quantities of low-value food from one end to the other, sometimes making the passage more than once.
Occasionally, rabbits suffer from bloat, which comes from a buildup of gas in the stomach.  If gas is created in the intestines rather than the stomach, are rabbits able to expel it or will it migrate to the stomach?

A:

While I did not find any reliable references that clearly put it as boldly as the question, there can be little doubt that rabbits do fart.
Lets begin by looking at a rabbits digestive track.

Image from Wikimedia Commons
Notice that the stomach is very early in the digestive track, this is the usual problem area noted for gas accumulation in bloat.  Then follows the small intestine, and the at the beginning of the large intestine is the caecum/cecum.
The rabbit cecum is much more developed than in most other animals.  Food products stop in the cecum and ferment (Nutritional Ecology of the Ruminant By Peter J. Van Soest Page 67) generally staying there until night, with gas as one of the products of fermentation.  The rabbit cecum is described in veterinary imaging references as a "large gas chamber that contains a mixture of food and gas" (Diagnostic Imaging of Exotic Pets: Birds, Small Mammals, Reptiles By Maria-Elisabeth Krautwald-Junghanns, Michael Pees, Sven Reese, Thomas Tully), which is particularly noted for it's difficulty to image (i.e. Xray, etc)
Disruption of motility of the cecum is called "cecolith" and can be diagnosed by an increase in the amount of gas in the cecum. (Ferrets, Rabbits and Rodents: Clinical Medicine and Surgery By Katherine Quesenberry, James W. Carpenter).
So we know that gas is produced in the cecum, and if there is decreased motility the gas increases, the logical conclusion is that in the healthy rabbit the gas continues through the colon, and is expelled from the anus. At this point there can be little doubt that healthy rabbits fart.
One of the recognized treatments for gas in rabbits is Simethicone, an anti-foaming agent that helps in the passing of gas (Rabbit Health in the 21st Century: A Guide for Bunny Parents By Kathy Smith).  Note that gas accumulation in rabbits is potentially (often) fatal, so prevention of accumulation is extremely important.

A:

Rabbits can definitely fart
The gas will need to be expelled somewhere, and it seems likely that if they can poop that they'll be able to fart also.
According to many websites, the jury seems to be out on whether it's common for rabbits to burp (and whether or not this is indicative of gastrointestinal problems.)  Intuitively, because rabbits can't vomit, they'll probably have some difficulty burping as well.


Q:

Refresh Navigation Drawer after Login

I have an App. After app launch, show the home screen. I am using Navigation Drawer. There is Login menu item in drawer. If they want to do same activities, user need to login.
Example, user choose login, show the login activity. After login, back to home page. Then reopen the drawer, I want to change the login to logout. May I know where do I refresh the drawer?

A:

If  they are different Activities, onResume in your Activity where is your Navigation Drawer.
If they are not you can do it onDrawerOpened.
@Override
   public void onDrawerOpened(View drawerView) {
   super.onDrawerOpened(drawerView);
  }


Q:

why is "if @user.save" used in this way?

I'm working through the Michael Hartl's rails book, and I'm curious how this works:
if @user.save

else

end

In if statements, the argument doesn't actually do anything much besides return true or false.
This method seems to save the model to the database and then return true or false. Is this common/am I right? Why do we do it this way?

A:

Normally the if @user.save is checking if the object was successfully saved to the database using ActiveRecord.  From there you could do something like set a flash message and redirect somewhere.  In the else clause you could potentially inspect the @user.errors to see what went wrong and deal with it.
Example:
def create
  #Set user object attributes using strong parameters
  @user = User.new(user_params)

  #Attempt to save @user
  if @user.save
    flash[:notice] = 'User saved successfully'
    redirect_to somewhere_else_url
  else
    #Saving failed, we can inspect @user.errors for more information
    flash[:alert] = 'User was not saved.'

    #If using a form library @user.errors will be displayed graphically when rendering the :new action
    render :new
  end
end


Q:

How to hide a popup by clicking outside

I am trying to come up with a way so that once #email-popup or #phone-popup is visible, if the user clicks anywhere EXCEPT the visible popup, then it is going to hide the popup.
My method for hiding the popups in the code below does not work well...
My JQuery so far
$(".email").click(function(){
    $("#email-popup").show("fast");
});
$(".phone").click(function(){
   $("#phone-popup").show();
});

$(document).click(function() {
     $("#email-popup").hide("fast");
     $("#phone-popup").hide("fast");
});

A:

You're close - just stop the propagation when the user clicks within the popups:
$("#email-popup, #phone-popup").on("click", function(e){
  e.stopPropagation();
});

$(".email").on("click", function(e){
  e.stopPropagation();
  $("#email-popup").show("fast");
});

$(".phone").on("click", function(e){
  e.stopPropagation();
  $("#phone-popup").show();
});

Also you have some repeated code in the document click. You're hiding the email popup twice.
$(document).on("click", function() {
  $("#email-popup, #phone-popup").hide("fast");
});


Q:

Kafka Producer deployed on Kubernetes not able to produce to Kafka cluster running on local machine

I have a Kafka cluster running on the local machine with default settings outside of my minikube setup. I have created a producer in one of my web services and deployed it on minikube.
For producer to connect to Kafka I am using 10.0.2.2 IP which I am also using to connect Cassandra and DGraph outside of minikube for these it is working fine.
However Kafka producer is not working and not even throwing an error saying Broker may not be available or any other errors while sending data. But I am not receiving anything on the consumer side.
When I run this web service outside the Kubernetes everything works.
Please if you guys have any idea what might be wrong here.
Below is the Kubernetes yaml file that I am using.
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: servicename
  labels:
    app: servicename
    metrics: kamon
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: servicename
        metrics: kamon
    spec:
      containers:
      - image: "image:app"
        imagePullPolicy: IfNotPresent
        name: servicename
        env:
        - name: CIRCUIT_BREAKER_MAX_FAILURES
          value: "10"
        - name: CIRCUIT_BREAKER_RESET_TIMEOUT
          value: 30s
        - name: CIRCUIT_BREAKER_CALL_TIMEOUT
          value: 30s
        - name: CONTACT_POINT_ONE
          value: "10.0.2.2"
        - name: DGRAPH_HOSTS
          value: "10.0.2.2"
        - name: DGRAPH_PORT
          value: "9080"
        - name: KAFKA_BOOTSTRAP_SERVERS
          value: "10.0.2.2:9092"
        - name: KAFKA_PRODUCER_NOTIFICATION_CLIENT_ID
          value: "notificationProducer"
        - name: KAFKA_NOTIFICATION_TOPIC
          value: "notification"
        - name: LAGOM_PERSISTENCE_READ_SIDE_OFFSET_TIMEOUT
          value: 5s
        - name: LAGOM_PERSISTENCE_READ_SIDE_FAILURE_EXPONENTIAL_BACKOFF_MIN
          value: 3s
        - name: LAGOM_PERSISTENCE_READ_SIDE_FAILURE_EXPONENTIAL_BACKOFF_MAX
          value: 30s
        - name: LAGOM_PERSISTENCE_READ_SIDE_FAILURE_EXPONENTIAL_BACKOFF_RANDOM_FACTOR
          value: "0.2"
        - name: LAGOM_PERSISTENCE_READ_SIDE_GLOBAL_PREPARE_TIMEOUT
          value: 30s
        - name: LAGOM_PERSISTENCE_READ_SIDE_RUN_ON_ROLE
          value: ""
        - name: LAGOM_PERSISTENCE_READ_SIDE_USE_DISPATCHER
          value: lagom.persistence.dispatcher
        - name: AKKA_TIMEOUT
          value: 30s
        - name: NUMBER_OF_DGRAPH_REPOSITORY_ACTORS
          value: "2"
        - name: DGRAPH_ACTOR_TIMEOUT_MILLIS
          value: "20000"
        - name: AKKA_ACTOR_PROVIDER
          value: "cluster"
        - name: AKKA_CLUSTER_SHUTDOWN_AFTER_UNSUCCESSFUL_JOIN_SEED_NODES
          value: 40s
        - name: AKKA_DISCOVERY_METHOD
          value: "kubernetes-api"
        - name: AKKA_IO_DNS_RESOLVER
          value: "async-dns"
        - name: AKKA_IO_DNS_ASYNC_DNS_PROVIDER_OBJECT
          value: "com.lightbend.rp.asyncdns.AsyncDnsProvider"
        - name: AKKA_IO_DNS_ASYNC_DNS_RESOLVE_SRV
          value: "true"
        - name: AKKA_IO_DNS_ASYNC_DNS_RESOLV_CONF
          value: "on"
        - name: AKKA_MANAGEMENT_HTTP_PORT
          value: "10002"
        - name: AKKA_MANAGEMENT_HTTP_BIND_HOSTNAME
          value: "0.0.0.0"
        - name: AKKA_MANAGEMENT_HTTP_BIND_PORT
          value: "10002"
        - name: AKKA_MANAGEMENT_CLUSTER_BOOTSTRAP_CONTACT_POINT_DISCOVERY_REQUIRED_CONTACT_POINT_NR
          value: "1"
        - name: AKKA_REMOTE_NETTY_TCP_PORT
          value: "10001"
        - name: AKKA_REMOTE_NETTY_TCP_BIND_HOSTNAME
          value: "0.0.0.0"
        - name: AKKA_REMOTE_NETTY_TCP_BIND_HOSTNAME
          value: "0.0.0.0"
        - name: AKKA_REMOTE_NETTY_TCP_BIND_PORT
          value: "10001"
        - name: LAGOM_CLUSTER_EXIT_JVM_WHEN_SYSTEM_TERMINATED
          value: "on"
        - name: PLAY_SERVER_HTTP_ADDRESS
          value: "0.0.0.0"
        - name: PLAY_SERVER_HTTP_PORT
          value: "9000"
        ports:
        - containerPort: 9000
        - containerPort: 9095
        - containerPort: 10001
        - containerPort: 9092
          name: "akka-remote"
        - containerPort: 10002
          name: "akka-mgmt-http"
---
apiVersion: v1
kind: Service
metadata:
  name: servicename
  labels:
    app: servicename
spec:
  ports:
    - name: "http"
      port: 9000
      nodePort: 31001
      targetPort: 9000
    - name: "akka-remote"
      port: 10001
      protocol: TCP
      targetPort: 10001
    - name: "akka-mgmt-http"
      port: 10002
      protocol: TCP
      targetPort: 10002
  selector:
    app: servicename
  type: NodePort

A:

I am already connecting to Cassandra and Dgraph running on the same machine as Kafka

Well, those services don't advertise their network address via Zookeeper.

My Kafka cluster is outside the K8. However, the producer is in K8.

In order for services outside of k8s to know Kafka's location, the advertised.listeners needs to be set to an external IP or DNS address that all producer/consumer services in the k8s environment will be recognize and that's the address that your services will connect to. For example PLAINTEXT://10.0.2.2:9092
In other words, if you had not set up the listeners, and it was only listening on localhost, just because the Kafka port is externally exposed, means that while you might be able to reach one broker, the address you get back as part of the protocol is not guaranteed to be the same thing as your client's configuration, and that's where the advertised listener address comes into play.


Q:

Jupiterlab print DataFrame nicely

If you let the a Dataframe at the end of a cell you get a nice table that react to the mouse (mouse-over makes the line blue). Considering that I want to print a set of DataFrames like that, how may I do it?

A:

You can use display function
from IPython.display import display

and in your targeted cell
display(df1)
#
# Some code here
#
display(df2)


Q:

Python sys.argv scoping rules

I just noticed sys.argv is visible in a imported script.
A.py
import sys
print("A")
print(sys.argv)
import B

B.py
import sys
print("B")
print(sys.argv)

Yields
>> python A.py --foo bar
>> A
>> ['path/to/A.py', '--foo', 'bar']
>> B
>> ['path/to/A.py', '--foo', 'bar']

This is nice since now I don't have to do the argument parsing in the main script (aka. manage.py).
The question is: can I rely on this behavior? Are there cases where this will not work?

A:

Module attributes, like sys.argv are objects. It does not matter from which module you access them, they are the same object.
That also means if one module modifies sys.argv, then that change will also affect any other module that accesses sys.argv.

A tip regarding coding style:
Although it is possible to access sys.argv from two different modules, I wouldn't recommend it, and here's why.
I like scripts that can also double as modules. This gives you the greatest flexibility in reusing code. sys.argv is only meaningful when the code is called as a script. In order for code to be useful as a module, the code should not depend on looking up values in sys.argv.
Therefore, I would recommend parsing sys.argv once in the main calling script:
if __name__ == '__main__':
    import argparse
    def parse_args():
        ... # argparse uses  sys.argv

    args = parse_args()

and then passing the values in args to functions as needed.
Thus, everything outside of the if __name__ == 'main__' statement need not depend on sys.argv, and can thus be used through simple function calls or module imports.

A:

This has nothing to do with the scope of sys.argv specifically, it's that all modules are loaded in a single global instance.
So if A.py imports a module and then modifies it, if B.py imports that same module, it's just gaining access to the module A.py imported.
For example:
A.py
import sys
sys.foo = "foo!"
import B

B.py
import sys
print sys.foo

Running A.py here would import B.py, which would have access to the modified sys module and the foo variable inside of it. However, if you were to run B.py directly, this code would raise an error that sys.foo doesn't exist.
This is a very poor behavior to rely upon, as it makes very strong assumptions of which module imports which, and makes for extremely brittle code.


Q:

Finding solutions of system of differential equations with eigenvectors

I was trying to solve this system of differential equations:

$$\frac{dx}{dt}=3x-y-z$$
  $$\frac{dy}{dt}=x+y-z$$
  $$\frac{dz}{dt}=x-y+z$$

I found the eigenvalues: $\lambda_1=1,\lambda_2=2$. The last one has multiplicity $2$. I found $\boldsymbol K_1 =\left(
\begin{array}{c}
1\\
1\\
1
\end{array}
\right)$ is an eigenvector, so a solution to the differential equation would be $\boldsymbol X_1=\boldsymbol K_1e^t.$ However when I want to find a solution with an eigenvector $\boldsymbol K_2 = \left(
\begin{array}{c}
k_1\\
k_2\\
k_3
\end{array}
\right)$ associated to $\lambda_2$ I have the equation $k_1-k_2-k_3=0$ three times. From this I know that two eigenvectors are $\left(
\begin{array}{c}
1\\
1\\
0
\end{array}
\right)$ and $\left(
\begin{array}{c}
1\\
0\\
1
\end{array}
\right)$. Now if I choose one of them, let's say the first one, then this will be a second eigenvector $\boldsymbol K_2$, such that $\boldsymbol X_2=\boldsymbol K_2e^{2t}$ solves the system. However if I try to find a third solution (which I already found: $\boldsymbol K_3e^{2t}$ from the third eigenvector; but I want to find it from here) that has the form $\boldsymbol X_3=\boldsymbol K_2te^{2t}+\boldsymbol P e^{2t}$, then I have to solve $(\boldsymbol A-2\boldsymbol I)\boldsymbol P = \boldsymbol K_2$. But this system doesn't have a solution:
$$(\boldsymbol A-2\boldsymbol I)\boldsymbol P = \boldsymbol K_2 \Longrightarrow \left(\begin{array}{ccc|c}1 & -1 & -1 & 1\\1 & -1 & -1 & 1\\1 & -1 & -1 & 0\\ \end{array}\right)???$$
Is it possible to obtain a third solution from the second one? I'm trying to construct this solution which should end up with an expression that involves the third eigenvector.
I appreciate any thoughts on this. Thanks.

A:

We have to look at the matrix $${\bf A} = \begin{bmatrix} 3 & -1 & -1\\ 1 & 1 & -1 \\ 1 & -1 & 1\end{bmatrix},$$ and the system ${\bf X}' = {\bf A}{\bf X}$.
I didn't checked, but I'll trust you that the eigenvalues are $\lambda_1 = 1$ and $\lambda_2 = 2$, they're too nice to be wrong. Let's go find eigenvectors:

$\lambda_1 = 1$: Solve $({\bf A}-{\bf I}){\bf K}_1 = {\bf 0}$, that
is: $$\begin{bmatrix} 2 & -1 & -1\\ 1 & 0 & -1 \\ 1 & -1 &
   0\end{bmatrix}\begin{bmatrix} a \\ b \\ c\end{bmatrix} =
   \begin{bmatrix} 0 \\ 0 \\ 0\end{bmatrix}$$ The first line is the sum
of the other, so it is useless. From the second equation we get $a=c$
and from the third, $a = b$. So far, so good: $${\bf K}_1 =
   \begin{bmatrix} a \\ b \\ c\end{bmatrix} = \begin{bmatrix} a \\ a \\
   a\end{bmatrix} = a\begin{bmatrix} 1 \\ 1 \\ 1\end{bmatrix},$$ so we
pick the vector $${\bf k}_1 = \begin{bmatrix} 1 \\ 1 \\
   1\end{bmatrix},$$ and get one row for the fundamental matrix of the
system: $$e^{\lambda_1t}{\bf k}_1 = e^{1t}\begin{bmatrix}1 \\ 1 \\ 1 \end{bmatrix} =
   \begin{bmatrix}e^t \\ e^t \\ e^t\end{bmatrix}.$$
$\lambda_2 = 2$: Solve $({\bf A}-2{\bf I}){\bf K}_2 = {\bf 0}$, that
is: $$\begin{bmatrix} 1 & -1 & -1\\ 1 & -1 & -1 \\ 1 & -1 &
   -1\end{bmatrix}\begin{bmatrix} a \\ b \\ c\end{bmatrix} =    \begin{bmatrix} 0 \\ 0 \\ 0\end{bmatrix}.$$ Better impossible, we
have the relation $a-b-c = 0$, that is, $a = b+c$. Then: $${\bf K}_2
   =    \begin{bmatrix} a \\ b \\ c\end{bmatrix} = \begin{bmatrix} b+c \\ b \\    c\end{bmatrix} = b\begin{bmatrix} 1 \\ 1 \\ 0\end{bmatrix}
   + c\begin{bmatrix} 1 \\ 0 \\ 1\end{bmatrix}.$$ Pick the vectors: $${\bf k}_2^{(1)} = \begin{bmatrix} 1 \\ 1 \\ 0\end{bmatrix} \quad
   \mbox{and} \quad{\bf k}_2^{(2)} = \begin{bmatrix} 1 \\ 0 \\
   1\end{bmatrix}.$$ This gives us the more independent rows of the
fundamental matrix: $$e^{\lambda_2t}{\bf k}_2^{(1)} =
   e^{2t}\begin{bmatrix}1 \\ 1 \\ 0 \end{bmatrix} =
   \begin{bmatrix}e^{2t} \\ e^{2t} \\ 0\end{bmatrix} \quad \mbox{and}
   \quad e^{\lambda_2t}{\bf k}_2^{(2)} = e^{2t}\begin{bmatrix}1 \\ 0 \\
   1 \end{bmatrix} =    \begin{bmatrix}e^{2t} \\ 0 \\
   e^{2t}\end{bmatrix}.$$

So, we get as fundamental matrix for the system, the matrix:
$${\cal A} = \begin{bmatrix} e^t & e^{2t} & e^{2t}\\ e^t & e^{2t} & 0 \\ e^t & 0 & e^{2t}\end{bmatrix},$$ and hence, given $c_1,c_2,c_3 \in \Bbb R$, we get the general solution to the system: $${\bf X} = {\cal A}{\bf C} \implies \begin{bmatrix}x(t) \\ y(t) \\ z(t)\end{bmatrix} = \begin{bmatrix} e^t & e^{2t} & e^{2t}\\ e^t & e^{2t} & 0 \\ e^t & 0 & e^{2t}\end{bmatrix}\begin{bmatrix}c_1 \\ c_2 \\ c_3\end{bmatrix} = \begin{bmatrix}c_1e^t+(c_2+c_3)e^{2t} \\ c_1e^t+c_2e^{2t} \\ c_1e^t+c_3e^{2t}\end{bmatrix}.$$


Q:

using greater than (>) or less than (<) inside {% if statement %} doesnt work

I am writing a code for a paginator on my website on my home.html file. When i tried to put a '>' and a '<' the atom text editor read it as an html code. And then the color of the codes after the signs changed as if it they were an html code.
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'-3' %}
    <a class="btn btn-outline-info mb-4" href="?page={{num}}">

and it made the other page numbers on my paginators disappear.
This is how my paginator should look like:

ufortunately this happened:

im missing two sets of numbers before and after my current page.

A:

Your boolean condition will never be met.
elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'-3'

you're checking if num is greater than page_obj.number-3 and then checking if num is also less than page_obj.number-3. It can't be both.
Maybe you're looking for:
elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3'


Q:

Maximum execution time of 300 seconds in Xampp on Windows

I have changed php.ini settings and max timeout in http-default.conf under apache but still I get the following error:
Maximum execution timeout of 300 seconds

I have even added set_time_limit and ini_set to the php script but still I get this error.
How do I resolve this?
Note:
I tried the options in Fatal error: Maximum execution time of 300 seconds exceeded.

A:

Change Maximum Execution Time
php.ini
max_execution_time = 30

From Code
Start your code with,
ini_set('MAX_EXECUTION_TIME', 3600);

.htaccess
php_value max_execution_time 3600

No matter which option you choose, restart Apache service.


Q:

Formula for Calculating bandwidth

Really confused with bandwidth calculation formula.
Referring to the bandwidth detection question Check the bandwidth rate in Android i am trying to calculate bandwidth as following.
long startTime = System.currentTimeMillis();
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
long contentLength = httpEntity.getContentLength();
long endTime = System.currentTimeMillis();
float bandwidth = contentLength / ((endTime-startTime) / 1000); // In the refereed question it is "((endTime-startTime) * 1000)" don't know why multiplication.

What i need is current bandwidth in bits (not bytes or kbytes). I don't know using above formula if it is calculating bandwidth in bytes or bits.
also if download time is 0 seconds then what should be the bandwidth is it downloaded content length.
can someone please suggest correct formula to calculate bandwidth in bits.

A:

First of all for precision's sake, you should use 1000.0 to convert to seconds since you are assigning your bandwidth to a float variable:
float bandwidth = (contentLength / (endTime-startTime)) / 1000.0;

Now since your contentLength is measured in bytes, you need to convert to bits (Kb, Mb, etc). There are 8 bits to each byte and socontentLength*8 converts bytes to bits.
Kilo->Mega->Giga ->... scale conversion for the unit of bits is on the order of 1000 which means converting bits to Megabits requires a division by 1000*1000. All this put together should yield:
int bits = contentLength * 8;
int megabits = contentLength / (1000*1000); //Megabits
float seconds = endTime-startTime / 1000.0;
float bandwidth = (megabits / seconds);  //Megabits-per-second (Mbps)

EDIT #1: If bandwidth is denominated by Bytes/Time (like KB/s for example), scale conversion is on the order of 1024
int bytes = contentLength;
int kilobytes = contentLength / 1024; //Kilobytes

EDIT #2: The definition of "Mega" and "Kilo" etc. when talking in terms of bandwidth can  be somewhat ambiguous I am realizing. Often times 1024 (210) and 1000 (103) may be used interchangeably (most likely an accident). For many cases 1024 may be favored as the order of magnitude when calculating bandwidth as memory storage space on computers is measured in base 2. However network bandwidth is usually controlled by the clock speed of a CPU which regulates the transmission of bits, and this rate is measured in hertz (MHz to be exact) which is on the order of magnitude of 1000, not 1024. However in most cases, these two numbers are close enough to not produce significant error.

A:

Based on your link that you gave its commented that its // Bandwidth : size(KB)/time(s) so just multiply it by 1024 to get bytes or 1024*8 to get it in bits, And if the download time is 0 then technically nothing has been downloaded because speed is amout/time
1.For calculating in bits just use
float bandwidth = contentLength / ((endTime-startTime) *(1000*1024*8));

2.If the dowload time is 0 then nothing has been downloaded so we cannot suggest the bandwith
EDIT 2
CALCULATION
Thats just simple math
If you have kb per second like 1 kb/ per 1 second
so speed is 1 kbps => 1*(1024 bytes)/ 1* (1000000000 nano seconds)
so its 0.000001024 bytes per nano seonds
now in bits would be 1*(1024 * 8 bits)/ 1* (1000000000 nano seconds)
so its 0.000008192 bits per nano seconds
now if you want it in seoncds then just multiply it by 1000000000
so its 0.000008192 * 1000000000 = 8192 bits per second
and (0.000008192/8) * 1000000000 = 1024 bytes per second or 1 kbps

A:

public static String internetSpeed(long msecs, long bytes)
{
    long  secs  = msecs / 1000;
    long  bits  = bytes * 8;
    float speed = bits / secs;

    long  Kbit  = 1024;
    long  Mbit  = Kbit * 1024;
    long  Gbit  = Mbit * 1024;

    if (speed < Kbit )                  return String.valueOf(speed)        + " bit-sec" ;
    if (speed > Kbit && speed < Mbit)   return String.valueOf(speed / Kbit) + " Kbit-sec";
    if (speed > Mbit && speed < Gbit)   return String.valueOf(speed / Mbit) + " Mbit-sec";
    if (speed > Gbit)                   return String.valueOf(speed / Gbit) + " Gbit-sec";
    return "???";
}

You can call this method like
....
System.out.println(internetSpeed((endTime-startTime), contentLength));
....


Q:

When should one pass data to a template and when call a function?

When having passed functions to a template via Funcs, these can be called directly in the template. Data can also be passed via Execute.
So far, I've passed general data to the template and only called functions when for example I had to format a Time or some String. See below.
Combining both:
{{range .AssignedTickets}}

FormatDate .Date

{{FormatEditorName .EditorID}}

{{end}}

Mostly using functions, assuming only EditorID was passed as data:
{{$assignedTickets := GetAssignedTickets .EditorID}}
{{range $assignedTickets}}

FormatDate .Date

{{FormatEditorName .EditorID}}

{{end}}

When should I pass data and when should I call a function? Are there performance reasons as to avoid one of these (I'd guess I should avoid calling functions inside the template?)

A:

The big advantage of data passed in is: It is constant. If you call a functions twice (e.g. current date) it might return two different values (e.g. if one call happened right before midnight and the other after midnight).
Also: Functions which may fail are best handled outside the template.
Calling formatting functions (display logic): yes as these functions are deterministic and do not fail.
Calling business logic: No.


Q:

I want to replace the timestamp in an html file using sed

I want to replace the timestamp in an html file using sed, the line I want to replace is:
"dateModified": "2019-04-03 00:35",

I want to update timestamp with current date and time when running the shell script:
"dateModified": "timestamp updated",

I have tried several things but I do not succeed, the closest I have been is:
sed 's/.*"dateModified":.*/"dateModified": "'$(date '+%Y-%m-%d %H:%M')'",/' /path to file/

but there is an error.
I am working on Ubuntu 18.
any suggestion will be very grateful.

A:

your data in 'dat', by gnu sed;
note `` !
d="`date`";sed -E "s/(.*\"dateModified\":).*/\1\"$d\",/i" dat

to really edit it, add -i :  sed -Ei ....


Q:

An efficient way to score two tests in an R data.table

Suppose I have the following data.table with answers to two different tests, red and blue:
library(data.table)
dt <- data.table(
  class = rep("math", 4),
  test = c("red", "red", "blue", "red"),
  student = 1:4,
  q1_answer = c("a", "a", "b", "a"),
  q2_answer = c("b", "c", "b", NA),
  q3_answer = c("c", "c", "c", NA)
)
# dt
#   class test student q1_answer q2_answer q3_answer
#1:  math  red       1         a         b         c
#2:  math  red       2         a         c         c
#3:  math blue       3         b         b         c
#4:  math  red       4         a      <NA>      <NA>

The answer keys for the blue and red tests are the following:
red_answer_key <- c("a", "b", "c")
blue_answer_key <- c("b", "c", "d")

How could I score the two tests so I would have the score column in the following table?
#   class test student q1_answer q2_answer q3_answer score
#1:  math  red       1         a         b         c     3
#2:  math  red       2         a         c         c     2
#3:  math blue       3         b         b         c     1
#4:  math  red       4         a      <NA>      <NA>     1  # count NA as incorrect

A:

One option:
key_list <- list(
  red = red_answer_key,
  blue = blue_answer_key
)
dt_long <- dt[, melt(.SD, id.vars = c("class", "test", "student"))]
dt_scores <- dt_long[, .(score = sum(value == key_list[[test]])), keyby = .(student, test)]
# Join back inz
dt[, score := dt_scores[.SD, on = .(student, test), score]]

#    class test student q1_answer q2_answer q3_answer score
# 1:  math  red       1         a         b         c     3
# 2:  math  red       2         a         c         c     2
# 3:  math blue       3         b         b         c     1
# 4:  math  red       4         a      <NA>      <NA>    NA


Q:

How to inspect the contents of a container of a pod deployed with Kubernetes

I run an .NET Core 2.1 in a container. It writes logs to a file within the container. I am able to run a docker exec bash command to inspect the log file, locally.
This application is then deployed with Kubernetes to a pod with more than one container.
How can I inspect the log file within each one of these containers?

A:

You can exec into container within pod:
kubectl -n <namespace> exec -it <pod name> -c <container name> bash

But the better approach is to make your application stream logs to stdout or stderr, so you can access it directly with:
kubectl -n <namespace> logs <pod name> -c <container name>


Q:

IRB doesn't respect dot (.) as a word-break character

I'm using irb on OS X, and when I press option left/right (or META+B/F) the cursor moves to the next/previous word. But irb doesn't wont to treat dot (.) character as a word separator.
I've tried to add the (.) to the .irbrc, so it looks like this now:
Readline.basic_word_break_characters = " \t\n`><=.;|&{("

But that has no effect.
I'm using the stock Mountain Lion ruby, and a manually compiled 1.9.3, both versions of irb behave similar. Also dot is treated as a separator in bash and in pry, so the system wide settings are probably fine.
Any help appreciated,
Thanks

A:

Ok, it seems that the problem was that there were no libreadline installed in my system at all. Installing the latest readline and recompiling ruby fixed the problem.
I've used readline 6.2 from ftp://ftp.cwru.edu/pub/bash/readline-6.2.tar.gz, which was installed used the basic ./configure && make && make install.
And I've installed ruby 1.9.3-p194 using ruby-build with the following options
sudo ruby-build 1.9.3-p194 /opt/ruby-1.9.3-p194 CONFIGURE_OPTS="--with-readline-dir=/usr/local"

After that IRB started treating dots, underscores and a bunch of other characters as word separators.
Also the properly working readline should return something like:
Readline::VERSION => "6.2"

and the misbehaving one says:
Readline::VERSION => "EditLine wrapper"


Q:

Random variable exercise

given the random variables $X$ and $Y$, such that
$Pr\{X=1\} = Pr\{X=2\} = Pr\{X=3\} = Pr\{X=4\} = Pr\{X=5\} = \frac15$
and
$Pr\{Y=1\} = \frac12$, $Pr\{Y=2\} = Pr\{Y=3\} = Pr\{Y=4\} = Pr\{Y=5\} = \frac18$,
where $Pr\{\}$ represents the probability that a random variable takes on a certain value, compute:
1) $Pr\{X > Y\}$;
2) the probability that $X + Y$ is odd;
3) the conditional probability of "$X$ is even" given "$X + Y$ is odd".
Could you help me to solve this problem?
Thank you!

A:

1) Hint: As $\Pr(X>x) = 1-\frac{x}{5}$, can you find $\Pr(X>Y) = \sum_{x=2}^{5} \Pr(X>x)\Pr(Y=y)\quad$  (assuming $X\perp Y$)
2) Hint: $\newcommand{\odd}{\operatorname{odd}}\newcommand{\even}{\operatorname{even}} \Pr(\odd(X+Y)) = \Pr(\odd(X),\even(Y)) + \Pr(\even(X),\odd(Y))$
3) To evaluate $\Pr(\even(X)\mid \odd(X+Y))$ use the definition of conditional probability (and the above).


Q:

Change Action Bar Overflow Icon in an app

I am trying to change the Action Bar Overflow Icon in an app.  I have seen some info on this site but it's not clear to me.  Does anyone know what code I should enter and in what files?

A:

You can change the Overflow Icon programmatically by using Toolbar.setOverflowIcon() method.
// ToolBar
Toobar toolbar = (Toolbar) findViewById(R.id.toolbar);

if (toolbar != null) {
    setSupportActionBar(toolbar);
    toolbar.setOverflowIcon(getResources().getDrawable(R.drawable.your_overflow_icon));
}

Toolbar XML
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Light"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

</android.support.v7.widget.Toolbar>

or, you can also define a style for custom Overflow Icon in your main styles.xml like this:
<style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="android:src">@drawable/your_overflow_icon</item>
</style>


Q:

batch rename multiple mp3's stripping leading digits

Hi could anyone help me? Im trying to strip leading digits from multiple mp3 files so
"01 some_file.mp3" would become "some_file.mp3" if any one could show me how to doit with zmv that would be great

A:

An script like this might work:
for f in *; do
    mv "$f" "${f:3}"
done

This will strip the first 3 characters of the filename (the two numbers and the space).
Or something like this:
for f in *; do
    mv "$f" "$(printf "$f" | cut -d' ' -f2-)"
done

If there is an actual blank space between the number and the rest of the name. This will print everything from the blank space up to the end of the file.
Note that this will only work for a fixed number of digits (first example) or if there's an actual space between the two fields (second example), if the case doesn't apply for any of the mentioned solutions, you can still count on regex matching:
for f in *; do
    mv "$f" "$(printf "$f" | sed s/[[:digit:]]*\ *//)"
done

This would work for any number of leading digits and/or spaces. For example:
echo '0001     hellow  aasa 1212.mp3' | sed s/[[:digit:]]*\ *//

Will print
hellow  aasa 1212.mp3


Q:

How do I ignore files in Subversion?

How do I ignore files in Subversion?
Also, how do I find files which are not under version control?

A:

(This answer has been updated to match SVN 1.8 and 1.9's behaviour)
You have 2 questions:
Marking files as ignored:
By "ignored file" I mean the file won't appear in lists even as "unversioned": your SVN client will pretend the file doesn't exist at all in the filesystem.
Ignored files are specified by a "file pattern". The syntax and format of file patterns is explained in SVN's online documentation: http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html "File Patterns in Subversion".
Subversion, as of version 1.8 (June 2013) and later, supports 3 different ways of specifying file patterns. Here's a summary with examples:
1 - Runtime Configuration Area - global-ignores option:

This is a client-side only setting, so your global-ignores list won't be shared by other users, and it applies to all repos you checkout onto your computer.
This setting is defined in your Runtime Configuration Area file:

Windows (file-based) - C:\Users\{you}\AppData\Roaming\Subversion\config
Windows (registry-based) - Software\Tigris.org\Subversion\Config\Miscellany\global-ignores in both HKLM and HKCU.
Linux/Unix - ~/.subversion/config

2 - The svn:ignore property, which is set on directories (not files):

This is stored within the repo, so other users will have the same ignore files. Similar to how .gitignore works.
svn:ignore is applied to directories and is non-recursive or inherited. Any file or immediate subdirectory of the parent directory that matches the File Pattern will be excluded.
While SVN 1.8 adds the concept of "inherited properties", the svn:ignore property itself is ignored in non-immediate descendant directories:
cd ~/myRepoRoot                             # Open an existing repo.
echo "foo" > "ignoreThis.txt"                # Create a file called "ignoreThis.txt".

svn status                                  # Check to see if the file is ignored or not.
> ?    ./ignoreThis.txt
> 1 unversioned file                        # ...it is NOT currently ignored.

svn propset svn:ignore "ignoreThis.txt" .   # Apply the svn:ignore property to the "myRepoRoot" directory.
svn status
> 0 unversioned files                       # ...but now the file is ignored!

cd subdirectory                             # now open a subdirectory.
echo "foo" > "ignoreThis.txt"                # create another file named "ignoreThis.txt".

svn status
> ?    ./subdirectory/ignoreThis.txt        # ...and is is NOT ignored!
> 1 unversioned file

(So the file ./subdirectory/ignoreThis is not ignored, even though "ignoreThis.txt" is applied on the . repo root).
Therefore, to apply an ignore list recursively you must use svn propset svn:ignore <filePattern> . --recursive.

This will create a copy of the property on every subdirectory.
If the <filePattern> value is different in a child directory then the child's value completely overrides the parents, so there is no "additive" effect.
So if you change the <filePattern> on the root ., then you must change it with --recursive to overwrite it on the child and descendant directories.

I note that the command-line syntax is counter-intuitive.

I started-off assuming that you would ignore a file in SVN by typing something like svn ignore pathToFileToIgnore.txt however this is not how SVN's ignore feature works.

3- The svn:global-ignores property. Requires SVN 1.8 (June 2013):

This is similar to svn:ignore, except it makes use of SVN 1.8's "inherited properties" feature.
Compare to svn:ignore, the file pattern is automatically applied in every descendant directory (not just immediate children).

This means that is unnecessary to set svn:global-ignores with the --recursive flag, as inherited ignore file patterns are automatically applied as they're inherited.

Running the same set of commands as in the previous example, but using svn:global-ignores instead:
cd ~/myRepoRoot                                    # Open an existing repo
echo "foo" > "ignoreThis.txt"                       # Create a file called "ignoreThis.txt"
svn status                                         # Check to see if the file is ignored or not
> ?    ./ignoreThis.txt
> 1 unversioned file                               # ...it is NOT currently ignored

svn propset svn:global-ignores "ignoreThis.txt" .
svn status
> 0 unversioned files                              # ...but now the file is ignored!

cd subdirectory                                    # now open a subdirectory
echo "foo" > "ignoreThis.txt"                       # create another file named "ignoreThis.txt"
svn status
> 0 unversioned files                              # the file is ignored here too!

For TortoiseSVN users:
This whole arrangement was confusing for me, because TortoiseSVN's terminology (as used in their Windows Explorer menu system) was initially misleading to me - I was unsure what the significance of the Ignore menu's "Add  recursively", "Add *" and "Add " options. I hope this post explains how the Ignore feature ties-in to the SVN Properties feature. That said, I suggest using the command-line to set ignored files so you get a feel for how it works instead of using the GUI, and only using the GUI to manipulate properties after you're comfortable with the command-line.
Listing files that are ignored:
The command svn status will hide ignored files (that is, files that match an RGA global-ignores pattern, or match an immediate parent directory's svn:ignore pattern or match any ancesor directory's svn:global-ignores pattern.
Use the --no-ignore option to see those files listed. Ignored files have a status of I, then pipe the output to grep to only show lines starting with "I".
The command is:
svn status --no-ignore | grep "^I"

For example:
svn status
> ? foo                             # An unversioned file
> M modifiedFile.txt                # A versioned file that has been modified

svn status --no-ignore
> ? foo                             # An unversioned file
> I ignoreThis.txt                  # A file matching an svn:ignore pattern
> M modifiedFile.txt                # A versioned file that has been modified

svn status --no-ignore | grep "^I"
> I ignoreThis.txt                  # A file matching an svn:ignore pattern

ta-da!

A:

Use the following command to create a list not under version control files.
svn status | grep "^\?" | awk "{print \$2}" > ignoring.txt

Then edit the file to leave just the files you want actually to ignore. Then use this one to ignore the files listed in the file:
svn propset svn:ignore -F ignoring.txt .

Note the dot at the end of the line. It tells SVN that the property is being set on the current directory.
Delete the file:
rm ignoring.txt

Finally commit,
svn ci --message "ignoring some files"

You can then check which files are ignored via:
svn proplist -v

A:

.gitignore like approach
You can ignore a file or directory like .gitignore. Just create a text file of list of directories/files you want to ignore and run the code below:
svn propset svn:ignore -F ignorelist.txt .

OR if you don't want to use a text file, you can do it like this:
svn propset svn:ignore "first
 second
 third" .

Source: Karsten's Blog - Set svn:ignore for multiple files from command line


Q:

Objective Pascal - How do you ensure that you call a decendant's methods when cast as an acestor?

I'm currently creating a small RPG engine. I've just gotten to the point of implementing a class tree for the game's objects and I'm not 100% sure which method directives I should use where and in what cases.
I've looked over the Free Pascal Complier's reference guide and various other internet resources but I'm still not confident.
The way I'm planning to implement the handling of game objects requires that categories of game objects have a common base class and will be stored in an array of that class, thus casting them as an ancestor.
What I mainly need to understand is how to ensure that when I call a class cast as one of it's ancestors that it calls the overloaded/overridden/reintroduced method of the actual class rather than that of the ancestor's.
Thanks for your time!
I'm quite happy to clarify/re-word anything here if I'm not being clear enough.

A:

You're not "casting" when you put them into an array of their parent class, and you shouldn't be; that's not how inheritance and polymorphism works.
You create a virtual method in the parent (ancestor), and then each child inherits the parent's method and overrides it with their own specific behavior. When you call the parent method, polymorphism makes sure the proper method gets called.
Here's a quick (trivial) example of how something like this should be constructed. It's in the form of a console application, so that you can actually run it to see the output.
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  // Base class
  TAnimal=class
    procedure Sit; virtual;   // Virtual keyword *necessary* for things to work
    procedure Speak; virtual;
  end;

  // Descendent classes
  TDog=class(TAnimal)
    procedure Sit; override;    // Override keyword required here
    procedure Speak; override;
  end;

  TCat=class(TAnimal)
    // No implementation of Sit, because cats don't sit on command
    procedure Speak; override;  // Override required here also
  end;

  // Array type to hold them, so we don't have to typecast anything
  TAnimalArray = array of TAnimal;

// Implementation of classes

{ TAnimal }
procedure TAnimal.Sit;
begin

end;

procedure TAnimal.Speak;
begin
  // Parent does nothing
end;

{ TCat }
procedure TCat.Speak;
begin
  inherited;
  WriteLn('Meow.');
end;

{ TDog }
procedure TDog.Sit;
begin
  inherited;
  WriteLn('Sitting down now.');
end;

procedure TDog.Speak;
begin
  inherited;
  Writeln('Woof! Woof!');
end;

// Test code to demonstrate use of inheritance and polymorphism
var
  Animals: TAnimalArray;
  i: Integer;
  Pet: TAnimal;   // Variable that holds parent type (TAnimal)

const
  NumberOfAnimals = 5;

begin
  SetLength(Animals, NumberOfAnimals);

  // Fill array with a mix of both dogs and cats
  for i := 0 to High(Animals) do
  begin
    if Odd(i) then
      Animals[i] := TDog.Create
    else
      Animals[i] := TCat.Create;
  end;

  // Loop to use each one regardless of which type, by just accessing the
  // virtual Speak method they overrode from their parent class

  for Pet in Animals do
  begin
    Pet.Speak;
    Pet.Sit;     // Call method only defined for TDog
  end;

  WriteLn('');  // Blank line in console to separate loops.

  // If FreePascal doesn't support the enumeration (for..in) method, do it
  // using a counter:

  for i := 0 to High(Animals) do
  begin
    Animals[i].Speak;
    Animals[i].Sit;     // Call method only defined for TDog
  end;

  // In real life code, you'd loop through the array and free each one here.
  // In this test code, we're exiting right away, and there's really no point
  Readln;
end.

The above produces the output:
Meow.
Woof! Woof!
Sitting down.
Meow.
Woof! Woof!
Sitting down.
Meow.

Meow.
Woof! Woof!
Sitting down.
Meow.
Woof! Woof!
Sitting down.
Meow.

You can find a fairly complete discussion of Delphi's implementation of OOP at the docwiki. Although it's not FreePascal, much of it is compatible, and so it should be somewhat equivalent. I'm not aware of any documentation like it for FPC.


Q:

How to inspect OData Command collection in Web API?

I have a Web API service exposing an OData API resource. The flow of logic is simple: the Get() method calls the repository to get all (people) and the filtering as a result from the OData commands on the query string happens automatically in my API controller because of the OData configuration.
However, my People resultset is getting large so I've implemented caching of that (since it's mostly static and only updates daily) and it works well. At some point though I may need to place the filtering that came as a part of the OData request to the repository query, rather than pulling back the entire dataset and then doing the filtering.
At code camp recently I thought it was mentioned that you could get access to the OData commands used on the API call, and it would require a manual interpretation of these and applying them manually on the query.
Is there a way to see what OData commands exist on the API call in the controller so that I can eager filter my results?

A:

Actually on further review I found there is a much easier way to extract and inspect the query options. When trying to use the ODataQueryOptions parameter in the GET call I ended up with the following error:

Multiple actions were found that match the request

According to ASP.NET WebAPI OData - Inheriting from EntitySetController<> but using Get(ODataQueryOptions options) rather than [Queryable]Get() this is because EntitySetController already defines a Get method. However EntitySetController defines a QueryOptions parameter I was unaware of that is accessible directly as shown below and the easiest way to inspect the OData command parameters:
public override IQueryable<Pharmacy> Get()
{
    //Inspect the query options passed in on the query string
    var opts = this.QueryOptions

}


Q:

Numpy fft2 frequency shift

I don't understand how to make frequency shift in fft2 or higher dimensions.  Could anyone explain it, please?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

%matplotlib inline

numb_steps = 100
x = np.linspace(-10, 10, numb_steps)
y = np.linspace(-10, 10, numb_steps)

X,Y = np.meshgrid(x,y)

R = 1

Z = np.zeros((100, 100))
# circle
for i in range(numb_steps):
    for j in range(numb_steps):
        if x[i]**2+y[j]**2 > R:
            Z[i,j] = 0
        else:
            Z[i,j] = 1

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X,Y,Z)

I only can get those plots

fig = plt.figure()
ax = fig.gca(projection='3d')

Z_fft = np.fft.fft2(Z)
FreqCompRows = np.fft.fftfreq(Z.shape[0],d=2)
FreqCompCols = np.fft.fftfreq(Z.shape[1],d=2)
FreqCompRows = np.fft.fftshift(FreqCompRows)
FreqCompCols = np.fft.fftshift(FreqCompCols)

S,D = np.meshgrid(FreqCompRows, FreqCompCols)

ax.plot_surface(S, D, np.abs(Z_fft))

plt.imshow(np.abs(Z_fft))

plt.xticks(range(len(x_ax)), np.round(x_ax))
plt.yticks(range(len(y_ax)), np.round(y_ax))

P.S. Yes, the ticks overlap is my problem as well

A:

You can solve this using scipy.fftpack (sfft) instead of np.fft, because the sfft implementation can be directly used on 2-dimensionnal arrays so you don't have to do it in a convoluted way (ba dum tsss).
In your code header, add :
import scipy.fftpack as sfft

Then, to calculate the fft and shift the spectrum, use :
Z_fft = sfft.fft2(Z)
Z_shift = sfft.fftshift(Z_fft)

The obtained spectrum is then nicely arranged for image display :
plt.figure(4)
plt.imshow(np.abs(Z_shift))

Also, the way you are constructing the circle seems overly complicated, you can take advantage of python's syntax using boolean syntax :
X,Y = np.meshgrid(x,y)
Z = X**2+Y**2
R = 1
Z[Z > R] = 0;Z[Z > 0] = 1;

What I did here is using the meshgrid you created to calculate the circle equation result, in the form of Z. Then I test Z for all values above R, put them to zero, and the other values to 1.
My code is below :
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import scipy.fftpack as sfft # you have to import this package

plt.close('all')

numb_steps = 100
x = np.linspace(-10, 10, numb_steps)
y = np.linspace(-10, 10, numb_steps)

#constructing the disk in a simpler manner
X,Y = np.meshgrid(x,y)
Z = X**2+Y**2
R = 1
Z[Z > R] = 0;Z[Z > 0] = 1;

# Here, use sfft routines instead of np.fft
Z_fft = sfft.fft2(Z)
Z_shift = sfft.fftshift(Z_fft)
FreqCompRows = np.fft.fftfreq(Z.shape[0],d=2)
FreqCompCols = np.fft.fftfreq(Z.shape[1],d=2)
FreqCompRows = np.fft.fftshift(FreqCompRows)
FreqCompCols = np.fft.fftshift(FreqCompCols)

S,D = np.meshgrid(FreqCompRows, FreqCompCols)

# plotting your disk signal image
fig = plt.figure(1)
ax = fig.gca(projection='3d')
ax.plot_surface(X,Y,Z)

# plotting "3D" fft non-shifted
fig = plt.figure(2)
ax = fig.gca(projection='3d')
ax.plot_surface(S, D, np.abs(Z_fft))

# plotting images of FFT's
plt.figure(3)
plt.imshow(np.abs(Z_fft))

plt.figure(4)
plt.imshow(np.abs(Z_shift))


Q:

How is physicalism true?

Assumptions:

Human auras exist.
There is a subset of the population who are capable of discerning their properties, by whatever means.
Machines can not sense human auras.

Following these assumptions, how is physicalism true?

Physicalism is the thesis that everything is physical, or as contemporary philosophers sometimes put it, that everything supervenes on, or is necessitated by, the physical.

EDITED IN RESPONSE TO COMMENTS

A:

I can smell peach-flavored oolong tea and tell you what it is; a machine cannot (not yet, anyway).
This has nothing to do with mind-body duality.  We simply haven't built chemosensors as diverse and sensitive as those in our noses.
Auras are, logically, just like the smell of peach-flavored oolong tea (except for not having good evidence that they actually exist).


Q:

Как можно передать документ на печать с сервера?

Каким образом можно реализовать систему передачи документа в печать напрямую в принтер как в этом видео? https://www.youtube.com/watch?v=K3JmJWDMmcI&feature=youtu.be
Что это за приставка? Роутер? Как это можно сделать на Python, с помощью каких библиотек и протоколов?

A:

Мелкая белая коробочка - это tp-link tl-mr3020 - роутер, который не умеет печатать сам.
На нем установленна openwrt и программа p910nd - принт-сервер jet-direct.
Проброшен порт jet-direct, этот порт подключается к серверу печати , например, cups. Бот может отправить pdf файл на cups по протоколу ipp( install the Web Server (IIS) role, the Print Services role, and the Internet Printing role service in the Print Services role. - на виндовс сервер можно сделать) или вызовом команды, а купс его переводит на язык принтера и отправляет в принтер.


Q:

How to print the string variable in mysql

i was using sql before but now iam using Mysql i need to know how to print the variable.
In Sql
 Declare @name varachar(50)
set @name ='xxxxxxx'
print  @name

the result will be xxxxxxx. How to get this output in mysql.

A:

Try this, I think this will help you:
SELECT @name


Q:

Using Subqueries to Define Column Alias

I have two tables which I have simplified below for clarity. One stores data values while the other defines the units and type of data. Some tests have one result, others may have more (My actual table has results 1-10):
Table 'Tests':
ID            Result1        Result2        TestType(FK to TestTypes Type)
----------    ------------   -----------    -----------
1001           50            29             1
1002           90.9          NULL           2
1003           12.4          NULL           2
1004           20.2          30             1

Table 'TestTypes':
Type        TestName         Result1Name    Result1Unit   Result2Name     Result2Unit   ..........
-------     ---------        ------------   -----------   ------------    -----------
1           Temp Calib.      Temperature    F             Variance        %
2           Clarity          Turbidity      CU            NULL            NULL

I would like to use the ResultXName as the column alias when I join the two tables. In other words, if a user wants to see all Type 1 'Temp Calib' tests, the data would be formatted as follows:
Temperature      Variance
------------     -----------
50 F             10.1%
20.2 F           4.4%

Or if they look at Type 2, which only uses 1 result and should ignore the NULL:
Turbidity
----------
90.9 CU
12.4 CU

I have had some success in combining the two columns of the tables:
SELECT CONCAT(Result1, ' ', ISNULL(Result1Unit, ''))
FROM Tests
INNER JOIN TestTypes ON Tests.TestType = TestTypes.Type

But I cannot figure out how to use the TestName as the new column alias. This is what I've been trying using a subquery, but it seems subqueries are not allowed in the AS clause:
SELECT CONCAT(Result1, ' ', ISNULL(Result1Unit, '')) AS (SELECT TOP(1) Result1Name FROM TestTypes WHERE Type = 1)
FROM Tests
INNER JOIN TestTypes ON Tests.TestType = TestTypes.Type

Is there a different method I can use? Or do I need to restructure my data to achieve this? I am using MSSQL.

A:

Yes, this can be fully automated by constructing a dynamic SQL string carefully. The key points in this solution and references is listed as follows.

Count the Result variables (section 1.)
Get the new column name of ResultXName by using sp_executesql with the output definition (section 2-1)
Append the clause for the new column (section 2-2)

N.B.1. Although a dynamic table schema is usually considered a bad design, sometimes people are simply ordered to do that. Therefore I do not question the adequacy of this requirement.
N.B.2. Mind the security problem of arbitrary string execution. Additional string filters may be required depending on your use case.
Test Dataset
use [testdb];
GO

if OBJECT_ID('testdb..Tests') is not null
    drop table testdb..Tests;
create table [Tests] (
    [ID] int,
    Result1 float,
    Result2 float,
    TestType int
)
insert into [Tests]([ID], Result1, Result2, TestType)
values (1001,50,29,1),
       (1002,90.9,NULL,2),
       (1003,12.4,NULL,2),
       (1004,20.2,30,1);

if OBJECT_ID('testdb..TestTypes') is not null
    drop table testdb..TestTypes;
create table [TestTypes] (
    [Type] int,
    TestName varchar(50),
    Result1Name varchar(50),
    Result1Unit varchar(50),
    Result2Name varchar(50),
    Result2Unit varchar(50)
)
insert into [TestTypes]([Type], TestName, Result1Name, Result1Unit, Result2Name, Result2Unit)
values (1,'Temp Calib.','Temperature','F','Variance','%'),
       (2,'Clarity','Turbidity','CU',NULL,NULL);

--select * from [Tests];
--select * from [TestTypes];

Solution
/* Input Parameter */
declare @type_no int = 1;

/* 1. determine the number of Results */

declare @n int;

-- If there are hundreds of results please use the method as of (2-1)
select @n = LEN(COALESCE(LEFT(Result1Name,1),''))
          + LEN(COALESCE(LEFT(Result2Name,1),''))
FROM [TestTypes]
where [Type] = @type_no;

/* 2. build dynamic query string */

-- cast type number as string
declare @s_type varchar(10) = cast(@type_no as varchar(10));
-- sql query string
declare @sql nvarchar(max) = '';
declare @sql_colname nvarchar(max) = '';
-- loop variables
declare @i int = 1;  -- loop index
declare @s varchar(10);  -- stringified @i
declare @colname varchar(max);  -- new column name

set @sql += '
select
    L.[ID]';

-- add columns one by one
while @i <= @n begin

    set @s = cast(@i as varchar(10));

    -- (2-1) find the new column name
    SET @sql_colname = N'select @colname = Result' + @s + 'Name
        from [TestTypes]
        where [Type] = ' + @s_type;

    EXEC SP_EXECUTESQL
        @Query = @sql_colname,
        @Params = N'@colname varchar(max) OUTPUT',
        @colname = @colname OUTPUT;

    -- (2-2) sql clause of the new column
    set @sql += ',
      cast(L.Result' + @s + ' as varchar(10)) + '' '' + R.Result' + @s + 'Unit as [' + @colname + ']'

    -- next Result
    set @i += 1
end

set @sql += '
    into [ans]
    from [Tests] as L
    inner join [TestTypes] as R
        on L.TestType = R.Type
    where R.[Type] = ' + @s_type;

/* execute */

print @sql;  -- check the query string

if OBJECT_ID('testdb..ans') is not null
    drop table testdb..ans;
exec sp_sqlexec @sql;

/* show */
select * from [ans];

Result (type = 1)
| ID   | Temperature | Variance |
|------|-------------|----------|
| 1001 | 50 F        | 29 %     |
| 1004 | 20.2 F      | 30 %     |

/* the query string */

select
    L.[ID],
      cast(L.Result1 as varchar(10)) + ' ' + R.Result1Unit as [Temperature],
      cast(L.Result2 as varchar(10)) + ' ' + R.Result2Unit as [Variance]
into [ans]
from [Tests] as L
inner join [TestTypes] as R
    on L.TestType = R.Type
where R.[Type] = 1

Tested on SQL Server 2017 (linux docker image, latest version) on debian 10


Q:

imshow when you are plotting data, not images. Realtion between aspect and extent?

I am plotting a 2D data array with imshow in matplotlib. I have a problem trying to scale the resulting plot. The size of the array is 30x1295 points, but the extent in units are:
    extent = [-130,130,0,77]
If I plot the array without the extent, I get the right plot, but if I use extent, I get this plot with the wrong aspect.
It is a pretty beginner question, but there is always a first time: How I can control the aspect and the size of the plot at the same time?
Thanks,
Alex
P.D. The code is, for the right case:
    imshow(np.log10(psirhoz+1e-5),origin='lower')
and for the wrong one:
    imshow(np.log10(psirhoz+1e-5),origin='lower',
    extent =[z_ax.min(),z_ax.max(),rho_ax.min(),rho_ax.max()])
I hope this clarify a bit things.

A:

I'm guessing that you're wanting "square" pixels in the final plot?
For example, if we plot random data similar to yours:
import numpy as np
import matplotlib.pyplot as plt

data = np.random.random((30, 1295))

fig, ax = plt.subplots()
ax.imshow(data, extent=[-130,130,0,77])
plt.show()

We'll get an image with "stretched" pixels:

So, first off, "aspect" in matplotlib refers to the aspect in data coordinates.  This means we have to jump through a couple of hoops to get what you want.
import numpy as np
import matplotlib.pyplot as plt

def main():
    shape = (30, 1295)
    extent = [-130,130,0,77]

    data = np.random.random(shape)

    fig, ax = plt.subplots()
    ax.imshow(data, extent=extent, aspect=calculate_aspect(shape, extent))
    plt.show()

def calculate_aspect(shape, extent):
    dx = (extent[1] - extent[0]) / float(shape[1])
    dy = (extent[3] - extent[2]) / float(shape[0])
    return dx / dy

main()

A:

In this case, pyplot.matshow() might also be useful:
from matplotlib import pyplot as plt
import numpy as np
dat = np.array(range(9)).reshape(3,3)
plt.matshow(dat)
plt.show()

result:


Q:

bootstrap form-groups in input

I need your help with bootstrap form-group`s.
this is my html
<form action="#" class="form-inline" role="form">

        <input type="text" class="form-control no-margin" placeholder="Search..." />
        <select class="form-control selectcity no-margin" id="sel1">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
        </select>

            <input type="text" class="form-control col-md-3" placeholder="თარიღი" style="padding: 0 5px;" />

    <button class="btn btn-blue" type="submit">Search</button>
</form>

it looks like they are inline
but they have margin from each other.
I tryed margin:0 in css but it not working
please help me.
this image shows how it looks now
Image 1
and on this image is how I need to be
Image 2
please help me.

A:

This is default behavior of inline/inline-block elements: they respect whitespaces between them, including newlines, tabs, etc. The simplest fix in your case is to set font-size: 0 to .form-group container, so that whitespaces are effectively rendered as zero-width:
.form-group.no-margin {
    font-size: 0;
}

This is trick won't affect inner input elements, as for they have more specific font-size settings, but gaps between will disappear.


Q:

How to make a login div ease in and bounce like this?

The login box flies from the top and the input fields animate with it until the bounce is over.  It looks very cool to me.
I want to know how to make an effect like this. I think it's CSS3 animation. Is there any plugin or library for this?
http://themeforest.net/item/katniss-premium-admin-template/full_screen_preview/3878281

A:

You can use animation: bounceY 0.9s linear; if your looking for a quick solution.
Or
You can use a custom cubic bezier transition like this:
-webkit-transition: all 0.5s cubic-bezier(.21,-1,.48,2);
        transition: all 0.5s cubic-bezier(.21,-1,.48,2);

Demo here jsfiddle. Just hover over the back div.
You can change and adjust the effect until you get it just right!


Q:

how to avoid row duplicate in crystal report?

crystal report have duplicated rows when i use suppress  if duplicate its hide value only not full row
as shown in picture
As Example
ACT Status
987 Blank
987 received
987
252 Blank
252 received
475 Blank
522 Received

A:

Use Select Distinct Records so that only distinct records are displayed.
write a condition in supress of the section not on the column.
if ACT=next(ACT)
then true
else false


Q:

Using chunks of MP4 file for thumbnails

I want to extract single frames (as thumbs) from videos, without having to download the full video file. I would like to just read the mp4 header (the info should be in the moov atom) and then download the required byte ranges. Afaik thats what browsers (HTML5 video) do when you skip to an unbuffered part
I already looked at: How can HTML5 video's byte-range requests (pseudo-streaming) work? but i can't figure out how to use it with ffmpeg for example.
Thanks a lot!

A:

Here's how a general algorithm might operate if you were absolutely determined to make this approach work:

download the first kilobyte of the MP4 file
make sure the moov atom is up front; determine moov atom's length and make another request to fetch the rest of the atom
dig through the moov atom to find the video trak atom; dig into that atom to find the following atoms: stsd, stss, stco/co64, and stsz
the stsd will give you initialization information required to feed into the H.264 video decoder
the stss atom gives you a list of all the sync samples (keyframes); these can be decoded independently and would be ideal for your thumbnailing prospects
when you know which frames are keyframes, courtesy of the stss atom, you can cross reference with the stco or co64 atoms (a trak will have one or the other) in order to find the absolute file location, and the stsz atom, which will tell you exactly how many bytes are in the frame

With all of this information combined, you should be able to download and decode (and thus resize and re-compress for thumbnailing) just the keyframes of an MP4 video.


Q:

Rearrange rows in data frame

I have a data frame in R which looks like this with two columns:
ID     phone_number
Mark     866458
Paul     986564
Jack     987543
Mary     523422

I would like to have this kind of output where I only have one single column
Mark
866458
Paul
986564
Jack
987543
Mary
523422

Anybody knows which R code could I use to obtain the output?

Data for reproducibility:
structure(list(ID = c("Mark", "Paul", "Jack", "Mary"), phone_number = c(866458,
                                                                        986564, 987543, 523422)), row.names = c(NA, -4L), class = c("tbl_df", "data.frame"))

A:

We can transpose the dataframe and then create one vector of values
data.frame(new_col = c(t(df)))

#  new_col
#1    Mark
#2  866458
#3    Paul
#4  986564
#5    Jack
#6  987543
#7    Mary
#8  523422

Another base R option using mapply
data.frame(new_col = c(mapply(c, df$ID, df$phone_number)))


Q:

Batch MYSQL Inserts with parent relations in transaction

Considering two tables (I've simplified it a bit, in reality there are more related tables and more columns):
TABLE 'visit'
-------------
- id (auto increment)
- visit_country
- visit_browser

TABLE 'pageview'
----------------
- id
- visit_id (relates to visit.id)
- page_url

Every day, I want to insert a PHP array with around 100.000 visits and 400.000 hits into these tables. The way to speed this process up is by

adding multiple inserts into one query
and wrapping up the entire bunch of queries into a transaction.

However, my problem is that in order to insert the pageview, the Last Insert ID of the parent visit is required. In a transaction where let's say a 1000 visits are inserted using one query, I can no longer use PDO's lastInsertId() method.
Ideally I keep everything into one transaction. A less ideal solution would be to insert all visits and add a reference column, then execute, check which ID each visit got and then use a new transaction to insert the hits. But that is far from ideal.
What would be the way to approach this? How do ORM's like Doctrine solve this problem (I need to rely on raw SQL through PDO here)?

A:

you can do make the query something like this
$sql = "INSERT INTO `visit` (`id`, `visit_country`, `visit_browser`)
VALUES (NULL, :visit_country, :visit_browser);
INSERT INTO `pageview` (`visit_id`, `page_url`)
VALUES (NULL, LAST_INSERT_ID(), :page_url)";

than prepare, bindparam & execute


Q:

Python Tkinter refresh canvas

Hello I have a tuple  in python with colours that are related to squares that are drawn in the canvas by the following dictionary:
colour_mapping = {0: "red", 1: "green", 2: "blue" , 3:"purple"}

To be more specific for example a node at the tuple is:
((2, 3), (3, 3))

This means that 4 squares should be drawn this way:
blue square    purple square
purple square     purple square

and then their colours should be changed accordingly to the next node in my tuple
To do this I iterate the tuple and for each element I draw a new rectangle at the canvas and then I call the time.sleep() function in order to give time to the user to see the differences to the previous state.
My problem is that only the last node is rendered correctly while all the others aren't shown. Can you help me?
Here is my code so far:
self.parent.title("AlienTiles")
self.style = Style()
self.style.theme_use("default")

self.frame =  Frame(self, relief=RAISED, borderwidth=1)
self.frame.pack(fill=BOTH, expand=1)

self.canvas = Canvas(self.frame)
self.canvas.pack(fill=BOTH, expand=1)

self.pack(fill=BOTH, expand=1)

for i in range(len(path)) : #the tuple is path

            state = path[i].state
            print state
            time.sleep(1)
            y_offset=10
            for x in state:
                start_x=40
                start_y=10
                i=1
                x_offset=0

                for y in x:

                    x0=(start_x*i)+x_offset
                    y0=(start_y*i)+y_offset
                    x1=x0+size
                    y1=y0+size
                    colour=colour_mapping[y]

                    print colour

                    self.canvas.create_rectangle(x0, y0, x1, y1, fill=colour)
                    x_offset=x_offset+size+10

                y_offset=y_offset+size+10

All in all, I try to make an animation described above. Is there anything I don't think correctly or something to refresh the canvas at each loop?

A:

The only way for the canvas to refresh is for the event loop to service "redraw" events. In your loop you're never giving the event loop a chance to update, so you don't see any changes.
The quick fix is to call self.canvas.update_idletasks, but that's just a hack and not a proper solution.
The proper way to do animation is to use the event loop to do the iterations. You do this by placing work to be done on a queue -- in this case, the idle event queue. You can place things on this queue with the after command.
What you should do is write a function that does one iteration of your animation. Essentially, take everything in your while loop and move it to a function. Then, arrange for that function to be continually be called as long as there is work to do. You can either place the call to after in that function, or have a separate function controlling the animation.
Roughly speaking, the solution looks like this:
def do_one_frame(self, ...):
    # do whatever you need to draw one frame

    if (there_is_more_work_to_be_done):
        self.after(10, do_one_frame)

This will draw one frame of your animation, check to see if there are any new frames to be drawn, and then arranges for the next frame to be drawn in 10ms. Of course, you can set that value to whatever you want in order to control the speed of the animation.
There are working examples of this technique on this website. For example, see https://stackoverflow.com/a/25431690/7432


Q:

how to scale divs content equal to browser window

I'm messing around with a special case a customer wants. Back in the days, we all know the advantage of Flash where it's very simple to scale things up and down with just simply give widths and heights of the file.
Exactly this is what I want to do with a div-wrapper. As seen in this picture
this is similar to the enter-page. What I would like to archieve is, if the browser-window scales all squares keep the same aspect-ratio and get smaller or bigger.
Assuming I'm using divs with background-images and the markup is something like this:

is there any css or jquery solution to make this possible?
Any hints are much appreciated. Thanks

A:

You can do this by Javascript or CSS. However, for text adjustments I suggest you do it through Javascript, but if you need full browser compatibility and assured effectiveness, you should rely on plugins that give you a good control over what you are doing (building this without them can consume unnecessary time).
Through CSS you can attribute the images' width and height with percentages relative to the body's total size.
for example: JSfiddle
html, body{
   width:100%;
   height:100%;
}
img{
   position:relative;
   width:50%;
   height:100%;
}

Through Javascript you can choose from various plugins such as:

Adaptive Images
ResponsiveImg
JQuery Picture

For more detailed info check this out:

Which responsive images solution should you use?
Choosing a responsive image solution


Q:

How to call a server side function from client side (e.g. html button onclick) in Node.js?

I need a complete basic example in Node.js of calling a server-side function from (client side) html button onclick event, just like in ASP.NET and C#.
I am new to Node.js and using the Express framework.
Any help?
IMPROVED QUESTION:
//server side :
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();

// all environments

app.set('views',__dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'html');

app.use(app.router);

app.get("/",function(req,res)
{
  res.render('home.html');
});

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

//Client Side
 <input type="button" onclick="" />  <--just want to call the serverside function from here-->

A:

Here's an example using Express and a HTML form.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);

app.use(express.bodyParser());
app.post('/', function(req, res) {
  console.log(req.body);
  res.send(200);
});

server.listen(process.env.PORT, process.env.IP);

The code above will start an instance of Express, which is a web application framework for Node. The bodyParser() module is used for parsing the request body, so you can read post data. It will then listen for POST requests on the route /.
<form method="post" action="/">
  <input type="test" name="field1">
  <input type="test" name="field2">
  <input type="submit">
</form>

And if you submit that form, in req.body for the route /, you will get the result:
{ field1: 'form contents', field2: 'second field contents' }

To run a function, just put it inside the POST handler like this:
var foo = function() {
  // do something
};

app.post('/', function(req, res) {
  console.log(req.body);
  res.send(200);

  // sending a response does not pause the function
  foo();
});

If you don't want to use Express then you can use the native HTTP module, but you'd have to parse the HTTP request body yourself.
var http = require('http');
http.createServer(function(request, response) {
  if (request.method === 'POST') {
    var data = '';

    request.on('data', function(chunk) {
      data += chunk;
    });

    request.on('end', function() {
      // parse the data
      foo();
    });
  }
}).listen(80);


Q:

Hebrew Israelites recognition by mainstream Judaism

Are the adherents of 'Hebrew Israelites' church Jews from the 'mainstream' point of view and why (why yes or why not)? I have found mixed information on the topic.
Also some of them seek conversion, some migrated to Jerusalem (??? it is real - how and why?) and some oppose 'mainstream' Jewish decominations and hold they are the true Hebrews but are not recognized by other groups.

A:

From what I gather (from here and elsewhere), the group is a Christian group which accepts Jesus as a messianic figure and which considers itself to be the only valid set of descendants from the ancient tribal sons of Jacob. They have no connection to Judaism that modern Judaism would accept (without matrilineal descent or an approved process of conversion) and claim that the proof of their connection is that black people found world-wide suffer the curses in Leviticus 26 and Deuteronomy 28, and this defines who is a proper "Israelite". They deny, then that modern Judaism has anything to do with who Israelites are or that anyone else who isn't black can claim any connection.
Because they lack any actual familial tradition of connection, and do not practice Judaism, they are not accepted as Jews.

A:

The Hebrew Israelite issue is a demonstration of how complete and unfounded wannabism can be turned into a reality.
Towards the end of the 19th century some African-Americans churches who previously had identified themselves with the ancient Hebrews shifted into an identification as ancient Hebrews. This movement gave birth to various groups, mostly clear Christian denominations and others that mix Jewish and Evangelical elements in their worship. The Commandment Keepers founded by Wentworth A. Matthew, for example, adopted mostly traditional Jewish worship and lifestyle and kept cordial ties with the mainstream Judaism.
While the Commandment Keepers viewed the non-black Jews as those who preserved Judaism over the centuries many of the present-day Hebrew Israelites accuse the rabbinic Jews of being white impostors. The Anti-Defamation League has accused some groups of promoting black supremacy.
Ben Carter, later to be known as Ben Ammi Ben-Israel, founded the African Hebrew Israelites of Jerusalem in Chicago in 1966 and moved in 1969 with a group of 30 adherents to Israel. About 600 members have moved after them to Israel where the community in Dimona now counts ca. 2,500 members and reveres Ben-Israel as their "messiah".
Many of them clearly state that they are "Hebrews" or "Israelites" as opposed to traditional Jews. It is unclear up to what extent they follow the New Testament. However they completely deny the authority of the Jewish Oral Law.
Some members of the Hebrew Israelite community in Dimona have converted to Judaism, it is unclear to me what their status is in their strictly closed community after the gijur. The general acceptance of the Hebrew Israelites among the Israeli public has improved and now they even serve in the IDF. However, their Jewish status is clearly denied.
The "Israelite" elements in the H-I religion obviously date back no further than to the times of conversion to Christianity of their ancestors after being transferred to America from western Africa. They cannot prove any pre-existing linguistic, religious or cultural connection to Judaism whatsoever like what you can find in the case of the crypto-Jews' and their descendants.


Q:

no symbol in current context for global variable

I'm new to GDB, and I'm stepping through a function causing me trouble.  I'm trying to print the value of a global variable (which determines control flow) but I'm getting no symbol in current context.  I don't know where the symbol is defined, but shouldn't it be present here?
The block I'm looking at:
if (present(weights)) then
      numWeights = size(weights,1)
>     if (numWeights == NSPECIES) then
         weightsFull = weights
      else
         weightsFull = weights(1)
      endif
else
      weightsFull = 1.0
endif

And I'm trying to get the value of NSPECIES

A:

Is it possible that NSPECIES is a macro rather than a variable?  If it is then you will need to compile your program with -g3 in order to get the macro information included in the binary.


Q:

populating a div with html with query

Possible Duplicate:
how to get the value of a textarea in jquery?

I have the following HTML:

And the following jQuery (var gets value from a form textarea):
var description = $('#inputDescription').html();
$('#textdescription').html(description);

How can I get the value into #description

A:

val() : val() method is primarily used to get the values of form elements such as input, select and textarea.
html(): Get the HTML contents of the first element in the set of matched elements.
text(): Get the combined text contents of each element in the set of matched elements, including their descendants.
   var description = $('#inputDescription').val();
     $('#textdescription').html(description);

see demo here JsFiddle Demo


Q:

Get a variable from an array in perl

I am running a following command and getting the 4 lines as output.
userid@server:/home/userid# ps -ef|grep process

This is the output for the command.
userid  10117  9931  0 06:25 pts/0    00:00:00 grep process
userid  15329     1  0 Jul11 ?        00:03:40 process APP1
userid  15334 15329  1 Jul11 ?        2-00:40:53 process1 APP1
userid  15390 15334  0 Jul11 ?        05:19:31 process2 APP1

I want to save the value APP1 to a variable using perl. So I want an output like $APP = APP1.

A:

I used a single line command to get the required result.
#!/usr/bin/perl
use strict;
use warnings;
my $app1
$app1 = ( split /\s+/, `pgrep -f process1` )[-1];
print ($app1);


Q:

logic behind providing the $scope object as the argument to watchers within $digest

I'm not too clear why is the $scope object provided as an argument to both the watcher as well as the listener function.
I found this bit of code on GitHub, it's the piece that iterates over the watchers array within $digest:
    this.$$watchers.forEach(function(watcher) {
    var newValue = watcher.watchFn(self);
    var oldValue = watcher.last;

    if (watcher.deep && newValue === oldValue) {
      deppCompare(newValue, oldValue);
    } else {
      if (newValue !== oldValue) dirty = true;
    }

    watcher.listenerFn(newValue, oldValue, self);
    watcher.last = newValue;
  });

A:

Behind the scenes, when you declare it a watch function in a certain scope, angular parse the expression given in a function:
//The code of a random watcher
$scope.$watch('myVariable', listenerFunction);

//Behind the scenes
$scope.$watch(function(scope){
  return scope.myVariable;
}, listenerFunction);

When you register a watcher, the expected behaviour it's that "in THIS SCOPE, i need watch the changes for the variable attached in THIS SCOPE", therefore, behind the scenes the first argument of the $watch() parsed by angular for return the expected variable should be a variable in the scope where a watch function was attached.


Q:

AJAX in ASP.NET - How do I check a checkbox and have the action reflected in the database?

This is about as beginner as it gets regarding AJAX, but here it goes.

I want to have one checkbox somewhere on an ASP.NET web form (ASPX).
When the user clicks the checkbox, I want one of those spinning indicators to show.
While that spinning indicator is showing, I want an update operation to occur in the database to reflect that the user has intended for that checkbox to be checked.
update MyTable set CheckboxChecked = 1
Then, as soon as the update operation has completed (must be verified to actually have been written), I want that to be reflected in the checkbox by removing the spinning indicator and replacing it with the standard checked checkbox.

I'm guessing this is done with an UpdatePanel and possibly an update statement followed by a looped call to a select statement... but I have never used AJAX before and have no idea how to go about it.
Thanks!

A:

Add an update progess like this:
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="0">
<ProgressTemplate>

          <asp:Image ID="Image3" runat="server" ImageUrl="~/Images/progress.gif" />
          Please wait....

</ProgressTemplate>

Wrap your grid with an update panel
Subscibe to your Checkbox OnCheckedChanged and call Update


Q:

Implied string comparison, 0=='', but 1=='1'

I was debugging something and discovered some strangeness in JavaScript:
alert(1=='') ==> false
alert(0=='') ==> true
alert(-1=='') ==> false

It would make sense that an implied string comparison that 0 should = '0'. This is true for all non-zero values, but why not for zero?

A:

According to the Mozilla documentation on Javascript Comparison Operators

If the two operands are not of the same type, JavaScript converts the
  operands then applies strict
  comparison. If either operand is a
  number or a boolean, the operands are
  converted to numbers; if either
  operand is a string, the other one is
  converted to a string

What's actually happening is that the strings are being converted to numbers.
For example:
1 == '1' becomes 1 == Number('1') becomes 1 == 1: true
Then try this one:
1 == '1.' becomes 1 == Number('1.') becomes 1 == 1: true
If they were becoming strings, then you'd get '1' == '1.', which would be false.
It just so happens that Number('') == 0, therefore 0 == '' is true

A:

When javascript does implicit type conversions, the empty string literal will match the 0 integer.  Do your comparison like this and you'll get your expected result:
alert(1==='') ==> false
alert(0==='') ==> false
alert(-1==='') ==> false

A:

ECMA-262, 3rd edition, 11.9.3 regarding x == y, step 16:

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

The empty string '' gets converted to 0 before the comparison.


Q:

Vim regex equivalent in vs code

In Vim I can use :g/^\s*T\y A to copy all lines starting with T in a file to register a, then paste it to wherever I need it from said register.
How can I, or what is the equivalent regex to do the same in Visual Studio Code?
Be mindful that I am NOT fluent with regex and two days new to VS Code.
Thanks for your help in advance.

A:

I don't think you can copy to multiple registers like that in VSCode unless someone has an extension to do it.  Otherwise, one at a time you can:
Put ^\s*T.*$ in the search field
ALT-Enter will select all occurences of those matches
CTRL-C to copy to clipboard
Then paste to where you want it.