Programs & Examples On #Non nullable

OperationalError, no such column. Django

I think you skipped this steps...run the following commands to see if you had forgotten to execute them...it worked for me.

$ python manage.py makemigrations

$ python manage.py migrate

Thank you.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

Do you already have database entries in the table UserProfile? If so, when you add new columns the DB doesn't know what to set it to because it can't be NULL. Therefore it asks you what you want to set those fields in the column new_fields to. I had to delete all the rows from this table to solve the problem.

(I know this was answered some time ago, but I just ran into this problem and this was my solution. Hopefully it will help anyone new that sees this)

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I am also new to MVC and I received the same error and found that it is not passing proper routeValues in the Index view or whatever view is present to view the all data.

It was as below

<td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>

I changed it to the as show below and started to work properly.

<td>
            @Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>

Basically this error can also come because of improper navigation also.

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

Redirect to Action by parameter mvc

This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.

public static void RegisterRoutes(RouteCollection routes)
{
    //adding the {id} and setting is as optional so that you do not need to use it for every action
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Now you should be able to redirect to your controller the way you have set it up.

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index","ProductImageManager", new { id });

    //if the action is in the same controller, you can omit the controller:
    //RedirectToAction("Index", new { id });
}

In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter

return RedirectToAction("Index", new RouteValueDictionary( 
    new { controller = "ProductImageManager", action = "Index", id = id } ) 
);

If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index). See this so question for more information.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

I also had same issue. I investigated and found missing {action} attribute from route template.

Before code (Having Issue):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

After Fix(Working code):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Show empty string when date field is 1/1/1900

Try this code

(case when CONVERT(VARCHAR(10), CreatedDate, 103) = '01/01/1900' then '' else CONVERT(VARCHAR(24), CreatedDate, 121) end) as Date_Resolved

Pass parameter to controller from @Html.ActionLink MVC 4

I have to pass two parameters like:

/Controller/Action/Param1Value/Param2Value

This way:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= Param1Value, 
        Param2Name = Param2Value 
    },
    htmlAttributes: null
)

will generate this url

/Controller/Action/Param1Value?Param2Name=Param2Value

I used a workaround method by merging parameter two in parameter one and I get what I wanted:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= "Param1Value / Param2Value" ,      
    },
    htmlAttributes: null
)

And I get :

/Controller/Action/Param1Value/Param2Value

How to set time to midnight for current day?

Using some of the above recommendations, the following function and code is working for search a date range:

Set date with the time component set to 00:00:00

public static DateTime GetDateZeroTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}

Usage

var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);

var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));

Custom method names in ASP.NET Web API

Web Api by default expects URL in the form of api/{controller}/{id}, to override this default routing. you can set routing with any of below two ways.

First option:

Add below route registration in WebApiConfig.cs

config.Routes.MapHttpRoute(
    name: "CustomApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Decorate your action method with HttpGet and parameters as below

[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
                        string param2, string param3)

 {

// your code here

}

for calling above method url will be like below

http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1&param2=value2&param3=value3

Second option Add route prefix to Controller class and Decorate your action method with HttpGet as below. In this case no need change any WebApiConfig.cs. It can have default routing.

[RoutePrefix("api/{controller}/{action}")]
public class MyDataController : ApiController
{

[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
                        string param2, string param3)

{

// your code here

}

}

for calling above method url will be like below

http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1&param2=value2&param3=value3

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

string is a reference type, a class. You can only use Nullable<T> or the T? C# syntactic sugar with non-nullable value types such as int and Guid.

In particular, as string is a reference type, an expression of type string can already be null:

string lookMaNoText = null;

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

The reason you're facing this is due to the difference between composition and aggregation.

In composition, the child object is created when the parent is created and is destroyed when its parent is destroyed. So its lifetime is controlled by its parent. e.g. A blog post and its comments. If a post is deleted, its comments should be deleted. It doesn't make sense to have comments for a post that doesn't exist. Same for orders and order items.

In aggregation, the child object can exist irrespective of its parent. If the parent is destroyed, the child object can still exist, as it may be added to a different parent later. e.g.: the relationship between a playlist and the songs in that playlist. If the playlist is deleted, the songs shouldn't be deleted. They may be added to a different playlist.

The way Entity Framework differentiates aggregation and composition relationships is as follows:

  • For composition: it expects the child object to a have a composite primary key (ParentID, ChildID). This is by design as the IDs of the children should be within the scope of their parents.

  • For aggregation: it expects the foreign key property in the child object to be nullable.

So, the reason you're having this issue is because of how you've set your primary key in your child table. It should be composite, but it's not. So, Entity Framework sees this association as aggregation, which means, when you remove or clear the child objects, it's not going to delete the child records. It'll simply remove the association and sets the corresponding foreign key column to NULL (so those child records can later be associated with a different parent). Since your column does not allow NULL, you get the exception you mentioned.

Solutions:

1- If you have a strong reason for not wanting to use a composite key, you need to delete the child objects explicitly. And this can be done simpler than the solutions suggested earlier:

context.Children.RemoveRange(parent.Children);

2- Otherwise, by setting the proper primary key on your child table, your code will look more meaningful:

parent.Children.Clear();

Nullable type as a generic parameter possible?

Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.

However, you can use the generic constraints to make sure that the methods are used correctly.

In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.

I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.

    public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
        where TSource: class
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a class is null
        return result;
    }

    public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
        where TSource : struct
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a nullable is null
        return result;
    }

C# nullable string error

String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.

 let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
    'callback': function(response) {
        recaptchVerified = true;
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        // ...
    },
    'expired-callback': function() {
        // Response expired. Ask user to solve reCAPTCHA again.
        // ...
    }
});

Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.

So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.

Grouping functions (tapply, by, aggregate) and the *apply family

There are lots of great answers which discuss differences in the use cases for each function. None of the answer discuss the differences in performance. That is reasonable cause various functions expects various input and produces various output, yet most of them have a general common objective to evaluate by series/groups. My answer is going to focus on performance. Due to above the input creation from the vectors is included in the timing, also the apply function is not measured.

I have tested two different functions sum and length at once. Volume tested is 50M on input and 50K on output. I have also included two currently popular packages which were not widely used at the time when question was asked, data.table and dplyr. Both are definitely worth to look if you are aiming for good performance.

library(dplyr)
library(data.table)
set.seed(123)
n = 5e7
k = 5e5
x = runif(n)
grp = sample(k, n, TRUE)

timing = list()

# sapply
timing[["sapply"]] = system.time({
    lt = split(x, grp)
    r.sapply = sapply(lt, function(x) list(sum(x), length(x)), simplify = FALSE)
})

# lapply
timing[["lapply"]] = system.time({
    lt = split(x, grp)
    r.lapply = lapply(lt, function(x) list(sum(x), length(x)))
})

# tapply
timing[["tapply"]] = system.time(
    r.tapply <- tapply(x, list(grp), function(x) list(sum(x), length(x)))
)

