Programs & Examples On #Mbrola

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Daniel answer is right on the spot. If you want to query more than one field do this:

Employee.objects.values_list('eng_name','rank')

This will return list of tuples. You cannot use named=Ture when querying more than one field.

Moreover if you know that only one field exists with that info and you know the pk id then do this:

Employee.objects.values_list('eng_name','rank').get(pk=1)

Including one C source file in another?

No.

Depending on your build environment (you don't specify), you may find that it works in exactly the way that you want.

However, there are many environments (both IDEs and a lot of hand crafted Makefiles) that expect to compile *.c - if that happens you will probably end up with linker errors due to duplicate symbols.

As a rule this practice should be avoided.

If you absolutely must #include source (and generally it should be avoided), use a different file suffix for the file.

Could not find main class HelloWorld

JAVA_HOME is not necessary if you start java and javac from the command line. But JAVA_HOME should point to the real jdk directory, C:\Program Files\Java\jdk1.7.0 in your case.

I'd never use the CLASSPATH environment variable outside of build scripts, especially not global defined. The -cp flag is better. But in your case, as you do not need additional libraries (rt.jardoesn't count), you won't need a classpath declaration. A missing -cp is equivalent to a -cp . and that's what you need here)

The HelloWorld class needs to be declared as public. This actually may be the cause for your problems. (I was pretty sure, that a source file needs one public class... or was it one public class at most ?)

Disable Pinch Zoom on Mobile Web

To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.

But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.

Android notification is not showing

You also need to change the build.gradle file, and add the used Android SDK version into it:

implementation 'com.android.support:appcompat-v7:28.0.0'

This worked like a charm in my case.

Angular directives - when and how to use compile, controller, pre-link and post-link

What is the difference between a source template and an instance template?

The fact that Angular allows DOM manipulation means that the input markup into the compilation process sometimes differ from the output. Particularly, some input markup may be cloned a few times (like with ng-repeat) before being rendered to the DOM.

Angular terminology is a bit inconsistent, but it still distinguishes between two types of markups:

  • Source template - the markup to be cloned, if needed. If cloned, this markup will not be rendered to the DOM.
  • Instance template - the actual markup to be rendered to the DOM. If cloning is involved, each instance will be a clone.

The following markup demonstrates this:

<div ng-repeat="i in [0,1,2]">
    <my-directive>{{i}}</my-directive>
</div>

The source html defines

    <my-directive>{{i}}</my-directive>

which serves as the source template.

But as it is wrapped within an ng-repeat directive, this source template will be cloned (3 times in our case). These clones are instance template, each will appear in the DOM and be bound to the relevant scope.

Using AngularJS date filter with UTC date

Could it work declaring the filter the following way?

   app.filter('dateUTC', function ($filter) {

       return function (input, format) {
           if (!angular.isDefined(format)) {
               format = 'dd/MM/yyyy';
           }

           var date = new Date(input);

           return $filter('date')(date.toISOString().slice(0, 23), format);

       };
    });

How do you use window.postMessage across domains?

Probably you try to send your data from mydomain.com to www.mydomain.com or reverse, NOTE you missed "www". http://mydomain.com and http://www.mydomain.com are different domains to javascript.

Enable remote connections for SQL Server Express 2012

I had to add a firewall inbound port rule to open UDP port 1434. This is the one Sql Server Browser listens on.

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Flask ImportError: No Module Named Flask

After activating the virtual environment and installing Flask, I created an app.py file. I run it like this : python -m flask run. Hope this will help!

Where does Oracle SQL Developer store connections?

for macOS

/Users/joseluisbz/.sqldeveloper/system18.1.0.095.1630/o.jdeveloper.db.connection/connections.xml

Create a rounded button / button with border-radius in Flutter

You can use this code for a transparent rounded button by passing a transparent color to the color property inside BoxDecoration. eg. color: Colors.transparent. Also, take note that this button makes use of only the Container and GestureDetector widgets.

Container(
    height: 50.0,
    child: GestureDetector(
        onTap: () {},
        child: Container(
            decoration: BoxDecoration(
                border: Border.all(
                    color: Color(0xFFF05A22),
                    style: BorderStyle.solid,
                    width: 1.0,
                ),
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(30.0),
            ),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                    Center(
                        child: Text(
                           "BUTTON",
                            style: TextStyle(
                                color: Color(0xFFF05A22),
                                fontFamily: 'Montserrat',
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                letterSpacing: 1,
                            ),
                        ),
                    )
                ],
            ),
        ),
    ),
)

Transaparent Background Button

Case insensitive string compare in LINQ-to-SQL

where row.name.StartsWith(q, true, System.Globalization.CultureInfo.CurrentCulture)

How to implement class constructor in Visual Basic?

Suppose your class is called MyStudent. Here's how you define your class constructor:

Public Class MyStudent
    Public StudentId As Integer

    'Here's the class constructor:
    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Here's how you call it:

Dim student As New MyStudent(studentId)

Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.

jQuery to remove an option from drop down list, given option's text/value

I have used the above option to .hide entries from 2 drops down boxes (first you select the city, then you selected the area within that city). It works fine on screen but the hidden options are still selectable via keyboard inputs.

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted

/etc/selinux/config before change:

SELINUX=enforcing and SELINUXTYPE=permissive

/etc/selinux/config after change: SELINUX=permissive and SELINUXTYPE=permissive

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

You can then call it like this:

window.location.href = nextImage();

Demo here: http://jsfiddle.net/jfriend00/3VPEq/

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I ran into this error because I was attempting to write a string to a cell which started with an "=".

The solution was to put an "'" (apostrophe) before the equals sign, which is a way to tell excel that you're not, in fact, trying to write a formula, and just want to print the equals sign.

How to delete a column from a table in MySQL

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;

Here's a working example.

Note that the COLUMN keyword is optional, as MySQL will accept just DROP IsDeleted. Also, to drop multiple columns, you have to separate them by commas and include the DROP for each one.

ALTER TABLE tbl_Country
  DROP COLUMN IsDeleted,
  DROP COLUMN CountryName;

This allows you to DROP, ADD and ALTER multiple columns on the same table in the one statement. From the MySQL reference manual:

You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.

How to show first commit by 'git log'?

git log --format="%h" | tail -1 gives you the commit hash (ie 0dd89fb), which you can feed into other commands, by doing something like

git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD to view all the commits in the last day.

jQuery: outer html()

Just use standard DOM functionality:

$('#xxx')[0].outerHTML

outerHTML is well supported - verify at Mozilla or caniuse.

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

How do I define global variables in CoffeeScript?

To add to Ivo Wetzel's answer

There seems to be a shorthand syntax for exports ? this that I can only find documented/mentioned on a Google group posting.

I.e. in a web page to make a function available globally you declare the function again with an @ prefix:

<script type="text/coffeescript">
    @aglobalfunction = aglobalfunction = () ->
         alert "Hello!"
</script>

<a href="javascript:aglobalfunction()" >Click me!</a>

Checking if a number is an Integer in Java

With Z I assume you mean Integers , i.e 3,-5,77 not 3.14, 4.02 etc.

A regular expression may help:

Pattern isInteger = Pattern.compile("\\d+");

Insert picture/table in R Markdown

Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.

Images

The bookdown book does a great job of explaining that the best way to include images is by using include_graphics(). For example, a full width image can be printed with a caption below:

```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```

The reason this method is better than the pandoc approach ![your image](path/to/image):

  • It automatically changes the command based on the output format (HTML/PDF/Word)
  • The same syntax can be used to the size of the plot (fig.width), the output width in the report (out.width), add captions (fig.cap) etc.
  • It uses the best graphical devices for the output. This means PDF images remain high resolution.

Tables

knitr::kable() is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.

```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```

If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table package. It provides a tidy graphical interface for making tables.

Achieving custom styling of the table column width is beyond the scope of knitr, but the kableExtra package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html

Style Tips

The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.

If you are looking for potential extensions to the formatting, the bookdown package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html

Do Git tags only apply to the current branch?

When calling just git tag <TAGNAME> without any additional parameters, Git will create a new tag from your current HEAD (i.e. the HEAD of your current branch). When adding additional commits into this branch, the branch HEAD will keep up with those new commits, while the tag always refers to the same commit.

When calling git tag <TAGNAME> <COMMIT> you can even specify which commit to use for creating the tag.

Regardless, a tag is still simply a "pointer" to a certain commit (not a branch).

