Programs & Examples On #Raid

RAID (Redundant Array of Independent Disks) is a technology that provides increased storage functions and reliability through redundancy.

Node.js heap out of memory

If I remember correctly, there is a strict standard limit for the memory usage in V8 of around 1.7 GB, if you do not increase it manually.

In one of our products we followed this solution in our deploy script:

 node --max-old-space-size=4096 yourFile.js

There would also be a new space command but as I read here: a-tour-of-v8-garbage-collection the new space only collects the newly created short-term data and the old space contains all referenced data structures which should be in your case the best option.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

REST API - file (ie images) processing - best practices

There are several decisions to make:

  1. The first about resource path:

    • Model the image as a resource on its own:

      • Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly

      • In the root path (/image):

        • The client is held responsible for establishing the relationship between the image and the user, or;

        • If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.

    • Embed the image as part of the user

  2. The second decision is about how to represent the image resource:

    • As Base 64 encoded JSON payload
    • As a multipart payload

This would be my decision track:

  • I usually favor design over performance unless there is a strong case for it. It makes the system more maintainable and can be more easily understood by integrators.
  • So my first thought is to go for a Base64 representation of the image resource because it lets you keep everything JSON. If you chose this option you can model the resource path as you like.
    • If the relationship between user and image is 1 to 1 I'd favor to model the image as an attribute specially if both data sets are updated at the same time. In any other case you can freely choose to model the image either as an attribute, updating the it via PUT or PATCH, or as a separate resource.
  • If you choose multipart payload I'd feel compelled to model the image as a resource on is own, so that other resources, in our case, the user resource, is not impacted by the decision of using a binary representation for the image.

Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.

My choice Base64:

  • Consistent design decision
  • Negligible performance impact
  • As browsers understand data URIs (base64 encoded images), there is no need to transform these if the client is a browser
  • I won't cast a vote on whether to have it as an attribute or standalone resource, it depends on your problem domain (which I don't know) and your personal preference.

Google Chrome forcing download of "f.txt" file

This can occur on android too not just computers. Was browsing using Kiwi when the site I was on began to endlessly redirect so I cut net access to close it out and noticed my phone had DL'd something f.txt in my downloaded files.

Deleted it and didn't open.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Looks like the solution has been baked into Homebrew now:

$ brew info postgresql
...
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database
....

Error: getaddrinfo ENOTFOUND in nodejs for get call