# by
timing[["by"]] = system.time(
    r.by <- by(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)

# aggregate
timing[["aggregate"]] = system.time(
    r.aggregate <- aggregate(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)

# dplyr
timing[["dplyr"]] = system.time({
    df = data_frame(x, grp)
    r.dplyr = summarise(group_by(df, grp), sum(x), n())
})

# data.table
timing[["data.table"]] = system.time({
    dt = setnames(setDT(list(x, grp)), c("x","grp"))
    r.data.table = dt[, .(sum(x), .N), grp]
})

# all output size match to group count
sapply(list(sapply=r.sapply, lapply=r.lapply, tapply=r.tapply, by=r.by, aggregate=r.aggregate, dplyr=r.dplyr, data.table=r.data.table), 
       function(x) (if(is.data.frame(x)) nrow else length)(x)==k)
#    sapply     lapply     tapply         by  aggregate      dplyr data.table 
#      TRUE       TRUE       TRUE       TRUE       TRUE       TRUE       TRUE 

# print timings
as.data.table(sapply(timing, `[[`, "elapsed"), keep.rownames = TRUE
              )[,.(fun = V1, elapsed = V2)
                ][order(-elapsed)]
#          fun elapsed
#1:  aggregate 109.139
#2:         by  25.738
#3:      dplyr  18.978
#4:     tapply  17.006
#5:     lapply  11.524
#6:     sapply  11.326
#7: data.table   2.686

Include of non-modular header inside framework module

You can set Allow Non-modular includes in Framework Modules in Build Settings for the affected target to YES. This is the build setting you need to edit:

Build Settings item you need to edit

NOTE: You should use this feature to uncover the underlying error, which I have found to be frequently caused by duplication of angle-bracketed global includes in files with some dependent relationship, i.e.:

#import <Foo/Bar.h> // referred to in two or more dependent files

If setting Allow Non-modular includes in Frame Modules to YES results in a set of "X is an ambiguous reference" errors or something of the sort, you should be able to track down the offending duplicate(s) and eliminate them. After you've cleaned up your code, set Allow Non-modular includes in Frame Modules back to NO.

Cleanest way to toggle a boolean variable in Java?

Unfortunately, there is no short form like numbers have increment/decrement:

i++;

I would like to have similar short expression to invert a boolean, dmth like:

isEmpty!;

What is the most efficient way to check if a value exists in a NumPy array?

Fascinating. I needed to improve the speed of a series of loops that must perform matching index determination in this same way. So I decided to time all the solutions here, along with some riff's.

Here are my speed tests for Python 2.7.10:

import timeit
timeit.timeit('N.any(N.in1d(sids, val))', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

18.86137104034424

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = [20010401010101+x for x in range(1000)]')

15.061666011810303

timeit.timeit('N.in1d(sids, val)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

11.613027095794678

timeit.timeit('N.any(val == sids)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

7.670552015304565

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

5.610057830810547

timeit.timeit('val == sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

1.6632978916168213

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = set([20010401010101+x for x in range(1000)])')

0.0548710823059082

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = dict(zip([20010401010101+x for x in range(1000)],[True,]*1000))')

0.054754018783569336

Very surprising! Orders of magnitude difference!

To summarize, if you just want to know whether something's in a 1D list or not:

  • 19s N.any(N.in1d(numpy array))
  • 15s x in (list)
  • 8s N.any(x == numpy array)
  • 6s x in (numpy array)
  • .1s x in (set or a dictionary)

If you want to know where something is in the list as well (order is important):

  • 12s N.in1d(x, numpy array)
  • 2s x == (numpy array)

Find commit by hash SHA in Git

Just use the following command

git show a2c25061

or (the exact equivalent):

git log -p -1 a2c25061

Go / golang time.Now().UnixNano() convert to milliseconds?

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

Hashing with SHA1 Algorithm in C#

public string Hash(byte [] temp)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(temp);
        return Convert.ToBase64String(hash);
    }
}

EDIT:

You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);

or

return System.Text.Encoding.Unicode.GetString(hash);

Is 'bool' a basic datatype in C++?

Allthough it's now a native type, it's still defined behind the scenes as an integer (int I think) where the literal false is 0 and true is 1. But I think all logic still consider anything but 0 as true, so strictly speaking the true literal is probably a keyword for the compiler to test if something is not false.

if(someval == true){

probably translates to:

if(someval !== false){ // e.g. someval !== 0

by the compiler

Why can't I use Docker CMD multiple times to run multiple services?

Even though CMD is written down in the Dockerfile, it really is runtime information. Just like EXPOSE, but contrary to e.g. RUN and ADD. By this, I mean that you can override it later, in an extending Dockerfile, or simple in your run command, which is what you are experiencing. At all times, there can be only one CMD.

If you want to run multiple services, I indeed would use supervisor. You can make a supervisor configuration file for each service, ADD these in a directory, and run the supervisor with supervisord -c /etc/supervisor to point to a supervisor configuration file which loads all your services and looks like

[supervisord]
nodaemon=true

[include]
files = /etc/supervisor/conf.d/*.conf

If you would like more details, I wrote a blog on this subject here: http://blog.trifork.com/2014/03/11/using-supervisor-with-docker-to-manage-processes-supporting-image-inheritance/

Error when deploying an artifact in Nexus

Server id should match with the repository id of maven settings.xml

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

How do I associate file types with an iPhone application?

BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.

We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.

Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):

In app did load at top, just do this...

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, 
                                                                   (CFStringRef)@"icz", 
                                                                   NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.

But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.

$ curl -D headers THEURLGOESHERE > /dev/null
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 27393  100 27393    0     0  24983      0  0:00:01  0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive

The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
                                                                   (CFStringRef)@"text/calendar", 
                                                                   NULL);

CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.

So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.

How to pass boolean parameter value in pipeline to downstream jobs?

In addition to Jesse Glick answer, if you want to pass string parameter then use:

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

What are the rules for calling the superclass constructor?

The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.

Class2::Class2(string id) : Class1(id) {
....
}

Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.

Script to Change Row Color when a cell changes text

Realise this is an old thread, but after seeing lots of scripts like this I noticed that you can do this just using conditional formatting.

Assuming the "Status" was Column D:

Highlight cells > right click > conditional formatting. Select "Custom Formula Is" and set the formula as

=RegExMatch($D2,"Complete")

or

=OR(RegExMatch($D2,"Complete"),RegExMatch($D2,"complete"))

Edit (thanks to Frederik Schøning)

=RegExMatch($D2,"(?i)Complete") then set the range to cover all the rows e.g. A2:Z10. This is case insensitive, so will match complete, Complete or CoMpLeTe.

You could then add other rules for "Not Started" etc. The $ is very important. It denotes an absolute reference. Without it cell A2 would look at D2, but B2 would look at E2, so you'd get inconsistent formatting on any given row.

How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

What is the best way to auto-generate INSERT statements for a SQL Server table?

I made a simple to use utility, hope you enjoy.

  • It doesn't need to create any objects on the database (easy to use on production environment).
  • You don't need to install anything. It's just a regular script.
  • You don't need special permissions. Just regular read access is enough.
  • Let you copy all the lines of a table, or specify WHERE conditions so only the lines you want will be generated.
  • Let you specify a single or multiple tables and different condition statements to be generated.

If the generated INSERT statements are being truncated, check the limit text length of the results on the Management Studio Options: Tools > Options, Query Results > SQL Server > Results to Grid, "Non XML data" value under "Maximum Characters Retrieved".

    -- Make sure you're on the correct database
    SET NOCOUNT ON;
    BEGIN TRY
    BEGIN TRANSACTION

    DECLARE @Tables TABLE (
        TableName          varchar(50) NOT NULL,
        Arguments           varchar(1000) NULL
    );

    -- INSERT HERE THE TABLES AND CONDITIONS YOU WANT TO GENERATE THE INSERT STATEMENTS
    INSERT INTO @Tables (TableName, Arguments) VALUES ('table1', 'WHERE field1 = 3101928464');
    -- (ADD MORE LINES IF YOU LIKE) INSERT INTO @Tables (TableName, Arguments) VALUES ('table2', 'WHERE field2 IN (1, 3, 5)');



    -- YOU DON'T NEED TO EDIT FROM NOW ON.
    -- Generating the Script
    DECLARE @TableName  varchar(50),
            @Arguments  varchar(1000),
            @ColumnName varchar(50),
            @strSQL     varchar(max),
            @strSQL2    varchar(max),
            @Lap        int,
            @Iden       int,
            @TypeOfData int;

    DECLARE C1 CURSOR FOR
    SELECT TableName, Arguments FROM @Tables
    OPEN C1
    FETCH NEXT FROM C1 INTO @TableName, @Arguments;
    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- If you want to delete the lines before inserting, uncomment the next line
        -- PRINT 'DELETE FROM ' + @TableName + ' ' + @Arguments

        SET @strSQL = 'INSERT INTO ' + @TableName + ' (';

        -- List all the columns from the table (to the INSERT into columns...)
        SET @Lap = 0;
        DECLARE C2 CURSOR FOR
        SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
        OPEN C2
        FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF(@Lap>0)
            BEGIN
                SET @strSQL = @strSQL + ', ';
            END

            SET @strSQL = @strSQL + @ColumnName;
            SET @Lap = @Lap + 1;
            FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        END
        CLOSE C2
        DEALLOCATE C2

        SET @strSQL = @strSQL + ')'
        SET @strSQL2 = 'SELECT ''' + @strSQL + '
SELECT '' + ';

        -- List all the columns from the table again (for the SELECT that will be the input to the INSERT INTO statement)
        SET @Lap = 0;
        DECLARE C2 CURSOR FOR
        SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
        OPEN C2
        FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF(@Lap>0)
            BEGIN
                SET @strSQL2 = @strSQL2 + ' + '', '' + ';
            END

            -- For each data type, convert the data properly
            IF(@TypeOfData IN (55, 106, 56, 108, 63, 38, 109, 50, 48, 52)) -- Numbers
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (62)) -- Float Numbers
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), CONVERT(decimal(18,5), ' + @ColumnName + ')), ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (61, 111)) -- Datetime
                SET @strSQL2 = @strSQL2 + 'ISNULL( '''''''' + CONVERT(varchar(max),' + @ColumnName + ', 121) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (47, 39)) -- Texts
                SET @strSQL2 = @strSQL2 + 'ISNULL('''''''' + RTRIM(LTRIM(' + @ColumnName + ')) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE -- Unknown data types
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '(INCORRECT TYPE ' + CONVERT(varchar(10), @TypeOfData) + ')''';

            SET @Lap = @Lap + 1;
            FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        END
        CLOSE C2
        DEALLOCATE C2

        SET @strSQL2 = @strSQL2 + ' as [-- ' + @TableName + ']
FROM ' + @TableName + ' WITH (NOLOCK) ' + @Arguments

        SET @strSQL2 = @strSQL2 + ';
';
        --PRINT @strSQL;
        --PRINT @strSQL2;
        EXEC(@strSQL2);

        FETCH NEXT FROM C1 INTO @TableName, @Arguments;
    END
    CLOSE C1
    DEALLOCATE C1

    ROLLBACK
END TRY
BEGIN CATCH
    ROLLBACK TRAN
    SELECT 0 AS Situacao;
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage,
        @strSQL As strSQL,
        @strSQL2 as strSQL2;
END CATCH

Setting default value for TypeScript object passed as argument

Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.

interface IName {
  firstName: string
  lastName?: string
}

function sayName(params: IName) {
  const { firstName, lastName = "Smith" } = params
  const fullName = `${firstName} ${lastName}`

  console.log("FullName-> ", fullName)
}

sayName({ firstName: "Bob" })

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

mysql error 1364 Field doesn't have a default values

Set a default value for Created_By (eg: empty VARCHAR) and the trigger will update the value anyways.

create table try ( 
     name varchar(8), 
     CREATED_BY varchar(40) DEFAULT '' not null
);

Angular ReactiveForms: Producing an array of checkbox values?

My solution - solved it for Angular 5 with Material View
The connection is through the

formArrayName="notification"

(change)="updateChkbxArray(n.id, $event.checked, 'notification')"

This way it can work for multiple checkboxes arrays in one form. Just set the name of the controls array to connect each time.

_x000D_
_x000D_
constructor(_x000D_
  private fb: FormBuilder,_x000D_
  private http: Http,_x000D_
  private codeTableService: CodeTablesService) {_x000D_
_x000D_
  this.codeTableService.getnotifications().subscribe(response => {_x000D_
      this.notifications = response;_x000D_
    })_x000D_
    ..._x000D_
}_x000D_
_x000D_
_x000D_
createForm() {_x000D_
  this.form = this.fb.group({_x000D_
    notification: this.fb.array([])..._x000D_
  });_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
  this.createForm();_x000D_
}_x000D_
_x000D_
updateChkbxArray(id, isChecked, key) {_x000D_
  const chkArray = < FormArray > this.form.get(key);_x000D_
  if (isChecked) {_x000D_
    chkArray.push(new FormControl(id));_x000D_
  } else {_x000D_
    let idx = chkArray.controls.findIndex(x => x.value == id);_x000D_
    chkArray.removeAt(idx);_x000D_
  }_x000D_
}
_x000D_
<div class="col-md-12">_x000D_
  <section class="checkbox-section text-center" *ngIf="notifications  && notifications.length > 0">_x000D_
    <label class="example-margin">Notifications to send:</label>_x000D_
    <p *ngFor="let n of notifications; let i = index" formArrayName="notification">_x000D_
      <mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n.id, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>_x000D_
    </p>_x000D_
  </section>_x000D_
</div>
_x000D_
_x000D_
_x000D_

At the end you are getting to save the form with array of original records id's to save/update. The UI View

The relevat part of the json of the form

Will be happy to have any remarks for improvement.

Is there any way to do HTTP PUT in python

You should have a look at the httplib module. It should let you make whatever sort of HTTP request you want.

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How to create a unique index on a NULL column?

Strictly speaking, a unique nullable column (or set of columns) can be NULL (or a record of NULLs) only once, since having the same value (and this includes NULL) more than once obviously violates the unique constraint.

However, that doesn't mean the concept of "unique nullable columns" is valid; to actually implement it in any relational database we just have to bear in mind that this kind of databases are meant to be normalized to properly work, and normalization usually involves the addition of several (non-entity) extra tables to establish relationships between the entities.

Let's work a basic example considering only one "unique nullable column", it's easy to expand it to more such columns.

Suppose we the information represented by a table like this:

create table the_entity_incorrect
(
  id integer,
  uniqnull integer null, /* we want this to be "unique and nullable" */
  primary key (id)
);

We can do it by putting uniqnull apart and adding a second table to establish a relationship between uniqnull values and the_entity (rather than having uniqnull "inside" the_entity):

create table the_entity
(
  id integer,
  primary key(id)
);

create table the_relation
(
  the_entity_id integer not null,
  uniqnull integer not null,

  unique(the_entity_id),
  unique(uniqnull),
  /* primary key can be both or either of the_entity_id or uniqnull */
  primary key (the_entity_id, uniqnull), 
  foreign key (the_entity_id) references the_entity(id)
);

To associate a value of uniqnull to a row in the_entity we need to also add a row in the_relation.

For rows in the_entity were no uniqnull values are associated (i.e. for the ones we would put NULL in the_entity_incorrect) we simply do not add a row in the_relation.

Note that values for uniqnull will be unique for all the_relation, and also notice that for each value in the_entity there can be at most one value in the_relation, since the primary and foreign keys on it enforce this.

Then, if a value of 5 for uniqnull is to be associated with an the_entity id of 3, we need to:

start transaction;
insert into the_entity (id) values (3); 
insert into the_relation (the_entity_id, uniqnull) values (3, 5);
commit;

And, if an id value of 10 for the_entity has no uniqnull counterpart, we only do:

start transaction;
insert into the_entity (id) values (10); 
commit;

To denormalize this information and obtain the data a table like the_entity_incorrect would hold, we need to:

select
  id, uniqnull
from
  the_entity left outer join the_relation
on
  the_entity.id = the_relation.the_entity_id
;

The "left outer join" operator ensures all rows from the_entity will appear in the result, putting NULL in the uniqnull column when no matching columns are present in the_relation.

Remember, any effort spent for some days (or weeks or months) in designing a well normalized database (and the corresponding denormalizing views and procedures) will save you years (or decades) of pain and wasted resources.

Difference between @Mock and @InjectMocks

Many people have given a great explanation here about @Mock vs @InjectMocks. I like it, but I think our tests and application should be written in such a way that we shouldn't need to use @InjectMocks.

Reference for further reading with examples: https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/

How can I create a marquee effect?

Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.

No hardcoded value other than the scroll time, best suited for small scroll spaces

_x000D_
_x000D_
.marquee {_x000D_
    width: 100%;_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    display: inline-flex;    _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
    display: flex;        _x000D_
    flex-basis: 100%;_x000D_
    animation: marquee-reset;_x000D_
    animation-play-state: paused;                _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
    animation: marquee 2s linear infinite;_x000D_
    animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }    _x000D_
    50% {_x000D_
        transform: translate(-100%, 0);_x000D_
    }_x000D_
    50.001% {_x000D_
        transform: translate(100%, 0);_x000D_
    }_x000D_
    100% {_x000D_
        transform: translate(0%, 0);_x000D_
    }_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }  _x000D_
}
_x000D_
<span class="marquee">_x000D_
    <span>This is the marquee text</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Printing chars and their ASCII-code in C

Chars within single quote ('XXXXXX'), when printed as decimal should output its ASCII value.

int main(){

    printf("D\n");
    printf("The ASCII of D is %d\n",'D');

    return 0;

}

Output:

% ./a.out
>> D
>> The ASCII of D is 68

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

jQuery set checkbox checked

Dude try below code :

$("div.row-form input[type='checkbox']").attr('checked','checked')

OR

$("div.row-form #estado_cat").attr("checked","checked");

OR

$("div.row-form #estado_cat").attr("checked",true);

Calculate rolling / moving average in C++

You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.

Unable to connect PostgreSQL to remote database using pgAdmin

Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

  1. Open PuTTY. If you already have a session set up to connect to the EC2 instance, load that, but don't connect to it just yet. If you don't have such a session, see this post.
  2. Go to Connection > SSH > Tunnels
  3. Enter 5433 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the "Add" button.
  6. Go back to Session, and save your session, then click "Open" to connect.
  7. This opens a terminal window. Once you're connected, you can leave that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 5433 in the Port field. Specify a Name for the connection, and the username and password. Click OK when you're done.

How to convert string to boolean in typescript Angular 4

Boolean("true") will do the work too

Duplicate symbols for architecture x86_64 under Xcode

Another silly mistake that will cause this error is repeated files. I accidentally copied some files twice. First I went to Targets -> Build Phases -> Compile sources. There I noticed some files on that list twice and their locations.

Excel CSV - Number cell format

I know this is an old question, but I have a solution that isn't listed here.

When you produce the csv add a space after the comma but before your value e.g. , 005,.

This worked to prevent auto date formatting in excel 2007 anyway .

How can I get just the first row in a result set AFTER ordering?

This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select *
from  
  ( select * 
  from emp 
  order by sal desc ) 
  where ROWNUM <= 5;

Android: upgrading DB version and adding new table

You can use SQLiteOpenHelper's onUpgrade method. In the onUpgrade method, you get the oldVersion as one of the parameters.

In the onUpgrade use a switch and in each of the cases use the version number to keep track of the current version of database.

It's best that you loop over from oldVersion to newVersion, incrementing version by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.

Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.

For example:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
        String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
        db.execSQL(sql);
        break;

    case 2:
        String sql = "SOME_QUERY";
        db.execSQL(sql);
        break;
    }

}

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