MySQL Error 1215: Cannot add foreign key constraint

For MySQL (INNODB) ... get definitions for columns you want to link

SELECT * FROM information_schema.columns WHERE 
TABLE_NAME IN (tb_name','referenced_table_name') AND 
COLUMN_NAME  IN ('col_name','referenced_col_name')\G

compare and verify both column definitions have

same COLUMN_TYPE(length), same COLATION

could be helpfull to play like

set foreign_key_checks=0;
ALTER TABLE tb_name ADD FOREIGN KEY(col_name) REFERENCES ref_table(ref_column) ON DELETE ...
set foreign_key_checks=1;

How can I dynamically switch web service addresses in .NET without a recompile?

Just a note about difference beetween static and dynamic.

  • Static: you must set URL property every time you call web service. This because base URL if web service is in the proxy class constructor.
  • Dynamic: a special configuration key will be created for you in your web.config file. By default proxy class will read URL from this key.

Get commit list between tags in git

To style the output to your preferred pretty format, see the man page for git-log.

Example:

git log --pretty=format:"%h; author: %cn; date: %ci; subject:%s" tagA...tagB

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

Flutter : Vertically center column

With Column, use:

mainAxisAlignment: MainAxisAlignment.center

It align its children(s) to center of its parent Space vertically

java: How can I do dynamic casting of a variable from one type to another?

You'll need to write sort of ObjectConverter for this. This is doable if you have both the object which you want to convert and you know the target class to which you'd like to convert to. In this particular case you can get the target class by Field#getDeclaringClass().

You can find here an example of such an ObjectConverter. It should give you the base idea. If you want more conversion possibilities, just add more methods to it with the desired argument and return type.

Simple way to find if two different lists contain exactly the same elements?

The equals method on List will do this, Lists are ordered, so to be equal two Lists must have the same elements in the same order.

return list1.equals(list2);

UITapGestureRecognizer - single tap and double tap

Some view have there own double tap recognizers built in (MKMapView being an example). To get around this you will need to implement UIGestureRecognizerDelegate method shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES:

First implement your double and single recognizers:

// setup gesture recognizers
UITapGestureRecognizer* singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(mapViewTapped:)];
singleTapRecognizer.delegate = self;
singleTapRecognizer.numberOfTapsRequired = 1;


UITapGestureRecognizer* doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                      action:@selector(mapViewDoubleTapped:)];
doubleTapRecognizer.delegate = self;    // this allows
doubleTapRecognizer.numberOfTapsRequired = 2;
[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

And then implement:

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer {  return YES; }

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.

git checkout all the files

  • If you are in base directory location of your tracked files then git checkout . will works otherwise it won't work

How can I tell which button was clicked in a PHP form submit?

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. The user literally clicks the submit button with the mouse or pointing device
  2. Or there is focus on the submit button (they tabbed to it), and then the Enter key is pressed.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

VBA Excel Provide current Date in Text box

You were close. Add this code in the UserForm_Initialize() event handler:

tbxDate.Value = Date

Forms authentication timeout vs sessionState timeout

The difference is that one (Forms timeout) has to do with authenticating the user and the other (Session timeout) has to do with how long cached data is stored on the server. So they are very independent things, so one does not take precedence over the other.

SQlite - Android - Foreign key syntax

You have to define your TASK_CAT column first and then set foreign key on it.

private static final String TASK_TABLE_CREATE = "create table "
        + TASK_TABLE + " (" 
        + TASK_ID + " integer primary key autoincrement, " 
        + TASK_TITLE + " text not null, " 
        + TASK_NOTES + " text not null, "
        + TASK_DATE_TIME + " text not null,"
        + TASK_CAT + " integer,"
        + " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";

More information you can find on sqlite foreign keys doc.

How to check if a variable is not null?

The two conditional statements you list here are not better than one another. Your usage depends on the situation. You have a typo by the way in the 2nd example. There should be only one equals sign after the exclamation mark.

The 1st example determines if the value in myVar is true and executes the code inside of the {...}

The 2nd example evaluates if myVar does not equal null and if that case is true it will execute your code inside of the {...}

I suggest taking a look into conditional statements for more techniques. Once you are familiar with them, you can decide when you need them.

Change font size of UISegmentedControl

C# / Xamarin:

segment.SetTitleTextAttributes(new UITextAttributes { 
    Font = UIFont.SystemFontOfSize(font_size) }, UIControlState.Normal);

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

Less aggressive compilation with CSS3 calc

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

How do I install cURL on cygwin?

In order to use the command-line version of curl, you need the curl executable. So, run the Cygwins Setup.exe, and select curl (under Net->curl). That one uses libcurl3, which is located in Libs->libcurl3. But libcurl3 will be pulled in as a dependency if it's not already installed. So, just select Net->curl and you're good to go.

How to use LogonUser properly to impersonate domain user from workgroup client

Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.

How to loop backwards in python?

range() and xrange() take a third parameter that specifies a step. So you can do the following.

range(10, 0, -1)

Which gives

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

But for iteration, you should really be using xrange instead. So,

xrange(10, 0, -1)

Note for Python 3 users: There are no separate range and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.

How to calculate number of days between two dates

I made a quick re-usable function in ES6 using Moment.js.

_x000D_
_x000D_
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {_x000D_
  const getDateAsArray = (date) => {_x000D_
    return moment(date.split(/\D+/), date_format);_x000D_
  }_x000D_
  return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;_x000D_
}_x000D_
_x000D_
console.log(getDaysDiff('2019-10-01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019/10/01', '2019/10/30'));_x000D_
console.log(getDaysDiff('2019.10-01', '2019.10 30'));_x000D_
console.log(getDaysDiff('2019 10 01', '2019 10 30'));_x000D_
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));_x000D_
_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019'));_x000D_
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
_x000D_
_x000D_
_x000D_

Iterate through string array in Java

String[] elements = { "a", "a", "a", "a" };

for( int i = 0; i < elements.length - 1; i++)
{
    String element = elements[i];
    String nextElement = elements[i+1];
}

Note that in this case, elements.length is 4, so you want to iterate from [0,2] to get elements 0,1, 1,2 and 2,3.

Optimistic vs. Pessimistic locking

Lot of good things have been said above about optimistic and pessimistic locking. One important point to consider is as follows:

When using optimistic locking, we need to cautious of the fact that how will application recover from these failures.

Specially in asynchronous message driven architectures, this can lead of out of order message processing or lost updates.

Failures scenarios need to be thought through.

How to drop all tables in a SQL Server database?

The accepted answer doesn't support Azure. It uses an undocumented stored procedure "sp_MSforeachtable". If you get an "azure could not find stored procedure 'sp_msforeachtable" error when running or simply want to avoid relying on undocumented features (which can be removed or have their functionality changed at any point) then try the below.

This version ignores the entity framework migration history table "__MigrationHistory" and the "database_firewall_rules" which is an Azure table you will not have permission to delete.

Lightly tested on Azure. Do check to make this this has no undesired effects on your environment.

DECLARE @sql NVARCHAR(2000)