When I tried to install a new ionic app, I got the same error as follows, I tried many sources and found the mistake made in User Environment and System Environment unnecessarily included the PROXY value. I removed the ```user variables http://host:port PROXY

system Variables http_proxy http://username:password@host:port ```` and now it is working fine without trouble.

[ERROR] Network connectivity error occurred, are you offline?

        If you are behind a firewall and need to configure proxy settings, see: https://ion.link/cli-proxy-docs

        Error: getaddrinfo ENOTFOUND host host:80

Python, remove all non-alphabet chars from string

Use re.sub

import re

regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'

Alternatively, if you only want to remove a certain set of characters (as an apostrophe might be okay in your input...)

regex = re.compile('[,\.!?]') #etc.

How to use the 'main' parameter in package.json?

As far as I know, it's the main entry point to your node package (library) for npm. It's needed if your npm project becomes a node package (library) which can be installed via npm by others.


Let's say you have a library with a build/, dist/, or lib/ folder. In this folder, you got the following compiled file for your library:

-lib/
--bundle.js

Then in your package.json, you tell npm how to access the library (node package):

{
  "name": "my-library-name",
  "main": "lib/bundle.js",
  ...
}

After installing the node package with npm to your JS project, you can import functionalities from your bundled bundle.js file:

import { add, subtract } from 'my-library-name';

This holds also true when using Code Splitting (e.g. Webpack) for your library. For instance, this webpack.config.js makes use of code splitting the project into multiple bundles instead of one.

module.exports = {
  entry: {
    main: './src/index.js',
    add: './src/add.js',
    subtract: './src/subtract.js',
  },
  output: {
    path: `${__dirname}/lib`,
    filename: '[name].js',
    library: 'my-library-name',
    libraryTarget: 'umd',
  },
  ...
}

Still, you would define one main entry point to your library in your package.json:

{
  "name": "my-library-name",
  "main": "lib/main.js",
  ...
}

Then when using the library, you can import your files from your main entry point:

import { add, subtract } from 'my-library-name';

However, you can also bypass the main entry point from the package.json and import the code splitted bundles:

import add from 'my-library-name/lib/add';
import subtract from 'my-library-name/lib/subtract';

After all, the main property in your package.json only points to your main entry point file of your library.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Implementing IDisposable correctly

I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:

https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About

The only other thing that would likely be helpful is suppressing that code analysis warning... https://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017

Style disabled button with CSS

For the disabled buttons you can use the :disabled pseudo-element. It works for all the elements.

For browsers/devices supporting CSS2 only, you can use the [disabled] selector.

As with the image, don't put an image in the button. Use CSS background-image with background-position and background-repeat. That way, the image dragging will not occur.

Selection problem: here is a link to the specific question:

Example for the disabled selector:

_x000D_
_x000D_
button {_x000D_
  border: 1px solid #0066cc;_x000D_
  background-color: #0099cc;_x000D_
  color: #ffffff;_x000D_
  padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  border: 1px solid #0099cc;_x000D_
  background-color: #00aacc;_x000D_
  color: #ffffff;_x000D_
  padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:disabled,_x000D_
button[disabled]{_x000D_
  border: 1px solid #999999;_x000D_
  background-color: #cccccc;_x000D_
  color: #666666;_x000D_
}_x000D_
_x000D_
div {_x000D_
  padding: 5px 10px;_x000D_
}
_x000D_
<div>_x000D_
  <button> This is a working button </button>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <button disabled> This is a disabled button </button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android: How to use webcam in emulator?

I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :

http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html

His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.

Error: The 'brew link' step did not complete successfully

Had been wrecking my head on symlinking node .. and nothing seemed to work...but finally what worked is setting the right permissions . This 'sudo chown -R $(whoami) /usr/local' did the work for me.

How can I revert multiple Git commits (already pushed) to a published repository?

If you've already pushed things to a remote server (and you have other developers working off the same remote branch) the important thing to bear in mind is that you don't want to rewrite history

Don't use git reset --hard

You need to revert changes, otherwise any checkout that has the removed commits in its history will add them back to the remote repository the next time they push; and any other checkout will pull them in on the next pull thereafter.

If you have not pushed changes to a remote, you can use

git reset --hard <hash>

If you have pushed changes, but are sure nobody has pulled them you can use

git reset --hard
git push -f

If you have pushed changes, and someone has pulled them into their checkout you can still do it but the other team-member/checkout would need to collaborate:

(you) git reset --hard <hash>
(you) git push -f

(them) git fetch
(them) git reset --hard origin/branch

But generally speaking that's turning into a mess. So, reverting:

The commits to remove are the lastest

This is possibly the most common case, you've done something - you've pushed them out and then realized they shouldn't exist.

First you need to identify the commit to which you want to go back to, you can do that with:

git log

just look for the commit before your changes, and note the commit hash. you can limit the log to the most resent commits using the -n flag: git log -n 5

Then reset your branch to the state you want your other developers to see:

git revert  <hash of first borked commit>..HEAD

The final step is to create your own local branch reapplying your reverted changes:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Continue working in my-new-branch until you're done, then merge it in to your main development branch.

The commits to remove are intermingled with other commits

If the commits you want to revert are not all together, it's probably easiest to revert them individually. Again using git log find the commits you want to remove and then:

git revert <hash>
git revert <another hash>
..

Then, again, create your branch for continuing your work:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Then again, hack away and merge in when you're done.

You should end up with a commit history which looks like this on my-new-branch

2012-05-28 10:11 AD7six             o [my-new-branch] Revert "Revert "another mistake""
2012-05-28 10:11 AD7six             o Revert "Revert "committing a mistake""
2012-05-28 10:09 AD7six             o [master] Revert "committing a mistake"
2012-05-28 10:09 AD7six             o Revert "another mistake"
2012-05-28 10:08 AD7six             o another mistake
2012-05-28 10:08 AD7six             o committing a mistake
2012-05-28 10:05 Bob                I XYZ nearly works

Better way®

Especially that now that you're aware of the dangers of several developers working in the same branch, consider using feature branches always for your work. All that means is working in a branch until something is finished, and only then merge it to your main branch. Also consider using tools such as git-flow to automate branch creation in a consistent way.

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

use this syntax: alter table table_name modify column col_name varchar (10000);

How to clear/remove observable bindings in Knockout.js?

You could try using the with binding that knockout offers: http://knockoutjs.com/documentation/with-binding.html The idea is to use apply bindings once, and whenever your data changes, just update your model.

Lets say you have a top level view model storeViewModel, your cart represented by cartViewModel, and a list of items in that cart - say cartItemsViewModel.

You would bind the top level model - the storeViewModel to the whole page. Then, you could separate the parts of your page that are responsible for cart or cart items.

Lets assume that the cartItemsViewModel has the following structure:

var actualCartItemsModel = { CartItems: [
  { ItemName: "FirstItem", Price: 12 }, 
  { ItemName: "SecondItem", Price: 10 }
] }

The cartItemsViewModel can be empty at the beginning.

The steps would look like this:

  1. Define bindings in html. Separate the cartItemsViewModel binding.

      
        <div data-bind="with: cartItemsViewModel">
          <div data-bind="foreach: CartItems">
            <span data-bind="text: ItemName"></span>
            <span data-bind="text: Price"></span>
          </div>
        </div>
      
    
  2. The store model comes from your server (or is created in any other way).

    var storeViewModel = ko.mapping.fromJS(modelFromServer)

  3. Define empty models on your top level view model. Then a structure of that model can be updated with actual data.

      
        storeViewModel.cartItemsViewModel = ko.observable();
        storeViewModel.cartViewModel = ko.observable();
     
    
  4. Bind the top level view model.

    ko.applyBindings(storeViewModel);

  5. When the cartItemsViewModel object is available then assign it to the previously defined placeholder.

    storeViewModel.cartItemsViewModel(actualCartItemsModel);

If you would like to clear the cart items: storeViewModel.cartItemsViewModel(null);

Knockout will take care of html - i.e. it will appear when model is not empty and the contents of div (the one with the "with binding") will disappear.

How do I search an SQL Server database for a string?

This will search every column of every table in a specific database. Create the stored procedure on the database that you want to search in.

The Ten Most Asked SQL Server Questions And Their Answers:

CREATE PROCEDURE FindMyData_String
    @DataToFind NVARCHAR(4000),
    @ExactMatch BIT = 0
AS
SET NOCOUNT ON

DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)

    INSERT  INTO @Temp(TableName,SchemaName, ColumnName, DataType)
    SELECT  C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
    FROM    Information_Schema.Columns AS C
            INNER Join Information_Schema.Tables AS T
                ON C.Table_Name = T.Table_Name
        AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
    WHERE   Table_Type = 'Base Table'
            And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')


DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)

SELECT  @SQLTemplate = CASE WHEN @ExactMatch = 1
                            THEN 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       = ''' + @DataToFind + '''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            ELSE 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       Like ''%' + @DataToFind + '%''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            END,
        @PARAMETERS = '@DataExists Bit OUTPUT',
        @i = 1

SELECT @i = 1, @MAX = MAX(RowId)
FROM   @Temp

WHILE @i <= @MAX
    BEGIN
        SELECT  @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
        FROM    @Temp
        WHERE   RowId = @i


        PRINT @SQL
        EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT

        IF @DataExists =1
            UPDATE @Temp SET DataFound = 1 WHERE RowId = @i

        SET @i = @i + 1
    END

SELECT  SchemaName,TableName, ColumnName
FROM    @Temp
WHERE   DataFound = 1
GO

To run it, just do this:

exec FindMyData_string 'google', 0

It works amazingly well!!!

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

Console.log(); How to & Debugging javascript

console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.

It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.

To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.

How to make external HTTP requests with Node.js

I would combine node-http-proxy and express.

node-http-proxy will support a proxy inside your node.js web server via RoutingProxy (see the example called Proxy requests within another http server).

Inside your custom server logic you can do authentication using express. See the auth sample here for an example.

Combining those two examples should give you what you want.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

I had a similar problem. Using size_t was not working. I tried the other one which worked for me. (as below)

for(int i = things.size()-1;i>=0;i--)
{
 //...
}

Multiple inputs on one line

Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:

cin >> a;
cin >> b;
cin >> c;

This is due to a technique called "operator chaining".

Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.

Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.

SQL Server - after insert trigger - update another column in the same table

Yea...having an additional step to update a table in which you can set the value in the inital insert is probably an extra, avoidable process. Do you have access to the original insert statement where you can actually just insert the part_description into the part_description_upper column using UPPER(part_description) value?

After thinking, you probably don't have access as you would have probably done that so should also give some options as well...

1) Depends on the need for this part_description_upper column, if just for "viewing" then can just use the returned part_description value and "ToUpper()" it (depending on programming language).

2) If want to avoid "realtime" processing, can just create a sql job to go through your values once a day during low traffic periods and update that column to the UPPER part_description value for any that are currently not set.

3) go with your trigger (and watch for recursion as others have mentioned)...

HTH

Dave

click or change event on radio using jquery

_x000D_
_x000D_
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
     console.log(e.type);_x000D_
     return false;_x000D_
});
_x000D_
_x000D_
_x000D_

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.

Difference in months between two dates

Public Class ClassDateOperation
    Private prop_DifferenceInDay As Integer
    Private prop_DifferenceInMonth As Integer
    Private prop_DifferenceInYear As Integer


    Public Function DayMonthYearFromTwoDate(ByVal DateStart As Date, ByVal DateEnd As Date) As ClassDateOperation
        Dim differenceInDay As Integer
        Dim differenceInMonth As Integer
        Dim differenceInYear As Integer
        Dim myDate As Date

        DateEnd = DateEnd.AddDays(1)

        differenceInYear = DateEnd.Year - DateStart.Year

        If DateStart.Month <= DateEnd.Month Then
            differenceInMonth = DateEnd.Month - DateStart.Month
        Else
            differenceInYear -= 1
            differenceInMonth = (12 - DateStart.Month) + DateEnd.Month
        End If


        If DateStart.Day <= DateEnd.Day Then
            differenceInDay = DateEnd.Day - DateStart.Day
        Else

            myDate = CDate("01/" & DateStart.AddMonths(1).Month & "/" & DateStart.Year).AddDays(-1)
            If differenceInMonth <> 0 Then
                differenceInMonth -= 1
            Else
                differenceInMonth = 11
                differenceInYear -= 1
            End If

            differenceInDay = myDate.Day - DateStart.Day + DateEnd.Day

        End If

        prop_DifferenceInDay = differenceInDay
        prop_DifferenceInMonth = differenceInMonth
        prop_DifferenceInYear = differenceInYear

        Return Me
    End Function

    Public ReadOnly Property DifferenceInDay() As Integer
        Get
            Return prop_DifferenceInDay
        End Get
    End Property

    Public ReadOnly Property DifferenceInMonth As Integer
        Get
            Return prop_DifferenceInMonth
        End Get
    End Property

    Public ReadOnly Property DifferenceInYear As Integer
        Get
            Return prop_DifferenceInYear
        End Get
    End Property

End Class

How do I remove the old history from a git repository?

According to the Git repo of the BFG tool, it "removes large or troublesome blobs as git-filter-branch does, but faster - and is written in Scala".

https://github.com/rtyley/bfg-repo-cleaner

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

Script not served by static file handler on IIS7.5

Navigate to your flavor of .Net and CPU architecture directory using CMD or powershell

Enter this command: aspnet_regiis –r

C dynamically growing array

As with everything that seems scarier at first than it was later, the best way to get over the initial fear is to immerse yourself into the discomfort of the unknown! It is at times like that which we learn the most, after all.

Unfortunately, there are limitations. While you're still learning to use a function, you shouldn't assume the role of a teacher, for example. I often read answers from those who seemingly don't know how to use realloc (i.e. the currently accepted answer!) telling others how to use it incorrectly, occasionally under the guise that they've omitted error handling, even though this is a common pitfall which needs mention. Here's an answer explaining how to use realloc correctly. Take note that the answer is storing the return value into a different variable in order to perform error checking.

Every time you call a function, and every time you use an array, you are using a pointer. The conversions are occurring implicitly, which if anything should be even scarier, as it's the things we don't see which often cause the most problems. For example, memory leaks...

Array operators are pointer operators. array[x] is really a shortcut for *(array + x), which can be broken down into: * and (array + x). It's most likely that the * is what confuses you. We can further eliminate the addition from the problem by assuming x to be 0, thus, array[0] becomes *array because adding 0 won't change the value...

... and thus we can see that *array is equivalent to array[0]. You can use one where you want to use the other, and vice versa. Array operators are pointer operators.

malloc, realloc and friends don't invent the concept of a pointer which you've been using all along; they merely use this to implement some other feature, which is a different form of storage duration, most suitable when you desire drastic, dynamic changes in size.

It is a shame that the currently accepted answer also goes against the grain of some other very well-founded advice on StackOverflow, and at the same time, misses an opportunity to introduce a little-known feature which shines for exactly this usecase: flexible array members! That's actually a pretty broken answer... :(

When you define your struct, declare your array at the end of the structure, without any upper bound. For example:

struct int_list {
    size_t size;
    int value[];
};

This will allow you to unite your array of int into the same allocation as your count, and having them bound like this can be very handy!

sizeof (struct int_list) will act as though value has a size of 0, so it'll tell you the size of the structure with an empty list. You still need to add to the size passed to realloc to specify the size of your list.

Another handy tip is to remember that realloc(NULL, x) is equivalent to malloc(x), and we can use this to simplify our code. For example:

int push_back(struct int_list **fubar, int value) {
    size_t x = *fubar ? fubar[0]->size : 0
         , y = x + 1;

    if ((x & y) == 0) {
        void *temp = realloc(*fubar, sizeof **fubar
                                   + (x + y) * sizeof fubar[0]->value[0]);
        if (!temp) { return 1; }
        *fubar = temp; // or, if you like, `fubar[0] = temp;`
    }

    fubar[0]->value[x] = value;
    fubar[0]->size = y;
    return 0;
}

struct int_list *array = NULL;

The reason I chose to use struct int_list ** as the first argument may not seem immediately obvious, but if you think about the second argument, any changes made to value from within push_back would not be visible to the function we're calling from, right? The same goes for the first argument, and we need to be able to modify our array, not just here but possibly also in any other function/s we pass it to...

array starts off pointing at nothing; it is an empty list. Initialising it is the same as adding to it. For example:

struct int_list *array = NULL;
if (!push_back(&array, 42)) {
    // success!
}

P.S. Remember to free(array); when you're done with it!

Why in C++ do we use DWORD rather than unsigned int?

For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.

DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform

A good Sorted List for Java

Generally you can't have constant time look up and log time deletions/insertions, but if you're happy with log time look ups then you can use a SortedList.

Not sure if you'll trust my coding but I recently wrote a SortedList implementation in Java, which you can download from http://www.scottlogic.co.uk/2010/12/sorted_lists_in_java/. This implementation allows you to look up the i-th element of the list in log time.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Normally, you run IE 32 bit.
However, on 64-bit versions of Windows, there is a separate link in the Start Menu to Internet Explorer (64 bit). There's no real reason to use it, though.

In Help, About, the 64-bit version of IE will say 64-bit Edition (just after the full version string).

The 32-bit and 64-bit versions of IE have separate addons lists (because 32-bit addons cannot be loaded in 64-bit IE, and vice-versa), so you should make sure that Java appears on both lists.

In general, you can tell whether a process is 32-bit or 64-bit by right-clicking the application in Task Manager and clicking Go To Process. 32-bit processes will end with *32.

Sort array by value alphabetically php

  • If you just want to sort the array values and don't care for the keys, use sort(). This will give a new array with numeric keys starting from 0.
  • If you want to keep the key-value associations, use asort().

See also the comparison table of sorting functions in PHP.

How to generate unique id in MySQL?

I use UUID() to create a unique value.

example:

insert into Companies (CompanyID, CompanyName) Values(UUID(), "TestUUID");

Port 80 is being used by SYSTEM (PID 4), what is that?

I knew these answers were right , but my services.msc was not showing the services, however this did the trick:

sc stop "MsDepSvc" 
sc config "MsDepSvc" start= disabled 

Why do I need an IoC container as opposed to straightforward DI code?

IoC Containers are also good for loading deeply nested class dependencies. For example if you had the following code using Depedency Injection.

public void GetPresenter()
{
    var presenter = new CustomerPresenter(new CustomerService(new CustomerRepository(new DB())));
}

class CustomerPresenter
{
    private readonly ICustomerService service;
    public CustomerPresenter(ICustomerService service)
    {
        this.service = service;
    }
}

class CustomerService
{
    private readonly IRespository<Customer> repository;
    public CustomerService(IRespository<Customer> repository)
    {
        this.repository = repository;
    }
}

class CustomerRepository : IRespository<Customer>
{
    private readonly DB db;
    public CustomerRepository(DB db)
    {
        this.db = db;
    }
}

class DB { }

If you had all of these dependencies loaded into and IoC container you could Resolve the CustomerService and the all the child dependencies will automatically get resolved.

For example:

public static IoC
{
   private IUnityContainer _container;
   static IoC()
   {
       InitializeIoC();
   }

   static void InitializeIoC()
   {
      _container = new UnityContainer();
      _container.RegisterType<ICustomerService, CustomerService>();
      _container.RegisterType<IRepository<Customer>, CustomerRepository>();
   }

   static T Resolve<T>()
   {
      return _container.Resolve<T>();
   }
}

public void GetPresenter()
{
   var presenter = IoC.Resolve<CustomerPresenter>();
   // presenter is loaded and all of its nested child dependencies 
   // are automatically injected
   // -
   // Also, note that only the Interfaces need to be registered
   // the concrete types like DB and CustomerPresenter will automatically 
   // resolve.
}

CSV parsing in Java - working example..?

i had to use a csv parser about 5 years ago. seems there are at least two csv standards: http://en.wikipedia.org/wiki/Comma-separated_values and what microsoft does in excel.

i found this libaray which eats both: http://ostermiller.org/utils/CSV.html, but afaik, it has no way of inferring what data type the columns were.

When do you use varargs in Java?

I have a varargs-related fear, too:

If the caller passes in an explicit array to the method (as opposed to multiple parameters), you will receive a shared reference to that array.

If you need to store this array internally, you might want to clone it first to avoid the caller being able to change it later.

 Object[] args = new Object[] { 1, 2, 3} ;

 varArgMethod(args);  // not varArgMethod(1,2,3);

 args[2] = "something else";  // this could have unexpected side-effects

While this is not really different from passing in any kind of object whose state might change later, since the array is usually (in case of a call with multiple arguments instead of an array) a fresh one created by the compiler internally that you can safely use, this is certainly unexpected behaviour.

Executing multiple commands from a Windows cmd script

Note that you don't need semicolons in batch files. And the reason why you need to use call is that mvn itself is a batch file and batch files need to call each other with call, otherwise control does not return to the caller.

SQL Server Management Studio – tips for improving the TSQL coding process

If you work with developers, often get a sliver of code that is formatted as one long line of code, then sql pretty printer add-on for SQL Server management Studio may helps a lot with more than 60+ formatter options. http://www.dpriver.com/sqlpp/ssmsaddin.html

How to tell which disk Windows Used to Boot

You can try use simple command line. bcdedit is what you need, just run cmd as administrator and type bcdedit or bcdedit \v, this doesn't work on XP, but hope it is not an issue.

Anyway for XP you can take a look into boot.ini file.

What does += mean in Python?

FYI: it looks like you might have an infinite loop in your example...

if cnt > 0 and len(aStr) > 1:
    while cnt > 0:                  
        aStr = aStr[1:]+aStr[0]
        cnt += 1
  • a condition of entering the loop is that cnt is greater than 0
  • the loop continues to run as long as cnt is greater than 0
  • each iteration of the loop increments cnt by 1

The net result is that cnt will always be greater than 0 and the loop will never exit.

Integer.toString(int i) vs String.valueOf(int i)

There have no differences between Integer.toString(5) and String.valueOf(5);

because String.valueOf returns:

public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}

etc..

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

What is the default database path for MongoDB?

For a Windows machine start the mongod process by specifying the dbpath:

mongod --dbpath \mongodb\data

Reference: Manage mongod Processes

Pythonic way to check if a file exists?

If (when the file doesn't exist) you want to create it as empty, the simplest approach is

with open(thepath, 'a'): pass

(in Python 2.6 or better; in 2.5, this requires an "import from the future" at the top of your module).

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath):/else statement blocks are probably more suitable.

CSS "color" vs. "font-color"

I know this is an old post but as MisterZimbu stated, the color property is defining the values of other properties, as the border-color and, with CSS3, of currentColor.

currentColor is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).

Example:

_x000D_
_x000D_
.element {_x000D_
  color: green;_x000D_
  background: red;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
  border: solid 10px;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
  background: currentColor;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <div class="innerElement1"></div>_x000D_
  <div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to open a new form from another form

You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.

It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.

How to move a marker in Google Maps API

moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().

Demo: http://jsfiddle.net/ThinkingStiff/Rsp22/

HTML:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS:

#map-canvas 
{ 
height: 400px; 
width: 500px;
}

Script:

function initialize() {

    var myLatLng = new google.maps.LatLng( 50, 50 ),
        myOptions = {
            zoom: 4,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            },
        map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
        marker = new google.maps.Marker( {position: myLatLng, map: map} );

    marker.setMap( map );
    moveBus( map, marker );

}

function moveBus( map, marker ) {

    marker.setPosition( new google.maps.LatLng( 0, 0 ) );
    map.panTo( new google.maps.LatLng( 0, 0 ) );

};

initialize();

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

Disable ScrollView Programmatically?

I don't have enough points to comment on an answer, but I wanted to say that mikec's answer worked for me except that I had to change it to return !isScrollable like so:

mScroller.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      return !isScrollable;
    }
});

A simple algorithm for polygon intersection

I understand the original poster was looking for a simple solution, but unfortunately there really is no simple solution.

Nevertheless, I've recently created an open-source freeware clipping library (written in Delphi, C++ and C#) which clips all kinds of polygons (including self-intersecting ones). This library is pretty simple to use: http://sourceforge.net/projects/polyclipping/ .

Getting the class name from a static method in Java

If you are using reflection, you can get the Method object and then:

method.getDeclaringClass().getName()

To get the Method itself, you can probably use:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)

getMinutes() 0-9 - How to display two digit numbers?

Elegant ES6 function to format a date into hh:mm:ss:

const leadingZero = (num) => `0${num}`.slice(-2);

const formatTime = (date) =>
  [date.getHours(), date.getMinutes(), date.getSeconds()]
  .map(leadingZero)
  .join(':');

Check if a specific tab page is selected (active)

To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}

This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

How to call python script on excel vba?

I just came across this old post. Nothing listed above actually worked for me. I tested the script below, and it worked fine on my system. Sharing here, for the benefit of others who come here after me.

Sub RunPython()

Dim objShell As Object
Dim PythonExe, PythonScript As String

    Set objShell = VBA.CreateObject("Wscript.Shell")

    PythonExe = """C:\your_path\Python\Python38\python.exe"""
    PythonScript = "C:\your_path\from_vba.py"

    objShell.Run PythonExe & PythonScript

End Sub

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

Calculate distance between 2 GPS coordinates

Scala version

  def deg2rad(deg: Double) = deg * Math.PI / 180.0

  def rad2deg(rad: Double) = rad / Math.PI * 180.0

  def getDistanceMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double) = {
    val theta = lon1 - lon2
    val dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) *
      Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta))
    Math.abs(
      Math.round(
        rad2deg(Math.acos(dist)) * 60 * 1.1515 * 1.609344 * 1000)
    )
  }

Query Mongodb on month, day, year... of a datetime

Use the $expr operator which allows the use of aggregation expressions within the query language. This will give you the power to use the Date Aggregation Operators in your query as follows:

month = 11
db.mydatabase.mycollection.find({ 
    "$expr": { 
        "$eq": [ { "$month": "$date" }, month ] 
    } 
})

or

day = 17
db.mydatabase.mycollection.find({ 
    "$expr": { 
        "$eq": [ { "$dayOfMonth": "$date" }, day ] 
    } 
})

You could also run an aggregate operation with the aggregate() function that takes in a $redact pipeline:

month = 11
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [ { "$month": "$date" }, month ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

For the other request

day = 17
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [ { "$dayOfMonth": "$date" }, day ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Using OR

month = 11
day = 17
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$or": [ 
                        { "$eq": [ { "$month": "$date" }, month ] },
                        { "$eq": [ { "$dayOfMonth": "$date" }, day ] }
                    ] 
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Using AND

var month = 11,
    day = 17;
db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$and": [ 
                        { "$eq": [ { "$month": "$createdAt" }, month ] },
                        { "$eq": [ { "$dayOfMonth": "$createdAt" }, day ] }
                    ] 
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

The $redact operator incorporates the functionality of $project and $match pipeline and will return all documents match the condition using $$KEEP and discard from the pipeline those that don't match using the $$PRUNE variable.

List of Java processes

ps axuwww | grep java | grep -v grep

The above will

  • show you all processes with long lines (arg: www)
  • filter (grep) only lines what contain the word java, and
  • filter out the line "grep java" :)

(btw, this example is not the effective one, but simple to remember) ;)

you can pipe the above to another commands, for example:

ps axuwww | grep java | grep -v grep | sed '.....'  | while read something
do
    something_another $something
done

etc...

Read file line by line in PowerShell

Get-Content has bad performance; it tries to read the file into memory all at once.

C# (.NET) file reader reads each line one by one

Best Performace

foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
{
       $line
}

Or slightly less performant

[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
       $_
}

The foreach statement will likely be slightly faster than ForEach-Object (see comments below for more information).

How to ALTER multiple columns at once in SQL Server

Thanks to Evan's code sample, I was able to modify it more and get it more specific to tables starting with, specific column names AND handle specifics for constraints too. I ran that code and then copied the [CODE] column and executed it without issue.

USE [Table_Name]
GO
SELECT
     TABLE_CATALOG
    ,TABLE_SCHEMA
    ,TABLE_NAME
    ,COLUMN_NAME
    ,DATA_TYPE
    ,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] DROP CONSTRAINT [DEFAULT_'+TABLE_NAME+'_'+COLUMN_NAME+']; 
ALTER TABLE  ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] datetime2 (7) NOT NULL 
ALTER TABLE  ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ADD CONSTRAINT [DEFAULT_'+TABLE_NAME+'_'+COLUMN_NAME+'] DEFAULT (''3/6/2018 6:47:23 PM'') FOR ['+COLUMN_NAME+']; 
GO' AS '[CODE]'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'form_%' AND TABLE_SCHEMA = 'dbo'
 AND (COLUMN_NAME = 'FormInserted' OR COLUMN_NAME = 'FormUpdated')
 AND DATA_TYPE = 'datetime'

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How to write to a CSV line by line?

General way:

##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
    for line in text:
        file.write(line)
        file.write('\n')

OR

Using CSV writer :

import csv
with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)

OR

Simplest way:

f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

MongoDB: How to update multiple documents with a single command?

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :

db.test.update({"foo":"bar"},{"$set":{"test":"success!"}}, {multi:true} )

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

Bootstrap4 adding scrollbar to div

Use the overflow-y: scroll property on the element that contains the elements.

The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

Remove a symlink to a directory

use the "unlink" command and make sure not to have the / at the end

$ unlink mySymLink

unlink() deletes a name from the file system. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse. If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.

I think this may be problematic if I'm reading it correctly.

If the name referred to a symbolic link the link is removed.

If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.

https://linux.die.net/man/2/unlink

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

How large should my recv buffer be when calling recv in the socket library

There is no absolute answer to your question, because technology is always bound to be implementation-specific. I am assuming you are communicating in UDP because incoming buffer size does not bring problem to TCP communication.

According to RFC 768, the packet size (header-inclusive) for UDP can range from 8 to 65 515 bytes. So the fail-proof size for incoming buffer is 65 507 bytes (~64KB)

However, not all large packets can be properly routed by network devices, refer to existing discussion for more information:

What is the optimal size of a UDP packet for maximum throughput?
What is the largest Safe UDP Packet Size on the Internet

Unzip a file with php

you can use prepacked function

function unzip_file($file, $destination){
    // create object
    $zip = new ZipArchive() ;
    // open archive
    if ($zip->open($file) !== TRUE) {
        return false;
    }
    // extract contents to destination directory
    $zip->extractTo($destination);
    // close archive
    $zip->close();
        return true;
}

How to use it.

if(unzip_file($file["name"],'uploads/')){
echo 'zip archive extracted successfully';
}else{
  echo 'zip archive extraction failed';
}

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

Visual Studio Code: How to show line endings

If you want to set it to LF as default, you can go to File->Preferences->Settings and under user settings you can paste this line in below your other user settings.

"files.eol": "\n"

For example.

"git.confirmSync": false,
"window.zoomLevel": -1,
"workbench.activityBar.visible": true,
"editor.wordWrap": true,
"workbench.iconTheme": "vscode-icons",
"window.menuBarVisibility": "default",
"vsicons.projectDetection.autoReload": true,
"files.eol": "\n"

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

How do I change selected value of select2 dropdown with JqGrid?

Looking at the select2 docs you use the below to get/set the value.

$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value

@PanPipes has pointed out that this has changed for 4.x (go toss him an upvote below). val is now called directly

$("#select").val("CA");

So within the loadComplete of the jqGrid you can get whatever value you are looking for then set the selectbox value.

Notice from the docs

Notice that in order to use this method you must define the initSelection function in the options so Select2 knows how to transform the id of the object you pass in val() to the full object it needs to render selection. If you are attaching to a select element this function is already provided for you.

forEach is not a function error with JavaScript array

parent.children is not an array. It is HTMLCollection and it does not have forEach method. You can convert it to the array first. For example in ES6:

Array.from(parent.children).forEach(child => {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

Change remote repository credentials (authentication) on Intellij IDEA 14

  1. Go to [project]/.git directory.
  2. Open for edit 'config' file.
  3. In '[remote "origin"]' section find 'url' property and replace your old password with new one.
  4. Press Ctrl+T in Intellij IDEA to update project.

How do I print the content of httprequest request?

If you want the content string and this string does not have parameters you can use

    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null){
        System.out.println(line);
    }

How to compile and run C in sublime text 3?

If you code C or C++ language. I think we are lucky because we could use a file to input. It is so convenient and clear. I often do that. This is argument to implement it :

{
freopen("inputfile", "r", stdin);
}

Notice that inputfile must locate at same directory with source code file, r is stand for read.

Bootstrap modal in React.js

You can try this modal:https://github.com/xue2han/react-dynamic-modal It is stateless and can be rendered only when needed.So it is very easy to use.Just like this:

    class MyModal extends Component{
       render(){
          const { text } = this.props;
          return (
             <Modal
                onRequestClose={this.props.onRequestClose}
                openTimeoutMS={150}
                closeTimeoutMS={150}
                style={customStyle}>
                <h1>What you input : {text}</h1>
                <button onClick={ModalManager.close}>Close Modal</button>
             </Modal>
          );
       }
    }

    class App extends Component{
        openModal(){
           const text = this.refs.input.value;
           ModalManager.open(<MyModal text={text} onRequestClose={() => true}/>);
        }
        render(){
           return (
              <div>
                <div><input type="text" placeholder="input something" ref="input" /></div>
                <div><button type="button" onClick={this.openModal.bind(this)}>Open Modal </button> </div>
              </div>
           );
        }
    }

    ReactDOM.render(<App />,document.getElementById('main'));

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

I agree with Mark. I set the output to text mode and then sp_HelpText 'sproc'. I have this binded to Crtl-F1 to make it easy.

Most pythonic way to delete a file which may not exist

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()

mysql: SOURCE error 2?

It's probably the file path to your file. If you don't know the exact location of the file you want to use, try to find your file in Finder, then drag the file into Terminal window

mysql> SOURCE dragfilePathHere 

What is the <leader> in a .vimrc file?

In my system its the \ key. it's used for commands so that you can combine it with other chars.

Change Bootstrap tooltip color

This is already been answered right but i think i should give my opinion too. Like cozen says this is a border, and for it to work you must specify the classes to format this in the same way that bootstrap specifies it. So, you can do this

.tooltip .tooltip-inner {background-color: #00a8c4; color: black;} 
.tooltip.top .tooltip-arrow {border-top-color: #00a8c4;}

or you can do the next one, just for the tooltip-arrow but you must add the !important, so that it overwrites the bootstrap css

.tooltip-arrow {border-top-color: #00a8c4!important;}

mailto using javascript

No need for jQuery. And it isn't necessary to open a new window. Protocols which doesn't return HTTP data to the browser (mailto:, irc://, magnet:, ftp:// (<- it depends how it is implemented, normally the browser has an FTP client built in)) can be queried in the same window without losing the current content. In your case:

function redirect()
{
    window.location.href = "mailto:[email protected]";
}
<body onload="javascript: redirect();">

Or just directly

<body onload="javascript: window.location.href='mailto:[email protected]';">

img onclick call to JavaScript function

Put the javascript part and the end right before the closing </body> then it should work.

http://jsfiddle.net/Q3Zy3/1/

  <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
  <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>

  <script type="text/javascript">
      function exportToForm(a,b,c,d,e) {
      alert(a + b);
      window.external.values(a.value, b.value, c.value, d.value, e.value);
  }
</script>

Removing pip's cache?

If using virtualenv, look for the build directory under your environments root.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Turning PAE/NX on/off didn't work for me. I just needed to turn on virtualization on my computer. I was working on a HP Compaq 8200 and followed the steps below to turn on virtualization. If you are working on a different computer, you probably just need to look up how to turn on virtualization on your pc. The steps below for HP Compaq 8200 (or similar) is copied verbatim from the comment posted by the user qqdmax5 on Hp discussion board here.


To run Oracle VM Virtual Box / VMware machines on 64-bit host there is a need to enable Virtualization Technology (VTx) and Virtualization Technology Directed I/O (VTd).

Usually these setting are disabled on the level of BIOS.

To enable VTx and VTd you have to change corresponding settings in the BIOS.

Here is an example how to do it for HP Compaq 8200 or similar PC:

  1. Start the machine.
  2. Press F10 to enter BIOS.
  3. Security-> System Security
  4. Enable Virtualization Technology (VTx) and Virtualization Technology Directed I/O (VTd).
  5. Save and restart the machine.

There is also some discussion on this on askubuntu.

CSS3 Transition not working

Transition is more like an animation.

div.sicon a {
    background:-moz-radial-gradient(left, #ffffff 24%, #cba334 88%);
    transition: background 0.5s linear;
    -moz-transition: background 0.5s linear; /* Firefox 4 */
    -webkit-transition: background 0.5s linear; /* Safari and Chrome */
    -o-transition: background 0.5s linear; /* Opera */
    -ms-transition: background 0.5s linear; /* Explorer 10 */
}

So you need to invoke that animation with an action.

div.sicon a:hover {
    background:-moz-radial-gradient(left, #cba334 24%, #ffffff 88%);
}

Also check for browser support and if you still have some problem with whatever you're trying to do! Check css-overrides in your stylesheet and also check out for behavior: ***.htc css hacks.. there may be something overriding your transition!

You should check this out: http://www.w3schools.com/css/css3_transitions.asp

ViewDidAppear is not called when opening app from background

Just have your view controller register for the UIApplicationWillEnterForegroundNotification notification and react accordingly.

Java Returning method which returns arraylist?

Your method can be called and the arraylist can be stored like this

YourClassName class = new YourClassName();
Arraylist<Integer> numbers = class.numbers(); 

This also allows the arraylist to be manipulated further in this class

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

AngularJS Error: $injector:unpr Unknown Provider

I was getting this problem and it turned out I had included my controller both in ui.router and in the html template as in

.config(['$stateProvider',
  function($stateProvider) {
    $stateProvider.state('dashboard', {
      url: '/dashboard',
      templateUrl: 'dashboard/views/index.html',
      controller: 'DashboardController'
    });
  }
]);

and

<section data-ng-controller="DashboardController">

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.

select 
  *
from
  yourtable t
where
  /* Greater or equal to the start of last month */
  t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
  /* Smaller or equal than one month ago */
  t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)

QtCreator: No valid kits found

In my case the issue was that my default kit's Qt version was None.

Go to Tools -> Options... -> Build & Run -> Kits tab, click on the kit you want to make as default and you'll see a list of fields beneath, one of which is Qt version. If it's None, change it to one of the versions available to you in the Qt versions tab which is just next to the Kits tab.

How do you access a website running on localhost from iPhone browser

In my case first i connected my pc and mobile on the same network, you can ping your mobile from pc to test the connection.

I running my project with GGTS(Groovy/Grails Tool Suite) locally then accessing website from mobile using PC IP address and it's work very well.

PS. running from local it would give url like (http://localhost:8080/projectname) you should replace localhost with PC IP address if you are trying to access your local website from mobile

Load a HTML page within another HTML page

iframe is the tag which you can use for call other html pages into your web page

<iframe src="http://www.google.co.in" name="targetframe" allowTransparency="true" scrolling="no" frameborder="0" >
    </iframe>

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

You might be importing Application instead of Module. Well you can change it in module's gradle also.

Change

apply plugin: 'com.android.application'

to

apply plugin: 'com.android.library'

You also need to remove applicationId from the gradle.

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How can I check if a directory exists in a Bash shell script?

Actually, you should use several tools to get a bulletproof approach:

DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # Now you're testing
    echo "It's a dir";
fi

There isn't any need to worry about spaces and special characters as long as you use "${}".

Note that [[]] is not as portable as [], but since most people work with modern versions of Bash (since after all, most people don't even work with command line :-p), the benefit is greater than the trouble.

How to remove white space characters from a string in SQL Server

How about this?

CASE WHEN ProductAlternateKey is NOT NULL THEN
CONVERT(NVARCHAR(25), LTRIM(RTRIM(ProductAlternateKey))) 
FROM DimProducts
where ProductAlternateKey  like '46783815%'

PHP Error: Cannot use object of type stdClass as array (array and object issues)

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

Notice Allowed methods in the response

Connection: close
Date: Tue, 11 Feb 2014 15:17:24 GMT 
Content-Length: 34 
Content-Type: text/html 
Allow: GET, DELETE 
X-Powered-By: Servlet/2.5 JSP/2.1

It accepts only GET and DELETE. Hence, you need to tweak the server to enable PUT and POST as well.

Allow: GET, DELETE

How to generate components in a specific folder with Angular CLI?

Create a component inside a specific folder:

ng g c folder-name/component-name

Create a component inside a folder for a specific (existing) module with Angular-CLI:

ng g c folder-name/component-name --module=folder-name/moduleName.module.ts

Finding local maxima/minima with Numpy in a 1D numpy array

If you are looking for all entries in the 1d array a smaller than their neighbors, you can try

numpy.r_[True, a[1:] < a[:-1]] & numpy.r_[a[:-1] < a[1:], True]

You could also smooth your array before this step using numpy.convolve().

I don't think there is a dedicated function for this.

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • Executing Batch File in C#

    Have you tried starting it as an administrator? Start Visual Studio as an administrator if you use it, because working with .bat files requires those privileges.

    scroll up and down a div on button click using jquery

    Where did it come from scrollBottom this is not a valid property it should be scrollTop and this can be positive(+) or negative(-) values to scroll down(+) and up(-), so you can change:

    scrollBottom 
    

    to this scrollTop:

    $("#upClick").on("click", function () {
        scrolled = scrolled - 300;
    
        $(".cover").animate({
            scrollTop: scrolled
        });//^^^^^^^^------------------------------this one
    });
    

    Why can't I inherit static classes?

    A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:

    public class TestClass<T>
    {
        protected TestClass()
        { }
    
        public static T Add(T x, T y)
        {
            return (dynamic)x + (dynamic)y;
        }
    }
    
    public class TestClass : TestClass<double>
    {
        // Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
        protected TestClass()
        { }
    }
    
    TestClass.Add(3.0, 4.0)
    TestClass<int>.Add(3, 4)
    
    // Creating a class instance is not allowed because the constructors are inaccessible.
    // new TestClass();
    // new TestClass<int>();
    

    Unfortunately because of the "by-design" language limitation we can't do:

    public static class TestClass<T>
    {
        public static T Add(T x, T y)
        {
            return (dynamic)x + (dynamic)y;
        }
    }
    
    public static class TestClass : TestClass<double>
    {
    }
    

    Could not find a version that satisfies the requirement <package>

    If you facing this issue at the workplace. This might be the solution for you.

    pip install -U <package_name> --user --proxy=<your proxy>
    

    Trying to get Laravel 5 email to work

    You are getting an authentication error because the username and password in your config file is setup wrong.

    Change this:

    'username' => env('[email protected]'),
    'password' => env('MyPassword'),
    

    To this:

    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    

    The env method checks your .env file. In your .env file you call these MAIL_USERNAME, so that's what you need to pass to the env method.

    One troubleshooting tip: add dd(Config::get('mail')); so that you can see the actual generated config. This will help you spot issues like this, and know exactly what information Laravel is going to try and use. So you may want to stop that in your test route temporarily to examine what you have:

    Route::get('test', function()
    {
        dd(Config::get('mail'));
    });
    

    How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

    To install an apk on one of your emulators:

    First get the list of devices:

    -> adb devices
    List of devices attached
    25sdfsfb3801745eg        device
    emulator-0954   device
    

    Then install the apk on your emulator with the -s flag:

    -> adb -s "25sdfsfb3801745eg" install "C:\Users\joel.joel\Downloads\release.apk"
    Performing Streamed Install
    Success
    

    Ps.: the order here matters, so -s <id> has to come before install command, otherwise it won't work.

    Hope this helps someone!

    R - Markdown avoiding package loading messages

    This is an old question, but here's another way to do it.

    You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

    ```{r echo=FALSE}
    suppressWarnings(suppressMessages(suppressPackageStartupMessages({
    source("C:/Rscripts/source.R")
    })
    ```
    

    You can also put those functions around your library() calls inside the "source.R" script.

    "undefined" function declared in another file?

    you should use go modules now, if you are not following How to write go code

    With go module you don't have to put the code in the $GOPATH/src. it can live in any other location as well.

    You can move the code to different directory like /employee, To make it work Just under employee directory initialise the go module

    go mod init example.com/employee
    

    Get div to take up 100% body height, minus fixed-height header and footer

    The new, modern way to do this is to calculate the vertical height by subtracting the height of both the header and the footer from the vertical-height of the viewport.

    //CSS
    header { 
      height: 50px;
    }
    footer { 
      height: 50px;
    }
    #content { 
      height: calc(100vh - 50px - 50px);
    }
    

    IndexError: tuple index out of range ----- Python

    This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

    Cannot instantiate the type List<Product>

    List can be instantiated by any class implementing the interface.By this way,Java provides us polymorphic behaviour.See the example below:

    List<String> list = new ArrayList<String>();
    

    Instead of instantiating an ArrayList directly,I am using a List to refer to ArrayList object so that we are using only the List interface methods and do not care about its actual implementation.

    Examples of classes implementing List are ArrayList,LinkedList,Vector.You probably want to create a List depending upon your requirements.

    Example:- a LinkedList is more useful when you hve to do a number of inertion or deletions .Arraylist is more performance intensive as it is backed by a fixed size array and array contents have to be changed by moving or regrowing the array.

    Again,using a List we can simply change our object instantiation without changing any code further in your programs.

    Suppose we are using ArrayList<String> value = new ArrayList<String>();

    we may use a specific method of ArrrayList and out code will not be robust

    By using List<String> value = new ArrayList<String>();

    we are making sure we are using only List interface methods..and if we want to change it to a LinkedList we simply have to change the code :

    List<String> value = new ArrayList<String>(); 
    

    ------ your code uses List interface methods.....

    value = new LinkedList<String>(); 
    

    -----your code still uses List interface methods and we do not have to change anything---- and we dont have to change anything in our code further

    By the way a LinkedList also works a Deque which obviously also you cannot instantiate as it is also an interface

    PHP passing $_GET in linux command prompt

    php -r 'parse_str($argv[2],$_GET);include $argv[1];' index.php 'a=1&b=2'

    You could make the first part as an alias:

    alias php-get='php -r '\''parse_str($argv[2],$_GET);include $argv[1];'\'

    then simply use:

    php-get some_script.php 'a=1&b=2&c=3'

    Download data url file

    This can be solved 100% entirely with HTML alone. Just set the href attribute to "data:(mimetypeheader),(url)". For instance...

    <a
        href="data:video/mp4,http://www.example.com/video.mp4"
        target="_blank"
        download="video.mp4"
    >Download Video</a>
    

    Working example: JSFiddle Demo.

    Because we use a Data URL, we are allowed to set the mimetype which indicates the type of data to download. Documentation:

    Data URLs are composed of four parts: a prefix (data:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself. (Source: MDN Web Docs: Data URLs.)

    Components:

    • <a ...> : The link tag.
    • href="data:video/mp4,http://www.example.com/video.mp4" : Here we are setting the link to the a data: with a header preconfigured to video/mp4. This is followed by the header mimetype. I.E., for a .txt file, it would would be text/plain. And then a comma separates it from the link we want to download.
    • target="_blank" : This indicates a new tab should be opened, it's not essential, but it helps guide the browser to the desired behavior.
    • download: This is the name of the file you're downloading.

    How to determine the screen width in terms of dp or dip at runtime in Android?

    Your problem is with casting the float to an int, losing precision. You should also multiply with the factor and not divide.

    Do this:

    int dp = (int)(pixel*getResources().getDisplayMetrics().density);
    

    Use of min and max functions in C++

    If your implementation provides a 64-bit integer type, you may get a different (incorrect) answer by using fmin or fmax. Your 64-bit integers will be converted to doubles, which will (at least usually) have a significand that's smaller than 64-bits. When you convert such a number to a double, some of the least significant bits can/will be lost completely.

    This means that two numbers that were really different could end up equal when converted to double -- and the result will be that incorrect number, that's not necessarily equal to either of the original inputs.

    Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

    The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

    Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

    var foomodule = require('foo');
    // do something with fooModule
    

    What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

    var module = require(path); // Call RequireJS require
    

    ...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

    var moduleName = 'foo';
    require([moduleName], function(fooModule){
        // do something with fooModule
    })
    

    Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

    define(['dyn_modules'], function (dynModules) {
        require(dynModules, function(){
            // use arguments since you don't know how many modules you're getting in the callback
            for (var i = 0; i < arguments.length; i++){
                var mymodule = arguments[i];
                // do something with mymodule...
            }
        });
    
    });
    

    EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

    How to call getClass() from a static method in Java?

    Simply use a class literal, i.e. NameOfClass.class

    position fixed header in html

    body{
      margin:0;
      padding:0 0 0 0;
    }
    div#header{
      position:absolute;
      top:0;
      left:0;
      width:100%;
      height:25;
    }
    @media screen{
     body>div#header{
       position: fixed;
     }
    }
    * html body{
      overflow:hidden;
    } 
    * html div#content{
      height:100%;
      overflow:auto;
    }
    

    set environment variable in python script

    bash:

    LD_LIBRARY_PATH=my_path
    sqsub -np $1 /path/to/executable
    

    Similar, in Python:

    import os
    import subprocess
    import sys
    
    os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
    subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                          env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))
    

    Using StringWriter for XML Serialization

    When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.

    SQL Server works on a similar principle; any string passed into an xml column must be encoded as UTF-16. SQL Server will reject any string where the XML declaration does not specify UTF-16. If the XML declaration is not present, then the XML standard requires that it default to UTF-8, so SQL Server will reject that as well.

    Bearing this in mind, here are some utility methods for doing the conversion.

    public static string Serialize<T>(T value) {
    
        if(value == null) {
            return null;
        }
    
        XmlSerializer serializer = new XmlSerializer(typeof(T));
    
        XmlWriterSettings settings = new XmlWriterSettings()
        {
            Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string
            Indent = false,
            OmitXmlDeclaration = false
        };
    
        using(StringWriter textWriter = new StringWriter()) {
            using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
                serializer.Serialize(xmlWriter, value);
            }
            return textWriter.ToString();
        }
    }
    
    public static T Deserialize<T>(string xml) {
    
        if(string.IsNullOrEmpty(xml)) {
            return default(T);
        }
    
        XmlSerializer serializer = new XmlSerializer(typeof(T));
    
        XmlReaderSettings settings = new XmlReaderSettings();
        // No settings need modifying here
    
        using(StringReader textReader = new StringReader(xml)) {
            using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
                return (T) serializer.Deserialize(xmlReader);
            }
        }
    }
    

    Abstract Class vs Interface in C++

    Pure Virtual Functions are mostly used to define:

    a) abstract classes

    These are base classes where you have to derive from them and then implement the pure virtual functions.

    b) interfaces

    These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

    Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

    Parse rfc3339 date strings in Python?

    You should have a look at moment which is a python port of the excellent js lib momentjs.

    One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

    import moment
    time_string='2012-10-09T19:00:55Z'
    
    m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
    print m.format('YYYY-M-D H:M')
    print m.weekday
    

    Result:

    2012-10-09 19:10
    2
    

    Cast Object to Generic Type for returning

    You have to use a Class instance because of the generic type erasure during compilation.

    public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch(ClassCastException e) {
            return null;
        }
    }
    

    The declaration of that method is:

    public T cast(Object o)
    

    This can also be used for array types. It would look like this:

    final Class<int[]> intArrayType = int[].class;
    final Object someObject = new int[]{1,2,3};
    final int[] instance = convertInstanceOfObject(someObject, intArrayType);
    

    Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

    How do I get the height of a div's full content with jQuery?

    You can get it with .outerHeight().

    Sometimes, it will return 0. For the best results, you can call it in your div's ready event.

    To be safe, you should not set the height of the div to x. You can keep its height auto to get content populated properly with the correct height.

    $('#x').ready( function(){
    // alerts the height in pixels
    alert($('#x').outerHeight());
    })
    

    You can find a detailed post here.

    Sorting HashMap by values

    found a solution but not sure the performance if the map has large size, useful for normal case.

       /**
         * sort HashMap<String, CustomData> by value
         * CustomData needs to provide compareTo() for comparing CustomData
         * @param map
         */
    
        public void sortHashMapByValue(final HashMap<String, CustomData> map) {
            ArrayList<String> keys = new ArrayList<String>();
            keys.addAll(map.keySet());
            Collections.sort(keys, new Comparator<String>() {
                @Override
                public int compare(String lhs, String rhs) {
                    CustomData val1 = map.get(lhs);
                    CustomData val2 = map.get(rhs);
                    if (val1 == null) {
                        return (val2 != null) ? 1 : 0;
                    } else if (val1 != null) && (val2 != null)) {
                        return = val1.compareTo(val2);
                    }
                    else {
                        return 0;
                    }
                }
            });
    
            for (String key : keys) {
                CustomData c = map.get(key);
                if (c != null) {
                    Log.e("key:"+key+", CustomData:"+c.toString());
                } 
            }
        }
    

    How to make link not change color after visited?

    In order to avoid duplicate code, I recommend you to define the color once, for both states:

    a, a:visited{
         color: /* some color */;
    }
    

    This, indeeed, will mantain your <a> color (whatever this color is) even when the link has been visited.

    Notice that, if the color of the element inside of the <a> is being inherited (e.g. the color is set in the body), you could do the following trick:

    a, a:visited {
        color: inherit;
    }
    

    PHP check if file is an image

    Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

    for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

    Sending a file over TCP sockets in Python

    Remove below code

    s.send("Hello server!")
    

    because your sending s.send("Hello server!") to server, so your output file is somewhat more in size.

    Using getline() in C++

    I know I'm late but I hope this is useful. Logic is for taking one line at a time if the user wants to enter many lines

    int main() 
    { 
    int t;                    // no of lines user wants to enter
    cin>>t;
    string str;
    cin.ignore();            // for clearing newline in cin
    while(t--)
    {
        getline(cin,str);    // accepting one line, getline is teminated when newline is found 
        cout<<str<<endl; 
    }
    return 0; 
    } 
    

    input :

    3

    Government collage Berhampore

    Serampore textile collage

    Berhampore Serampore

    output :

    Government collage Berhampore

    Serampore textile collage

    Berhampore Serampore

    How to import a new font into a project - Angular 5

    You can try creating a css for your font with font-face (like explained here)

    Step #1

    Create a css file with font face and place it somewhere, like in assets/fonts

    customfont.css

    @font-face {
        font-family: YourFontFamily;
        src: url("/assets/font/yourFont.otf") format("truetype");
    }
    

    Step #2

    Add the css to your .angular-cli.json in the styles config

    "styles":[
     //...your other styles
     "assets/fonts/customFonts.css"
     ]
    

    Do not forget to restart ng serve after doing this

    Step #3

    Use the font in your code

    component.css

    span {font-family: YourFontFamily; }
    

    Better way to shuffle two numpy arrays in unison

    This seems like a very simple solution:

    import numpy as np
    def shuffle_in_unison(a,b):
    
        assert len(a)==len(b)
        c = np.arange(len(a))
        np.random.shuffle(c)
    
        return a[c],b[c]
    
    a =  np.asarray([[1, 1], [2, 2], [3, 3]])
    b =  np.asarray([11, 22, 33])
    
    shuffle_in_unison(a,b)
    Out[94]: 
    (array([[3, 3],
            [2, 2],
            [1, 1]]),
     array([33, 22, 11]))
    

    How to re-render flatlist?

    I have replaced FlatList with SectionList and it is updates properly on state change.

    <SectionList
      keyExtractor={(item) => item.entry.entryId} 
      sections={section}
      renderItem={this.renderEntries.bind(this)}
      renderSectionHeader={() => null}
    />
    

    The only thing need to keep in mind is that section have diff structure:

    const section = [{
      id: 0,
      data: this.state.data,
    }]
    

    Why does cURL return error "(23) Failed writing body"?

    In my case, I was doing: curl <blabla> | jq | grep <blibli>

    With jq . it worked: curl <blabla> | jq . | grep <blibli>

    Required attribute on multiple checkboxes with the same name?

    A little jQuery fix:

    $(function(){
        var chbxs = $(':checkbox[required]');
        var namedChbxs = {};
        chbxs.each(function(){
            var name = $(this).attr('name');
            namedChbxs[name] = (namedChbxs[name] || $()).add(this);
        });
        chbxs.change(function(){
            var name = $(this).attr('name');
            var cbx = namedChbxs[name];
            if(cbx.filter(':checked').length>0){
                cbx.removeAttr('required');
            }else{
                cbx.attr('required','required');
            }
        });
    });
    

    Oracle 10g: Extract data (select) from XML (CLOB Type)

    You can try creating DBMS_XMLPARSER.parser object from the CLOB XML and get a DBMS_XMLDOM.DOMDocument object from it. Then use DBMS_XMLDOM package methods to get the value of any node.

       xml_            CLOB := 'X';
       p               DBMS_XMLPARSER.parser;
       doc_            DBMS_XMLDOM.DOMDocument;
    
          -- Convert the CLOB into a XML-document
          P := DBMS_XMLPARSER.newparser();
          -- Parse the clob and get the XML-document
          DBMS_XMLPARSER.parseclob(p, xml_);
          doc_ := DBMS_XMLPARSER.getDocument(p);
    

    Then use the below methods to extract node value

    DBMS_XMLDOM.getElementsByTagName(doc_, 'NodeName'); DBMS_XMLDOM.GetNodeValue(node_obj_);

    Refer more about DBMS_XMLDOM methods here.

    Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

    In Postgres, you can make almost any single value query return a value or null by wrapping it:

    SELECT (SELECT <query>) AS value
    

    and hence avoid complexity in the caller.

    What is the best way to compare 2 folder trees on windows?

    You can use git for exactly this purpose. Basically, you create a git repository in folder A (the repo is in A/.git), then copy A/.git to B/.git, then change to B folder and compare simply by running git diff. And the --exclude functionality can be achieved with .gitignore.

    So, sticking to your example (but using bash shell on Linux):

    # Create a Git repo in current_vss
    pushd current_vss
    printf ".svn\n*.vspscc\n*.scc" >> .gitignore
    git init && git add . && git commit -m 'initial'
    popd
    
    # Copy the repo to current_svn and compare
    cp -r current_vss/.git* current_svn/
    pushd current_svn
    git diff
    

    Increasing nesting function calls limit

    Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

    Output errors and see where this is being triggered.

    Component is not part of any NgModule or the module has not been imported into your module

    I ran into this same issue and none of what I was seeing here was working. If you are listing your Component in the app-routing.module issue you may have run into the same problem I was having.

    app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    
    import { AppComponent } from './app.component';
    import { NavbarComponent } from './navbar/navbar.component';
    import { TopbarComponent } from './topbar/topbar.component';
    import { FooterbarComponent } from './footerbar/footerbar.component';
    import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
    import {AppRoutingModule} from './app.routing';
    import {HomeModule} from './Home/home.module';
    // import HomeComponent here
    
    @NgModule({
      declarations: [
        AppComponent,
        FooterbarComponent,
        TopbarComponent,
        NavbarComponent,
        // add HomeComponent here
      ],
      imports: [
        BrowserModule,
        HttpModule,
        AppRoutingModule,
        HomeModule  // remove this
    
      ],
      providers: [MRDBGlobalConstants],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    home/index.ts

    export * from './';
    

    app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { HomeComponent } from './components';
    
    const routes: Routes = [
        { path: 'app/home', component: HomeComponent },
        { path: '', redirectTo: 'app/home', pathMatch: 'full' },
        { path: '**', redirectTo: 'app/home' }
    ];
    
    @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    home/home.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    // import { HomeComponent } from './home.component'; This would cause app to break
    import { HomeComponent } from './';
    @NgModule({
      imports: [
        CommonModule
      ],
      exports: [HomeComponent],
      declarations: [HomeComponent]
    })
    export class HomeModule { }
    

    I won't claim to understand exactly why this is the case, but when using indexing to export components (and I would assume the same for services, etc.), when referencing the same component in separate modules you need to import them from the same file, in this case the index, in order to avoid this issue.

    How do I get the path of the Python script I am running in?

    If you have even the relative pathname (in this case it appears to be ./) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.

    Of course, there are better solutions, as posted. I just kind of like mine.

    Obtain smallest value from array in Javascript?

    Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

    const findMin = (arr, min, i) => arr.length === i ? min :
      findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
    

    Code snippet:

    _x000D_
    _x000D_
    const findMin = (arr, min, i) => arr.length === i ? min :_x000D_
      findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)_x000D_
      _x000D_
    const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
    const min = findMin(arr, arr[0], 0)_x000D_
    console.log(min);
    _x000D_
    _x000D_
    _x000D_

    invalid target release: 1.7

    This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.

    Check Mike's answer to his own question here: stackoverflow question 24705877

    This solved the issue for me both command line AND within eclipse.

    Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.

    Using success/error/finally/catch with Promises in AngularJS

    What type of granularity are you looking for? You can typically get by with:

    $http.get(url).then(
      //success function
      function(results) {
        //do something w/results.data
      },
      //error function
      function(err) {
        //handle error
      }
    );
    

    I've found that "finally" and "catch" are better off when chaining multiple promises.

    Pyinstaller setting icons don't change

    The below command can set the icon on an executable file.

    Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".

    pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py
    

    For example:

    If the app.py file is present in the current directory and app.ico is present inside the Images folder within the current directory.

    Then the command should be as below. The final executable file will be generated inside the dist folder

    pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py
    

    Send JSON data from Javascript to PHP?

        <html>
    <script type="text/javascript">
    var myJSONObject = {"bindings": 11};
    alert(myJSONObject);
    
    var stringJson =JSON.stringify(myJSONObject);
    alert(stringJson);
    </script>
    </html>
    

    How do I increment a DOS variable in a FOR /F loop?

    I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames

    set TEXT_T="myfile.txt"
    
    set /a c=1
    
    setlocal ENABLEDELAYEDEXPANSION
    
    FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
        set /a c=c+1
        set OUTPUT_FILE_NAME=output_!c!.txt
        echo Output file is !OUTPUT_FILE_NAME!
        echo %%i, !c!
    )
    
    endlocal
    

    Python Pandas - Missing required dependencies ['numpy'] 1

    I had this problem with last version of numpy 1.16.x

    Problem resolved with

    python3 -m pip uninstall numpy

    python3 -m pip install numpy==1.14.0

    Where is the WPF Numeric UpDown control?

    I have a naive solution but useful. Here is the code:

    <Grid Name="TVGrid" Background="#7F000000">  <ScrollBar Background="Black" Orientation="Vertical" Height="35" HorizontalAlignment="Left" Margin="215,254,0,0" Minimum="0" Maximum="10" LargeChange="10" Value="{Binding ElementName=channeltext2, Path=Text}" x:Name="scroll" VerticalAlignment="Top" Width="12" RenderTransformOrigin="0.5,0.5" ValueChanged="scroll_ValueChanged" >  
            <ScrollBar.RenderTransform>  
                <TransformGroup>  
                    <ScaleTransform/>  
                    <SkewTransform/>  
                    <RotateTransform Angle="-180"/>  
                    <TranslateTransform/>  
                </TransformGroup>  
            </ScrollBar.RenderTransform>  
        </ScrollBar>  
        <TextBox Name="channeltext" HorizontalContentAlignment="Center" FontSize="20"  Background="Black" Foreground="White" Height="35" HorizontalAlignment="Left" Margin="147,254,0,0" VerticalAlignment="Top" Width="53" Text="0" />  
        <TextBox Name="channeltext2" Visibility="Hidden" HorizontalContentAlignment="Center" FontSize="20"  Background="Black" Foreground="White" Height="35" HorizontalAlignment="Left" Margin="147,254,0,0" VerticalAlignment="Top" Width="53" Text="0" />  </Grid>  
    

    Await operator can only be used within an Async method

    You can only use await in an async method, and Main cannot be async.

    You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

    If you want a good intro, see my async/await intro post.

    Dismissing a Presented View Controller

    I think Apple are covering their backs a little here for a potentially kludgy piece of API.

      [self dismissViewControllerAnimated:NO completion:nil]
    

    Is actually a bit of a fiddle. Although you can - legitimately - call this on the presented view controller, all it does is forward the message on to the presenting view controller. If you want to do anything over and above just dismissing the VC, you will need to know this, and you need to treat it much the same way as a delegate method - as that's pretty much what it is, a baked-in somewhat inflexible delegate method.

    Perhaps they've come across loads of bad code by people not really understanding how this is put together, hence their caution.

    But of course, if all you need to do is dismiss the thing, go ahead.

    My own approach is a compromise, at least it reminds me what is going on:

      [[self presentingViewController] dismissViewControllerAnimated:NO completion:nil]
    

    [Swift]

      self.presentingViewController?.dismiss(animated: false, completion:nil)
    

    On postback, how can I check which control cause postback in Page_Init event

    An addition to previous answers, to use Request.Params["__EVENTTARGET"] you have to set the option:

    buttonName.UseSubmitBehavior = false;
    

    CXF: No message body writer found for class - automatically mapping non-simple resources

    When programmatically creating server, you can add message body writers for json/xml by setting Providers.

    JAXRSServerFactoryBean bean = new JAXRSServerFactoryBean();
    bean.setAddress("http://localhost:9000/");
    
    List<Object> providers = new ArrayList<Object>();
    providers.add(new JacksonJaxbJsonProvider());
    providers.add(new JacksonJaxbXMLProvider());
    bean.setProviders(providers);
    
    List<Class< ? >> resourceClasses = new ArrayList<Class< ? >>();
    resourceClasses.add(YourRestServiceImpl.class);
    bean.setResourceClasses(resourceClasses);
    
    bean.setResourceProvider(YourRestServiceImpl.class, new SingletonResourceProvider(new YourRestServiceImpl()));
    
    BindingFactoryManager manager = bean.getBus().getExtension(BindingFactoryManager.class);
    JAXRSBindingFactory restFactory = new JAXRSBindingFactory();
    restFactory.setBus(bean.getBus());
    manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, restFactory);
    
    bean.create();
    

    BeautifulSoup getting href

    You can use find_all in the following way to find every a element that has an href attribute, and print each one:

    from BeautifulSoup import BeautifulSoup
    
    html = '''<a href="some_url">next</a>
    <span class="class"><a href="another_url">later</a></span>'''
    
    soup = BeautifulSoup(html)
    
    for a in soup.find_all('a', href=True):
        print "Found the URL:", a['href']
    

    The output would be:

    Found the URL: some_url
    Found the URL: another_url
    

    Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


    If you want all tags with an href, you can omit the name parameter:

    href_tags = soup.find_all(href=True)
    

    YouTube Video Embedded via iframe Ignoring z-index?

    wmode=opaque or transparent at the beginning of my query string didnt solve anything. This issue for me only occurs on Chrome, and not across even all computers. Just one cpu. It occurs in vimeo embeds as well, and possibly others.

    My solution to to attach to the 'shown' and 'hidden' event of the bootstrap modals I am using, add a class which sets the iframe to 1x1 pixels, and remove the class when the modal closes. Seems like it works and is simple to implement.

    set default schema for a sql query

    SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.

    Pass variables to AngularJS controller, best practice?

    You could use ng-init in an outer div:

    <div ng-init="param='value';">
        <div ng-controller="BasketController" >
            <label>param: {{value}}</label>
        </div>
    </div>  
    

    The parameter will then be available in your controller's scope:

    function BasketController($scope) {
            console.log($scope.param);
    }
    

    jQuery Force set src attribute for iframe

    $(document).ready(function() {
        $('#abc_frame').attr('src',url);
    })
    

    async for loop in node.js

    I like to use the recursive pattern for this scenario. For example, something like this:

    // If config is an array of queries
    var config = JSON.parse(queries.querrryArray);   
    
    // Array of results
    var results;
    
    processQueries(config);
    
    function processQueries(queries) {
        var searchQuery;
    
        if (queries.length == 0) {
            // All queries complete
            res.writeHead(200, {'content-type': 'application/json'});
            res.end(JSON.stringify({results: results}));
            return;
        }
    
        searchQuery = queries.pop();
    
        search(searchQuery, function(result) {
            results.push(JSON.stringify({result: result}); 
            processQueries();            
        });
    
    }
    

    processQueries is a recursive function that will pull a query element out of an array of queries to process. Then the callback function calls processQueries again when the query is complete. The processQueries knows to end when there are no queries left.

    It is easiest to do this using arrays, but it could be modified to work with object key/values I imagine.

    Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

    I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.

    Remove Sub String by using Python

    BeautifulSoup(text, features="html.parser").text 
    

    For the people who were seeking deep info in my answer, sorry.

    I'll explain it.

    Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

    The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

    Once done so, we just request all the text from within the HTML object.

    Android Webview - Webpage should fit the device screen

    Try with this HTML5 tips

    http://www.html5rocks.com/en/mobile/mobifying.html

    And with this if your Android Version is 2.1 or greater

      WebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    

    Commenting code in Notepad++

    Try the following shortcut:

    Ctrl+K.

    How to use a WSDL

    Use WSDL.EXE utility to generate a Web Service proxy from WSDL.

    You'll get a long C# source file that contains a class that looks like this:

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
    public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
        ...
    }
    

    In your client-side, Web-service-consuming code:

    1. instantiate MyService.
    2. set its Url property
    3. invoke Web methods

    How to filter rows containing a string pattern from a Pandas dataframe

    >>> mask = df['ids'].str.contains('ball')    
    >>> mask
    0     True
    1     True
    2    False
    3     True
    Name: ids, dtype: bool
    
    >>> df[mask]
         ids  vals
    0  aball     1
    1  bball     2
    3  fball     4
    

    Format a message using MessageFormat.format() in Java

    Add an extra apostrophe ' to the MessageFormat pattern String to ensure the ' character is displayed

    String text = 
         java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
                                             ^
    

    An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc

    A single quote itself must be represented by doubled single quotes '' throughout a String.

    The String You\\'re is equivalent to adding a backslash character to the String so the only difference will be that You\re will be produced rather than Youre. (before double quote solution '' applied)

    How do I know the script file name in a Bash script?

    $BASH_SOURCE gives the correct answer when sourcing the script.

    This however includes the path so to get the scripts filename only, use:

    $(basename $BASH_SOURCE) 
    

    Should I write script in the body or the head of the html?

    I would answer this with multiple options actually, the some of which actually render in the body.

    • Place library script such as the jQuery library in the head section.
    • Place normal script in the head unless it becomes a performance/page load issue.
    • Place script associated with includes, within and at the end of that include. One example of this is .ascx user controls in asp.net pages - place the script at the end of that markup.
    • Place script that impacts the render of the page at the end of the body (before the body closure).
    • do NOT place script in the markup such as <input onclick="myfunction()"/> - better to put it in event handlers in your script body instead.
    • If you cannot decide, put it in the head until you have a reason not to such as page blocking issues.

    Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).

    EDIT: references:

    Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; } on the div)

    Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html

    EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.

    Convert String to Integer in XSLT 1.0

    XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

    Create two threads, one display odd & other even numbers

    @aymeric answer wont print the numbers in their natural order, but this code will. Explanation at the end.

    public class Driver {
        static Object lock = new Object();
    
        public static void main(String[] args) {
            Thread t1 = new Thread(new Runnable() {
                public void run() {
    
                    for (int itr = 1; itr < 51; itr = itr + 2) {
                        synchronized (lock) {
                            System.out.print(" " + itr);
                            try {
                                lock.notify();
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
            Thread t2 = new Thread(new Runnable() {
                public void run() {
    
                    for (int itr = 2; itr < 51; itr = itr + 2) {
                        synchronized (lock) {
                            System.out.print(" " + itr);
                            try {
                                lock.notify();
                                if(itr==50)
                                    break;
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
            try {
                t1.start();
                t2.start();
                t1.join();
                t2.join();
                System.out.println("\nPrinting over");
            } catch (Exception e) {
    
            }
        }
    }
    

    In order to achieve so, the run methods of the two threads above have to be called one after the other, i.e. they need to be synchronized and I am achieving that using locks.

    The code works like this: t1.run prints the odd number and notifies any waiting thread that it is going to release the lock, then goes into a wait state.

    At this point t2.run is invoked, it prints the next even number, notifies other threads that it is about to release the lock it holds and then goes into wait state.

    This continues till the itr in t2.run() reaches 50, at this point our goal has been achieved and we need to kill these two threads.

    By breaking, I avoid calling lock.wait() in t2.run and t2 thread is thus shutdown, the control will now go to t1.run since it was waiting to acquire the lock; but here itr value will be > 51 and we will come out of its run(), thus shutting down the thread.

    If break is not used in t2.run(), though we will see numbers 1 to 50 on the screen but the two threads will get into a deadlock situation and continue to be in wait state.

    How to solve WAMP and Skype conflict on Windows 7?

    A small update for the new Skype options window. Please follow this:

    Go to Tools ? Options ? Advanced ? Connection and uncheck the box use port 80 and 443 as alternatives for incoming connections.

    Android; Check if file exists without creating a new one

    It worked for me:

    File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
        if(file.exists()){
           //Do something
        }
        else{
           //Nothing
         }
    

    Override element.style using CSS

    As per my knowledge Inline sytle comes first so css class should not work.

    Use Jquery as

    $(document).ready(function(){
    
       $("#demoFour li").css("display","inline");
      });
    
    You can also try 
    
    #demoFour li { display:inline !important;}
    

    tar: Error is not recoverable: exiting now

    Try to get your archive using wget, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:

    wget http://PATH_TO_ARCHIVE
    

    Should a function have only one return statement?

    I currently am working on a codebase where two of the people working on it blindly subscribe to the "single point of exit" theory and I can tell you that from experience, it's a horrible horrible practice. It makes code extremely difficult to maintain and I'll show you why.

    With the "single point of exit" theory, you inevitably wind up with code that looks like this:

    function()
    {
        HRESULT error = S_OK;
    
        if(SUCCEEDED(Operation1()))
        {
            if(SUCCEEDED(Operation2()))
            {
                if(SUCCEEDED(Operation3()))
                {
                    if(SUCCEEDED(Operation4()))
                    {
                    }
                    else
                    {
                        error = OPERATION4FAILED;
                    }
                }
                else
                {
                    error = OPERATION3FAILED;
                }
            }
            else
            {
                error = OPERATION2FAILED;
            }
        }
        else
        {
            error = OPERATION1FAILED;
        }
    
        return error;
    }
    

    Not only does this make the code very hard to follow, but now say later on you need to go back and add an operation in between 1 and 2. You have to indent just about the entire freaking function, and good luck making sure all of your if/else conditions and braces are matched up properly.

    This method makes code maintenance extremely difficult and error prone.

    Node.js - How to send data from html to express

    Using http.createServer is very low-level and really not useful for creating web applications as-is.

    A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

    When you have, you can create a basic application to handle your form:

    var express = require('express');
    var bodyParser = require('body-parser');
    var app     = express();
    
    //Note that in version 4 of express, express.bodyParser() was
    //deprecated in favor of a separate 'body-parser' module.
    app.use(bodyParser.urlencoded({ extended: true })); 
    
    //app.use(express.bodyParser());
    
    app.post('/myaction', function(req, res) {
      res.send('You sent the name "' + req.body.name + '".');
    });
    
    app.listen(8080, function() {
      console.log('Server running at http://127.0.0.1:8080/');
    });
    

    You can make your form point to it using:

    <form action="http://127.0.0.1:8080/myaction" method="post">
    

    The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

    PHP PDO: charset, set names?

    This is probably the most elegant way to do it.
    Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):

    $connect = new PDO(
      "mysql:host=$host;dbname=$db", 
      $user, 
      $pass, 
      array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
      )
    );
    

    Works great for me.

    How to set time delay in javascript

    I'll give my input because it helps me understand what im doing.

    To make an auto scrolling slide show that has a 3 second wait I did the following:

    var isPlaying = true;
    
    function autoPlay(playing){
       var delayTime = 3000;
       var timeIncrement = 3000;
    
       if(playing){
            for(var i=0; i<6; i++){//I have 6 images
                setTimeout(nextImage, delayTime);
                delayTime += timeIncrement;
            }
            isPlaying = false;
    
       }else{
           alert("auto play off");
       }
    }
    
    autoPlay(isPlaying);
    

    Remember that when executing setTimeout() like this; it will execute all time out functions as if they where executed at the same time assuming that in setTimeout(nextImage, delayTime);delay time is a static 3000 milliseconds.

    What I did to account for this was add an extra 3000 milli/s after each for loop incrementation via delayTime += timeIncrement;.

    For those who care here is what my nextImage() looks like:

    function nextImage(){
        if(currentImg === 1){//change to img 2
            for(var i=0; i<6; i++){
                images[i].style.zIndex = "0";
            }
            images[1].style.zIndex = "1";
            imgNumber.innerHTML = imageNumber_Text[1];
            imgDescription.innerHTML = imgDescText[1];
    
            currentImg = 2;
        }
        else if(currentImg === 2){//change to img 3
            for(var i=0; i<6; i++){
                images[i].style.zIndex = "0";
            }
            images[2].style.zIndex = "1";
            imgNumber.innerHTML = imageNumber_Text[2];
            imgDescription.innerHTML = imgDescText[2];
    
            currentImg = 3;
        }
        else if(currentImg === 3){//change to img 4
            for(var i=0; i<6; i++){
                images[i].style.zIndex = "0";
            }
            images[3].style.zIndex = "1";
            imgNumber.innerHTML = imageNumber_Text[3];
            imgDescription.innerHTML = imgDescText[3];
    
            currentImg = 4;
        }
        else if(currentImg === 4){//change to img 5
            for(var i=0; i<6; i++){
                images[i].style.zIndex = "0";
            }
            images[4].style.zIndex = "1";
            imgNumber.innerHTML = imageNumber_Text[4];
            imgDescription.innerHTML = imgDescText[4];
    
            currentImg = 5;
        }
        else if(currentImg === 5){//change to img 6
        for(var i=0; i<6; i++){
                images[i].style.zIndex = "0";
            }
            images[5].style.zIndex = "1";
            imgNumber.innerHTML = imageNumber_Text[5];
            imgDescription.innerHTML = imgDescText[5];
    
            currentImg = 6;
        }
        else if(currentImg === 6){//change to img 1
            for(var i=0; i<6; i++){
                images[i].style.zIndex = "0";
            }
            images[0].style.zIndex = "1";
            imgNumber.innerHTML = imageNumber_Text[0];
            imgDescription.innerHTML = imgDescText[0];
    
            currentImg = 1;
        }
    }
    

    How to read from stdin line by line in Node

    You can use the readline module to read from stdin line by line:

    var readline = require('readline');
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      terminal: false
    });
    
    rl.on('line', function(line){
        console.log(line);
    })
    

    The POM for project is missing, no dependency information available

    Change:

    <!-- ANT4X -->
    <dependency>
      <groupId>net.sourceforge</groupId>
      <artifactId>ant4x</artifactId>
      <version>${net.sourceforge.ant4x-version}</version>
      <scope>provided</scope>
    </dependency>
    

    To:

    <!-- ANT4X -->
    <dependency>
      <groupId>net.sourceforge.ant4x</groupId>
      <artifactId>ant4x</artifactId>
      <version>${net.sourceforge.ant4x-version}</version>
      <scope>provided</scope>
    </dependency>
    

    The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

    Generating (pseudo)random alpha-numeric strings

    This is something I use:

    $cryptoStrong = true; // can be false
    $length = 16; // Any length you want
    $bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
    $randomString = bin2hex($bytes);
    

    You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here

    JPA Query.getResultList() - use in a generic way

    General rule is the following:

    • If select contains single expression and it's an entity, then result is that entity
    • If select contains single expression and it's a primitive, then result is that primitive
    • If select contains multiple expressions, then result is Object[] containing the corresponding primitives/entities

    So, in your case list is a List<Object[]>.

    Find nearest value in numpy array

    With slight modification, the answer above works with arrays of arbitrary dimension (1d, 2d, 3d, ...):

    def find_nearest(a, a0):
        "Element in nd array `a` closest to the scalar value `a0`"
        idx = np.abs(a - a0).argmin()
        return a.flat[idx]
    

    Or, written as a single line:

    a.flat[np.abs(a - a0).argmin()]
    

    What is Python buffer type for?

    I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer in this mailinglist post).

    For example, numpy seems to use buffer for efficient data storage:

    import numpy
    a = numpy.ndarray(1000000)
    

    the a.data is a:

    <read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
    

    Pip error: Microsoft Visual C++ 14.0 is required

    You need to install Microsoft Visual C++ 14.0 to install pycrypto:

    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
    C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
    

    In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

    In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

    I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

    After you have installed Visual C++, just re-run the original command:

    pip install -U steem
    

    To find out what the various install options mean, run this command:

    pip help install
    

    The help for the -U option says

    -U, --upgrade        Upgrade all specified packages to the newest available
                         version. The handling of dependencies depends on the
                         upgrade-strategy used.
    

    If you do not already have the steem library installed, you can run the command without the -U option.

    Change the background color in a twitter bootstrap modal?

    It gets a little bit more complicated if you want to add the background to a specific modal. One way of solving that is to add and call something like this function instead of showing the modal directly:

    function showModal(selector) {
        $(selector).modal('show');
        $('.modal-backdrop').addClass('background-backdrop');
    }
    

    Any css can then be applied to the background-backdrop class.

    No input file specified

    GoDaddy is currently (Feb '13) supporting modification of FastCGI for some accounts using PHP 5.2.x or earlier. See GoDaddy article "Disabling FastCGI in Your Hosting Account".
    (In my case, this is apparently necessary to help get the current version of LimeSurvey (2.0) towards a running state.)

    Auto highlight text in a textbox control

     textBoxX1.Focus();
     this.ActiveControl = textBoxX1;
     textBoxX1.SelectAll();
    

    Android + Pair devices via bluetooth programmatically

    In my first answer the logic is shown for those who want to go with the logic only.

    I think I was not able to make clear to @chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.

    BluetoothDemo.java

    public class BluetoothDemo extends Activity {
    
        ListView listViewPaired;
        ListView listViewDetected;
        ArrayList<String> arrayListpaired;
        Button buttonSearch,buttonOn,buttonDesc,buttonOff;
        ArrayAdapter<String> adapter,detectedAdapter;
        static HandleSeacrh handleSeacrh;
        BluetoothDevice bdDevice;
        BluetoothClass bdClass;
        ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
        private ButtonClicked clicked;
        ListItemClickedonPaired listItemClickedonPaired;
        BluetoothAdapter bluetoothAdapter = null;
        ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
        ListItemClicked listItemClicked;
    
        @Override 
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            listViewDetected = (ListView) findViewById(R.id.listViewDetected);
            listViewPaired = (ListView) findViewById(R.id.listViewPaired);
            buttonSearch = (Button) findViewById(R.id.buttonSearch);
            buttonOn = (Button) findViewById(R.id.buttonOn);
            buttonDesc = (Button) findViewById(R.id.buttonDesc);
            buttonOff = (Button) findViewById(R.id.buttonOff); 
            arrayListpaired = new ArrayList<String>();
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            clicked = new ButtonClicked();
            handleSeacrh = new HandleSeacrh();
            arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
            /*
             * the above declaration is just for getting the paired bluetooth devices;
             * this helps in the removing the bond between paired devices.
             */
            listItemClickedonPaired = new ListItemClickedonPaired();
            arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
            adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
            detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
            listViewDetected.setAdapter(detectedAdapter);
            listItemClicked = new ListItemClicked();
            detectedAdapter.notifyDataSetChanged();
            listViewPaired.setAdapter(adapter);
        }
    
        @Override
        protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            getPairedDevices();
            buttonOn.setOnClickListener(clicked);
            buttonSearch.setOnClickListener(clicked);
            buttonDesc.setOnClickListener(clicked);
            buttonOff.setOnClickListener(clicked);
            listViewDetected.setOnItemClickListener(listItemClicked);
            listViewPaired.setOnItemClickListener(listItemClickedonPaired);
        }
        private void getPairedDevices() {
            Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();            
            if(pairedDevice.size()>0)
            {
                for(BluetoothDevice device : pairedDevice)
                {
                    arrayListpaired.add(device.getName()+"\n"+device.getAddress());
                    arrayListPairedBluetoothDevices.add(device);
                }
            }
            adapter.notifyDataSetChanged();
        }
        class ListItemClicked implements OnItemClickListener
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                bdDevice = arrayListBluetoothDevices.get(position);
                //bdClass = arrayListBluetoothDevices.get(position);
                Log.i("Log", "The dvice : "+bdDevice.toString());
                /*
                 * here below we can do pairing without calling the callthread(), we can directly call the
                 * connect(). but for the safer side we must usethe threading object.
                 */
                //callThread();
                //connect(bdDevice);
                Boolean isBonded = false;
                try {
                    isBonded = createBond(bdDevice);
                    if(isBonded)
                    {
                        //arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
                        //adapter.notifyDataSetChanged();
                        getPairedDevices();
                        adapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace(); 
                }//connect(bdDevice);
                Log.i("Log", "The bond is created: "+isBonded);
            }       
        }
        class ListItemClickedonPaired implements OnItemClickListener
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
                bdDevice = arrayListPairedBluetoothDevices.get(position);
                try {
                    Boolean removeBonding = removeBond(bdDevice);
                    if(removeBonding)
                    {
                        arrayListpaired.remove(position);
                        adapter.notifyDataSetChanged();
                    }
    
    
                    Log.i("Log", "Removed"+removeBonding);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        /*private void callThread() {
            new Thread(){
                public void run() {
                    Boolean isBonded = false;
                    try {
                        isBonded = createBond(bdDevice);
                        if(isBonded)
                        {
                            arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
                            adapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace(); 
                    }//connect(bdDevice);
                    Log.i("Log", "The bond is created: "+isBonded);
                }           
            }.start();
        }*/
        private Boolean connect(BluetoothDevice bdDevice) { 
            Boolean bool = false;
            try {
                Log.i("Log", "service method is called ");
                Class cl = Class.forName("android.bluetooth.BluetoothDevice");
                Class[] par = {};
                Method method = cl.getMethod("createBond", par);
                Object[] args = {};
                bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
                //Log.i("Log", "This is: "+bool.booleanValue());
                //Log.i("Log", "devicesss: "+bdDevice.getName());
            } catch (Exception e) {
                Log.i("Log", "Inside catch of serviceFromDevice Method");
                e.printStackTrace();
            }
            return bool.booleanValue();
        };
    
    
        public boolean removeBond(BluetoothDevice btDevice)  
        throws Exception  
        {  
            Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
            Method removeBondMethod = btClass.getMethod("removeBond");  
            Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);  
            return returnValue.booleanValue();  
        }
    
    
        public boolean createBond(BluetoothDevice btDevice)  
        throws Exception  
        { 
            Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
            Method createBondMethod = class1.getMethod("createBond");  
            Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
            return returnValue.booleanValue();  
        }  
    
    
        class ButtonClicked implements OnClickListener
        {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                case R.id.buttonOn:
                    onBluetooth();
                    break;
                case R.id.buttonSearch:
                    arrayListBluetoothDevices.clear();
                    startSearching();
                    break;
                case R.id.buttonDesc:
                    makeDiscoverable();
                    break;
                case R.id.buttonOff:
                    offBluetooth();
                    break;
                default:
                    break;
                }
            }
        }
        private BroadcastReceiver myReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Message msg = Message.obtain();
                String action = intent.getAction();
                if(BluetoothDevice.ACTION_FOUND.equals(action)){
                    Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
    
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    try
                    {
                        //device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
                        //device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
                    }
                    catch (Exception e) {
                        Log.i("Log", "Inside the exception: ");
                        e.printStackTrace();
                    }
    
                    if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
                    {                                           // device to the arraylist.
                        detectedAdapter.add(device.getName()+"\n"+device.getAddress());
                        arrayListBluetoothDevices.add(device);
                        detectedAdapter.notifyDataSetChanged();
                    }
                    else
                    {
                        boolean flag = true;    // flag to indicate that particular device is already in the arlist or not
                        for(int i = 0; i<arrayListBluetoothDevices.size();i++)
                        {
                            if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
                            {
                                flag = false;
                            }
                        }
                        if(flag == true)
                        {
                            detectedAdapter.add(device.getName()+"\n"+device.getAddress());
                            arrayListBluetoothDevices.add(device);
                            detectedAdapter.notifyDataSetChanged();
                        }
                    }
                }           
            }
        };
        private void startSearching() {
            Log.i("Log", "in the start searching method");
            IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
            bluetoothAdapter.startDiscovery();
        }
        private void onBluetooth() {
            if(!bluetoothAdapter.isEnabled())
            {
                bluetoothAdapter.enable();
                Log.i("Log", "Bluetooth is Enabled");
            }
        }
        private void offBluetooth() {
            if(bluetoothAdapter.isEnabled())
            {
                bluetoothAdapter.disable();
            }
        }
        private void makeDiscoverable() {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
            Log.i("Log", "Discoverable ");
        }
        class HandleSeacrh extends Handler
        {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case 111:
    
                    break;
    
                default:
                    break;
                }
            }
        }
    }
    

    Here is the main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <Button 
            android:id="@+id/buttonOn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="On"/>
        <Button 
            android:id="@+id/buttonDesc"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Make Discoverable"/>
       <Button 
           android:id="@+id/buttonSearch"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="Search"/>
       <Button 
           android:id="@+id/buttonOff"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="Bluetooth Off"/>
    
       <ListView 
           android:id="@+id/listViewPaired"
           android:layout_width="match_parent"
           android:layout_height="120dp">
    
       </ListView>
    
       <ListView 
           android:id="@+id/listViewDetected"
           android:layout_width="match_parent"
           android:layout_height="match_parent">
    
       </ListView>
    </LinearLayout>
    

    Add this permissions to your AndroidManifest.xml file:

     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.BLUETOOTH" />  
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    

    The output for this code will look like this. Bluutooth Demo

    Writing string to a file on a new line every time

    If you use it extensively (a lot of written lines), you can subclass 'file':

    class cfile(file):
        #subclass file to have a more convienient use of writeline
        def __init__(self, name, mode = 'r'):
            self = file.__init__(self, name, mode)
    
        def wl(self, string):
            self.writelines(string + '\n')
    

    Now it offers an additional function wl that does what you want:

    fid = cfile('filename.txt', 'w')
    fid.wl('appends newline charachter')
    fid.wl('is written on a new line')
    fid.close()
    

    Maybe I am missing something like different newline characters (\n, \r, ...) or that the last line is also terminated with a newline, but it works for me.

    When is it appropriate to use UDP instead of TCP?

    UDP does have less overhead and is good for doing things like streaming real time data like audio or video, or in any case where it is ok if data is lost.

    Best method for reading newline delimited files and discarding the newlines?

    What do you think about this approach?

    with open(filename) as data:
        datalines = (line.rstrip('\r\n') for line in data)
        for line in datalines:
            ...do something awesome...
    

    Generator expression avoids loading whole file into memory and with ensures closing the file

    How to do Base64 encoding in node.js?

    The accepted answer previously contained new Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

    The Buffer constructor is deprecated according to the documentation.

    Here is an example of a vulnerability that can result from using it in the ws library.

    The code snippets should read:

    console.log(Buffer.from("Hello World").toString('base64'));
    console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
    

    After this answer was written, it has been updated and now matches this.

    List of IP Space used by Facebook

    The list from 2020-05-23 is:

    31.13.24.0/21
    31.13.64.0/18
    45.64.40.0/22
    66.220.144.0/20
    69.63.176.0/20
    69.171.224.0/19
    74.119.76.0/22
    102.132.96.0/20
    103.4.96.0/22
    129.134.0.0/16
    147.75.208.0/20
    157.240.0.0/16
    173.252.64.0/18
    179.60.192.0/22
    185.60.216.0/22
    185.89.216.0/22
    199.201.64.0/22
    204.15.20.0/22
    

    The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:

    whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
    

    Recommended way of making React component/div draggable

    The answer by Jared Forsyth is horribly wrong and outdated. It follows a whole set of antipatterns such as usage of stopPropagation, initializing state from props, usage of jQuery, nested objects in state and has some odd dragging state field. If being rewritten, the solution will be the following, but it still forces virtual DOM reconciliation on every mouse move tick and is not very performant.

    UPD. My answer was horribly wrong and outdated. Now the code alleviates issues of slow React component lifecycle by using native event handlers and style updates, uses transform as it doesn't lead to reflows, and throttles DOM changes through requestAnimationFrame. Now it's consistently 60 FPS for me in every browser I tried.

    const throttle = (f) => {
        let token = null, lastArgs = null;
        const invoke = () => {
            f(...lastArgs);
            token = null;
        };
        const result = (...args) => {
            lastArgs = args;
            if (!token) {
                token = requestAnimationFrame(invoke);
            }
        };
        result.cancel = () => token && cancelAnimationFrame(token);
        return result;
    };
    
    class Draggable extends React.PureComponent {
        _relX = 0;
        _relY = 0;
        _ref = React.createRef();
    
        _onMouseDown = (event) => {
            if (event.button !== 0) {
                return;
            }
            const {scrollLeft, scrollTop, clientLeft, clientTop} = document.body;
            // Try to avoid calling `getBoundingClientRect` if you know the size
            // of the moving element from the beginning. It forces reflow and is
            // the laggiest part of the code right now. Luckily it's called only
            // once per click.
            const {left, top} = this._ref.current.getBoundingClientRect();
            this._relX = event.pageX - (left + scrollLeft - clientLeft);
            this._relY = event.pageY - (top + scrollTop - clientTop);
            document.addEventListener('mousemove', this._onMouseMove);
            document.addEventListener('mouseup', this._onMouseUp);
            event.preventDefault();
        };
    
        _onMouseUp = (event) => {
            document.removeEventListener('mousemove', this._onMouseMove);
            document.removeEventListener('mouseup', this._onMouseUp);
            event.preventDefault();
        };
    
        _onMouseMove = (event) => {
            this.props.onMove(
                event.pageX - this._relX,
                event.pageY - this._relY,
            );
            event.preventDefault();
        };
    
        _update = throttle(() => {
            const {x, y} = this.props;
            this._ref.current.style.transform = `translate(${x}px, ${y}px)`;
        });
    
        componentDidMount() {
            this._ref.current.addEventListener('mousedown', this._onMouseDown);
            this._update();
        }
    
        componentDidUpdate() {
            this._update();
        }
    
        componentWillUnmount() {
            this._ref.current.removeEventListener('mousedown', this._onMouseDown);
            this._update.cancel();
        }
    
        render() {
            return (
                <div className="draggable" ref={this._ref}>
                    {this.props.children}
                </div>
            );
        }
    }
    
    class Test extends React.PureComponent {
        state = {
            x: 100,
            y: 200,
        };
    
        _move = (x, y) => this.setState({x, y});
    
        // you can implement grid snapping logic or whatever here
        /*
        _move = (x, y) => this.setState({
            x: ~~((x - 5) / 10) * 10 + 5,
            y: ~~((y - 5) / 10) * 10 + 5,
        });
        */
    
        render() {
            const {x, y} = this.state;
            return (
                <Draggable x={x} y={y} onMove={this._move}>
                    Drag me
                </Draggable>
            );
        }
    }
    
    ReactDOM.render(
        <Test />,
        document.getElementById('container'),
    );
    

    and a bit of CSS

    .draggable {
        /* just to size it to content */
        display: inline-block;
        /* opaque background is important for performance */
        background: white;
        /* avoid selecting text while dragging */
        user-select: none;
    }
    

    Example on JSFiddle.

    What is the main difference between PATCH and PUT request?

    Here are the difference between POST, PUT and PATCH methods of a HTTP protocol.

    POST

    A HTTP.POST method always creates a new resource on the server. Its a non-idempotent request i.e. if user hits same requests 2 times it would create another new resource if there is no constraint.

    http post method is like a INSERT query in SQL which always creates a new record in database.

    Example: Use POST method to save new user, order etc where backend server decides the resource id for new resource.

    PUT

    In HTTP.PUT method the resource is first identified from the URL and if it exists then it is updated otherwise a new resource is created. When the target resource exists it overwrites that resource with a complete new body. That is HTTP.PUT method is used to CREATE or UPDATE a resource.

    http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.

    PUT request is idempotent i.e. hitting the same requests twice would update the existing recording (No new record created). In PUT method the resource id is decided by the client and provided in the request url.

    Example: Use PUT method to update existing user or order.

    PATCH

    A HTTP.PATCH method is used for partial modifications to a resource i.e. delta updates.

    http patch method is like a UPDATE query in SQL which sets or updates selected columns only and not the whole row.

    Example: You could use PATCH method to update order status.

    PATCH /api/users/40450236/order/10234557

    Request Body: {status: 'Delivered'}

    Please help me convert this script to a simple image slider

    Problems only surface when I am I trying to give the first loaded content an active state

    Does this mean that you want to add a class to the first button?

    $('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

    instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

    CSS:

    .image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

    JavaScript:

    var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

    http://jsfiddle.net/RmF57/

    What does InitializeComponent() do, and how does it work in WPF?

    The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

    This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

    In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

    Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

    Hope this helps!

    Setting different color for each series in scatter plot on matplotlib

    This works for me:

    for each series, use a random rgb colour generator

    c = color[np.random.random_sample(), np.random.random_sample(), np.random.random_sample()]
    

    Remove all child elements of a DOM node in JavaScript

    with jQuery :

    $("#foo").find("*").remove();
    

    What is the difference/usage of homebrew, macports or other package installation tools?

    By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).

    For more detail:

    This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/

    whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907

    I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!

    How to install PHP mbstring on CentOS 6.2

    *Make sure you update your linux box first

    yum update
    

    In case someone still has this problem, this is a valid solution:

    centos-release : rpm -q centos-release

    Centos 6.*

    wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
    rpm -ivh epel-release-6-8.noarch.rpm
    wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
    rpm -Uvh remi-release-6*.rpm
    

    Centos 5.*

    wget http://ftp.jaist.ac.jp/pub/Linux/Fedora/epel/5/x86_64/epel-release-5-4.noarch.rpm
    rpm -ivh epel-release-5-4.noarch.rpm
    wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
    rpm -Uvh remi-release-5*.rpm
    

    Then just do this to update:

    yum --enablerepo=remi upgrade php-mbstring
    

    Or this to install:

    yum --enablerepo=remi install php-mbstring
    

    jQuery check/uncheck radio button onclick

    here is simple solution i hope it will help you. here's a simple example to improve answer.

    $('[type="radio"]').click(function () {
    
                if ($(this).attr('checked')) {
    
                    $(this).removeAttr('checked');
                    $(this).prop('checked',false);
    
                } else {
    
                    $(this).attr('checked', 'checked');
    
                }
            });
    

    Demo sorry for too late.. :)

    What is IllegalStateException?

    Illegal State Exception is an Unchecked exception.

    It indicate that method has been invoked at wrong time.

    example:

    Thread t = new Thread();
    t.start();
    //
    //
    t.start();
    

    output:

    Runtime Excpetion: IllegalThreadStateException
    

    We cant start the Thread again, it will throw IllegalStateException.

    What is the difference between an annotated and unannotated tag?

    TL;DR

    The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

    More About Lightweight Tags

    According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

    • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
    • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
    • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
    • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

    Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

    How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

    Pardon my ignorance, but why are you using $('.salesperson') instead of $('#salesperson') when dealing with an ID?

    Generate C# class from XML

    I realise that this is a rather old post and you have probably moved on.

    But I had the same problem as you so I decided to write my own program.

    The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.

    It is in no way elegant but it did the job for me.

    You can get it here: Please make suggestions if you like it.

    SimpleXmlToCode

    Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

    I actually tried to implement connection pooling on the django end using:

    https://github.com/gmcguire/django-db-pool

    but I still received this error, despite lowering the number of connections available to below the standard development DB quota of 20 open connections.

    There is an article here about how to move your postgresql database to the free/cheap tier of Amazon RDS. This would allow you to set max_connections higher. This will also allow you to pool connections at the database level using PGBouncer.

    https://www.lewagon.com/blog/how-to-migrate-heroku-postgres-database-to-amazon-rds

    UPDATE:

    Heroku responded to my open ticket and stated that my database was improperly load balanced in their network. They said that improvements to their system should prevent similar problems in the future. Nonetheless, support manually relocated my database and performance is noticeably improved.

    How can I disable ReSharper in Visual Studio and enable it again?

    In ReSharper 8: Tools -> Options -> ReSharper -> Suspend Now

    Rendering React Components from Array of Objects

    You can map the list of stations to ReactElements.

    With React >= 16, it is possible to return multiple elements from the same component without needing an extra html element wrapper. Since 16.2, there is a new syntax <> to create fragments. If this does not work or is not supported by your IDE, you can use <React.Fragment> instead. Between 16.0 and 16.2, you can use a very simple polyfill for fragments.

    Try the following

    // Modern syntax >= React 16.2.0
    const Test = ({stations}) => (
      <>
        {stations.map(station => (
          <div className="station" key={station.call}>{station.call}</div>
        ))}
      </>
    ); 
    
    // Modern syntax < React 16.2.0
    // You need to wrap in an extra element like div here
    
    const Test = ({stations}) => (
      <div>
        {stations.map(station => (
          <div className="station" key={station.call}>{station.call}</div>
        ))}
      </div>
    ); 
    
    // old syntax
    var Test = React.createClass({
        render: function() {
            var stationComponents = this.props.stations.map(function(station) {
                return <div className="station" key={station.call}>{station.call}</div>;
            });
            return <div>{stationComponents}</div>;
        }
    });
    
    var stations = [
      {call:'station one',frequency:'000'},
      {call:'station two',frequency:'001'}
    ]; 
    
    ReactDOM.render(
      <div>
        <Test stations={stations} />
      </div>,
      document.getElementById('container')
    );
    

    Don't forget the key attribute!

    https://jsfiddle.net/69z2wepo/14377/

    What do the return values of Comparable.compareTo mean in Java?

    System.out.println(A.compareTo(B)>0?"Yes":"No")

    if the value of A>B it will return "Yes" or "No".

    How to call a C# function from JavaScript?

    You can't. Javascript runs client side, C# runs server side.

    In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.

    To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.

    How to Display Multiple Google Maps per page with API V3

    You could try nex approach css

     .map {
                height: 300px;
                width: 100%;
            }
    

    HTML

    @foreach(var map in maps)
    {
      <div id="[email protected]" lat="@map.Latitude" lng="@map.Longitude" class="map">
      </div>
    }
    

    JavaScript

     <script>
        var maps = [];
        var markers = [];
        function initMap() {
            var $maps = $('.map');
            $.each($maps, function (i, value) {
                var uluru = { lat: parseFloat($(value).attr('lat')), lng: parseFloat($(value).attr('lng')) };
    
                var mapDivId = $(value).attr('id');
    
                maps[mapDivId] = new google.maps.Map(document.getElementById(mapDivId), {
                    zoom: 17,
                    center: uluru
                });
    
                markers[mapDivId] = new google.maps.Marker({
                    position: uluru,
                    map: maps[mapDivId]
                });
            })
        }
    </script>
    
    <script async defer
            src="https://maps.googleapis.com/maps/api/js?language=ru-Ru&key=YOUR_KEY&callback=initMap">
    </script>
    

    /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

    In my case it was gcc 6 the one missing

    sudo apt-get install gcc-6 g++-6 -y 
    

    Update

    sudo apt-get install gcc-7 g++-7 -y
    

    Build project into a JAR automatically in Eclipse

    This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.

    Button Listener for button in fragment in android

    You only have to get the view of activity that carry this fragment and this could only happen when your fragment is already created

    override the onViewCreated() method inside your fragment and enjoy its magic :) ..

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button button = (Button) view.findViewById(R.id.YOURBUTTONID);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             //place your action here
             }
        });
    

    Hope this could help you ;

    How to export SQL Server database to MySQL?

    if you have a MSSQL compatible SQL dump you can convert it to MySQL queries one by one using this online tool

    http://burrist.com/mstomy.php

    Hope it saved your time

    grabbing first row in a mysql query only

    You can get the total number of rows containing a specific name using:

    SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'
    

    Given the count, you can now get the nth row using:

    SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1
    

    Where 1 <= n <= COUNT(*) from the first query.

    Example:

    getting the 3rd row

    SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1
    

    Convert Dictionary to JSON in Swift

    Swift 3.0

    With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

    let dic = ["2": "B", "1": "A", "3": "C"]
    
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
        // here "jsonData" is the dictionary encoded in JSON data
    
        let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
        // here "decoded" is of type `Any`, decoded from JSON data
    
        // you can now cast it with the right type        
        if let dictFromJSON = decoded as? [String:String] {
            // use dictFromJSON
        }
    } catch {
        print(error.localizedDescription)
    }
    

    Swift 2.x

    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
        // here "jsonData" is the dictionary encoded in JSON data
    
        let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
        // here "decoded" is of type `AnyObject`, decoded from JSON data
    
        // you can now cast it with the right type 
        if let dictFromJSON = decoded as? [String:String] {
            // use dictFromJSON
        }
    } catch let error as NSError {
        print(error)
    }
    

    Swift 1

    var error: NSError?
    if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
        if error != nil {
            println(error)
        } else {
            // here "jsonData" is the dictionary encoded in JSON data
        }
    }
    
    if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
        if error != nil {
            println(error)
        } else {
            // here "decoded" is the dictionary decoded from JSON data
        }
    }
    

    Can two applications listen to the same port?

    Yes.

    From this article:
    https://lwn.net/Articles/542629/

    The new socket option allows multiple sockets on the same host to bind to the same port

    How to find duplicate records in PostgreSQL

    From "Find duplicate rows with PostgreSQL" here's smart solution:

    select * from (
      SELECT id,
      ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
      FROM tbl
    ) dups
    where 
    dups.Row > 1
    

    How to add and remove item from array in components in Vue 2

    There are few mistakes you are doing:

    1. You need to add proper object in the array in addRow method
    2. You can use splice method to remove an element from an array at particular index.
    3. You need to pass the current row as prop to my-item component, where this can be modified.

    You can see working code here.

    addRow(){
       this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
    },
    removeRow(index){
       this. itemList.splice(index, 1)
    }
    

    Get current NSDate in timestamp format

    // The following method would return you timestamp after converting to milliseconds. [RETURNS STRING]

    - (NSString *) timeInMiliSeconds
    {
        NSDate *date = [NSDate date];
        NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
        return timeInMS;
    }
    

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

    $('#id option').remove();
    

    This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();

    How to change owner of PostgreSql database?

    ALTER DATABASE name OWNER TO new_owner;
    

    See the Postgresql manual's entry on this for more details.

    ORA-12560: TNS:protocol adaptor error

    If none the above work, then try this : Modify the LISTENER.ora (mine is found in : oracle\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora) ==> add a custom listener that points to your database(SID), example my SID is XZ0301, so :

    ## Base XZ03001
    
    SID_LIST_LISTENER_XZ03001=(SID_LIST=(SID_DESC=(ORACLE_HOME =
    E:\oracle\product\11.2.0\dbhome_1)(SID_NAME= XZ03001)))
    
    LISTENER_XZ03001=(DESCRIPTION_LIST=(ADDRESS=(PROTOCOL =
    TCP)(HOST=MyComputerName)(PORT= 1521)))
    
    DIAG_ADR_ENABLED_LISTENER_XZ03001=ON
    
    ADR_BASE_LISTENER_XZ03001=E:\oracle
    

    Restart your machine

    For Windows 7, use the following to modify the LISTENER.ora: - Go to Start > All Programs > Accessories - Right click Notepad and then click Run as Administrator . - File>open and navigate to the tnsnames.ora file. - Make the changes then it should allow you to save

    Android - How To Override the "Back" button so it doesn't Finish() my Activity?

    simply do this..

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
    }
    

    commenting out the //super.onBackPressed(); will do the trick

    What is pluginManagement in Maven's pom.xml?

    So if i understood well, i would say that <pluginManagement> just like <dependencyManagement> are both used to share only the configuration between a parent and it's sub-modules.

    For that we define the dependencie's and plugin's common configurations in the parent project and then we only have to declare the dependency/plugin in the sub-modules to use it, without having to define a configuration for it (i.e version or execution, goals, etc). Though this does not prevent us from overriding the configuration in the submodule.

    In contrast <dependencies> and <plugins> are inherited along with their configurations and should not be redeclared in the sub-modules, otherwise a conflict would occur.

    is that right ?

    How can I convert a DateTime to the number of seconds since 1970?

    If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:

    long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();