android button selector

You can use this code:

<Button
android:id="@+id/img_sublist_carat"
android:layout_width="70dp"
android:layout_height="68dp"
android:layout_centerVertical="true"
android:layout_marginLeft="625dp"
android:contentDescription=""
android:background="@drawable/img_sublist_carat_selector"
android:visibility="visible" />

(Selector File) img_sublist_carat_selector.xml:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_focused="true" 
       android:state_pressed="true"        
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:state_pressed="true" 
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:drawable="@drawable/img_sublist_carat_normal" />
</selector>

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

How can I determine installed SQL Server instances and their versions?

I had this same issue when I was assessing 100+ servers, I had a script written in C# to browse the service names consist of SQL. When instances installed on the server, SQL Server adds a service for each instance with service name. It may vary for different versions like 2000 to 2008 but for sure there is a service with instance name.

I take the service name and obtain instance name from the service name. Here is the sample code used with WMI Query Result:

if (ServiceData.DisplayName == "MSSQLSERVER" || ServiceData.DisplayName == "SQL Server (MSSQLSERVER)")
            {
                InstanceData.Name = "DEFAULT";
                InstanceData.ConnectionName = CurrentMachine.Name;
                CurrentMachine.ListOfInstances.Add(InstanceData);
            }
            else
                if (ServiceData.DisplayName.Contains("SQL Server (") == true)
                {
                    InstanceData.Name = ServiceData.DisplayName.Substring(
                                            ServiceData.DisplayName.IndexOf("(") + 1,
                                            ServiceData.DisplayName.IndexOf(")") - ServiceData.DisplayName.IndexOf("(") - 1
                                        );
                    InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
                    CurrentMachine.ListOfInstances.Add(InstanceData);
                }
                else
                    if (ServiceData.DisplayName.Contains("MSSQL$") == true)
                    {
                        InstanceData.Name = ServiceData.DisplayName.Substring(
                                                ServiceData.DisplayName.IndexOf("$") + 1,
                                                ServiceData.DisplayName.Length - ServiceData.DisplayName.IndexOf("$") - 1
                                            );

                        InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
                        CurrentMachine.ListOfInstances.Add(InstanceData);
                    }

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN 
SELECT LAST_NAME,FRST_NAME  
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

Authentication versus Authorization

Definitions

Authentication - Are you the person you claim to be?

Authorization - Are you authorized to do whatever it is you're trying to do?

Example

A web app uses Google Sign-In. After a user successfully signs in, Google sends back:

  1. A JWT token. This can be validated and decoded to get authentication information. Is the token signed by Google? What is the user's name and email?
  2. An access token. This authorizes the web app to access Google APIs on behalf of the user. For example, can the app access the user's Google Calendar events? These permissions depend on the scopes that were requested, and whether or not the user allowed it.

Additionally:

The company may have an admin dashboard that allows customer support to manage the company's users. Instead of providing a custom signup solution that would allow customer support to access this dashboard, the company uses Google Sign-In.

The JWT token (received from the Google sign in process) is sent to the company's authorization server to figure out if the user has a G Suite account with the organization's hosted domain ([email protected])? And if they do, are they a member of the company's Google Group that was created for customer support? If yes to all of the above, we can consider them authenticated.

The company's authorization server then sends the dashboard app an access token. This access token can be used to make authorized requests to the company's resource server (e.g. ability to make a GET request to an endpoint that sends back all of the company's users).

Seeding the random number generator in Javascript

No, but here's a simple pseudorandom generator, an implementation of Multiply-with-carry I adapted from Wikipedia (has been removed since):

var m_w = 123456789;
var m_z = 987654321;
var mask = 0xffffffff;

// Takes any integer
function seed(i) {
    m_w = (123456789 + i) & mask;
    m_z = (987654321 - i) & mask;
}

// Returns number between 0 (inclusive) and 1.0 (exclusive),
// just like Math.random().
function random()
{
    m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
    m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
    var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
    result /= 4294967296;
    return result;
}

EDIT: fixed seed function by making it reset m_z
EDIT2: Serious implementation flaws have been fixed

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

Python: How to create a unique file name?

I didn't think your question was very clear, but if all you need is a unique file name...

import uuid

unique_filename = str(uuid.uuid4())

Why is visible="false" not working for a plain html table?

Who "they"? I don't think there's a visible attribute in html.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

My view is to always use ++ and -- by themselves on a single line, as in:

i++;
array[i] = foo;

instead of

array[++i] = foo;

Anything beyond that can be confusing to some programmers and is just not worth it in my view. For loops are an exception, as the use of the increment operator is idiomatic and thus always clear.

When is layoutSubviews called?

I tracked the solution down to Interface Builder's insistence that springs cannot be changed on a view that has the simulated screen elements turned on (status bar, etc.). Since the springs were off for the main view, that view could not change size and hence was scrolled down in its entirety when the in-call bar appeared.

Turning the simulated features off, then resizing the view and setting the springs correctly caused the animation to occur and my method to be called.

An extra problem in debugging this is that the simulator quits the app when the in-call status is toggled via the menu. Quit app = no debugger.

Why would $_FILES be empty when uploading files to PHP?

Another possible culprit is apache redirects. In my case I had apache's httpd.conf set up to redirect certain pages on our site to http versions, and other pages to https versions of the page, if they weren't already. The page on which I had a form with a file input was one of the pages configured to force ssl, but the page designated as the action of the form was configured to be http. So the page would submit the upload to the ssl version of the action page, but apache was redirecting it to the http version of the page and the post data, including the uploaded file was lost.

jQuery UI DatePicker - Change Date Format

So I struggled with this and thought I was going mad, the thing is bootstrap datepicker was being implemented not jQuery so teh options were different;

$('.dateInput').datepicker({  format: 'dd/mm/yyyy'})

How to strip HTML tags from string in JavaScript?

cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

Distilled from this website (web.achive).

This regex looks for <, an optional slash /, one or more characters that are not >, then either > or $ (the end of the line)

Examples:

'<div>Hello</div>' ==> 'Hello'
 ^^^^^     ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
                  ^^

But it is not bulletproof:

'If you are < 13 you cannot register' ==> 'If you are '
            ^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
 ^^^^^^^^^^^^^^^^^^          ^^^^^^

If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.

If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

TABLOCK vs TABLOCKX

Big difference, TABLOCK will try to grab "shared" locks, and TABLOCKX exclusive locks.

If you are in a transaction and you grab an exclusive lock on a table, EG:

SELECT 1 FROM TABLE WITH (TABLOCKX)

No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.

TABLOCK only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED (default). If your isolation level is higher, for example: SERIALIZABLE, shared locks are held until the end of a transaction.


Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK). However, if transaction A holds a shared lock on a table, transaction B will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.


Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).

In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.

In general you would not use TABLOCK or TABLOCKX unless you absolutely needed it for some edge case.

How to empty (clear) the logcat buffer in Android

For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