WHILE(EXISTS(SELECT 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY'))
BEGIN
    SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    EXEC(@sql)
    PRINT @sql
END

WHILE(EXISTS(SELECT * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'))
BEGIN
    SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_NAME != 'database_firewall_rules'
    EXEC(@sql)
    PRINT @sql
END

Taken from:

https://edspencer.me.uk/2013/02/25/drop-all-tables-in-a-sql-server-database-azure-friendly/

http://www.sqlservercentral.com/blogs/sqlservertips/2011/10/11/remove-all-foreign-keys/

replace String with another in java

There is a possibility not to use extra variables

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);

Spacing between elements

It depends on what exactly you want to accomplish. Let's assume you have this structure:

<p style="width:400px;">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.
</p>

If you want the space between the single lines to be bigger, you should increase

line-height

If you want the space at the end to be bigger, you should increase

margin-bottom

If you want the space at the end to be bigger, but have the background fill the space (or the border around the space) use

padding-bottom

Of course, there are also the corresponding values for space on the top:

padding-top
margin-top

Some examples:

<p style="line-height: 30px; width: 300px; border: 1px solid black;">
     Space between single lines 
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
</p>
<p style="margin-bottom: 30px; width: 300px; border: 1px solid black;">
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
</p>
<p style="padding-bottom: 30px; width: 300px; border: 1px solid black;">
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
</p>

here you can see this code in action: http://jsfiddle.net/ramsesoriginal/H7qxd/

Of course you should put your styles in a separate stylesheet, the inline code was just to show the effect.

here you have a little schematic demonstration of what which value affects:

                                   line-height
           content                 +
                                   |      padding-bottom
                  <----------------+      +
           content                        |    border-bottom
                                          |    +
                                          |    |
        +-------------+<------------------+    |       margin-bottom
                                               |       +
     +===================+ <-------------------+       |
                                                       |
  +-------------------------+ <------------------------+

How to get the Development/Staging/production Hosting Environment in ConfigureServices

The hosting environment comes from the ASPNET_ENV environment variable, which is available during Startup using the IHostingEnvironment.IsEnvironment extension method, or one of the corresponding convenience methods of IsDevelopment or IsProduction. Either save what you need in Startup(), or in ConfigureServices call:

var foo = Environment.GetEnvironmentVariable("ASPNET_ENV");

Simple way to convert datarow array to datatable

DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();

What is an attribute in Java?

¦ What is an attribute?

– A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members

¦ How else can it be called?

– field or instance variable

¦ How do you create one? What is the syntax?

– You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following: ;

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

How to start rails server?

I also faced the same issue, but my fault was that I was running "rails s" outside of my application directory. After opening the cmd, just go inside your application and run the commands from their, it worked for me.

How to use AND in IF Statement

Brief syntax lesson

Cells(Row, Column) identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)

.Cells(Row, Column) identifies a cell within a sheet identified in a earlier With statement:

With ActiveSheet
  :
  .Cells(Row,Column)
  :
End With

If you omit the dot, Cells(Row,Column) is within the active worksheet. So wsh = ActiveWorkbook wsh.Range is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:

With ActiveSheet
  :
  .Range.  
  :
End With

Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:

With Sheets("xxxx")
  :
  .Range.  
  :
End With

because my code only works on sheet xxxx.

Cells(Row,Column) identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value is good.

Cells(Row,Column) like "*Miami*" will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.

Cells(Row,Column).Value = "Miami" will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:

Lcase(Cells(Row,Column).Value) = "miami"  

My suggestions

Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami" when I started typing this.

Use

If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
  Cells(i, "C").Value = "BA"

if you want to accept, for example, "South Miami" and "Miami, North".

Use

If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
  Cells(i, "C").Value = "BA"

if you want to accept, exactly, "Miami" and "Florida".

Use

If Lcase(Cells(i, "A").Value) = "miami" And _
   Lcase(Cells(i, "D").Value) = "florida" Then
  Cells(i, "C").Value = "BA"

if you don't care about case.

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

iframe refuses to display

It means that the http server at cw.na1.hgncloud.com send some http headers to tell web browsers like Chrome to allow iframe loading of that page (https://cw.na1.hgncloud.com/crossmatch/) only from a page hosted on the same domain (cw.na1.hgncloud.com) :

Content-Security-Policy: frame-ancestors 'self' https://cw.na1.hgncloud.com
X-Frame-Options: ALLOW-FROM https://cw.na1.hgncloud.com

You should read that :

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I got this error when stubbing with sinon.

The fix is to use npm package sinon-as-promised when resolving or rejecting promises with stubs.

Instead of ...

sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))

Use ...

require('sinon-as-promised');
sinon.stub(Database, 'connect').rejects(Error('oops'));

There is also a resolves method (note the s on the end).

See http://clarkdave.net/2016/09/node-v6-6-and-asynchronously-handled-promise-rejections

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

Fatal error: Out of memory, but I do have plenty of memory (PHP)

For starters, memory_get_peak_usage() will not be helpful here. It will only return the amount of memory which was allocated, and that is the same number which caused the error.

memory_get_usage will return the active amount of memory which is being allocated when it is called.

ini_set('memory_limit', '256M'); will set the maximum allowance of PHP's footprint on your systems Memory. If you are getting OOM at 768K, upping it will not fix the problem.

There is no indication as to what version of PHP you are using, but I would suggest an upgrade immediately. There are several bugs where Zend's Memory Manager fails to deallocate memory, which would lead you exactly to the same problem.

Are both your local server and your production server running the same version of OS, the same long bit and the same version of PHP? The answer will be no.

If it is unrelated to the windows malloc() issue, being it is a sub domain and probably within a VirtualHost, and allocating only 768k, it almost sounds like an OS issue.

Run tasklist from the command prompt when you access your script. Do you see an additional Apache thread, or Memory usage across the processes spike?

One last idea is, run flush() and/or ob_flush(); after each loop for the table row/column. This should clear your buffer and save you some memory in the event this is where the issue is occurring.

How to create a HTML Cancel button that redirects to a URL

With Jquery:

$(".cancel-button").click(function (e) {
  e.preventDefault();
});

SET NAMES utf8 in MySQL?

Thanks @all!

don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)

some little thing in parctice:

status:

  • mysql server by default talks latin1
  • your hole app is in utf8
  • connection is made without any extra (so: latin1) (no SET NAMES utf8 ..., no set_charset() method/function)

Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).

until now this is not a problem! (wrong but works often (in europe)) ..

..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In Python there is a method for doing this: driver.refresh(). It may not be the same in Java.

Alternatively, you could driver.get("http://foo.bar");, although I think the refresh method should work just fine.

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

How to set date format in HTML date input tag?

You don't.

Firstly, your question is ambiguous - do you mean the format in which it is displayed to the user, or the format in which it is transmitted to the web server?

If you mean the format in which it is displayed to the user, then this is down to the end-user interface, not anything you specify in the HTML. Usually, I would expect it to be based on the date format that it is set in the operating system locale settings. It makes no sense to try to override it with your own preferred format, as the format it displays in is (generally speaking) the correct one for the user's locale and the format that the user is used to writing/understanding dates in.

If you mean the format in which it's transmitted to the server, you're trying to fix the wrong problem. What you need to do is program the server-side code to accept dates in yyyy-mm-dd format.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I ran into a similar issue that impacted all my browsers. After completely uninstalling all my JREs and JDKs then startig from scratch, I ran into the same issue. I'm running Win 7 pro 64 bit.

I detailed out the solution here (Why does Java 7 fail to Verify after successful JRE installation - Java 7 not running my any browser)

but basically I added this "-Djava.net.preferIPv4Stack=true" to my vm args (set in the Java Control Panel, under Java tab / View) and that solved the issues I was facing... seems like a hack but I guess the latest JRE does not handle IPv6 type requests properly

bypass invalid SSL certificate in .net core

I solve with this:

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            }
        });

YourService.cs

public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
        _clientFactory = clientFactory;
    }

var request = new HttpRequestMessage(...

var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");

HttpResponseMessage response = await client.SendAsync(request);

Two arrays in foreach loop

Walk it out...

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
  • PHP 5.3+

    array_walk($codes, function ($code,$key) use ($names) { 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    });
    
  • Before PHP 5.3

    array_walk($codes, function ($code,$key,$names){ 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    },$names);
    
  • or combine

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        echo '<option value="' . $code . '">' . $name . '</option>';
    })
    
  • in select

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        @$opts = '<option value="' . $code . '">' . $name . '</option>';
    })
    echo "<select>$opts</select>";
    

demo

How can I get Docker Linux container information from within the container itself?

I've found out that the container id can be found in /proc/self/cgroup

So you can get the id with :

cat /proc/self/cgroup | grep -o  -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"

How to revert uncommitted changes including files and folders?

Git 2.23 introduced git restore command to restore working tree files.

https://git-scm.com/docs/git-restore

To restore all files in the current directory

git restore .

If you want to restore all C source files to match the version in the index, you can do

git restore '*.c'

Android Studio : unmappable character for encoding UTF-8

If above answeres did not work, then you can try my answer because it worked for me.
Here's what worked for me.

  1. Close Android Studio
  2. Go to C:\Usersyour username
  3. Locate the Android Studio settings directory named .AndroidStudioX.X (X.X being the version)
  4. C:\Users\my_user_name.AndroidStudio4.0\system\caches
  5. Delete the caches folder and open android studio

This should fix the issue.

Git fast forward VS no fast forward merge

I can give an example commonly seen in project.