Daylight saving time and time zone best practices

For those struggling with this on .NET, see if using DateTimeOffset and/or TimeZoneInfo are worth your while.

If you want to use IANA/Olson time zones, or find the built in types are insufficient for your needs, check out Noda Time, which offers a much smarter date and time API for .NET.

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50

If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.

That's what worked for me!!!! hope it will help!!!!

PHP - Notice: Undefined index:

For starters,

mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.

Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.

From line 215, update:

if (isset($_POST)) {
    $Name = $_POST['Name'];
    $Surname = $_POST['Surname'];

    $Username = $_POST['Username'];

    $Email = $_POST['Email'];
    $C_Email = $_POST['C_Email'];

    $Password = $_POST['password'];
    $C_Password = $_POST['c_password'];

    $SecQ = $_POST['SecQ'];
    $SecA = $_POST['SecA'];
}

POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.

You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:

if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}

Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm

How to download a file from a URL in C#?

using (var client = new WebClient())
{
    client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

How to run console application from Windows Service?

Services are required to connect to the Service Control Manager and provide feedback at start up (ie. tell SCM 'I'm alive!'). That's why C# application have a different project template for services. You have two alternatives:

  • wrapp your exe on srvany.exe, as described in KB How To Create a User-Defined Service
  • have your C# app detect when is launched as a service (eg. command line param) and switch control to a class that inherits from ServiceBase and properly implements a service.

Compiler error: "class, interface, or enum expected"

You forgot your class declaration:

public class MyClass {
...

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

by installing AspNetMVC4Setup.exe ( Here is the link :https://www.microsoft.com/en-us/download/details.aspx?id=30683) solves the issue.

by restart/reinstalling Microsoft.AspNet.Mvc Package doesn't help me.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......

Can someone explain __all__ in Python?

__all__ customizes * in from <module> import *

__all__ customizes * in from <package> import *


A module is a .py file meant to be imported.

A package is a directory with a __init__.py file. A package usually contains modules.


MODULES

""" cheese.py - an example module """

__all__ = ['swiss', 'cheddar']

swiss = 4.99
cheddar = 3.99
gouda = 10.99

__all__ lets humans know the "public" features of a module.[@AaronHall] Also, pydoc recognizes them.[@Longpoke]

from module import *

See how swiss and cheddar are brought into the local namespace, but not gouda:

>>> from cheese import *
>>> swiss, cheddar
(4.99, 3.99)
>>> gouda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'gouda' is not defined

Without __all__, any symbol (that doesn't start with an underscore) would have been available.


Imports without * are not affected by __all__


import module

>>> import cheese
>>> cheese.swiss, cheese.cheddar, cheese.gouda
(4.99, 3.99, 10.99)

from module import names

>>> from cheese import swiss, cheddar, gouda
>>> swiss, cheddar, gouda
(4.99, 3.99, 10.99)

import module as localname

>>> import cheese as ch
>>> ch.swiss, ch.cheddar, ch.gouda
(4.99, 3.99, 10.99)

PACKAGES

In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.[@MartinStettner]

Here's an excerpt from the Python MySQL Connector __init__.py:

__all__ = [
    'MySQLConnection', 'Connect', 'custom_error_exception',

    # Some useful constants
    'FieldType', 'FieldFlag', 'ClientFlag', 'CharacterSet', 'RefreshOption',
    'HAVE_CEXT',

    # Error handling
    'Error', 'Warning',

    ...etc...

    ]

The default case, asterisk with no __all__ for a package, is complicated, because the obvious behavior would be expensive: to use the file system to search for all modules in the package. Instead, in my reading of the docs, only the objects defined in __init__.py are imported:

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements.


And lastly, a venerated tradition for stack overflow answers, professors, and mansplainers everywhere, is the bon mot of reproach for asking a question in the first place:

Wildcard imports ... should be avoided, as they [confuse] readers and many automated tools.

[PEP 8, @ToolmakerSteve]

List files recursively in Linux CLI with path relative to the current directory

In mycase, with tree command

Relative path

tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\./.*' | while read file; do
  echo $file
done

Absolute path

tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\./.*' | while read file; do
  echo $file | sed -e "s|^.|$PWD|g"
done

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.

How to insert text in a td with id, using JavaScript

If your <td> is not empty, one popular trick is to insert a non breaking space &nbsp; in it, such that:

 <td id="td1">&nbsp;</td>

Then you will be able to use:

 document.getElementById('td1').firstChild.data = 'New Value';

Otherwise, if you do not fancy adding the meaningless &nbsp you can use the solution that Jonathan Fingland described in the other answer.

Adding Git-Bash to the new Windows Terminal

I did as follows:

  1. Add "%programfiles%\Git\Bin" to your PATH
  2. On the profiles.json, set the desired command-line as "commandline" : "sh --cd-to-home"
  3. Restart the Windows Terminal

It worked for me.

Merge unequal dataframes and replace missing rows with 0

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

Updated many years later to address follow up question

You need to identify the variable names in the second data table that you aren't merging on - I use setdiff() for this. Check out the following:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e', NA))
df2 = data.frame(x=c('a', 'b', 'c'),y1 = c(0,1,0), y2 = c(0,1,0))

#merge as before
df3 <- merge(df1, df2, all = TRUE)
#columns in df2 not in df1
unique_df2_names <- setdiff(names(df2), names(df1))
df3[unique_df2_names][is.na(df3[, unique_df2_names])] <- 0 

Created on 2019-01-03 by the reprex package (v0.2.1)

Resetting a form in Angular 2 after submit

For Angular 2 Final, we now have a new API that cleanly resets the form:

@Component({...})
class App {

    form: FormGroup;
     ...
    reset() {
       this.form.reset();
   }
}

This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

setInterval in a React app

I see 4 issues with your code:

  • In your timer method you are always setting your current count to 10
  • You try to update the state in render method
  • You do not use setState method to actually change the state
  • You are not storing your intervalId in the state

Let's try to fix that:

componentDidMount: function() {
   var intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
},

componentWillUnmount: function() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
},

timer: function() {
   // setState method is used to update the state
   this.setState({ currentCount: this.state.currentCount -1 });
},

render: function() {
    // You do not need to decrease the value here
    return (
      <section>
       {this.state.currentCount}
      </section>
    );
}

This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:

timer: function() {
   var newCount = this.state.currentCount - 1;
   if(newCount >= 0) { 
       this.setState({ currentCount: newCount });
   } else {
       clearInterval(this.state.intervalId);
   }
},

How do I programmatically set device orientation in iOS 7?

The only way that worked for me is presenting dummy modal view controller.

UIViewController* dummyVC = [[UIViewController alloc] init];
dummyVC.view = [[UIView alloc] init];
[self presentModalViewController:dummyVC animated:NO];
[self dismissModalViewControllerAnimated:NO];

Your VC will be asked for updated interface orientations when modal view controller is dismissed.

Curious thing is that UINavigationController does exactly this when pushing/popping child view controllers with different supported interface orientations (tested on iOS 6.1, 7.0).

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

Question mark and colon in JavaScript

This is probably a bit clearer when written with brackets as follows:

hsb.s = (max != 0) ? (255 * delta / max) : 0;

What it does is evaluate the part in the first brackets. If the result is true then the part after the ? and before the : is returned. If it is false, then what follows the : is returned.

How to know the version of pip itself

For windows:

import pip

help(pip) 

shows the version at the end of the help file.

How to find out the number of CPUs using python

Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up:

# jython
try:
    from java.lang import Runtime
    runtime = Runtime.getRuntime()
    res = runtime.availableProcessors()
    if res > 0:
        return res
except ImportError:
    pass

How do I detect if software keyboard is visible on Android Device or not?

I converted the answer to the kotlin, hope this helps for kotlin users.

private fun checkKeyboardVisibility() {
    var isKeyboardShowing = false

    binding.coordinator.viewTreeObserver.addOnGlobalLayoutListener {
        val r = Rect()
        binding.coordinator.getWindowVisibleDisplayFrame(r)
        val screenHeight = binding.coordinator.rootView.height

        // r.bottom is the position above soft keypad or device button.
        // if keypad is shown, the r.bottom is smaller than that before.
        val keypadHeight = screenHeight - r.bottom


        if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
            // keyboard is opened
            if (!isKeyboardShowing) {
                isKeyboardShowing = true

            }
        } else {
            // keyboard is closed
            if (isKeyboardShowing) {
                isKeyboardShowing = false

            }
        }
    }
}

Is there an operator to calculate percentage in Python?

Very quickly and sortly-code implementation by using the lambda operator.

In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

Is it possible to see more than 65536 rows in Excel 2007?

I have found that the 65536 limit still applies to pivot tables, even in Excel 2007.

Delete dynamically-generated table row using jQuery

You should use Event Delegation, because of the fact that you are creating dynamic rows.

$(document).on('click','button.removebutton', function() {
    alert("aa");
  $(this).closest('tr').remove();
  return false;
});

Live Demo

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

how to create a logfile in php?

For printing log use this function, this will create log file in log folder. Create log folder if its not exists .

logger("Your msg in log ", "Filename you want ", "Data to be log string or array or object");


function logger($logMsg="logger", $filename="logger", $logData=""){     
            $log  = date("j.n.Y h:i:s")." || $logMsg : ".print_r($logData,1).PHP_EOL .                  
            "-------------------------".PHP_EOL;
            file_put_contents('./log/'.$filename.date("j.n.Y").'.log', $log, FILE_APPEND);                      
    }

How to trigger click event on href element

Triggering a click via JavaScript will not open a hyperlink. This is a security measure built into the browser.

See this question for some workarounds, though.

Making a Sass mixin with optional arguments

Even DRYer way!

@mixin box-shadow($args...) {
  @each $pre in -webkit-, -moz-, -ms-, -o- {
    #{$pre + box-shadow}: $args;
  } 
  #{box-shadow}: #{$args};
}

And now you can reuse your box-shadow even smarter:

.myShadow {
  @include box-shadow(2px 2px 5px #555, inset 0 0 0);
}

How to allow http content within an iframe on a https site

You will always get warnings of blocked content in most browsers when trying to display non secure content on an https page. This is tricky if you want to embed stuff from other sites that aren't behind ssl. You can turn off the warnings or remove the blocking in your own browser but for other visitors it's a problem.

One way to do it is to load the content server side and save the images and other things to your server and display them from https.

You can also try using a service like embed.ly and get the content through them. They have support for getting the content behind https.

Submit button not working in Bootstrap form

  • If you put type=submit it is a Submit Button
  • if you put type=button it is just a button, It does not submit your form inputs.

and also you don't want to use both of these

How can a file be copied?

As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):

from pathlib import Path

source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())

write_bytes will overwrite whatever was at the destination's location

Why does .json() return a promise?

This difference is due to the behavior of Promises more than fetch() specifically.

When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.

The 2nd snippet could also have been written as:

iterator.then(response =>
    response.json().then(post => document.write(post.title))
);

In both this form and yours, the value of post is provided by the Promise returned from response.json().


When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:

iterator.then(response =>
    Promise.resolve({
      data: response.json(),
      status: response.status
    })
    .then(post => document.write(post.data))
);

post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.

remove white space from the end of line in linux

sed -i 's/[[:blank:]]\{1,\}$//' YourFile

[:blank:] is for space, tab mainly and {1,} to exclude 'no space at the end' of the substitution process (no big significant impact if line are short and file are small)

CSS selector for first element with class

The :first-child selector is intended, like the name says, to select the first child of a parent tag. The children have to be embedded in the same parent tag. Your exact example will work (Just tried it here):

<body>
    <p class="red">first</p>
    <div class="red">second</div>
</body>

Maybe you have nested your tags in different parent tags? Are your tags of class red really the first tags under the parent?

Notice also that this doesnt only apply to the first such tag in the whole document, but everytime a new parent is wrapped around it, like:

<div>
    <p class="red">first</p>
    <div class="red">second</div>
</div>
<div>
    <p class="red">third</p>
    <div class="red">fourth</div>
</div>

first and third will be red then.

Update:

I dont know why martyn deleted his answer, but he had the solution, the :nth-of-type selector:

_x000D_
_x000D_
.red:nth-of-type(1)_x000D_
{_x000D_
    border:5px solid red;_x000D_
} 
_x000D_
<div class="home">_x000D_
    <span>blah</span>_x000D_
    <p class="red">first</p>_x000D_
    <p class="red">second</p>_x000D_
    <p class="red">third</p>_x000D_
    <p class="red">fourth</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Credits to Martyn. More infos for example here. Be aware that this is a CSS 3 selector, therefore not all browsers will recognize it (e.g. IE8 or older).

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem, the annotation @Autowired in the test code did not work under using the Maven command line while it worked fine in Eclipse. I just update my JUnit version from 4.4 to 4.9 and the problem was solved.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.1</version>
</dependency>

Is there a way to specify which pytest tests to run from a file?

My answer provides a ways to run a subset of test in different scenarios.

Run all tests in a project

pytest

Run tests in a Single Directory

To run all the tests from one directory, use the directory as a parameter to pytest:

pytest tests/my-directory

Run tests in a Single Test File/Module

To run a file full of tests, list the file with the relative path as a parameter to pytest:

pytest tests/my-directory/test_demo.py

Run a Single Test Function

To run a single test function, add :: and the test function name:

pytest -v tests/my-directory/test_demo.py::test_specific_function

-v is used so you can see which function was run.

Run a Single Test Class

To run just a class, do like we did with functions and add ::, then the class name to the file parameter:

pytest -v tests/my-directory/test_demo.py::TestClassName

Run a Single Test Method of a Test Class

If you don't want to run all of a test class, just one method, just add another :: and the method name:

pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method

Run a Set of Tests Based on Test Name

The -k option enables you to pass in an expression to run tests that have certain names specified by the expression as a substring of the test name. It is possible to use and, or, and not to create complex expressions.

For example, to run all of the functions that have _raises in their name:

pytest -v -k _raises

How to duplicate a git repository? (without forking)

Open Terminal.

Create a bare clone of the repository.

git clone --bare https://github.com/exampleuser/old-repository.git

Mirror-push to the new repository.

cd old-repository.git

git push --mirror https://github.com/exampleuser/new-repository.git

How to get the wsdl file from a webservice's URL

By postfixing the URL with ?WSDL

If the URL is for example:

http://webservice.example:1234/foo

You use:

http://webservice.example:1234/foo?WSDL

And the wsdl will be delivered.

http://localhost:50070 does not work HADOOP

Since Hadoop 3.0.0 - Alpha 1 there was a Change in the port configuration:

http://localhost:50070

was moved to

http://localhost:9870

see https://issues.apache.org/jira/browse/HDFS-9427

CodeIgniter - How to return Json response from controller

This is not your answer and this is an alternate way to process the form submission

$('.signinform').click(function(e) { 
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: 'index.php/user/signin', // target element(s) to be updated with server response 
      dataType:'json',
      success : function(response){ console.log(response); alert(response)}
     });
}); 

Node.js EACCES error when listening on most ports

OMG!! In my case I was doing ....listen(ip, port) instead of ...listen(port, ip) and that was throwing up the error msg: Error: listen EACCES localhost

I was using port numbers >= 3000 and even tried with admin access. Nothing worked out. Then with a closer relook, I noticed the issue. Changed it to ...listen(port, ip) and everything started working fine!!

Just calling this out in case if its useful to someone else...

Convert Python ElementTree to string

If you just need this for debugging to see how the XML looks like, then instead of print(xml.etree.ElementTree.tostring(e)) you can use dump like this:

xml.etree.ElementTree.dump(e)

And this works both with Element and ElementTree objects as e, so there should be no need for getroot.

The documentation of dump says:

xml.etree.ElementTree.dump(elem)

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.

elem is an element tree or an individual element.

Changed in version 3.8: The dump() function now preserves the attribute order specified by the user.

Create a menu Bar in WPF?

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
            <MenuItem Header="_Save"/>
        </MenuItem>
    </Menu>
    <StackPanel></StackPanel>
</DockPanel>

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you don't want to upgrade your tomcat, Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

It works for me http://www.zhoulujun.cn/zhoulujun/html/java/tomcat/2018_0508_8109.html

Requested registry access is not allowed

I was trying the verb = "runas", but I still was getting UnauthorizedAccessException when trying to update registry value. Turned out it was due to not opening the subkey with writeable set to true.

Registry.OpenSubKey("KeyName", true);

Cannot write to Registry Key, getting UnauthorizedAccessException

How do I match any character across multiple lines in a regular expression?

I had the same problem and solved it in probably not the best way but it works. I replaced all line breaks before I did my real match:

mystring= Regex.Replace(mystring, "\r\n", "")

I am manipulating HTML so line breaks don't really matter to me in this case.

I tried all of the suggestions above with no luck, I am using .Net 3.5 FYI

Is it possible to change the radio button icon in an android radio button group

Yes that's possible you have to define your own style for radio buttons, at res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomTheme" parent="android:Theme">
   <item name="android:radioButtonStyle">@style/RadioButton</item>
</style>
<style name="RadioButton" parent="@android:style/Widget.CompoundButton.RadioButton">
   <item name="android:button">@drawable/radio</item>
</style>
</resources>

'radio' here should be a stateful drawable, radio.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
        android:drawable="@drawable/radio_hover" />
    <item android:state_checked="false" android:state_window_focused="false"
        android:drawable="@drawable/radio_normal" />
    <item android:state_checked="true" android:state_pressed="true"
        android:drawable="@drawable/radio_active" />
    <item android:state_checked="false" android:state_pressed="true"
        android:drawable="@drawable/radio_active" />
    <item android:state_checked="true" android:state_focused="true"
        android:drawable="@drawable/radio_hover" />
    <item android:state_checked="false" android:state_focused="true"
        android:drawable="@drawable/radio_normal_off" />
    <item android:state_checked="false" android:drawable="@drawable/radio_normal" />
    <item android:state_checked="true" android:drawable="@drawable/radio_hover" />
    </selector>

Then just apply the Custom theme either to whole app or to activities of your choice.

For more info about themes and styles look at http://brainflush.wordpress.com/2009/03/15/understanding-android-themes-and-styles/ that is good guide.

How to get milliseconds from LocalDateTime in Java 8

Why didn't anyone mentioned the method LocalDateTime.toEpochSecond():

LocalDateTime localDateTime = ... // whatever e.g. LocalDateTime.now()
long time2epoch = localDateTime.toEpochSecond(ZoneOffset.UTC);

This seems way shorter that many suggested answers above...

How to SELECT the last 10 rows of an SQL table which has no ID field?

Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.

SELECT * FROM big_table ORDER BY A DESC LIMIT 10

Executing set of SQL queries using batch file?

Different ways:

  1. Using SQL Server Agent (If local instance)
    schedule a job in sql server agent with a new step having type as "T-SQL" then run the job.

  2. Using SQLCMD
    To use SQLCMD refer http://technet.microsoft.com/en-us/library/ms162773.aspx

  3. Using SQLPS
    To use SQLPS refer http://technet.microsoft.com/en-us/library/cc280450.aspx

Apply style ONLY on IE

Here is a COMPLETE Javascript-free, CSS-based solution that allows you to target Internet Explorer 1-11!

My Internet Explorer Only CSS Solution

This works by hiding IE1-7 from all your modern sheets using @import, giving IE1-7 a clean, white page layout, then applies three simple CSS media query "hacks" to isolate IE8-11 in the imported sheet. It even affects IE on Mac!

The advantage to this strategy is its 100% effective in targeting IE1-11, giving you complete control over how you customize CSS for those targeted browsers, while freeing you up as a designer to focus on newer CSS3 and cutting-edge styles and layouts in Edge and all other modern browsers going forward. I have been using a version of this since 2004 but recently updated it for 2021.

HOW IT WORKS

First create two CSS style sheet links. The first is a basic element style sheet that gives all browsers, old and new, a simple white, block-level layout. Linked CSS has wide support in older CSS1 browsers going back to 1995. A wide range of old browsers will see this first sheet and display your content and layouts in a clean, white block-level content page. I like to put "reset" element-only styles in here. The second sheet is an import sheet that will load all your advanced CSS styles using a single @import rule that hides styles to a wide range of browsers including IE1-7.

<link media="screen" rel="stylesheet" type="text/css" href="OldBrowsers.css" />
<link media="screen" rel="stylesheet" type="text/css" href="Import.css" />

Next, in your "Import.css" sheet add this @import rule exactly as formatted (Its hidden from IE1-7 and a wide range of older browsers listed below):

@import 'ModernBrowsers.css' all;

All CSS in this imported sheet will be hidden from IE1-7 and a wide range of older browsers. IE 1-7 doesn't understand "media type" value "all" so will fail to import this sheet. This specific version of import is also not recognized by many older browsers (pre-2001). Those browsers are so old now, you just need to deliver them a white web page with stacked blocks of content. Use "OldBrowsers" to do so.

Next, in "ModernBrowsers.css" you want to target IE8-11 using CSS media query "hacks" alongside all your normal selectors and classes. Simply apply the following media query, IE-only fixes to your modern, imported style sheet to target these specific IE browsers. Drop into these blocks any styles specific to them. You can attack your layout or other style issues in IE now in media query "batches" now rather than by multiple selector "hacks":

/* IE8 */
@media \0screen {
    body {
        background: red !important;
    }
}

/* IE9 */
@media all and (monochrome:0) {
    body {
        background: blue\9 !important;
    }
}