Here, option --no-ff (i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff (i.e. fast-forward merge) is by default.

$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature'         // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk                           // => see details with graph

$ git checkout -b anotherFeature        // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature       // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk                           // => see details with graph

(*) Note that here if the newFeature branch is re-used, instead of creating a new branch, git will have to do a --no-ff merge anyway. This means fast forward merge is not always eligible.

Class 'ViewController' has no initializers in swift

The error could be improved, but the problem with your first version is you have a member variable, delegate, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.

When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.

What is exactly the base pointer and stack pointer? To what do they point?

First of all, the stack pointer points to the bottom of the stack since x86 stacks build from high address values to lower address values. The stack pointer is the point where the next call to push (or call) will place the next value. It's operation is equivalent to the C/C++ statement:

 // push eax
 --*esp = eax
 // pop eax
 eax = *esp++;

 // a function call, in this case, the caller must clean up the function parameters
 move eax,some value
 push eax
 call some address  // this pushes the next value of the instruction pointer onto the
                    // stack and changes the instruction pointer to "some address"
 add esp,4 // remove eax from the stack

 // a function
 push ebp // save the old stack frame
 move ebp, esp
 ... // do stuff
 pop ebp  // restore the old stack frame
 ret

The base pointer is top of the current frame. ebp generally points to your return address. ebp+4 points to the first parameter of your function (or the this value of a class method). ebp-4 points to the first local variable of your function, usually the old value of ebp so you can restore the prior frame pointer.

Find html label associated with a given input

The best answer works perfectly fine but in most cases, it is overkill and inefficient to loop through all the label elements.

Here is an efficent function to get the label that goes with the input element:

function getLabelForInput(id)
{
    var el = document.getElementById(id);
    if (!el)
        return null;
    var elPrev = el.previousElementSibling;
    var elNext = el.nextElementSibling;
    while (elPrev || elNext)
    {
        if (elPrev)
        {
            if (elPrev.htmlFor === id)
                return elPrev;
            elPrev = elPrev.previousElementSibling;
        }
        if (elNext)
        {
            if (elNext.htmlFor === id)
                return elNext;
            elNext = elNext.nextElementSibling;
        }
    }
    return null;
}

For me, this one line of code was sufficient:

el = document.getElementById(id).previousElementSibling;

In most cases, the label will be very close or next to the input, which means the loop in the above function only needs to iterate a very small number of times.

How to get the path of running java program

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use

System.getProperty("java.class.path")

Above mentioned System property provides

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

How does the communication between a browser and a web server take place?

The links for specifications of each aspect of the question is as follows:

  • GET, POST verbs (among others) - The HTTP Specification exhaustively discusses all aspects of HTTP communication (the protocol for communication between the web server and the browser). It explains the Request message and Response message protocols.

  • Cookies - are set by attaching a Set-Cookie HTTP Header to the HTTP response.

  • QueryStrings - are the part of the URL in the HTTP request that follow the first occurrence of a "?" character. The linked specification is for section 3.4 of the URI specification.

  • Sessions - HTTP is a synchronous, stateless protocol. Sessions, or the illusion of state, can be created by (1) using cookies to store state data as plain text on the client's computer, (2) passing data-values in the URL and querystring of the request, (3) submitting POST requests with a collection of values that may indicate state and, (4) storing state information by a server-side persistence mechanism that is retrieved by a session-key (the session key is resolved from either the cookie, URL/Querystring or POST value collection.

An explanation of HTTP can go on for days, but I have attempted to provide a concise yet conceptually complete answer, and include the appropriate links for further reading of official specifications.

How to get twitter bootstrap modal to close (after initial launch)

Try on this..

$('body').removeClass('modal-open');

$('.modal-backdrop').remove();

How do I build a graphical user interface in C++?

Given the comment of "say Windows XP as an example", then your options are:

  • Interact directly with the operating system via its API, which for Microsoft Windows is surprise surprise call Windows API. The definitive reference for the WinAPI is Microsoft's MSDN website. A popular online beginner tutorial for that is theForger's Win32 API Programming Tutorial. The classic book for that is Charles Petzold's Programming Windows, 5th Edition.

  • Use a platform (both in terms of OS and compiler) specific library such as MFC, which wraps the WinAPI into C++ class. The reference for that is again MSDN. A classic book for that is Jeff Prosise's Programming Windows with MFC, 2nd Edition. If you are using say CodeGear C++ Builder, then the option here is VCL.

  • Use a cross platform library such as GTK+ (C++ wrapper: gtkmm), Qt, wxWidgets, or FLTK that wrap the specific OS's API. The advantages with these are that in general, your program could been compiled for different OS without having to change the source codes. As have already been mentioned, they each have its own strengths and weaknesses. One consideration when selecting which one to use is its license. For the examples given, GTK+ & gtkmm is license under LGPL, Qt is under various licenses including proprietary option, wxWidgets is under its own wxWindows Licence (with a rename to wxWidgets Licence), and FLTK is under LGPL with exception. For reference, tutorial, and or books, refer to each one's website for details.

Shortcut for creating single item list in C#

I've got this little function:

public static class CoreUtil
{    
    public static IEnumerable<T> ToEnumerable<T>(params T[] items)
    {
        return items;
    }
}

Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like

CoreUtil.ToEnumerable("title").ToList();

But of course it also allows

CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();

I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:

CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))

Saves a few ToList() and Add statements.

(Late answer, but I stumbled upon this oldie and thought this could be helpful)

Difference between Hashing a Password and Encrypting it

Hashing algorithms are usually cryptographic in nature, but the principal difference is that encryption is reversible through decryption, and hashing is not.

An encryption function typically takes input and produces encrypted output that is the same, or slightly larger size.

A hashing function takes input and produces a typically smaller output, typically of a fixed size as well.

While it isn't possible to take a hashed result and "dehash" it to get back the original input, you can typically brute-force your way to something that produces the same hash.

In other words, if a authentication scheme takes a password, hashes it, and compares it to a hashed version of the requires password, it might not be required that you actually know the original password, only its hash, and you can brute-force your way to something that will match, even if it's a different password.

Hashing functions are typically created to minimize the chance of collisions and make it hard to just calculate something that will produce the same hash as something else.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.

The error message indirectly tells you what character set Python was trying to use:

  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

This means the charset is cp850.

You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).

It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)

But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:

>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

So, how do you print a string that won't print on your console?

You can replace every print function with something like this:

>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

… but that's going to get pretty tedious pretty fast.

The simple thing to do is to just set the error handler on sys.stdout:

>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:

with open('path', 'w', encoding='cp850') as f:

Do this:

with open('path', 'w', encoding='cp850', errors='replace') as f:

… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:

with open('path', 'w', encoding='utf-8') as f:

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

JS search in object values

The search function will return all objects which contain a value which has contains the search query

_x000D_
_x000D_
function search(arr, s){_x000D_
    var matches = [], i, key;_x000D_
    _x000D_
    for( i = arr.length; i--; )_x000D_
        for( key in arr[i] )_x000D_
            if( arr[i].hasOwnProperty(key) && arr[i][key].indexOf(s) > -1 )_x000D_
                matches.push( arr[i] );  // <-- This can be changed to anything_x000D_
_x000D_
    return matches;_x000D_
};_x000D_
_x000D_
// dummy data_x000D_
var items = [_x000D_
      {_x000D_
        "foo" : "bar",_x000D_
        "bar" : "sit"_x000D_
      },_x000D_
      {_x000D_
        "foo" : "lorem",_x000D_
        "bar" : "ipsum"_x000D_
      },_x000D_
      {_x000D_
        "foo" : "dolor",_x000D_
        "bar" : "amet"_x000D_
      }_x000D_
];_x000D_
    _x000D_
var result = search(items, 'lo'); // search "items" for a query value_x000D_
console.log(result); // print the result
_x000D_
_x000D_
_x000D_

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How to change root logging level programmatically for logback

using logback 1.1.3 I had to do the following (Scala code):

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]

Array vs. Object efficiency in JavaScript

In NodeJS if you know the ID, the looping through the array is very slow compared to object[ID].

const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;

//create data
for(var i=0;i<1000000;i++){
  var getUnique = `${uniqueString()}`;
  if(i===888555) seeking = getUnique;
  arr.push(getUnique);
  obj[getUnique] = true;
}

//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
  if(arr[x]===seeking){
    console.log('Array result:');
    console.timeEnd('arrTimer');
    break;
  }
}

//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');

And the results:

Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms

Even if the seeking ID is the first one in the array/object:

Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms

Force IE8 Into IE7 Compatiblity Mode

A note to this:

IE 8.0s emulation only promises to display the page the same. There are subtle differences that might cause functionality to break. I recently had a problem with just that. Where IE 7.0 uses a javascript wrapper-function called "anonymous()" in IE 8.0 the wrapper was named differently.

So do not expect things like JavaScript to "just work", because you turn on emulation.

Comparing the contents of two files in Sublime Text

There's a BeyondCompare plugin as well. It opens the 2 files in a BeyondCompare window. Pretty convenient to open files from the sublime window.

You will need BC3 installation present in the system. After installing the plugin, you will have to provide the path to the installation.

Example:

{
    //Define a custom path to beyond compare
    "beyond_compare_path": "G:/Softwares/Beyond Compare 3/BCompare.exe"
}

$("#form1").validate is not a function

I had this same issue. It turned out that I was loading the jQuery JavaScript file more than once on the page. This was due to included pages (or JSPs, in my case). Once I removed the duplicate reference to the jQuery js file, this error went away.

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

TypeError: module.__init__() takes at most 2 arguments (3 given)

Your error is happening because Object is a module, not a class. So your inheritance is screwy.

Change your import statement to:

from Object import ClassName

and your class definition to:

class Visitor(ClassName):

or

change your class definition to:

class Visitor(Object.ClassName):
   etc

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

Is there any way to wait for AJAX response and halt execution?

When using promises they can be used in a promise chain. async=false will be deprecated so using promises is your best option.

function functABC() {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: 'myPage.php',
      data: {id: id},
      success: function(data) {
        resolve(data) // Resolve promise and go to then()
      },
      error: function(err) {
        reject(err) // Reject the promise and go to catch()
      }
    });
  });
}

functABC().then(function(data) {
  // Run this when your request was successful
  console.log(data)
}).catch(function(err) {
  // Run this when promise was rejected via reject()
  console.log(err)
})

jQuery Combobox/select autocomplete?

This works great for me and I'm doing more, writing less with jQuery's example modified.

I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.