/* IE10-11 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    body {
        background: green !important;
    }
}

Simple! You have now targeted styles for IE1-11 (all Internet Explorer browsers!)

With this solution you achieve the following:

  1. The @import excludes IE 1-7 from your modern styles, completely! Those agents, along with the list below, will never see your modern imported styles and get a clean white style sheet content page older browsers can still use as far as viewing your content (use "OldBrowsers.css" to style them). The following browsers are excluded from "ModernBrowsers.css" using the above @import rule:

    • Windows Internet Explorer 1-7.x
    • Macintosh Internet Explorer 1-5.x
    • Netscape 1-4.8
    • Opera 1-3.5
    • Konqueror 1-2.1
    • Windows Amaya 1-5.1
    • iCab 1-2
    • OmniWeb
  2. In your "ModernBrowsers" imported sheet, you can now safely target IE browsers version 8-11 using simple media query "hacks".

  3. This system uses a simple @import style sheet system that is fast and manageable using traditional, non-support for external style rules rather than CSS fixes sprinkled throughout multiple sheets. (BTW...Do not listen to anyone saying @import is slow, as it is not. My import sheet has ONE LINE and is maybe a kilobyte or less in size! @import has been used since the birth of the WWW and is no different than a simple CSS link. Compare this to the Megabytes of Javascript kids today are shoving into browsers using these new "modern" ECMAScript SPA API's just to display a tiny paragraph of news!)

  4. All old IE browsers and a wide range of other user agnets are excluded from modern styles now using this import strategy, which allows these agents to collapse back to plain, "block-level", white pages and stacked content layouts that are fully accessible by older browsers.

  5. Notice this solution has no IE conditional comments! (you should NEVER use those)

  6. With this solution, web designs are now 100% free to use custom, cutting edge CSS3 technologies without having to ever worry about older browsers and IE1-11 ever again!

I will be posting my formal version of this Universal CSS System on GitHub soon! So stay tuned...

This is part of the new "progressive" CSS, 100% Javacript-free, design concept in 2021 for addressing cross-browser style issues, where older agents are allowed to degrade gracefully to simpler layouts rather than struggling to fix problems in cryptic old, broken, box-model agents (IE6) that don't need custom layouts any longer today as the long tail of their slow demise continues online.

And its my hope we stop creating these gigantic, CPU-hog, Javascripted, polyfill nightmare solutions for addressing what used to be years ago solved by simple CSS solutions like this one.

Get docker container id from container name

The simplest way I can think of is to parse the output of docker ps

Let's run the latest ubuntu image interactively and connect to it

docker run -it ubuntu /bin/bash

If you run docker ps in another terminal you can see something like

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
8fddbcbb101c        ubuntu:latest       "/bin/bash"         10 minutes ago      Up 10 minutes                           gloomy_pasteur

Unfortunately, parsing this format isn't easy since they uses spaces to manually align stuff

$ sudo docker ps | sed -e 's/ /@/g'
CONTAINER@ID@@@@@@@@IMAGE@@@@@@@@@@@@@@@COMMAND@@@@@@@@@@@@@CREATED@@@@@@@@@@@@@STATUS@@@@@@@@@@@@@@PORTS@@@@@@@@@@@@@@@NAMES
8fddbcbb101c@@@@@@@@ubuntu:latest@@@@@@@"/bin/bash"@@@@@@@@@13@minutes@ago@@@@@@Up@13@minutes@@@@@@@@@@@@@@@@@@@@@@@@@@@gloomy_pasteur@@@@@@

Here is a script that converts the output to JSON.

https://gist.github.com/mminer/a08566f13ef687c17b39

Actually, the output is a bit more convenient to work with than that. Every field is 20 characters wide. [['CONTAINER ID',0],['IMAGE',20],['COMMAND',40],['CREATED',60],['STATUS',80],['PORTS',100],['NAMES',120]]

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

How do I close an open port from the terminal on the Mac?

However you opened the port, you close it in the same way. For example, if you created a socket, bound it to port 0.0.0.0:5955, and called listen, close that same socket.

You can also just kill the process that has the port open.

If you want to find out what process has a port open, try this:

lsof -i :5955

If you want to know whether a port is open, you can do the same lsof command (if any process has it open, it's open; otherwise, it's not), or you can just try to connect to it, e.g.:

nc localhost 5955

If it returns immediately with no output, the port isn't open.

It may be worth mentioning that, technically speaking, it's not a port that's open, but a host:port combination. For example, if you're plugged into a LAN as 10.0.1.2, you could bind a socket to 127.0.0.1:5955, or 10.0.1.2:5955, without either one affecting the other, or you could bind to 0.0.0.0:5955 to handle both at once. You can see all of your computer's IPv4 and IPv6 addresses with the ifconfig command.

How to filter an array from all elements of another array

You can setup the filter function to iterate over the "filter array".

var arr = [1, 2, 3 ,4 ,5, 6, 7];
var filter = [4, 5, 6];

var filtered = arr.filter(
  function(val) {
    for (var i = 0; i < filter.length; i++) {
      if (val == filter[i]) {
        return false;
      }
    }
    return true;
  }
); 

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Injecting $scope into an angular service function()

You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.

The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,

var students = $http.get(path).then(function (resp) {
  return resp.data;
}); // then() returns a promise object, not resp.data

There's a simple way to get around this and it's to supply a callback function.

.service('StudentService', [ '$http',
    function ($http) {
    // get some data via the $http
    var path = '/students';

    //save method create a new student if not already exists
    //else update the existing object
    this.save = function (student, doneCallback) {
      $http.post(
        path, 
        {
          params: {
            student: student
          }
        }
      )
      .then(function (resp) {
        doneCallback(resp.data); // when the async http call is done, execute the callback
      });  
    }
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
  $scope.saveUser = function (user) {
    StudentService.save(user, function (data) {
      $scope.message = data; // I'm assuming data is a string error returned from your REST API
    })
  }
}]);

The form:

<div class="form-message">{{message}}</div>

<div ng-controller="StudentSaveController">
  <form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" /><br />
    E-mail: <input type="email" ng-model="user.email" /><br />
    Gender: <input type="radio" ng-model="user.gender" value="male" />male
    <input type="radio" ng-model="user.gender" value="female" />female<br />
    <input type="button" ng-click="reset()" value="Reset" />
    <input type="submit" ng-click="saveUser(user)" value="Save" />
  </form>
</div>

This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.

VBA Go to last empty row

try this:

Sub test()

With Application.WorksheetFunction
    Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With

End Sub

Hope this works for you.

C default arguments

Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.

For a detailed explanation see my post at

http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/

Jens

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Instead of

$("form").submit()

try this

 $("<input type='submit' id='btn_tmpSubmit'/>").css('display','none').appendTo('form');
 $("#btn_tmpSubmit").click();

How can I read and manipulate CSV file data in C++?

If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model:

struct Customer {
    int id;
    std::string first_name;
    std::string last_name;
    struct {
        std::string street;
        std::string unit;
    } address;
    char state[2];
    int zip;
};

Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer> or std::set<Customer>.

With that in mind, think of your CSV handling as two operations:

// if you wanted to go nuts, you could use a forward iterator concept for both of these
class CSVReader {
public:
    CSVReader(const std::string &inputFile);
    bool hasNextLine();
    void readNextLine(std::vector<std::string> &fields);
private:
    /* secrets */
};
class CSVWriter {
public:
    CSVWriter(const std::string &outputFile);
    void writeNextLine(const std::vector<std::string> &fields);
private:
    /* more secrets */
};
void readCustomers(CSVReader &reader, std::vector<Customer> &customers);
void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers);

Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits:

  1. Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files).
  2. You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML <table> rendering.
  3. Your memory footprint is likely to be smaller (depends on relative sizeof(Customer) vs. the number of bytes in a single row).
  4. CSVReader and CSVWriter can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.

Using GCC to produce readable assembly?

If you give GCC the flag -fverbose-asm, it will

Put extra commentary information in the generated assembly code to make it more readable.

[...] The added comments include:

  • information on the compiler version and command-line options,
  • the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
  • hints on which high-level expressions correspond to the various assembly instruction operands.

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to encrypt/decrypt data in php?

It took me quite a while to figure out, how to not get a false when using openssl_decrypt() and get encrypt and decrypt working.

    // cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
    $encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
    $encrypted = $encrypted . ':' . base64_encode($iv);

    // decrypt to get again $plaintext
    $parts = explode(':', $encrypted);
    $decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1])); 

If you want to pass the encrypted string via a URL, you need to urlencode the string:

    $encrypted = urlencode($encrypted);

To better understand what is going on, read:

To generate 16 bytes long keys you can use:

    $bytes = openssl_random_pseudo_bytes(16);
    $hex = bin2hex($bytes);

To see error messages of openssl you can use: echo openssl_error_string();

Hope that helps.

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

Disable activity slide-in animation when launching new activity?

I'm on 4.4.2, and calling overridePendingTransition(0, 0) in the launching activity's onCreate() will disable the starting animation (calling overridePendingTransition(0, 0) immediately after startActivity() did NOT work). As noted in another answer, calling overridePendingTransition(0, 0) after finish() disables the closing animation.

Btw, I found that setting the style with "android:windowAnimationStyle">@null (another answer mentioned here) caused a crash when my launching activity tried to set the action bar title. Debugging further, I discovered that somehow this causes window.hasFeature(Window.FEATURE_ACTION_BAR) to fail in the Activity's initActionBar().

Convert string to nullable type (int, double, etc...)

The generic answer provided by "Joel Coehoorn" is good.

But, this is another way without using those GetConverter... or try/catch blocks... (i'm not sure but this may have better performance in some cases):

public static class StrToNumberExtensions
{
    public static short ToShort(this string s, short defaultValue = 0) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long ToLong(this string s, long defaultValue = 0) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal ToDecimal(this string s, decimal defaultValue = 0) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float ToFloat(this string s, float defaultValue = 0) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double ToDouble(this string s, double defaultValue = 0) => double.TryParse(s, out var v) ? v : defaultValue;

    public static short? ToshortNullable(this string s, short? defaultValue = null) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int? ToIntNullable(this string s, int? defaultValue = null) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long? ToLongNullable(this string s, long? defaultValue = null) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal? ToDecimalNullable(this string s, decimal? defaultValue = null) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float? ToFloatNullable(this string s, float? defaultValue = null) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double? ToDoubleNullable(this string s, double? defaultValue = null) => double.TryParse(s, out var v) ? v : defaultValue;
}

Usage is as following:

var x1 = "123".ToInt(); //123
var x2 = "abc".ToInt(); //0
var x3 = "abc".ToIntNullable(); // (int?)null 
int x4 = ((string)null).ToInt(-1); // -1
int x5 = "abc".ToInt(-1); // -1

var y = "19.50".ToDecimal(); //19.50

var z1 = "invalid number string".ToDoubleNullable(); // (double?)null
var z2 = "invalid number string".ToDoubleNullable(0); // (double?)0

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

@ViewChild in *ngIf

Use a setter for the ViewChild:

 private contentPlaceholder: ElementRef;

 @ViewChild('contentPlaceholder') set content(content: ElementRef) {
    if(content) { // initially setter gets called with undefined
        this.contentPlaceholder = content;
    }
 }

The setter is called with an element reference once *ngIf becomes true.

Note, for Angular 8 you have to make sure to set { static: false }, which is a default setting in other Angular versions:

 @ViewChild('contentPlaceholder', { static: false })

Note: if contentPlaceholder is a component you can change ElementRef to your component Class:

  private contentPlaceholder: MyCustomComponent;

  @ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
     if(content) { // initially setter gets called with undefined
          this.contentPlaceholder = content;
     }
  }

Dynamically Changing log4j log level

You can use following code snippet

((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));

rmagick gem install "Can't find Magick-config"

On ubuntu, you also have to install imagemagick and libmagickcore-dev like this :

sudo apt-get install imagemagick libmagickcore-dev libmagickwand-dev

Everything is written in the doc.

#pragma once vs include guards?