$(function() {
   var mySource = [];
   $("#mySelect").children("option").map(function() {
      mySource.push($(this).text());
   });

   $("#myInput").autocomplete({
      source: mySource,
      minLength: 3
   });
}

Static link of shared library function in gcc

A bit late but ... I found a link that I saved a couple of years ago and I thought it might be useful for you guys:

CDE: Automatically create portable Linux applications

http://www.pgbovine.net/cde.html

  • Just download the program
  • Execute the binary passing as a argument the name of the binary you want make portable, for example: nmap

    ./cde_2011-08-15_64bit nmap

The program will read all of libs linked to nmap and its dependencias and it will save all of them in a folder called cde-package/ (in the same directory that you are).

  • Finally, you can compress the folder and deploy the portable binary in whatever system.

Remember, to launch the portable program you have to exec the binary located in cde-package/nmap.cde

Best regards

Postgres could not connect to server

Try

sudo systemctl start postgresql@12-main

Here my postgresql version is 12.

Controller 'ngModel', required by directive '...', can't be found

You can also remove the line

  require: 'ngModel',

if you don't need ngModel in this directive. Removing ngModel will allow you to make a directive without thatngModel error.

change the date format in laravel view page

Try this:

date('d-m-Y', strtotime($user->from_date));

It will convert date into d-m-Y or whatever format you have given.

Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

public ChannelSearchEnum[] getChannelSearchEnum(Response response) {
        return response.as(ChannelSearchEnum[].class, ObjectMapperType.GSON);
}

Above will solve and passing response will returned mapped object array of the class

How can I use JavaScript in Java?

You can use ScriptEngine, example:


public class Main {
    public static void main(String[] args) {
        StringBuffer javascript = null;
        ScriptEngine runtime = null;

        try {
            runtime = new ScriptEngineManager().getEngineByName("javascript");
            javascript = new StringBuffer();

            javascript.append("1 + 1");

            double result = (Double) runtime.eval(javascript.toString());

            System.out.println("Result: " + result);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Reason to Pass a Pointer by Reference in C++?

50% of C++ programmers like to set their pointers to null after a delete:

template<typename T>    
void moronic_delete(T*& p)
{
    delete p;
    p = nullptr;
}

Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.

Column calculated from another column?

I hope this still helps someone as many people might get to this article. If you need a computed column, why not just expose your desired columns in a view ? Don't just save data or overload the performance with triggers... simply expose the data you need already formatted/calculated in a view.

Hope this helps...

How to set image for bar button with swift?

Just choose Original image option when adding an image to assets in Xcode

enter image description here

Open a folder using Process.Start

You don't need the double backslash when using unescaped strings:

System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");

Installing R with Homebrew

homebrew/science was deprecated So, you should use the following command.

brew tap brewsci/science

jQuery onclick toggle class name

you can use toggleClass() to toggle class it is really handy.

case:1

<div id='mydiv' class="class1"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class2"></div>

case:2

<div id='mydiv' class="class2"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class1"></div>

case:3

<div id='mydiv' class="class1 class2 class3"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class3"></div>

How to get the difference between two dictionaries in Python?

Old question, but thought I'd share my solution anyway. Pretty simple.

dicta_set = set(dicta.items()) # creates a set of tuples (k/v pairs)
dictb_set = set(dictb.items())
setdiff = dictb_set.difference(dicta_set) # any set method you want for comparisons
for k, v in setdiff: # unpack the tuples for processing
    print(f"k/v differences = {k}: {v}")

This code creates two sets of tuples representing the k/v pairs. It then uses a set method of your choosing to compare the tuples. Lastly, it unpacks the tuples (k/v pairs) for processing.

How to convert a currency string to a double with jQuery or Javascript?

function NumberConvertToDecimal (number) {
    if (number == 0) {
       return '0.00'; 
    }
    number = parseFloat(number);
    number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
    number = number.split('.').join('*').split('*').join('.');
    return number;
}

Convert Base64 string to an image file?

That's an old thread, but in case you want to upload the image having same extension-

    $image = $request->image;
    $imageInfo = explode(";base64,", $image);
    $imgExt = str_replace('data:image/', '', $imageInfo[0]);      
    $image = str_replace(' ', '+', $imageInfo[1]);
    $imageName = "post-".time().".".$imgExt;
    Storage::disk('public_feeds')->put($imageName, base64_decode($image));

You can create 'public_feeds' in laravel's filesystem.php-

   'public_feeds' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads/feeds',
    ],

How can I force gradle to redownload dependencies?

None of the solutions above worked for me.

If you use IntelliJ, what resolved it for me was simply refreshing all Gradle projects:

enter image description here

How do I upload a file with the JS fetch API?

Jumping off from Alex Montoya's approach for multiple file input elements

const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();

for (const file of inputFiles) {
    formData.append(file.name, file.files[0]);
}

fetch(url, {
    method: 'POST',
    body: formData })

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

Rails 3.1 and Image Assets

when referencing images in CSS or in an IMG tag, use image-name.jpg

while the image is really located under ./assets/images/image-name.jpg

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

Call another rest api from my server in Spring-Boot

Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

Making button go full-width?

Bootstrap / CSS

Use col-12, btn-block, w-100, form-control or width:100%

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

         <button class="btn btn-success col-12">
             class="col-12"
         </button>
    
         <button class="btn btn-primary w-100">
             class="w-100"
         </button>

         <button class="btn btn-secondary btn-block">
             class="btn-block"
         </button>
         
         <button class="btn btn-success form-control">
             class="form-control"
         </button>
         
         <button class="btn btn-danger" style="width:100%">
             style="width:100%"
         </button>
_x000D_
_x000D_
_x000D_

How to write a cron that will run a script every day at midnight?

Put this sentence in a crontab file: 0 0 * * * /usr/local/bin/python /opt/ByAccount.py > /var/log/cron.log 2>&1

Adding attributes to an XML node

If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class UserNode
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string userName { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string passWord { get; set; }

    public int Age { get; set; }
    public string Name { get; set; }         
 }

 public class LoginNode 
 {
    public UserNode id { get; set; }
 }

Then you just serialize to XML an instance of LoginNode called "Login", and that's it!

Here you have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.

Locating child nodes of WebElements in selenium

The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"

So you could take a substring starting at the colon with something like this:

String selector = divA.toString().substring(s.indexOf(":") + 2);

With this, you could find your element inside your other element with this:

WebElement input = driver.findElement( By.xpath( selector + "//input" ) );

Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.

Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

All "relativity" aside, not fast. Based on the fact that you said you never programmed before...to become a basic programmer, a few years.

And to become a good to outstanding (using design patterns and industry recognized standards that relate to common standards as defined by ISO/IEC 9126 Standard such as testability, maintainability, etc.) programmer, it takes years of experience and coding often.. you do not become "Sr." or an "Architect" overnight and the same thing is true for a mid-level developer who doesn't code slop.

It's always a process where you improve. So learning is relative. But to learn the basics, seems simple until you start to design classes and interfaces. And even Leads stumble on the basics..doing things wrong. Everyone does. There is so much to be aware of.

If you're just going to be adding features (using classes your Lead or Architect has stubbed out for the team) and not really adding new classes, etc. it's easier....but you should take care in coding using standards and you still have to know complex areas of OOP. But that's not really OOP. When you start to creating classes, interfaces and knowing about inheritance, heap, references, etc. yada yada...and REALLY understanding it takes time no matter how smart you are or think you may be.

So, for a new programmer. Not easy. Be prepared to code a lot. And if you are not, find a job where you are. It's all about coding as much possible so you can get better.

Read these books FIRST. Do not dive into any others out there because they are not geared toward teaching you the language in a way you can get up to speed fast:

http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=pd_bbs_sr_4?ie=UTF8&s=books&qid=1231280335&sr=8-4

http://www.amazon.com/Head-First-SQL-Brain-Learners/dp/0596526849/ref=pd_bbs_sr_7?ie=UTF8&s=books&qid=1231280335&sr=8-7

http://www.amazon.com/Head-First-C-Brain-Friendly-Guides/dp/0596514824/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1231280393&sr=8-1

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=pd_bbs_sr_3?ie=UTF8&s=books&qid=1231280393&sr=8-3

they will get you the fasted jump start into understanding, better than any books out there.

Also for these lame type of responses, ignore them:

"Then again, plenty of people (most normal people, non-programmers) never learn those subjects, so if you're like "most" people then the answer would be "it would take forever" or "it will never happen"."

Those come from developers (typically leads) who have some Ego trip that DON'T want you to learn. Everyone learns differently and at different paces and eventually you will become "fast". I get very tired of hearing Sr. developers say statements like this when their sh** also stinks many times no matter how good they are. Instead they should be helping the team to succeed and learn as long as their team is working hard to keep abreast and doing what they can on their own as well (not leachers).

Make sure you try to get a Jr. Level Developer position first...

How to exit git log or git diff

Actually, there are three ways to do it, precisely.

Type any of the following 3 commands.

  1. :q
  2. :z or
  3. Ctrl + z

P.S.: Sometimes, for someone, one of these options doesn't seem to work and for others it works.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

Reading a key from the Web.Config using ConfigurationManager

Full Path for it is

System.Configuration.ConfigurationManager.AppSettings["KeyName"]

Setting default values to null fields when mapping with Jackson

Another option is to use InjectableValues and @JacksonInject. It is very useful if you need to use not always the same value but one get from DB or somewhere else for the specific case. Here is an example of using JacksonInject:

protected static class Some {
    private final String field1;
    private final String field2;

    public Some(@JsonProperty("field1") final String field1,
            @JsonProperty("field2") @JacksonInject(value = "defaultValueForField2",
                    useInput = OptBoolean.TRUE) final String field2) {
        this.field1 = requireNonNull(field1);
        this.field2 = requireNonNull(field2);
    }

    public String getField1() {
        return field1;
    }

    public String getField2() {
        return field2;
    }
}

@Test
public void testReadValueInjectables() throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final InjectableValues injectableValues =
            new InjectableValues.Std().addValue("defaultValueForField2", "somedefaultValue");
    mapper.setInjectableValues(injectableValues);

    final Some actualValueMissing = mapper.readValue("{\"field1\": \"field1value\"}", Some.class);
    assertEquals(actualValueMissing.getField1(), "field1value");
    assertEquals(actualValueMissing.getField2(), "somedefaultValue");

    final Some actualValuePresent =
            mapper.readValue("{\"field1\": \"field1value\", \"field2\": \"field2value\"}", Some.class);
    assertEquals(actualValuePresent.getField1(), "field1value");
    assertEquals(actualValuePresent.getField2(), "field2value");
}

Keep in mind that if you are using constructor to create the entity (this usually happens when you use @Value or @AllArgsConstructor in lombok ) and you put @JacksonInject not to the constructor but to the property it will not work as expected - value of the injected field will always override value in json, no matter whether you put useInput = OptBoolean.TRUE in @JacksonInject. This is because jackson injects those properties after constructor is called (even if the property is final) - field is set to the correct value in constructor but then it is overrided (check: https://github.com/FasterXML/jackson-databind/issues/2678 and https://github.com/rzwitserloot/lombok/issues/1528#issuecomment-607725333 for more information), this test is unfortunately passing:

protected static class Some {
    private final String field1;

    @JacksonInject(value = "defaultValueForField2", useInput = OptBoolean.TRUE)
    private final String field2;

    public Some(@JsonProperty("field1") final String field1,
            @JsonProperty("field2") @JacksonInject(value = "defaultValueForField2",
                    useInput = OptBoolean.TRUE) final String field2) {
        this.field1 = requireNonNull(field1);
        this.field2 = requireNonNull(field2);
    }

    public String getField1() {
        return field1;
    }

    public String getField2() {
        return field2;
    }
}

@Test
public void testReadValueInjectablesIncorrectBehavior() throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final InjectableValues injectableValues =
            new InjectableValues.Std().addValue("defaultValueForField2", "somedefaultValue");
    mapper.setInjectableValues(injectableValues);

    final Some actualValueMissing = mapper.readValue("{\"field1\": \"field1value\"}", Some.class);
    assertEquals(actualValueMissing.getField1(), "field1value");
    assertEquals(actualValueMissing.getField2(), "somedefaultValue");

    final Some actualValuePresent =
            mapper.readValue("{\"field1\": \"field1value\", \"field2\": \"field2value\"}", Some.class);
    assertEquals(actualValuePresent.getField1(), "field1value");
    // unfortunately "field2value" is overrided because of putting "@JacksonInject" to the field
    assertEquals(actualValuePresent.getField2(), "somedefaultValue");
}

Hope this helps to someone with a similar problem.

P.S. I'm using jackson v. 2.9.6

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

How to negate a method reference predicate

Another option is to utilize lambda casting in non-ambiguous contexts into one class:

public static class Lambdas {
    public static <T> Predicate<T> as(Predicate<T> predicate){
        return predicate;
    }

    public static <T> Consumer<T> as(Consumer<T> consumer){
        return consumer;
    }

    public static <T> Supplier<T> as(Supplier<T> supplier){
        return supplier;
    }

    public static <T, R> Function<T, R> as(Function<T, R> function){
        return function;
    }

}

... and then static import the utility class:

stream.filter(as(String::isEmpty).negate())

Difference between array_push() and $array[] =

both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element

IntelliJ - show where errors are

In IntelliJ Idea 2019 you can find scope "Problems" under the "Project" view. Default scope is "Project".

"Problems" scope

HTML not loading CSS file

This may be a 'special' case but was fiddling with this piece of code:

ForceType application/x-httpd-php SetHandler application/x-httpd-php

As a quick test for extentionless file handling, when a similar problem occurred.

Some but not all php files thereafter treated the css files as php and thus succesfully loaded the css but not handled it as css, thus zero rules were executed when checking f12 style editor.

Perhaps something similar might occur to any-one else here and this tidbit might help.

Auto-expanding layout with Qt-Designer

After creating your QVBoxLayout in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout should now stretch to fit the window and will resize automatically when the entire window is resized.

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

The operation is not allowed in chrome. You can either use a HTTP server(Tomcat) or you use Firefox instead.

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

How to serialize Object to JSON?

GSON is easy to use and has relatively small memory footprint. If you loke to have even smaller footprint, you can grab:

https://github.com/ko5tik/jsonserializer

Which is tiny wrapper around stripped down GSON libraries for just POJOs

How to find all combinations of coins when given some dollar value

Here's some absolutely straightforward C++ code to solve the problem which did ask for all the combinations to be shown.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("usage: change amount-in-cents\n");
        return 1;
    }

    int total = atoi(argv[1]);

    printf("quarter\tdime\tnickle\tpenny\tto make %d\n", total);

    int combos = 0;

    for (int q = 0; q <= total / 25; q++)
    {
        int total_less_q = total - q * 25;
        for (int d = 0; d <= total_less_q / 10; d++)
        {
            int total_less_q_d = total_less_q - d * 10;
            for (int n = 0; n <= total_less_q_d / 5; n++)
            {
                int p = total_less_q_d - n * 5;
                printf("%d\t%d\t%d\t%d\n", q, d, n, p);
                combos++;
            }
        }
    }

    printf("%d combinations\n", combos);

    return 0;
}

But I'm quite intrigued about the sub problem of just calculating the number of combinations. I suspect there's a closed-form equation for it.

Do you have to put Task.Run in a method to make it async?

One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.

private Task<int> DoWorkAsync()
{
    //create a task completion source
    //the type of the result value must be the same
    //as the type in the returning Task
    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
    Task.Run(() =>
    {
        int result = 1 + 2;
        //set the result to TaskCompletionSource
        tcs.SetResult(result);
    });
    //return the Task
    return tcs.Task;
}

private async void DoWork()
{
    int result = await DoWorkAsync();
}

How do you auto format code in Visual Studio?

Select the text you want to automatically indent.

Click Format Selection in Edit, Advanced, or press CTRL+K, CTRL+F. Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.

Step (1) :- CTRL+A

Step (2) :- CTRL+K

Step (3) :- CTRL+F

IIS Manager in Windows 10

Press the Windows Key and type Windows Features, select the first entry Turn Windows Features On or Off.

Make sure the box next to IIS is checked. You good to go.

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write() from such a script (well technically you can, but it won't do what you want).

You will need to replace any document.write() statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild() or .insertBefore() or setting .innerHTML or some mechanism for direct DOM manipulation like that.

For example, instead of this type of code in an inline script:

<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>

You would use this to replace the inline script above in a dynamically loaded script:

var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);

Or, if there was no other content in the container that you needed to just append to, you could simply do this:

var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';

Java: Static vs inner class

static inner class: can declare static & non static members but can only access static members of its parents class.

non static inner class: can declare only non static members but can access static and non static member of its parent class.

Android Studio: Module won't show up in "Edit Configuration"

I finally figure out why the module is not showed up when I add configuration for AndroidTests for a com.android.library module.

If you include your library module in your application's build.gradle like this:

compile project(':yourlibrary')

Since for library module it is compiled with release mode by default, you can't run Android Tests for it, that's why it won't show up in the module list. I fixed it with following modification:

Add following configuration to the build.gradle of your library module:

     publishNonDefault true

By make following changes, you can debug compile your library by editing the build.gradle of your application module like following:

-    compile project(':yourlibrary')
+    debugCompile project(path: ':yourlibrary', configuration: 'debug')
+    releaseCompile project(path: ':yourlibrary', configuration: 'release')

Then sync it and you'll find it shows in the list.

Firing a Keyboard Event in Safari, using JavaScript

This is due to a bug in Webkit.

You can work around the Webkit bug using createEvent('Event') rather than createEvent('KeyboardEvent'), and then assigning the keyCode property. See this answer and this example.

How to check command line parameter in ".bat" file?

Look at http://ss64.com/nt/if.html for an answer; the command is IF [%1]==[] GOTO NO_ARGUMENT or similar.

Laravel Pagination links not including other GET parameters

I think you should use this code in Laravel version 5+. Also this will work not only with parameter page but also with any other parameter(s):

$users->appends(request()->input())->links();

Personally, I try to avoid using Facades as much as I can. Using global helper functions is less code and much elegant.

UPDATE:

Do not use Input Facade as it is deprecated in Laravel v6+

How to go up a level in the src path of a URL in HTML?

Use ../:

background-image: url('../images/bg.png');

You can use that as often as you want, e.g. ../../images/ or even at different positions, e.g. ../images/../images/../images/ (same as ../images/ of course)

Whitespaces in java

boolean containsWhitespace = false;
for (int i = 0; i < text.length() && !containsWhitespace; i++) {
    if (Character.isWhitespace(text.charAt(i)) {
        containsWhitespace = true;
    }
}
return containsWhitespace;

or, using Guava,

boolean containsWhitespace = CharMatcher.WHITESPACE.matchesAnyOf(text);

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

How can I make Bootstrap columns all the same height?

You can use inline-flex as well which works pretty good and may be a little cleaner than modifying every row element with CSS.

For my project I wanted every row who's child elements had borders to be the same height so the borders would look jagged. For this I created a simple css class.

.row.borders{
    display: inline-flex;
    width: 100%;
}

How do I select an element in jQuery by using a variable for the ID?

You can do it like this:

row_id = 5;
row = $("body").find('#'+row_id);

Checking if type == list in python

You should try using isinstance()

if isinstance(object, list):
       ## DO what you want

In your case

if isinstance(tmpDict[key], list):
      ## DO SOMETHING

To elaborate:

x = [1,2,3]
if type(x) == list():
    print "This wont work"
if type(x) == list:                  ## one of the way to see if it's list
    print "this will work"           
if type(x) == type(list()):
    print "lets see if this works"
if isinstance(x, list):              ## most preferred way to check if it's list
    print "This should work just fine"

The difference between isinstance() and type() though both seems to do the same job is that isinstance() checks for subclasses in addition, while type() doesn’t.

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

What does "The APR based Apache Tomcat Native library was not found" mean?

I had the same problem when tom?at could not find the class. Try to view other log files. Sometimes No class def found error appears in different log files:

  • tomcat8-stdout
  • tomcat8-stderr
  • localhost

How to use paths in tsconfig.json?

Alejandros answer worked for me, but as I'm using the awesome-typescript-loader with webpack 4, I also had to add the tsconfig-paths-webpack-plugin to my webpack.config file for it to resolve correctly

Why is the console window closing immediately once displayed my output?

I assume the reason you don't want it to close in Debug mode, is because you want to look at the values of variables etc. So it's probably best to just insert a break-point on the closing "}" of the main function. If you don't need to debug, then Ctrl-F5 is the best option.

How to access the services from RESTful API in my angularjs page?

Just to expand on $http (shortcut methods) here: http://docs.angularjs.org/api/ng.$http

//Snippet from the page

$http.get('/someUrl').success(successCallback);
$http.post('/someUrl', data).success(successCallback);

//available shortcut methods

$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp

Touch move getting stuck Ignored attempt to cancel a touchmove

I had this problem and all I had to do is return true from touchend and the warning went away.

How to turn on/off MySQL strict mode in localhost (xampp)?

In my case, I need to add:

sql_mode="STRICT_TRANS_TABLES"

under [mysqld] in the file my.ini located in C:\xampp\mysql\bin.

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

How can I color a UIImage in Swift?

Swift 3 extension wrapper from @Nikolai Ruhe answer.

extension UIImageView {

    func maskWith(color: UIColor) {
        guard let tempImage = image?.withRenderingMode(.alwaysTemplate) else { return }
        image = tempImage
        tintColor = color
    }

}

It can be use for UIButton as well, e.g:

button.imageView?.maskWith(color: .blue)

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

In order to better understand [] and new Array():

> []
  []
> new Array()
  []
> [] == []
  false
> [] === []
  false
> new Array() == new Array()
  false
> new Array() === new Array()
  false
> typeof ([])
  "object"
> typeof (new Array())
  "object"
> [] === new Array()
  false
> [] == new Array()
  false

The above result is from Google Chrome console on Windows 7.

How to change UINavigationBar background color from the AppDelegate

In Swift 4.2 and Xcode 10.1

You can change your navigation bar colour from your AppDelegate directly to your entire project.

In didFinishLaunchingWithOptions launchOptions: write below to lines of code

UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)

Here

tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)

barTintColor is for navigation bar background colour

If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()

//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white

enter image description here

Find the index of a dict within a list, by matching the dict's value

One liner!?

elm = ([i for i in mylist if i['name'] == 'Tom'] or [None])[0]

Format specifier %02x

%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.

What's the difference between map() and flatMap() methods in Java 8?

.map is for A -> B mapping

Stream.of("dog", "cat")              // stream of 2 Strings
    .map(s -> s.length())            // stream of 2 Integers: [3, 3]

it converts any item A to any item B. Javadoc


.flatMap is for A -> Stream< B> concatinating