After engaging in an extended discussion about the supposed performance tradeoff between #pragma once and #ifndef guards vs. the argument of correctness or not (I was taking the side of #pragma once based on some relatively recent indoctrination to that end), I decided to finally test the theory that #pragma once is faster because the compiler doesn't have to try to re-#include a file that had already been included.

For the test, I automatically generated 500 header files with complex interdependencies, and had a .c file that #includes them all. I ran the test three ways, once with just #ifndef, once with just #pragma once, and once with both. I performed the test on a fairly modern system (a 2014 MacBook Pro running OSX, using XCode's bundled Clang, with the internal SSD).

First, the test code:

#include <stdio.h>

//#define IFNDEF_GUARD
//#define PRAGMA_ONCE

int main(void)
{
    int i, j;
    FILE* fp;

    for (i = 0; i < 500; i++) {
        char fname[100];

        snprintf(fname, 100, "include%d.h", i);
        fp = fopen(fname, "w");

#ifdef IFNDEF_GUARD
        fprintf(fp, "#ifndef _INCLUDE%d_H\n#define _INCLUDE%d_H\n", i, i);
#endif
#ifdef PRAGMA_ONCE
        fprintf(fp, "#pragma once\n");
#endif


        for (j = 0; j < i; j++) {
            fprintf(fp, "#include \"include%d.h\"\n", j);
        }

        fprintf(fp, "int foo%d(void) { return %d; }\n", i, i);

#ifdef IFNDEF_GUARD
        fprintf(fp, "#endif\n");
#endif

        fclose(fp);
    }

    fp = fopen("main.c", "w");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "#include \"include%d.h\"\n", i);
    }
    fprintf(fp, "int main(void){int n;");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "n += foo%d();\n", i);
    }
    fprintf(fp, "return n;}");
    fclose(fp);
    return 0;
}

And now, my various test runs:

folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.164s
user    0m0.105s
sys 0m0.041s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.140s
user    0m0.097s
sys 0m0.018s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.193s
user    0m0.143s
sys 0m0.024s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.031s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.170s
user    0m0.109s
sys 0m0.033s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.155s
user    0m0.105s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.181s
user    0m0.133s
sys 0m0.020s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.167s
user    0m0.119s
sys 0m0.021s
folio[~/Desktop/pragma] fluffy$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin17.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

As you can see, the versions with #pragma once were indeed slightly faster to preprocess than the #ifndef-only one, but the difference was quite negligible, and would be far overshadowed by the amount of time that actually building and linking the code would take. Perhaps with a large enough codebase it might actually lead to a difference in build times of a few seconds, but between modern compilers being able to optimize #ifndef guards, the fact that OSes have good disk caches, and the increasing speeds of storage technology, it seems that the performance argument is moot, at least on a typical developer system in this day and age. Older and more exotic build environments (e.g. headers hosted on a network share, building from tape, etc.) may change the equation somewhat but in those circumstances it seems more useful to simply make a less fragile build environment in the first place.

The fact of the matter is, #ifndef is standardized with standard behavior whereas #pragma once is not, and #ifndef also handles weird filesystem and search path corner cases whereas #pragma once can get very confused by certain things, leading to incorrect behavior which the programmer has no control over. The main problem with #ifndef is programmers choosing bad names for their guards (with name collisions and so on) and even then it's quite possible for the consumer of an API to override those poor names using #undef - not a perfect solution, perhaps, but it's possible, whereas #pragma once has no recourse if the compiler is erroneously culling an #include.

Thus, even though #pragma once is demonstrably (slightly) faster, I don't agree that this in and of itself is a reason to use it over #ifndef guards.

EDIT: Thanks to feedback from @LightnessRacesInOrbit I've increased the number of header files and changed the test to only run the preprocessor step, eliminating whatever small amount of time was being added in by the compile and link process (which was trivial before and nonexistent now). As expected, the differential is about the same.

Trim string in JavaScript?

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');
}

Can I scroll a ScrollView programmatically in Android?

I got this to work to scroll to the bottom of a ScrollView (with a TextView inside):

(I put this on a method that updates the TextView)

final ScrollView myScrollView = (ScrollView) findViewById(R.id.myScroller);
    myScrollView.post(new Runnable() {
    public void run() {
        myScrollView.fullScroll(View.FOCUS_DOWN);
    }
});

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

Hibernate Criteria Query to get specific columns

You can use multiselect function for this.

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            

This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

Git: how to reverse-merge a commit?

To revert a merge commit, you need to use: git revert -m <parent number>. So for example, to revert the recent most merge commit using the parent with number 1 you would use:

git revert -m 1 HEAD

To revert a merge commit before the last commit, you would do:

git revert -m 1 HEAD^

Use git show <merge commit SHA1> to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2

git merge documentation: http://schacon.github.com/git/git-merge.html

git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt

Service has zero application (non-infrastructure) endpoints

I got a more detailed exception when I added it programmatically - AddServiceEndpoint:

string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));  

host.AddServiceEndpoint(typeof(MyNamespace.IService),
                        new BasicHttpBinding(), baseAddress);
host.Open();

Simple Pivot Table to Count Unique Values

I found an easier way of doing this. Referring to Siddarth Rout's example, if I want to count unique values in column A:

  • add a new column C and fill C2 with formula "=1/COUNTIF($A:$A,A2)"
  • drag formula down to the rest of the column
  • pivot with column A as row label, and Sum{column C) in values to get the number of unique values in column A

JPA eager fetch does not join

Two things occur to me.

First, are you sure you mean ManyToOne for address? That means multiple people will have the same address. If it's edited for one of them, it'll be edited for all of them. Is that your intent? 99% of the time addresses are "private" (in the sense that they belong to only one person).

Secondly, do you have any other eager relationships on the Person entity? If I recall correctly, Hibernate can only handle one eager relationship on an entity but that is possibly outdated information.

I say that because your understanding of how this should work is essentially correct from where I'm sitting.

Initialise a list to a specific length in Python

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How do I change the title of the "back" button on a Navigation Bar

If you want not only to change the text of the Back button to the same text and remain the original left-arrow shape, but also to do something when user clicks the Back button, I recommend you to have a look around my "CustomNavigationController".

how to use font awesome in own css?

Try this way. In your css file change font-family: FontAwesome into font-family: "FontAwesome"; or font-family: 'FontAwesome';. I've solved the same problem using this method.

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

Servlet for serving static content

I had the same problem and I solved it by using the code of the 'default servlet' from the Tomcat codebase.

https://github.com/apache/tomcat/blob/master/java/org/apache/catalina/servlets/DefaultServlet.java

The DefaultServlet is the servlet that serves the static resources (jpg,html,css,gif etc) in Tomcat.

This servlet is very efficient and has some the properties you defined above.

I think that this source code, is a good way to start and remove the functionality or depedencies you don't need.

  • References to the org.apache.naming.resources package can be removed or replaced with java.io.File code.
  • References to the org.apache.catalina.util package are propably only utility methods/classes that can be duplicated in your source code.
  • References to the org.apache.catalina.Globals class can be inlined or removed.

Error : Index was outside the bounds of the array.

public int[] posStatus;       

public UsersInput()    
{    
    //It means postStatus will contain 9 elements from index 0 to 8. 
    this.posStatus = new int[9];   
}

int intUsersInput = 0;   

if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?    
{    
    posStatus[intUsersInput-1] += 1; //set it to 1    
} 

What does the ">" (greater-than sign) CSS selector mean?

> is the child combinator, sometimes mistakenly called the direct descendant combinator.1

That means the selector div > p.some_class only selects paragraphs of .some_class that are nested directly inside a div, and not any paragraphs that are nested further within.

An illustration:

_x000D_
_x000D_
div > p.some_class { 
    background: yellow;
}
_x000D_
<div>
    <p class="some_class">Some text here</p>     <!-- Selected [1] -->
    <blockquote>
        <p class="some_class">More text here</p> <!-- Not selected [2] -->
    </blockquote>
</div>
_x000D_
_x000D_
_x000D_

What's selected and what's not:

  1. Selected
    This p.some_class is located directly inside the div, hence a parent-child relationship is established between both elements.

  2. Not selected
    This p.some_class is contained by a blockquote within the div, rather than the div itself. Although this p.some_class is a descendant of the div, it's not a child; it's a grandchild.

    Consequently, while div > p.some_class won't match this element, div p.some_class will, using the descendant combinator instead.


1 Many people go further to call it "direct child" or "immediate child", but that's completely unnecessary (and incredibly annoying to me), because a child element is immediate by definition anyway, so they mean the exact same thing. There's no such thing as an "indirect child".

Why doesn't indexOf work on an array IE8?

The problem

IE<=8 simply doesn't have an indexOf() method for arrays.


The solution

If you need indexOf in IE<=8, you should consider using the following polyfill, which is recommended at the MDN :

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement, fromIndex) {
        var k;
        if (this == null) {
            throw new TypeError('"this" is null or not defined');
        }
        var o = Object(this);
        var len = o.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = +fromIndex || 0;
        if (Math.abs(n) === Infinity) {
            n = 0;
        }
        if (n >= len) {
            return -1;
        }
        k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
        while (k < len) {
            if (k in o && o[k] === searchElement) {
                return k;
            }
            k++;
        }
        return -1;
    };
}

Minified :

Array.prototype.indexOf||(Array.prototype.indexOf=function(r,t){var n;if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if(0===i)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=i)return-1;for(n=Math.max(a>=0?a:i-Math.abs(a),0);i>n;){if(n in e&&e[n]===r)return n;n++}return-1});

How do I convert from a money datatype in SQL server?

First of all, you should never use the money datatype. If you do any calculations you will get truncated results. Run the following to see what I mean

DECLARE
    @mon1 MONEY,
    @mon2 MONEY,
    @mon3 MONEY,
    @mon4 MONEY,
    @num1 DECIMAL(19,4),
    @num2 DECIMAL(19,4),
    @num3 DECIMAL(19,4),
    @num4 DECIMAL(19,4)

    SELECT
    @mon1 = 100, @mon2 = 339, @mon3 = 10000,
    @num1 = 100, @num2 = 339, @num3 = 10000

    SET @mon4 = @mon1/@mon2*@mon3
    SET @num4 = @num1/@num2*@num3

    SELECT @mon4 AS moneyresult,
    @num4 AS numericresult

Output: 2949.0000 2949.8525

Now to answer your question (it was a little vague), the money datatype always has two places after the decimal point. Use the integer datatype if you don't want the fractional part or convert to int.

Perhaps you want to use the decimal or numeric datatype?

Viewing local storage contents on IE

In IE11, you can see local storage in console on dev tools:

  1. Show dev tools (press F12)
  2. Click "Console" or press Ctrl+2
  3. Type localStorage and press Enter

Also, if you need to clear the localStorage, type localStorage.clear() on console.

jQuery calculate sum of values in all text fields

Use this function:

$(".price").each(function(){
total_price += parseInt($(this).val());
});

Creating a div element inside a div element in javascript

Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

How to prevent user from typing in text field without disabling the field?

If you want to prevent the user from adding anything, but provide them with the ability to erase characters:

_x000D_
_x000D_
<input value="CAN'T ADD TO THIS" maxlength="0" />
_x000D_
_x000D_
_x000D_

Setting the maxlength attribute of an input to "0" makes it so that the user is unable to add content, but still erase content as they wish.


But If you want it to be truly constant and unchangeable:

_x000D_
_x000D_
<input value="THIS IS READONLY" onkeydown="return false" />
_x000D_
_x000D_
_x000D_

Setting the onkeydown attribute to return false makes the input ignore user keypresses on it, thus preventing them from changing or affecting the value.

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I had the same problem with Eclipse 3.4(Ganymede) and dynamic web project.
The message didn't influence successfull deploy.But I had to delete row

<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>

from org.eclipse.wst.common.component file in .settings folder of Eclipse

Get pandas.read_csv to read empty values as empty string instead of nan

I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.

Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False:

pd.read_csv('test.csv', keep_default_na=False)

This issue is more clearly explained in

That was fixed on on Aug 19, 2012 for Pandas version 0.9 in

Unable to open debugger port in IntelliJ

For me, the problem was that catalina.sh didnt have execute permissions. The "Unable to open debugger port in intellij" message appeared in Intellij, but it sort of masked the 'could not execute catalina.sh' error that appeared in the logs immediately prior.

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece::datetime() can eliminate T.

use Time::Piece;
print localtime->datetime(T => q{ });

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use

AthleteList.AthleteList

In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

What is the Ruby <=> (spaceship) operator?

I will explain with simple example

  1. [1,3,2] <=> [2,2,2]

    Ruby will start comparing each element of both array from left hand side. 1 for left array is smaller than 2 of right array. Hence left array is smaller than right array. Output will be -1.

  2. [2,3,2] <=> [2,2,2]

    As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In case you are appending to the DOM, make sure the content is compatible:

modal.find ('div.modal-body').append (content) // check content

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

What are the recommendations for html <base> tag?

My recommendation is NOT to use the <base> element in managing url paths. Why?

It just trades one problem for another. Without the base element you can use any path system you like for your relative paths and links without fear they will break. The minute you set the base element to a path you are "locked in" to designing all your url's to work off that path and will now have to change ALL paths to work from the base path. Bad idea!

That means you have to now write LONGER paths AND keep track of where each path is relative to this base. Worse.....when using the <base> element they recommend you use a fully qualified base path to support older browsers ("https://www.example.com/"), so now you've hard-coded your domain into your page or made all your links dependent on a valid domain path.

On the other hand, the minute you remove the base path again from your website, you are now free again to use shorter relative paths, which can be fully qualified, use absolute paths from the root, or use paths that are truly relative to the file and folder you are in. Its much more flexible. And best of all fragments like "#hello" work correctly without any additional fixes. Again, people are creating problems that don't exist.

Also, the argument above that your use base url's to help you migrate folders of web pages to new subfolder locations doesn't really matter today since most modern servers allow you to quickly set up any subfolder as a new application root folder under any domain. The definition or the "root" of a web application is not constrained by either folders or domains now.

It seems kind of silly this whole debate. So I say leave out base url and support the older native server-client default path system that does not use it.

Note: If the problem you have is controlling paths due to some new API system, the solution is simple...be consistent in how you path all your url's and links in your API. Don't rely on browser support of base or HTML5 or newer circus tricks like the javascript API kiddies do. Simply path all your anchor tags consistently and you will never have issues. Whats more, your web application is instantly portable to new servers regardless of path systems used.

Whats old is new again! The base element is clearly about trying to create a solution to a problem that never existed in the Web World 20 years ago, much less today.

YouTube Video Embedded via iframe Ignoring z-index?

All you need on the iframe is:

...wmode="opaque"></iframe>

and in the URL:

http://www.youtube.com/embed/123?wmode=transparent

How can I remove duplicate rows?

I prefer the subquery\having count(*) > 1 solution to the inner join because I found it easier to read and it was very easy to turn into a SELECT statement to verify what would be deleted before you run it.

--DELETE FROM table1 
--WHERE id IN ( 
     SELECT MIN(id) FROM table1 
     GROUP BY col1, col2, col3 
     -- could add a WHERE clause here to further filter
     HAVING count(*) > 1
--)

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How do I make the method return type generic?

This question is very similar to Item 29 in Effective Java - "Consider typesafe heterogeneous containers." Laz's answer is the closest to Bloch's solution. However, both put and get should use the Class literal for safety. The signatures would become:

public <T extends Animal> void addFriend(String name, Class<T> type, T animal);
public <T extends Animal> T callFriend(String name, Class<T> type);

Inside both methods you should check that the parameters are sane. See Effective Java and the Class javadoc for more info.

setup android on eclipse but don't know SDK directory

a simple windows search for android-sdk should help you find it, assuming you named it that. You also might just wanna try sdk

What is the argument for printf that formats a long?

I think you mean:

unsigned long n;
printf("%lu", n);   // unsigned long

or

long n;
printf("%ld", n);   // signed long

Fastest way to reset every value of std::vector<int> to 0

I had the same question but about rather short vector<bool> (afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):

            -O0       -O3
         --------  --------
memset     0.666     1.045
fill      19.357     1.066
iterator  67.368     1.043
assign    17.975     0.530
for i     22.610     1.004

So apparently for these sizes, vector<bool>::assign() is faster. The code used for tests:

#include <vector>
#include <cstring>
#include <cstdlib>

#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;

using namespace std;

int main(int argc, char** argv) {

    std::vector<int> v(TEST_ARRAY_SIZE, 0);

    for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
        memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
        std::fill(v.begin(), v.end(), false);
   #elif TEST_METHOD == 3
        for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
            *it = 0;
        }
   #elif TEST_METHOD == 4
      v.assign(v.size(),false);
   #elif TEST_METHOD == 5
      for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
          v[i] = false;
      }
#endif
    }

    return EXIT_SUCCESS;
}

I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:

g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp

What's the difference between returning value or Promise.resolve from then()

You already got a good formal answer. I figured I should add a short one.

The following things are identical with Promises/A+ promises:

  • Calling Promise.resolve (In your Angular case that's $q.when)
  • Calling the promise constructor and resolving in its resolver. In your case that's new $q.
  • Returning a value from a then callback.
  • Calling Promise.all on an array with a value and then extract that value.

So the following are all identical for a promise or plain value X:

Promise.resolve(x);
new Promise(function(resolve, reject){ resolve(x); });
Promise.resolve().then(function(){ return x; });
Promise.all([x]).then(function(arr){ return arr[0]; });

And it's no surprise, the promises specification is based on the Promise Resolution Procedure which enables easy interoperation between libraries (like $q and native promises) and makes your life overall easier. Whenever a promise resolution might occur a resolution occurs creating overall consistency.

Filtering lists using LINQ

You can use the "Except" extension method (see http://msdn.microsoft.com/en-us/library/bb337804.aspx)

In your code

var difference = people.Except(exclusions);

How to "log in" to a website using Python's Requests module?

The requests.Session() solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token is required as a hidden field and add it to the payload with the username and password:

import requests
from bs4 import BeautifulSoup

payload = {
    'email': '[email protected]',
    'password': 'passw0rd'
}     

with requests.Session() as sess:
    res = sess.get(server_name + '/signin')
    signin = BeautifulSoup(res._content, 'html.parser')
    payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
    res = sess.post(server_name + '/auth/login', data=payload)

How to compare DateTime in C#?

Microsoft has also implemented the operators '<' and '>'. So you use these to compare two dates.

if (date1 < DateTime.Now)
   Console.WriteLine("Less than the current time!");

TextView Marquee not working

package com.app.relativejavawindow;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.text.TextUtils.TruncateAt;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final RelativeLayout relativeLayout = new RelativeLayout(this);
        final RelativeLayout relativeLayoutbotombar = new RelativeLayout(this);
        textView = new TextView(this);
        textView.setId(1);

        RelativeLayout.LayoutParams relativlayparamter = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);

        RelativeLayout.LayoutParams relativlaybottombar = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeLayoutbotombar.setLayoutParams(relativlaybottombar);


        textView.setText("Simple application that shows how to use marquee, with a long ");
        textView.setEllipsize(TruncateAt.MARQUEE);
        textView.setSelected(true);
        textView.setSingleLine(true);


        relativeLayout.addView(relativeLayoutbotombar);
        relativeLayoutbotombar.addView(textView);
        //relativeLayoutbotombar.setBackgroundColor(Color.BLACK);
        setContentView(relativeLayout, relativlayparamter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

this code work properly but if ur screen size is not fill this text it will not move try to palcing white space end of text

How to check if all inputs are not empty with jQuery

You can achive this with Regex and Replace or with just trimming.

Regex example:

if ($('input').val().replace(/[\s]/, '') == '') {
    alert('Input is not filled!');
}

With this replace() function you replace white spaces with nothing (removing white spaces).

Trimming Example:

if ($('input').val().trim() == '') {
    alert('Input is not filled!');
}

trim() function removes the leading and trailing white space and line terminator characters from a string.

Found conflicts between different versions of the same dependent assembly that could not be resolved

You could run the Dotnet CLI with full diagnostic verbosity to help find the issue.

dotnet run --verbosity diagnostic >> full_build.log

Once the build is complete you can search through the log file (full_build.log) for the error. Searching for "a conflict" for example, should take you right to the problem.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

How to change language settings in R

Change your current regional format to a different regional format in region settings on time&language settings in Windows by clicking on your time/date in lower right corner > adjust time/date > Region > change regional format to UK or US

Compare two files in Visual Studio

Visual Studio code is great for this - open a folder, right click both files and compare.

How to find where gem files are installed

To complete other answers, the gem-path gem can find the installation path of a particular gem.

Installation:

gem install gem-path

Usage:

gem path rails
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-4.0.13
gem path rails '< 4'
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-3.2.21

This is really handy as you can use it to grep or edit files:

grep -R 'Internal server error' "$(gem path thin)"
subl "$(gem path thin)"

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Printing the value of a variable in SQL Developer

You need to turn on dbms_output. In Oracle SQL Developer:

  1. Show the DBMS Output window (View->DBMS Output).
  2. Press the "+" button at the top of the Dbms Output window and then select an open database connection in the dialog that opens.

In SQL*Plus:

 SET SERVEROUTPUT ON

ImportError: No module named 'django.core.urlresolvers'

urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.

pip install django==2.0 --upgrade

Char to int conversion in C

As others have suggested, but wrapped in a function:

int char_to_digit(char c) {
    return c - '0';
}

Now just use the function. If, down the line, you decide to use a different method, you just need to change the implementation (performance, charset differences, whatever), you wont need to change the callers.

This version assumes that c contains a char which represents a digit. You can check that before calling the function, using ctype.h's isdigit function.

What is the difference between --save and --save-dev?

All explanations here are great, but lacking a very important thing: How do you install production dependencies only? (without the development dependencies). We separate dependencies from devDependencies by using --save or --save-dev. To install all we use:

npm i

To install only production packages we should use:

npm i --only=production

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

UIImageView aspect fit and center

[your_imageview setContentMode:UIViewContentModeCenter];

What's the scope of a variable initialized in an if statement?

Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables.

Note that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal "__main__" then you would get an exception: NameError: name 'x' is not defined.