Stream.of("dog", "cat")             // stream of 2 Strings
    .flatMapToInt(s -> s.chars())   // stream of 6 ints:      [d, o, g, c, a, t]

it --1 converts any item A into Stream< B>, then --2 concatenates all the streams into one (flat) stream. Javadoc


Note 1: Although the latter example flats to a stream of primitives (IntStream) instead of a stream of objects (Stream), it still illustrates the idea of the .flatMap.

Note 2: Despite the name, String.chars() method returns ints. So the actual collection will be: [100, 111, 103, 99, 97, 116] , where 100 is the code of 'd', 111 is the code of 'o' etc. Again, for illustrative purposes, it's presented as [d, o, g, c, a, t].

Is there a way to collapse all code blocks in Eclipse?

Shortcuts that worked for me in Versions Oxygen.2 Release (PHP/WINDOWS 7) were

  1. Collapse all code blocks: CTRL + SHIFT + NUMPAD_DIVIDE
  2. Expand all code blocks : CTRL + NUMPAD_MULTIPLY

C# - Fill a combo box with a DataTable

You need to set the binding context of the ToolStripComboBox.ComboBox.

Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.

I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?

If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.

var languages = new string[2];
languages[0] = "English";
languages[1] = "German";

DataSet myDataSet = new DataSet();

// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add(lName);

for (int i = 0; i < languages.Length; i++)
{
    DataRow lLang = lTable.NewRow();
    lLang["Language"] = languages[i];
    lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);

toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
toolStripComboBox1.ComboBox.DisplayMember = "Language";

toolStripComboBox1.ComboBox.BindingContext = this.BindingContext;

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

python3x or higher

  1. load file in byte stream:
     body = ''
        for lines in open('website/index.html','rb'):
            decodedLine = lines.decode('utf-8')
            body = body+decodedLine.strip()
        return body
  1. use global setting:
    import io
    import sys
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

HTML tag inside JavaScript

You will either have to document.write it or use the Document Object Model:

Example using document.write

<script type="text/javascript">
if(document.getElementById('number1').checked) {
    document.write("<h1>Hello member</h1>");
}
</script>

Example using DOM

<h1></h1> <!-- We are targeting this tag with JS. See code below -->
<input type="checkbox" id="number1" checked /><label for="number1">Agree</label>
<div id="container"> <p>Content</p> </div>

<script type="text/javascript">
window.onload = function() {
    if( document.getElementById('number1').checked ) {
        var h1 = document.createElement("h1");
        h1.appendChild(document.createTextNode("Hello member"));
        document.getElementById("container").appendChild(h1);
    }
}
</script>

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Pass value to iframe from a window

Here's another solution, usable if the frames are from different domains.

var frame = /*the iframe DOM object*/;
frame.contentWindow.postMessage({call:'sendValue', value: /*value*/}, /*frame domain url or '*'*/);

And in the frame itself:

window.addEventListener('message', function(event) {
    var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
    if (origin !== /*the container's domain url*/)
        return;
    if (typeof event.data == 'object' && event.data.call=='sendValue') {
        // Do something with event.data.value;
    }
}, false);

Don't know which browsers support this, though.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

setTimeout in for-loop does not print consecutive values

Well, another working solution based on Cody's answer but a little more general can be something like this:

function timedAlert(msg, timing){
    setTimeout(function(){
        alert(msg);    
    }, timing);
}

function yourFunction(time, counter){
    for (var i = 1; i <= counter; i++) {
        var msg = i, timing = i * time * 1000; //this is in seconds
        timedAlert (msg, timing);
    };
}

yourFunction(timeInSeconds, counter); // well here are the values of your choice.

'import' and 'export' may only appear at the top level

My error is caused by a System.import('xxx.js') statment. After replacing it with import xxx from 'xxx.js', the error solved.

I think it is because require('xxx.scss') also caused a dynamic import.

For the case in the question description, in my opinion, dynamic imports is not necessary, so the problem should be solved by just replacing all requires with import ... from ....

For some case which dynamic imports are necessary, you may need @babel/plugin-syntax-dynamic-import as other answers in this question.

Convert xlsx to csv in Linux with command line

The Gnumeric spreadsheet application comes with a command line utility called ssconvert that can convert between a variety of spreadsheet formats:

$ ssconvert Book1.xlsx newfile.csv
Using exporter Gnumeric_stf:stf_csv

$ cat newfile.csv 
Foo,Bar,Baz
1,2,3
123.6,7.89,
2012/05/14,,
The,last,Line

To install on Ubuntu:

apt-get install gnumeric

To install on Mac:

brew install gnumeric

How to group by week in MySQL?

You can use both YEAR(timestamp) and WEEK(timestamp), and use both of the these expressions in the SELECT and the GROUP BY clause.

Not overly elegant, but functional...

And of course you can combine these two date parts in a single expression as well, i.e. something like

SELECT CONCAT(YEAR(timestamp), '/', WEEK(timestamp)), etc...
FROM ...
WHERE ..
GROUP BY CONCAT(YEAR(timestamp), '/', WEEK(timestamp))

Edit: As Martin points out you can also use the YEARWEEK(mysqldatefield) function, although its output is not as eye friendly as the longer formula above.


Edit 2 [3 1/2 years later!]:
YEARWEEK(mysqldatefield) with the optional second argument (mode) set to either 0 or 2 is probably the best way to aggregate by complete weeks (i.e. including for weeks which straddle over January 1st), if that is what is desired. The YEAR() / WEEK() approach initially proposed in this answer has the effect of splitting the aggregated data for such "straddling" weeks in two: one with the former year, one with the new year.
A clean-cut every year, at the cost of having up to two partial weeks, one at either end, is often desired in accounting etc. and for that the YEAR() / WEEK() approach is better.

Append Char To String in C?

I do not think you can declare a string like that in c. You may only do that for const char* and of course you can not modify a const char * as it is const.

You may use dynamic char array but you will have to take care of the reallocation.

EDIT: in fact this syntax compiles correctly. Still you can should not modify what str points to if it is initialized in the way you do it (from string literal)

Passing std::string by Value or Reference

There are multiple answers based on what you are doing with the string.

1) Using the string as an id (will not be modified). Passing it in by const reference is probably the best idea here: (std::string const&)

2) Modifying the string but not wanting the caller to see that change. Passing it in by value is preferable: (std::string)

3) Modifying the string but wanting the caller to see that change. Passing it in by reference is preferable: (std::string &)

4) Sending the string into the function and the caller of the function will never use the string again. Using move semantics might be an option (std::string &&)

Getting scroll bar width using JavaScript

This function should give you width of scrollbar

function getScrollbarWidth() {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

Basic steps here are:

  1. Create hidden div (outer) and get it's offset width
  2. Force scroll bars to appear in div (outer) using CSS overflow property
  3. Create new div (inner) and append to outer, set its width to '100%' and get offset width
  4. Calculate scrollbar width based on gathered offsets

Working example here: http://jsfiddle.net/slavafomin/tsrmgcu9/

Update

If you're using this on a Windows (metro) App, make sure you set the -ms-overflow-style property of the 'outer' div to scrollbar, otherwise the width will not be correctly detected. (code updated)

Update #2 This will not work on Mac OS with the default "Only show scrollbars when scrolling" setting (Yosemite and up).

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

You can set TextBox properties for setting negative number display and decimal places settings.

  1. Right-click the cell and then click Text Box Properties.
  2. Select Number, and in the Category field, click Currency.

enter image description here

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

How to set the JSTL variable value in javascript?

Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.

Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.

Using colors with printf

This is a little function that prints colored text using bash scripting. You may add as many styles as you want, and even print tabs and new lines:

#!/bin/bash

# prints colored text
print_style () {

    if [ "$2" == "info" ] ; then
        COLOR="96m";
    elif [ "$2" == "success" ] ; then
        COLOR="92m";
    elif [ "$2" == "warning" ] ; then
        COLOR="93m";
    elif [ "$2" == "danger" ] ; then
        COLOR="91m";
    else #default color
        COLOR="0m";
    fi

    STARTCOLOR="\e[$COLOR";
    ENDCOLOR="\e[0m";

    printf "$STARTCOLOR%b$ENDCOLOR" "$1";
}

print_style "This is a green text " "success";
print_style "This is a yellow text " "warning";
print_style "This is a light blue with a \t tab " "info";
print_style "This is a red text with a \n new line " "danger";
print_style "This has no color";