Programs & Examples On #Ownership

how to move elasticsearch data from one server to another

Use ElasticDump

1) yum install epel-release

2) yum install nodejs

3) yum install npm

4) npm install elasticdump

5) cd node_modules/elasticdump/bin

6)

./elasticdump \

  --input=http://192.168.1.1:9200/original \

  --output=http://192.168.1.2:9200/newCopy \

  --type=data

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Speed up rsync with Simultaneous/Concurrent File Transfers?

Have you tried using rclone.org?

With rclone you could do something like

rclone copy "${source}/${subfolder}/" "${target}/${subfolder}/" --progress --multi-thread-streams=N

where --multi-thread-streams=N represents the number of threads you wish to spawn.

XAMPP Port 80 in use by "Unable to open process" with PID 4

I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready

opened the httpd.conf and changed the listen port from 80 to 1234 in both places

Listen 12.34.56.78:1234

Listen 1234

Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234

That worked.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

sending email via php mail function goes to spam

The problem is simple that the PHP-Mail function is not using a well configured SMTP Server.

Nowadays Email-Clients and Servers perform massive checks on the emails sending server, like Reverse-DNS-Lookups, Graylisting and whatevs. All this tests will fail with the php mail() function. If you are using a dynamic ip, its even worse.

Use the PHPMailer-Class and configure it to use smtp-auth along with a well configured, dedicated SMTP Server (either a local one, or a remote one) and your problems are gone.

https://github.com/PHPMailer/PHPMailer

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

os.chmod(
    'myfile',
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH
)

This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

VC++ fatal error LNK1168: cannot open filename.exe for writing

The Reason is that your previous build is still running in the background. I solve this problem by following these steps:

  • Open Task Manager
  • Goto Details Tab
  • Find Your Application
  • End Task it by right clicking on it
  • Done!

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Specify an SSH key for git push for a given domain

To use a specific key on the fly:

GIT_SSH_COMMAND='ssh -i $HOME/.ssh/id_ed25519 -o IdentitiesOnly=yes -F /dev/null' git push origin c13_training_network

Explanation:

  • local ENV var before doing the push
  • -i specifies key
  • -F forces an empty config so your global one doesn't overwrite this temporary command

mysql data directory location

If the software is Sequel pro the default install mysql on Mac OSX has data located here:

/usr/local/var/mysql

Are Git forks actually Git clones?

Cloning involves making a copy of the git repository to a local machine, while forking is cloning the repository into another repository. Cloning is for personal use only (although future merges may occur), but with forking you are copying and opening a new possible project path

How to limit depth for recursive file list?

Checkout the -maxdepth flag of find

find . -maxdepth 1 -type d -exec ls -ld "{}" \;

Here I used 1 as max level depth, -type d means find only directories, which then ls -ld lists contents of, in long format.

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

In my case, the solution was to make every directory in the directory path readable and accessible by mysql (chmod a+rx). The directory was still specified by its relative path in the command line.

chmod a+rx /tmp
chmod a+rx /tmp/migration
etc.

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

I also had this problem recently, and it was the SELinux which caused it. I was trying to have the post-commit of subversion to notify Jenkins that the code has change so Jenkins would do a build and deploy to Nexus.

I had to do the following to get it to work.

1) First I checked if SELinux is enabled:

    less /selinux/enforce

This will output 1 (for on) or 0 (for off)

2) Temporary disable SELinux:

    echo 0 > /selinux/enforce

Now test see if it works now.

3) Enable SELinux:

    echo 1 > /selinux/enforce

Change the policy for SELinux.

4) First view the current configuration:

    /usr/sbin/getsebool -a | grep httpd

This will give you: httpd_can_network_connect --> off

5) Set this to on and your post-commit will work with SELinux:

    /usr/sbin/setsebool -P httpd_can_network_connect on

Now it should be working again.

What good are SQL Server schemas?

I tend to agree with Brent on this one... see this discussion here. http://www.brentozar.com/archive/2010/05/why-use-schemas/

In short... schemas aren't terribly useful except for very specific use cases. Makes things messy. Do not use them if you can help it. And try to obey the K(eep) I(t) S(imple) S(tupid) rule.

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Do aman 2 sendfile. You only need to open the source file on the client and destination file on the server, then call sendfile and the kernel will chop and move the data.

ESLint Parsing error: Unexpected token

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

Check if object is a jQuery object

return el instanceof jQuery ? el.size() > 0 : (el && el.tagName);

Convert Unix timestamp into human readable date using MySQL

Need a unix timestamp in a specific timezone?

Here's a one liner if you have quick access to the mysql cli:

mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';

+---------------------+
| local time          |
+---------------------+
| 2016-06-27 23:37:31 |
+---------------------+

Replace 'MST' with your desired timezone. I live in Arizona thus the conversion from UTC to MST.

How to validate phone number in laravel 5.2?

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

Numbering rows within groups in a data frame

Another dplyr possibility could be:

df %>%
 group_by(cat) %>%
 mutate(num = 1:n())

   cat      val   num
   <fct>  <dbl> <int>
 1 aaa   0.0564     1
 2 aaa   0.258      2
 3 aaa   0.308      3
 4 aaa   0.469      4
 5 aaa   0.552      5
 6 bbb   0.170      1
 7 bbb   0.370      2
 8 bbb   0.484      3
 9 bbb   0.547      4
10 bbb   0.812      5
11 ccc   0.280      1
12 ccc   0.398      2
13 ccc   0.625      3
14 ccc   0.763      4
15 ccc   0.882      5

Breaking up long strings on multiple lines in Ruby without stripping newlines

Maybe this is what you're looking for?

string = "line #1"\
         "line #2"\
         "line #3"

p string # => "line #1line #2line #3"

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

MySQL remove all whitespaces from the entire column

Using below query you can remove leading and trailing whitespace in a MySQL.

UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);

Convert Year/Month/Day to Day of Year in Python

You could use strftime with a %j format string:

>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'

but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.

Setting a log file name to include current date in Log4j

Using log4j.properties file, and including apache-log4j-extras 1.1 in my POM with log4j 1.2.16

log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.LOGFILE.RollingPolicy.FileNamePattern=/logs/application_%d{yyyy-MM-dd}.log

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

Freely convert between List<T> and IEnumerable<T>

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.

Batch not-equal (inequality) operator

Use NEQ instead.

if "asdf" NEQ "fdas" echo asdf

HMAC-SHA256 Algorithm for signature calculation

If you're using Guava, its latest release now lets you use

 Hashing.hmacSha256()

Further documentation here: https://guava.dev/releases/23.0/api/docs/com/google/common/hash/Hashing.html#hmacSha256-byte:A-

Is there a way to force npm to generate package-lock.json?

When working with local packages, the only way I found to reliably regenerate the package-lock.json file is to delete it, as well as in the linked modules and all corresponding node_modules folders and let it be regenerated with npm i

Javascript foreach loop on associative array object

_x000D_
_x000D_
var obj = {_x000D_
  no: ["no", 32],_x000D_
  nt: ["no", 32],_x000D_
  nf: ["no", 32, 90]_x000D_
};_x000D_
_x000D_
count = -1; // which must be static value_x000D_
for (i in obj) {_x000D_
  count++;_x000D_
  if (obj.hasOwnProperty(i)) {_x000D_
    console.log(obj[i][count])_x000D_
  };_x000D_
};
_x000D_
_x000D_
_x000D_

in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array

perfect Method , if you interested, press like

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

T-SQL: Opposite to string concatenation - how to split string into multiple records

I use this function (SQL Server 2005 and above).

create function [dbo].[Split]
(
    @string nvarchar(4000),
    @delimiter nvarchar(10)
)
returns @table table
(
    [Value] nvarchar(4000)
)
begin
    declare @nextString nvarchar(4000)
    declare @pos int, @nextPos int

    set @nextString = ''
    set @string = @string + @delimiter

    set @pos = charindex(@delimiter, @string)
    set @nextPos = 1
    while (@pos <> 0)
    begin
        set @nextString = substring(@string, 1, @pos - 1)

        insert into @table
        (
            [Value]
        )
        values
        (
            @nextString
        )

        set @string = substring(@string, @pos + len(@delimiter), len(@string))
        set @nextPos = @pos
        set @pos = charindex(@delimiter, @string)
    end
    return
end

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

HTTP requests and JSON parsing in Python

Also for pretty Json on console:

 json.dumps(response.json(), indent=2)

possible to use dumps with indent. (Please import json)

How do I tell Spring Boot which main class to use for the executable jar?

For those using Gradle (instead of Maven), referencing here:

The main class can also be configured explicitly using the task’s mainClassName property:

bootJar {
    mainClassName = 'com.example.ExampleApplication'
}

Alternatively, the main class name can be configured project-wide using the mainClassName property of the Spring Boot DSL:

springBoot {
    mainClassName = 'com.example.ExampleApplication'
}

How to check status of PostgreSQL server Mac OS X

It depends on where your postgresql server is installed. You use the pg_ctl to manually start the server like below.

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

linux execute command remotely

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh

http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/

How to align the checkbox and label in same line in html?

You should use <label for=""> for the checkboxes or radios, and to align checkboxes vertical-align is enough

Try changing your markup to this

<li>
    <input id="checkid" type="checkbox" value="test" />
    <label for="checkid">testdata</label>
</li>

<li>
    <input id="checkid2" type="checkbox" value="test" />
    <label for="checkid2">testdata 2</label>
</li>

And set CSS like

input[type="checkbox"]
{
    vertical-align:middle;
}

In case of long text

label,input{
    display: inline-block;
    vertical-align: middle;
}

Side note: In label, value of for must be the id of checkbox.

Fiddle

Updated Fiddle

Convert a bitmap into a byte array

MemoryStream ms = new MemoryStream();
yourBitmap.Save(ms, ImageFormat.Bmp);
byte[] bitmapData = ms.ToArray();

Python: avoiding pylint warnings about too many arguments

Perhaps you could turn some of the arguments into member variables. If you need that much state a class sounds like a good idea to me.

Quickest way to convert a base 10 number to any base in .NET?

FAST "FROM" AND "TO" METHODS

I am late to the party, but I compounded previous answers and improved over them. I think these two methods are faster than any others posted so far. I was able to convert 1,000,000 numbers from and to base 36 in under 400ms in a single core machine.

Example below is for base 62. Change the BaseChars array to convert from and to any other base.

private static readonly char[] BaseChars = 
         "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
           .Select((c,i)=>new {Char=c, Index=i})
           .ToDictionary(c=>c.Char,c=>c.Index);

public static string LongToBase(long value)
{
   long targetBase = BaseChars.Length;
   // Determine exact number of characters to use.
   char[] buffer = new char[Math.Max( 
              (int) Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];

   var i = buffer.Length;
   do
   {
       buffer[--i] = BaseChars[value % targetBase];
       value = value / targetBase;
   }
   while (value > 0);

   return new string(buffer, i, buffer.Length - i);
}

public static long BaseToLong(string number) 
{ 
    char[] chrs = number.ToCharArray(); 
    int m = chrs.Length - 1; 
    int n = BaseChars.Length, x;
    long result = 0; 
    for (int i = 0; i < chrs.Length; i++)
    {
        x = CharValues[ chrs[i] ];
        result += x * (long)Math.Pow(n, m--);
    }
    return result;  
} 

EDIT (2018-07-12)

Fixed to address the corner case found by @AdrianBotor (see comments) converting 46655 to base 36. This is caused by a small floating-point error calculating Math.Log(46656, 36) which is exactly 3, but .NET returns 3 + 4.44e-16, which causes an extra character in the output buffer.

How to delete the contents of a folder?

import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

Open-Source Examples of well-designed Android Applications?

I recommend the Last.fm for Android application: http://github.com/c99koder/lastfm-android

UPDATE: I'm not sure this is a good example anymore, it hasn't been updated in 2-3 years.

Handling MySQL datetimes and timestamps in Java

In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date. It is basically backed by the Epoch time in flavor of a long, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.

In SQL side, there are several standard date and time types, DATE, TIME and TIMESTAMP (at some DB's also called DATETIME), which are represented in JDBC as java.sql.Date, java.sql.Time and java.sql.Timestamp, all subclasses of java.util.Date. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.

In contrary to java.util.Date, the java.sql.Date contains only information about the date part (year, month, day). The Time contains only information about the time part (hours, minutes, seconds) and the Timestamp contains information about the both parts, like as java.util.Date does.

The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().

java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);

The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().

Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.

Unexpected token }

Try running the entire script through jslint. This may help point you at the cause of the error.

Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.

Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.

This snippet of code is taken from your edit function which is in the inline script block of your HTML:

var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");

Note that this sets the onclick attribute of an element to invalid JavaScript code:

<input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">

The JS is:

save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value

Note the missing close paren to finish the call to save.

As an aside, inserting onclick attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.

How do you make a deep copy of an object?

Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

Android Spinner : Avoid onItemSelected calls during initialization

Code

spinner.setOnTouchListener(new View.OnTouchListener() { 
@Override public boolean onTouch(View view, MotionEvent motionEvent) { isSpinnerTouch=true; return false; }});

holder.spinner_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int slot_position, long l) {
                if(isSpinnerTouch)
                {
                    Log.d("spinner_from", "spinner_from");
                    spinnerItemClickListener.onSpinnerItemClickListener(position, slot_position, AppConstant.FROM_SLOT_ONCLICK_CODE);
                }
                else {

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

In SQL, is UPDATE always faster than DELETE+INSERT?

Obviously, the answer varies based on what database you are using, but UPDATE can always be implemented faster than DELETE+INSERT. Since in-memory ops are mostly trivial anyways, given a hard-drive based database, an UPDATE can change a database field in-place on the hdd, while a delete would remove a row (leaving an empty space), and insert a new row, perhaps to the end of the table (again, it's all in the implementation).

The other, minor, issue is that when you UPDATE a single variable in a single row, the other columns in that row remain the same. If you DELETE and then do an INSERT, you run the risk of forgetting about other columns and consequently leaving them behind (in which case you would have to do a SELECT before your DELETE to temporarily store your other columns before writing them back with INSERT).

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Creating PHP class instance with a string

Yes, you can!

$str = 'One';
$class = 'Class'.$str;
$object = new $class();

When using namespaces, supply the fully qualified name:

$class = '\Foo\Bar\MyClass'; 
$instance = new $class();

Other cool stuff you can do in php are:
Variable variables:

$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123

And variable functions & methods.

$func = 'my_function';
$func('param1'); // calls my_function('param1');

$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method. 

PHP FPM - check if running

For php7.0-fpm I call:

service php7.0-fpm status

php7.0-fpm start/running, process 25993

Now watch for the good part. The process name is actually php-fpm7.0

echo `/bin/pidof php-fpm7.0`

26334 26297 26286 26285 26282

Maximum number of threads in a .NET app?

I would recommend running ThreadPool.GetMaxThreads method in debug

ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);

Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

Group array items using object

One option is:

var res = myArray.reduce(function(groups, currentValue) {
    if ( groups.indexOf(currentValue.group) === -1 ) {
      groups.push(currentValue.group);
    }
    return groups;
}, []).map(function(group) {
    return {
        group: group,
        color: myArray.filter(function(_el) {
          return _el.group === group;
        }).map(function(_el) { return _el.color; })
    }
});

http://jsfiddle.net/dvgwodxq/

Using column alias in WHERE clause of MySQL query produces an error

Maybe my answer is too late but this can help others.

You can enclose it with another select statement and use where clause to it.

SELECT * FROM (Select col1, col2,...) as t WHERE t.calcAlias > 0

calcAlias is the alias column that was calculated.

What is a LAMP stack?

LAMP means: L = Linux (OS) A = Apache (web server) M = MySQL (database) P = PHP (language)

From LAMP (Wikipedia):

Short for Linux, Apache, MySQL and PHP, an open-source Web development platform, also called a Web stack, that uses Linux as the operating system, Apache as the Web server, MySQL as the RDBMS and PHP as the object-oriented scripting language. Perl or Python is often substituted for PHP.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

I know there were lots of answers here, but the TL;DR version is this (If you're using Xamarin Studio):

  1. Right click the Android project in the solution tree
  2. Select Options
  3. Go to Android Build
  4. Go to Advanced tab
  5. Check the architectures you use in your emulator (Probably x86 / armeabi-v7a / armeabi)
  6. Make a kickass app :)

Is it better to use path() or url() in urls.py for django 2.0?

Regular expressions don't seem to work with the path() function with the following arguments: path(r'^$', views.index, name="index").

It should be like this: path('', views.index, name="index").

The 1st argument must be blank to enter a regular expression.

How to print a string at a fixed width?

I found ljust() and rjust() very useful to print a string at a fixed width or fill out a Python string with spaces.

An example

print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89

For your case, you case use fstring to print

for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")

Expected Output

value  a   - num of occurrences = 1
value  ab  - num of occurrences = 1
value  abc - num of occurrences = 1
value  b   - num of occurrences = 1
value  bc  - num of occurrences = 1
value  bcd - num of occurrences = 1
value  c   - num of occurrences = 1
value  cd  - num of occurrences = 1
value  d   - num of occurrences = 1

You can change 3 to the highest length of your permutation string.

"R cannot be resolved to a variable"?

for me, the best solution to suggest to people that have problems with the "R" file would be to try the next steps (order doesn't matter) :

  1. update ADT & SDK , Eclipse and Java (both 1.6 and the latest one).

    EDIT: now the ADT supports Java 1.7 . link here.

  2. remove gen folder , and create it again .

  3. do a clean-project.

  4. right click the project and choose android-tools -> fix-project-properties .

  5. right click the project and choose properties -> java-build-path -> order-and-export. make sure the order is :

    • Android 4.4 (always the latest version)

    • Android private libraries

    • android dependencies

    • your library project/s if needed

    • yourAppProject/gen

    • yourAppProject/src

  6. make sure all files in the res folder's subfolders have names that are ok : only lowercase letters, digits and underscore ("_") .

  7. always make sure the targetSdk is pointed to the latest API (currently 19) , and set it in the project.properties file

  8. try to run Lint and read its warnings. they might help you out.

  9. make sure your project compiles on 1.6 java and not a different version.

  10. restart eclipse.

ECONNREFUSED error when connecting to mongodb from node.js

OK, this was another case of not being truly forthcoming in the info I posted above. My node.js app was very simple, but I was including another couple lines in my node.js code that apparently caused this issue.

Specifically, I had another variable declared which was calling some other code that made a separate database call using incorrect db info. This is why, when using Xinzz's code, the console log error seemed not to change. It wasn't actually the mongoose.connect command that was throwing the error!

Lesson learned, localize the problem and comment out unrelated code! Sorry guys, I knew this was me being dumb.

Copying files into the application folder at compile time

You can also put the files or links into the root of the solution explorer and then set the files properties:

Build action = Content

and

Copy to Output Directory = Copy if newer (for example)

For a link drag the file from the windows explorer into the solution explorer holding down the shift and control keys.

enter image description here

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I faced a similar (but not identical) issue.

I had to go to to Turn Windows features on or off in Control Panel and add ASP.NET 3.5 and 4.7: enter image description here

Then it worked for me.

How to install sshpass on mac?

Solution provided by lukesUbuntu from github works for me:

Just use brew

$ brew install http://git.io/sshpass.rb

What is the alternative for ~ (user's home directory) on Windows command prompt?

You're going to be disappointed: %userprofile%

You can use other terminals, though. Powershell, which I believe you can get on XP and later (and comes preinstalled with Win7), allows you to use ~ for home directory.

Difference between socket and websocket?

You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.

The Socket.IO module available for node.js can help a lot, but note that it is not a pure WebSocket module in its own right.

It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.

Hence if you want to use Socket.IO on the server end you must also use their client code and objects. You can't easily make raw WebSocket connections to a socket.io server as you'd have to emulate their message protocol.

Detecting negative numbers

if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")

Java string to date conversion

My humble test program. I use it to play around with the formatter and look-up long dates that I find in log-files (but who has put them there...).

My test program:

package be.test.package.time;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class TimeWork {

    public static void main(String[] args) {    

        TimeZone timezone = TimeZone.getTimeZone("UTC");

        List<Long> longs = new ArrayList<>();
        List<String> strings = new ArrayList<>();

        //Formatting a date needs a timezone - otherwise the date get formatted to your system time zone.
        //Use 24h format HH. In 12h format hh can be in range 0-11, which makes 12 overflow to 0.
        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
        formatter.setTimeZone(timezone);

        Date now = new Date();

        //Test dates
        strings.add(formatter.format(now));
        strings.add("01-01-1970 00:00:00.000");
        strings.add("01-01-1970 00:00:01.000");
        strings.add("01-01-1970 00:01:00.000");
        strings.add("01-01-1970 01:00:00.000");
        strings.add("01-01-1970 10:00:00.000");
        strings.add("01-01-1970 12:00:00.000");
        strings.add("01-01-1970 24:00:00.000");
        strings.add("02-01-1970 00:00:00.000");
        strings.add("01-01-1971 00:00:00.000");
        strings.add("01-01-2014 00:00:00.000");
        strings.add("31-12-1969 23:59:59.000");
        strings.add("31-12-1969 23:59:00.000");
        strings.add("31-12-1969 23:00:00.000");

        //Test data
        longs.add(now.getTime());
        longs.add(-1L);
        longs.add(0L); //Long date presentation at - midnight 1/1/1970 UTC - The timezone is important!
        longs.add(1L);
        longs.add(1000L);
        longs.add(60000L);
        longs.add(3600000L);
        longs.add(36000000L);
        longs.add(43200000L);
        longs.add(86400000L);
        longs.add(31536000000L);
        longs.add(1388534400000L);
        longs.add(7260000L);
        longs.add(1417706084037L);
        longs.add(-7260000L);

        System.out.println("===== String to long =====");

        //Show the long value of the date
        for (String string: strings) {
            try {
                Date date = formatter.parse(string);
                System.out.println("Formated date : " + string + " = Long = " + date.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        System.out.println("===== Long to String =====");

        //Show the date behind the long
        for (Long lo : longs) {
            Date date = new Date(lo);
            String string = formatter.format(date);
            System.out.println("Formated date : " + string + " = Long = " + lo);        
        }
    }
}

Test results:

===== String to long =====
Formated date : 05-12-2014 10:17:34.873 = Long = 1417774654873
Formated date : 01-01-1970 00:00:00.000 = Long = 0
Formated date : 01-01-1970 00:00:01.000 = Long = 1000
Formated date : 01-01-1970 00:01:00.000 = Long = 60000
Formated date : 01-01-1970 01:00:00.000 = Long = 3600000
Formated date : 01-01-1970 10:00:00.000 = Long = 36000000
Formated date : 01-01-1970 12:00:00.000 = Long = 43200000
Formated date : 01-01-1970 24:00:00.000 = Long = 86400000
Formated date : 02-01-1970 00:00:00.000 = Long = 86400000
Formated date : 01-01-1971 00:00:00.000 = Long = 31536000000
Formated date : 01-01-2014 00:00:00.000 = Long = 1388534400000
Formated date : 31-12-1969 23:59:59.000 = Long = -1000
Formated date : 31-12-1969 23:59:00.000 = Long = -60000
Formated date : 31-12-1969 23:00:00.000 = Long = -3600000
===== Long to String =====
Formated date : 05-12-2014 10:17:34.873 = Long = 1417774654873
Formated date : 31-12-1969 23:59:59.999 = Long = -1
Formated date : 01-01-1970 00:00:00.000 = Long = 0
Formated date : 01-01-1970 00:00:00.001 = Long = 1
Formated date : 01-01-1970 00:00:01.000 = Long = 1000
Formated date : 01-01-1970 00:01:00.000 = Long = 60000
Formated date : 01-01-1970 01:00:00.000 = Long = 3600000
Formated date : 01-01-1970 10:00:00.000 = Long = 36000000
Formated date : 01-01-1970 12:00:00.000 = Long = 43200000
Formated date : 02-01-1970 00:00:00.000 = Long = 86400000
Formated date : 01-01-1971 00:00:00.000 = Long = 31536000000
Formated date : 01-01-2014 00:00:00.000 = Long = 1388534400000
Formated date : 01-01-1970 02:01:00.000 = Long = 7260000
Formated date : 04-12-2014 15:14:44.037 = Long = 1417706084037
Formated date : 31-12-1969 21:59:00.000 = Long = -7260000

How to export data from Excel spreadsheet to Sql Server 2008 table

In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:

On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.

After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

How do you make an anchor link non-clickable or disabled?

Use pointer-events CSS style. (as Jason MacDonald suggested)

See MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events. Its supported in most browsers.

Simple adding "disabled" attribute to anchor will do the job if you have global CSS rule like following:

a[disabled], a[disabled]:hover {
   pointer-events: none;
   color: #e1e1e1;
}

What's the best way to validate an XML file against an XSD file?

The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

Update statement with inner join on Oracle

MERGE with WHERE clause:

MERGE into table1
USING table2
ON (table1.id = table2.id)
WHEN MATCHED THEN UPDATE SET table1.startdate = table2.start_date
WHERE table1.startdate > table2.start_date;

You need the WHERE clause because columns referenced in the ON clause cannot be updated.

Make iframe automatically adjust height according to the contents without using scrollbar?

This option will work 100%

<iframe id='iframe2' src="url.com" frameborder="0" style="overflow: hidden; height: 100%; width: 100%; position: absolute;" height="100%" width="100%"></iframe>

Passing data between different controller action methods

HTTP and redirects

Let's first recap how ASP.NET MVC works:

  1. When an HTTP request comes in, it is matched against a set of routes. If a route matches the request, the controller action corresponding to the route will be invoked.
  2. Before invoking the action method, ASP.NET MVC performs model binding. Model binding is the process of mapping the content of the HTTP request, which is basically just text, to the strongly typed arguments of your action method

Let's also remind ourselves what a redirect is:

An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult from an action.

Passing data

If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location header. This is what would happen if you used something like

return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });

as others have suggested

The reason that this will not work is that the XDocument is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument action parameter.

In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.

Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.

Storing data for retrieval on the next request

So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session (or TempData, which is more or less the same as the Session in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:

int documentId = _myDocumentRepository.Save(updatedResultsDocument);

and then you return that key to the client:

return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });

When you want to retrieve the document, you simply fetch it based on the key:

 public ActionResult UpdateConfirmation(int id)
 {
      XDocument doc = _myDocumentRepository.GetById(id);

      ConfirmationModel model = new ConfirmationModel(doc);

      return View(model);
 }

Contains case insensitive

Example for any language:

'My name is ??????'.toLocaleLowerCase().includes('??????'.toLocaleLowerCase())

C# looping through an array

This should work:

//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
    var a = theData[i];
    var b = theData[i + 1];
    var c = theData[i + 2];
}

I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.

How to correctly set Http Request Header in Angular 2

For us we used a solution like this:

this.http.get(this.urls.order + '&list', {
        headers: {
            'Cache-Control': 'no-cache',
        }
    }).subscribe((response) => { ...

Reference here

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

iOS 7 - Status bar overlaps the view

This is the default behaviour for UIViewController on iOS 7. The view will be full-screen which means the status bar will cover the top of your view.

If you have a UIViewController within a UINavigationController and the navigationBar is visible, you can have the following code in your viewDidLoad or have a background image for navigationBar do the trick.

self.edgesForExtendedLayout = UIRectEdgeNone;

If you have navigationBar hidden, then you have to adjust all the UIView elements by shifting 20 points. I dont't see any other solution. Use auto layout will help a little bit.

Here is the sample code for detecting the iOS version, if you want to backward compatibility.

NSUInteger DeviceSystemMajorVersion() {
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        NSString *systemVersion = [UIDevice currentDevice].systemVersion;
        _deviceSystemMajorVersion = [[systemVersion componentsSeparatedByString:@"."][0] intValue];
    });

   return _deviceSystemMajorVersion;
}

Access a JavaScript variable from PHP

The short answer is you can't.

I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).

You're doing a $_GET, which is used to retrieve form values:

The built-in $_GET function is used to collect values in a form with method="get".

In other words, if on your page you had:

<form method="get" action="blah.php">
    <input name="test"></input>
</form>

Your $_GET call would retrieve the value in that input field.

So how to retrieve a value from JavaScript?

Well, you could stick the javascript value in a hidden form field...

<script type="text/javascript" charset="utf-8">
    var test = "tester";
    // find the 'test' input element and set its value to the above variable
    document.getElementByID("test").value = test;
</script>

... elsewhere on your page ...

<form method="get" action="blah.php">
    <input id="test" name="test" visibility="hidden"></input>
    <input type="submit" value="Click me!"></input>
</form>

Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.

Find non-ASCII characters in varchar columns using SQL Server

To find which field has invalid characters:

SELECT * FROM Staging.APARMRE1 FOR XML AUTO, TYPE

You can test it with this query:

SELECT top 1 'char 31: '+char(31)+' (hex 0x1F)' field
from sysobjects
FOR XML AUTO, TYPE

The result will be:

Msg 6841, Level 16, State 1, Line 3 FOR XML could not serialize the data for node 'field' because it contains a character (0x001F) which is not allowed in XML. To retrieve this data using FOR XML, convert it to binary, varbinary or image data type and use the BINARY BASE64 directive.

It is very useful when you write xml files and get error of invalid characters when validate it.

Change limit for "Mysql Row size too large"

If this occures on a SELECT with many columns, the cause can be that mysql is creating a temporary table. If this table is too large to fit in memory, it will use its default temp table format, which is InnoDB, to store it on Disk. In this case the InnoDB size limits apply.

You then have 4 options:

  1. change the innodb row size limit like stated in another post, which requires reinitialization of the server.
  2. change your query to include less columns or avoid causing it to create a temporary table (by i.e. removing order by and limit clauses).
  3. changing max_heap_table_size to be large so the result fits in memory and does not need to get written to disk.
  4. change the default temp table format to MYISAM, this is what i did. Change in my.cnf:

    internal_tmp_disk_storage_engine=MYISAM
    

Restart mysql, query works.

printing all contents of array in C#

If it's an array of strings you can use Aggregate

var array = new string[] { "A", "B", "C", "D"};
Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D

that way you can reverses the order by changing the order of the parameters like so

Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A

Where does git config --global get written to?

I am using SmartGit with msysgit on Windows 8.1 and noticed that there can be three different locations for the gitconfig file:

%USERPROFILE%\.gitconfig
C:\Program Files (x86)\Git\etc\gitconfig
C:\Program Files (x86)\SmartGitHg\git\etc\gitconfig

But the one that is used is the one from %USERPROFILE%\.gitconfig.

Angular 2: How to call a function after get a response from subscribe http.post

You can do this be using a new Subject too:

Typescript:

let subject = new Subject();

get_categories(...) {
   this.http.post(...).subscribe( 
      (response) => {
         this.total = response.json();
         subject.next();
      }
   ); 

   return subject; // can be subscribed as well 
}

get_categories(...).subscribe(
   (response) => {
     // ...
   }
);

Flexbox: 4 items per row

Flex wrap + negative margin

Why flex vs. display: inline-block?

Why negative margin?

Either you use SCSS or CSS-in-JS for the edge cases (i.e. first element in column), or you set a default margin and get rid of the outer margin later.

Implementation

https://codepen.io/zurfyx/pen/BaBWpja

<div class="outerContainer">
    <div class="container">
        <div class="elementContainer">
            <div class="element">
            </div>
        </div>
        ...
    </div>
</div>
:root {
  --columns: 2;
  --betweenColumns: 20px; /* This value is doubled when no margin collapsing */
}

.outerContainer {
    overflow: hidden; /* Hide the negative margin */
}

.container {
    background-color: grey;
    display: flex;
    flex-wrap: wrap;
    margin: calc(-1 * var(--betweenColumns));
}

.elementContainer {
    display: flex; /* To prevent margin collapsing */
    width: calc(1/var(--columns) * 100% - 2 * var(--betweenColumns));
    margin: var(--betweenColumns);
}

.element {
    display: flex;
    border: 1px solid red;
    background-color: yellow;
    width: 100%;
    height: 42px;
}

sql - insert into multiple tables in one query

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.

START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;

http://dev.mysql.com/doc/refman/5.1/en/commit.html

JavaScript global event mechanism

Does this help you:

<script type="text/javascript">
window.onerror = function() {
    alert("Error caught");
};

xxx();
</script>

I'm not sure how it handles Flash errors though...

Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:

Mimic Window. onerror in Opera using javascript

ng-if check if array is empty

To overcome the null / undefined issue, try using the ? operator to check existence:

<p ng-if="post?.capabilities?.items?.length > 0">
  • Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf:

    <p *ngIf="post?.capabilities?.items?.length > 0">
    

Get the first item from an iterable that matches a condition

The most efficient way in Python 3 are one of the following (using a similar example):

With "comprehension" style:

next(i for i in range(100000000) if i == 1000)

WARNING: The expression works also with Python 2, but in the example is used range that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use xrange instead).

Note that the expression avoid to construct a list in the comprehension expression next([i for ...]), that would cause to create a list with all the elements before filter the elements, and would cause to process the entire options, instead of stop the iteration once i == 1000.

With "functional" style:

next(filter(lambda i: i == 1000, range(100000000)))

WARNING: This doesn't work in Python 2, even replacing range with xrange due that filter create a list instead of a iterator (inefficient), and the next function only works with iterators.

Default value

As mentioned in other responses, you must add a extra-parameter to the function next if you want to avoid an exception raised when the condition is not fulfilled.

"functional" style:

next(filter(lambda i: i == 1000, range(100000000)), False)

"comprehension" style:

With this style you need to surround the comprehension expression with () to avoid a SyntaxError: Generator expression must be parenthesized if not sole argument:

next((i for i in range(100000000) if i == 1000), False)

How to refresh activity after changing language (Locale) inside application

If I imagined that you set android:configChanges in manifest.xml and create several directory for several language such as: values-fr OR values-nl, I could suggest this code(In Activity class):

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // change language by onclick a button
             Configuration newConfig = new Configuration();
             newConfig.locale = Locale.FRENCH;
             onConfigurationChanged(newConfig);
        }
    });
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
    setContentView(R.layout.main);
    setTitle(R.string.app_name);

    // Checks the active language
    if (newConfig.locale == Locale.ENGLISH) {
        Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
    } else if (newConfig.locale == Locale.FRENCH){
        Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
    }
}

I tested this code, It is correct.

"std::endl" vs "\n"

The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

std::cout << '\n' << std::flush;

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \n if you are worried about performance (which is probably not the case if you are using the << operator).

I use \n on most lines.
Then use std::endl at the end of a paragraph (but that is just a habit and not usually necessary).

Contrary to other claims, the \n character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin and std::cout being special but still files (or file-like)).

selected value get from db into dropdown select box option using php mysql error

This may help you.

?php 
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res))
{
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
// Assuming $list['options'] is a coma seperated options string 
$arr=explode(",",$list['options']);
<?php foreach ($arr as $value) { ?>
   <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php } >
</select>

<?php 
}
?>

Error: free(): invalid next size (fast):

I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.

A simple:

    int* a;
    class foo{ 
    foo(){
       for(i=0;i<n;i++)
           a=new int[i];
     }

Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.

Function to convert column number to letter?

This will work regardless of what column inside your one code line for cell thats located in row X, in column Y:

Mid(Cells(X,Y).Address, 2, instr(2,Cells(X,Y).Address,"$")-2)

If you have a cell with unique defined name "Cellname":

Mid(Cells(1,val(range("Cellname").Column)).Address, 2, instr(2,Cells(1,val(range("Cellname").Column)).Address,"$")-2)

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Here is my answer to a similar question:

I think (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:

var x = this.Handle; 

(See http://ikriv.com/en/prog/info/dotnet/MysteriousHang.html)

Convert JSON format to CSV format for MS Excel

I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3 into CSV and prompt you to download/open in Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
    var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }

    DownloadJSON2CSV(json3.d);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            // Here is an example where you would wrap the values in double quotes
            // for (var index in array[i]) {
            //    line += '"' + array[i][index] + '",';
            // }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

</head>
<body>
    <h1>This page does nothing....</h1>
</body>
</html>

How do I format a number in Java?

public static void formatDouble(double myDouble){
 NumberFormat numberFormatter = new DecimalFormat("##.000");
 String result = numberFormatter.format(myDouble);
 System.out.println(result);
}

For instance, if the double value passed into the formatDouble() method is 345.9372, the following will be the result: 345.937 Similarly, if the value .7697 is passed to the method, the following will be the result: .770

HTML forms - input type submit problem with action=URL when URL contains index.aspx

I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.

<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

%matplotlib line magic causes SyntaxError in Python script

There are several reasons as to why this wouldn't work.

It is possible that matplotlib is not properly installed. have you tried running:

conda install matplotlib

If that doesn't work, look at your %PATH% environment variable, does it contain your libraries and python paths?

Similar problem on github anaconda

How do I print colored output to the terminal in Python?

What about the ansicolors library? You can simple do:

from colors import color, red, blue

# common colors
print(red('This is red'))
print(blue('This is blue'))

# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))

jQuery UI " $("#datepicker").datepicker is not a function"

If you think that there is a conflict you can use jQuery.noConflict() in your code. Details are in the docs.

REFERENCING MAGIC - SHORTCUTS FOR JQUERY

If you don't like typing the full "jQuery" all the time, there are some alternative shortcuts:

Reassign jQuery to another shortcut var $j = jQuery; (This might be the best approach if you wish to use different libraries) Use the following technique, which allows you to use $ inside of a block of code without permanently overwriting $:

(function($) { /* some code that uses $ */ })(jQuery)

Note: If you use this technique, you will not be able to use Prototype methods inside this capsuled function that expect $ to be Prototype's $, so you're making a choice to use only jQuery in that block. Use the argument to the DOM ready event:

jQuery(function($) { /*some code that uses $ */ });

Note: Again, inside that block you can't use Prototype methods

Thats from the end of the docs and might be useful to you

Why is width: 100% not working on div {display: table-cell}?

Putting display:table; inside .outer-wrapper seemed to work...

JSFiddle Link


EDIT: Two Wrappers Using Display Table Cell

I would comment on your answer but i have too little rep :( anyways...

Going off your answer, seems like all you need to do is add display:table; inside .outer-wrapper (Dejavu?), and you can get rid of table-wrapper whole-heartedly.

JSFiddle

But yeah, the position:absolute lets you place the div over the img, I read too quickly and thought that you couldn't use position:absolute at all, but seems like you figured it out already. Props!

I'm not going to post the source code, after all its 99% timshutes's work, so please refer to his answer, or just use my jsfiddle link

Update: One Wrapper Using Flexbox

It's been a while, and all the cool kids are using flexbox:

<div style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
    stuff to be centered
</div>

Full JSFiddle Solution

Browser Support (source): IE 11+, FireFox 42+, Chrome 46+, Safari 8+, iOS 8.4+ (-webkit- prefix), Android 4.1+ (-webkit- prefix)

CSS Tricks: a Guide to Flexbox

How to Center in CSS: input how you want your content to be centered, and it outputs how to do it in html and css. The future is here!

Is there a template engine for Node.js?

I found hogan.js from Twitter and recommended by Tim O'Reilly on his site. I have no best practice with it, but I trust on Twitter and O'Reilly. You should try...

Parallel.ForEach vs Task.Factory.StartNew

The first is a much better option.

Parallel.ForEach, internally, uses a Partitioner<T> to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved.

The second option will schedule a single Task per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower.

FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.ForEach, if so desired. For details, see Custom Partitioners on MSDN.

The main difference, at runtime, is the second will act asynchronous. This can be duplicated using Parallel.ForEach by doing:

Task.Factory.StartNew( () => Parallel.ForEach<Item>(items, item => DoSomething(item)));

By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

How can I auto increment the C# assembly version via our CI platform (Hudson)?

A simple alternative is to let the C# environment increment the assembly version for you by setting the version attribute to major.minor.* (as described in the AssemblyInfo file template.)

You may be looking for a more comprehensive solution, though.

EDIT (Response to the question in a comment):

From AssemblyInfo.cs:

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

Reading/writing an INI file

Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally "key = value". Same assumption as for sections - key name is unique.

/// <summary>
/// Loads .ini file into dictionary.
/// </summary>
public static Dictionary<String, Dictionary<String, String>> loadIni(String file)
{
    Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();

    String ini = File.ReadAllText(file);

    // Remove comments, preserve linefeeds, if end-user needs to count line number.
    ini = Regex.Replace(ini, @"^\s*;.*$", "", RegexOptions.Multiline);

    // Pick up all lines from first section to another section
    foreach (Match m in Regex.Matches(ini, "(^|[\r\n])\\[([^\r\n]*)\\][\r\n]+(.*?)(\\[([^\r\n]*)\\][\r\n]+|$)", RegexOptions.Singleline))
    {
        String sectionName = m.Groups[2].Value;
        Dictionary<String, String> lines = new Dictionary<String, String>();

        // Pick up "key = value" kind of syntax.
        foreach (Match l in Regex.Matches(ini, @"^\s*(.*?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline))
        {
            String key = l.Groups[1].Value;
            String value = l.Groups[2].Value;

            // Open up quotation if any.
            value = Regex.Replace(value, "^\"(.*)\"$", "$1");

            if (!lines.ContainsKey(key))
                lines[key] = value;
        }

        if (!d.ContainsKey(sectionName))
            d[sectionName] = lines;
    }

    return d;
}

ERROR 1064 (42000): You have an error in your SQL syntax;

Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.

target input by type and name (selector)

You can combine attribute selectors this way:

$("[attr1=val][attr2=val]")...

so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]. jQuery has a selector for that, namely :checkbox so the end result is:

$("input:checkbox[name=ProductCode]")...

Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:

<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">

allowing you to use the much faster selector of:

$("input.ProductCode")...

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

When making an Android app in eclipse, just right-click on the res folder, click New -> Other, and select Android Icon Set under Android.

This allows you to make more icons (or replace any existing ones) easily.

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

Call multiple functions onClick ReactJS

You can use nested.

There are tow function one is openTab() and another is closeMobileMenue(), Firstly we call openTab() and call another function inside closeMobileMenue().

function openTab() {
    window.open('https://play.google.com/store/apps/details?id=com.drishya');
    closeMobileMenue()   //After open new tab, Nav Menue will close.  
}

onClick={openTab}

Why is vertical-align: middle not working on my span or div?

In case you cannot rely on flexbox... Place .child into .parent's center. Works when pixel sizes are unknown (in other words, always) and no problems with IE9+ too.

_x000D_
_x000D_
.parent { position: relative; }_x000D_
_x000D_
.child {_x000D_
    position: absolute;_x000D_
    top : 50%;_x000D_
    left: 50%;_x000D_
    -ms-transform: translate(-50%, -50%);_x000D_
    transform    : translate(-50%, -50%);    _x000D_
}
_x000D_
<div class="parent" style="background:lightyellow; padding:6em"> _x000D_
  <div class="child" style="background:gold; padding:1em">&mdash;</div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Removing the fragment identifier from AngularJS urls (# symbol)

I write out a rule in web.config after $locationProvider.html5Mode(true) is set in app.js.

Hope, helps someone out.

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

In my index.html I added this to <head>

<base href="/">

Don't forget to install url rewriter for iis on server.

Also if you use Web Api and IIS, this match url will not work out, as it will change your api calls. So add third input(third line of condition) and give out a pattern that will exclude calls from www.yourdomain.com/api

How to make a new line or tab in <string> XML (eclipse/android)?

  • Include this line in your layout xmlns:tools="http://schemas.android.com/tools"
  • Now , use \n for new line and \t for space like tab.
  • Example :

    for \n : android:text="Welcome back ! \nPlease login to your account agilanbu"

    for \t : android:text="Welcome back ! \tPlease login to your account agilanbu"

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Py_Initialize fails - unable to load the file system codec

Ran into the same thing trying to install brew's python3 under Mac OS! The issue here is that in Mac OS, homebrew puts the "real" python a whole layer deeper than you think. You would think from the homebrew output that

$ echo $PYTHONHOME
/usr/local/Cellar/python3/3.6.2/
$ echo $PYTHONPATH
/usr/local/Cellar/python3/3.6.2/bin

would be correct, but invoking $PYTHONPATH/python3 immediately crashes with the abort 6 "can't find encodings." This is because although that $PYTHONHOME looks like a complete installation, having a bin, lib etc, it is NOT the actual Python, which is in a Mac OS "Framework". Do this:

PYTHONHOME=/usr/local/Cellar/python3/3.x.y/Frameworks/Python.framework/Versions/3.x
PYTHONPATH=$PYTHONHOME/bin

(substituting version numbers as appropriate) and it will work fine.

Django - limiting query results

As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10] as slicing will return the first 10 elements of the list, not the last 10...

To get the last 10 you should do [-10:] instead (see here). This will help you avoid using order_by('-id') with the - to reverse the elements.

Regular expression for decimal number

I just found TryParse() has an issue that it accounts for thousands seperator. Example in En-US, 10,36.00 is ok. I had a specific scenario where the thousands seperator should not be considered and hence regex \d(\.\d) turned out to be the best bet. Of course had to keep the decimal char variable for different locales.

Redirecting to authentication dialog - "An error occurred. Please try again later"

For me the issue was that the url of the app didn't completely match the url I was running it on (i.e different directories, same domain)

Securely storing passwords for use in python script

I typically have a secrets.py that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>. This way you can rely on the operating systems in-built file security system without re-inventing your own.

Using Base64 encoding/decoding is also another way to obfuscate the password though not completely secure

More here - Hiding a password in a python script (insecure obfuscation only)

Does IE9 support console.log, and is it a real function?

A simple solution to this console.log problem is to define the following at the beginning of your JS code:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.

Deserialize JSON string to c# object

Use this code:

var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

Jquery: Find Text and replace

Change by id or class for each tag

$("#id <tag>:contains('Text want to replaced')").html("Text Want to replaced with");


$(".className <tag>:contains('Text want to replaced')").html("Text Want to replaced with");

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

MySQL skip first 10 results

If your table has ordering by id, you could easily done by:

select * from table where id > 10

Most concise way to convert a Set<T> to a List<T>

Try this for Set:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 

Try this for Map:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());

How to get a jqGrid cell value when editing

I have a solution: 1. Using this.value to get the current editing value in the editing row. 2. Save the cell value to a hidden field when the cell lost its focus. 3. Read the hidden field when you need.

The code:

 colModel="[
       { name: 'Net', index: 'Net', editable:true, editoptions: { dataEvents: [ { type: 'focusout', fn: function(e) {$('#HiddenNet').val(this.value);} }] }, editrules:{custom:true,}},
       { name: 'Tax', index: 'Tax', editable:true, editoptions: { dataEvents: [ { type: 'focus', fn: function(e) {this.value=$('#HiddenNet').val(); } }] }, editrules:{custom:true}}
    ]" 

Good Luck

Reducing MongoDB database file size

There has been some considerable confusion over space reclamation in MongoDB, and some recommended practice are downright dangerous to do in certain deployment types. More details below:

TL;DR repairDatabase attempts to salvage data from a standalone MongoDB deployments that is trying to recover from a disk corruption. If it recovers space, it is purely a side effect. Recovering space should never be the primary consideration of running repairDatabase.

Recover space in a standalone node

WiredTiger: For a standalone node with WiredTiger, running compact will release space to the OS, with one caveat: The compact command on WiredTiger on MongoDB 3.0.x was affected by this bug: SERVER-21833 which was fixed in MongoDB 3.2.3. Prior to this version, compact on WiredTiger could silently fail.

MMAPv1: Due to the way MMAPv1 works, there is no safe and supported method to recover space using the MMAPv1 storage engine. compact in MMAPv1 will defragment the data files, potentially making more space available for new documents, but it will not release space back to the OS.

You may be able to run repairDatabase if you fully understand the consequences of this potentially dangerous command (see below), since repairDatabase essentially rewrites the whole database by discarding corrupt documents. As a side effect, this will create new MMAPv1 data files without any fragmentation on it and release space back to the OS.

For a less adventurous method, running mongodump and mongorestore may be possible as well in an MMAPv1 deployment, subject to the size of your deployment.

Recover space in a replica set

For replica set configurations, the best and the safest method to recover space is to perform an initial sync, for both WiredTiger and MMAPv1.

If you need to recover space from all nodes in the set, you can perform a rolling initial sync. That is, perform initial sync on each of the secondaries, before finally stepping down the primary and perform initial sync on it. Rolling initial sync method is the safest method to perform replica set maintenance, and it also involves no downtime as a bonus.

Please note that the feasibility of doing a rolling initial sync also depends on the size of your deployment. For extremely large deployments, it may not be feasible to do an initial sync, and thus your options are somewhat more limited. If WiredTiger is used, you may be able to take one secondary out of the set, start it as a standalone, run compact on it, and rejoin it to the set.

Regarding repairDatabase

Please don't run repairDatabase on replica set nodes. This is very dangerous, as mentioned in the repairDatabase page and described in more details below.

The name repairDatabase is a bit misleading, since the command doesn't attempt to repair anything. The command was intended to be used when there's disk corruption on a standalone node, which could lead to corrupt documents.

The repairDatabase command could be more accurately described as "salvage database". That is, it recreates the databases by discarding corrupt documents in an attempt to get the database into a state where you can start it and salvage intact document from it.

In MMAPv1 deployments, this rebuilding of the database files releases space to the OS as a side effect. Releasing space to the OS was never the purpose.

Consequences of repairDatabase on a replica set

In a replica set, MongoDB expects all nodes in the set to contain identical data. If you run repairDatabase on a replica set node, there is a chance that the node contains undetected corruption, and repairDatabase will dutifully remove the corrupt documents for you.

Predictably, this makes that node contains a different dataset from the rest of the set. If an update happens to hit that single document, the whole set could crash.

To make matters worse, it is entirely possible that this situation could stay dormant for a long time, only to strike suddenly with no apparent reason.

Checkout subdirectories in Git?

You can revert uncommitted changes only to particular file or directory:

git checkout [some_dir|file.txt]

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

ViewBag, ViewData and TempData

TempData will be always available until first read, once you read it its not available any more can be useful to pass quick message also to view that will be gone after first read. ViewBag Its more useful when passing quickly piece of data to the view, normally you should pass all data to the view through model , but there is cases when you model coming direct from class that is map into database like entity framework in that case you don't what to change you model to pass a new piece of data, you can stick that into the viewbag ViewData is just indexed version of ViewBag and was used before MVC3

How to get every first element in 2 dimensional list

You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a

Javascript .querySelector find <div> by innerTEXT

Since you have asked it in javascript so you can have something like this

function contains(selector, text) {
  var elements = document.querySelectorAll(selector);
  return Array.prototype.filter.call(elements, function(element){
    return RegExp(text).test(element.textContent);
  });
}

And then call it like this

contains('div', 'sometext'); // find "div" that contain "sometext"
contains('div', /^sometext/); // find "div" that start with "sometext"
contains('div', /sometext$/i); // find "div" that end with "sometext", case-insensitive

What are the differences between json and simplejson Python modules?

I came across this question as I was looking to install simplejson for Python 2.6. I needed to use the 'object_pairs_hook' of json.load() in order to load a json file as an OrderedDict. Being familiar with more recent versions of Python I didn't realize that the json module for Python 2.6 doesn't include the 'object_pairs_hook' so I had to install simplejson for this purpose. From personal experience this is why i use simplejson as opposed to the standard json module.

How to enumerate an object's properties in Python?

See inspect.getmembers(object[, predicate]).

Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.

>>> [name for name,thing in inspect.getmembers([])]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__',    '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', 
'__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 
'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 

Publish to IIS, setting Environment Variable

After extensive googling I found a working solution, which consists of two steps.

The first step is to set system wide environment variable ASPNET_ENV to Production and Restart the Windows Server. After this, all web apps are getting the value 'Production' as EnvironmentName.

The second step (to enable value 'Staging' for staging web) was rather more difficult to get to work correctly, but here it is:

  1. Create new windows user, for example StagingPool on the server.
  2. For this user, create new user variable ASPNETCORE_ENVIRONMENT with value 'Staging' (you can do it by logging in as this user or through regedit)
  3. Back as admin in IIS manager, find the Application Pool under which the Staging web is running and in Advanced Settings set Identity to user StagingPool.
  4. Also set Load User Profile to true, so the environment variables are loaded. <- very important!
  5. Ensure the StagingPool has access rights to the web folder and Stop and Start the Application Pool.

Now the Staging web should have the EnvironmentName set to 'Staging'.

Update: In Windows 7+ there is a command that can set environment variables from CMD prompt also for a specified user. This outputs help plus samples:

>setx /?

How to remove element from ArrayList by checking its value?

In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):

 a.remove(1);       // indexes are zero-based

Then, you can remove the first occurence of your string:

 a.remove("acbd");  // removes the first String object that is equal to the
                    // String represented by this literal

Or, remove all strings with a certain value:

 while(a.remove("acbd")) {}

It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using remove with an object that is equal to the one you want to delete.

In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:

 List<MyBean> deleteCandidates = new ArrayList<>();
 List<MyBean> myBeans = getThemFromSomewhere();

 // Pass 1 - collect delete candidates
 for (MyBean myBean : myBeans) {
    if (shallBeDeleted(myBean)) {
       deleteCandidates.add(myBean);
    }
 }

 // Pass 2 - delete
 for (MyBean deleteCandidate : deleteCandidates) {
    myBeans.remove(deleteCandidate);
 }

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

List of All Folders and Sub-folders

You can use find

find . -type d > output.txt

or tree

tree -d > output.txt

tree, If not installed on your system.

If you are using ubuntu

sudo apt-get install tree

If you are using mac os.

brew install tree

Safe Area of Xcode 9

The Safe Area Layout Guide helps avoid underlapping System UI elements when positioning content and controls.

The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. So when you add a Status bar to your app, the Safe Area shrink. When you add a Navigation Bar to your app, the Safe Area shrinks again.

On the iPhone X, the Safe Area provides additional inset from the top and bottom screen edges in portrait even when no bar is shown. In landscape, the Safe Area is inset from the sides of the screens and the home indicator.

This is taken from Apple's video Designing for iPhone X where they also visualize how different elements affect the Safe Area.

Deleting an SVN branch

For those using TortoiseSVN, you can accomplish this by using the Repository Browser (it's labeled "Repo-browser" in the context menu.)

context menu

Find the branch folder you want to delete, right-click it, and select "Delete."

deleting the folder

Enter your commit message, and you're done.

committing

How can I rename a project folder from within Visual Studio?

A proven solution for Visual Studio extension for Data Tools for Business Intelligence (SSDT-BI 2013):

  1. Move the Project folder to its new location (don't rename anything yet)
  2. In Solution Explorer, rename the Project / Solution.
  3. Close (and save) the newly-renamed project.
  4. Rename the project's folder and .sln file.
  5. Use a text editor and open the newly-renamed project solution file (.sln) (I used Notepad++)
  6. In line number 6 you'll see: "Project {fdjfksdjk4387!...} = "OLDPROJECT", "OLDFOLDER\OLDPROJECT.rptproj". Rename everything with the new names used in step 4. (i.e. ... = "NEWPROJECT", "NEWFOLDER\NEWPROJECT.rptproj"... )
  7. That's it!

It was tested 100% and worked flawlessly in my case.

NOTE: I can't confirm if it works under different project templates and other Visual Studio versions. As always, do backup everything beforehand.

`require': no such file to load -- mkmf (LoadError)

I also needed build-essential installed:

sudo apt-get install build-essential

ValidateRequest="false" doesn't work in Asp.Net 4

I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod with [ValidateInput(false)] and just switch off request validation for a single ActionMethod, which is handy. And you don't need to make any changes to the web.config file, so you can still use the .NET 4 request validation everywhere else.

e.g.

[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
    // Do your own checking of value since it could contain XSS stuff!
    return View();
}

Using JQuery to open a popup window and print

Are you sure you can't alter the HTML in the popup window?

If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

Install dependencies globally and locally using package.json

This is a bit old but I ran into the requirement so here is the solution I came up with.

The Problem:

Our development team maintains many .NET web application products we are migrating to AngularJS/Bootstrap. VS2010 does not lend itself easily to custom build processes and my developers are routinely working on multiple releases of our products. Our VCS is Subversion (I know, I know. I'm trying to move to Git but my pesky marketing staff is so demanding) and a single VS solution will include several separate projects. I needed my staff to have a common method for initializing their development environment without having to install the same Node packages (gulp, bower, etc.) several times on the same machine.

TL;DR:

  1. Need "npm install" to install the global Node/Bower development environment as well as all locally required packages for a .NET product.

  2. Global packages should be installed only if not already installed.

  3. Local links to global packages must be created automatically.

The Solution:

We already have a common development framework shared by all developers and all products so I created a NodeJS script to install the global packages when needed and create the local links. The script resides in "....\SharedFiles" relative to the product base folder:

/*******************************************************************************
* $Id: npm-setup.js 12785 2016-01-29 16:34:49Z sthames $
* ==============================================================================
* Parameters: 'links' - Create links in local environment, optional.
* 
* <p>NodeJS script to install common development environment packages in global
* environment. <c>packages</c> object contains list of packages to install.</p>
* 
* <p>Including 'links' creates links in local environment to global packages.</p>
* 
* <p><b>npm ls -g --json</b> command is run to provide the current list of 
* global packages for comparison to required packages. Packages are installed 
* only if not installed. If the package is installed but is not the required 
* package version, the existing package is removed and the required package is 
* installed.</p>.
*
* <p>When provided as a "preinstall" script in a "package.json" file, the "npm
* install" command calls this to verify global dependencies are installed.</p>
*******************************************************************************/
var exec = require('child_process').exec;
var fs   = require('fs');
var path = require('path');

/*---------------------------------------------------------------*/
/* List of packages to install and 'from' value to pass to 'npm  */
/* install'. Value must match the 'from' field in 'npm ls -json' */
/* so this script will recognize a package is already installed. */
/*---------------------------------------------------------------*/
var packages = 
  {
  "bower"                      :                      "[email protected]", 
  "event-stream"               :               "[email protected]",
  "gulp"                       :                       "[email protected]",
  "gulp-angular-templatecache" : "[email protected]",
  "gulp-clean"                 :                 "[email protected]", 
  "gulp-concat"                :                "[email protected]",
  "gulp-debug"                 :                 "[email protected]",
  "gulp-filter"                :                "[email protected]",
  "gulp-grep-contents"         :         "[email protected]",
  "gulp-if"                    :                    "[email protected]", 
  "gulp-inject"                :                "[email protected]", 
  "gulp-minify-css"            :            "[email protected]",
  "gulp-minify-html"           :           "[email protected]",
  "gulp-minify-inline"         :         "[email protected]",
  "gulp-ng-annotate"           :           "[email protected]",
  "gulp-processhtml"           :           "[email protected]",
  "gulp-rev"                   :                   "[email protected]",
  "gulp-rev-replace"           :           "[email protected]",
  "gulp-uglify"                :                "[email protected]",
  "gulp-useref"                :                "[email protected]",
  "gulp-util"                  :                  "[email protected]",
  "lazypipe"                   :                   "[email protected]",
  "q"                          :                          "[email protected]",
  "through2"                   :                   "[email protected]",

  /*---------------------------------------------------------------*/
  /* fork of 0.2.14 allows passing parameters to main-bower-files. */
  /*---------------------------------------------------------------*/
  "bower-main"                 : "git+https://github.com/Pyo25/bower-main.git" 
  }

/*******************************************************************************
* run */
/**
* Executes <c>cmd</c> in the shell and calls <c>cb</c> on success. Error aborts.
* 
* Note: Error code -4082 is EBUSY error which is sometimes thrown by npm for 
* reasons unknown. Possibly this is due to antivirus program scanning the file 
* but it sometimes happens in cases where an antivirus program does not explain 
* it. The error generally will not happen a second time so this method will call 
* itself to try the command again if the EBUSY error occurs.
* 
* @param  cmd  Command to execute.
* @param  cb   Method to call on success. Text returned from stdout is input.
*******************************************************************************/
var run = function(cmd, cb)
  {
  /*---------------------------------------------*/
  /* Increase the maxBuffer to 10MB for commands */
  /* with a lot of output. This is not necessary */
  /* with spawn but it has other issues.         */
  /*---------------------------------------------*/
  exec(cmd, { maxBuffer: 1000*1024 }, function(err, stdout)
    {
    if      (!err)                   cb(stdout);
    else if (err.code | 0 == -4082) run(cmd, cb);
    else throw err;
    });
  };

/*******************************************************************************
* runCommand */
/**
* Logs the command and calls <c>run</c>.
*******************************************************************************/
var runCommand = function(cmd, cb)
  {
  console.log(cmd);
  run(cmd, cb);
  }

/*******************************************************************************
* Main line
*******************************************************************************/
var doLinks  = (process.argv[2] || "").toLowerCase() == 'links';
var names    = Object.keys(packages);
var name;
var installed;
var links;

/*------------------------------------------*/
/* Get the list of installed packages for   */
/* version comparison and install packages. */
/*------------------------------------------*/
console.log('Configuring global Node environment...')
run('npm ls -g --json', function(stdout)
  {
  installed = JSON.parse(stdout).dependencies || {};
  doWhile();
  });

/*--------------------------------------------*/
/* Start of asynchronous package installation */
/* loop. Do until all packages installed.     */
/*--------------------------------------------*/
var doWhile = function()
  {
  if (name = names.shift())
    doWhile0();
  }

var doWhile0 = function()
  {
  /*----------------------------------------------*/
  /* Installed package specification comes from   */
  /* 'from' field of installed packages. Required */
  /* specification comes from the packages list.  */
  /*----------------------------------------------*/
  var current  = (installed[name] || {}).from;
  var required =   packages[name];

  /*---------------------------------------*/
  /* Install the package if not installed. */
  /*---------------------------------------*/
  if (!current)
    runCommand('npm install -g '+required, doWhile1);

  /*------------------------------------*/
  /* If the installed version does not  */
  /* match, uninstall and then install. */
  /*------------------------------------*/
  else if (current != required)
    {
    delete installed[name];
    runCommand('npm remove -g '+name, function() 
      {
      runCommand('npm remove '+name, doWhile0);
      });
    }

  /*------------------------------------*/
  /* Skip package if already installed. */
  /*------------------------------------*/
  else
    doWhile1();
  };

var doWhile1 = function()
  {
  /*-------------------------------------------------------*/
  /* Create link to global package from local environment. */
  /*-------------------------------------------------------*/
  if (doLinks && !fs.existsSync(path.join('node_modules', name)))
    runCommand('npm link '+name, doWhile);
  else
    doWhile();
  };

Now if I want to update a global tool for our developers, I update the "packages" object and check in the new script. My developers check it out and either run it with "node npm-setup.js" or by "npm install" from any of the products under development to update the global environment. The whole thing takes 5 minutes.

In addition, to configure the environment for the a new developer, they must first only install NodeJS and GIT for Windows, reboot their computer, check out the "Shared Files" folder and any products under development, and start working.

The "package.json" for the .NET product calls this script prior to install:

{ 
"name"                    : "Books",
"description"             : "Node (npm) configuration for Books Database Web Application Tools",
"version"                 : "2.1.1",
"private"                 : true,
"scripts":
  {
  "preinstall"            : "node ../../SharedFiles/npm-setup.js links",
  "postinstall"           : "bower install"
  },
"dependencies": {}
}

Notes

  • Note the script reference requires forward slashes even in a Windows environment.

  • "npm ls" will give "npm ERR! extraneous:" messages for all packages locally linked because they are not listed in the "package.json" "dependencies".

Edit 1/29/16

The updated npm-setup.js script above has been modified as follows:

  • Package "version" in var packages is now the "package" value passed to npm install on the command line. This was changed to allow for installing packages from somewhere other than the registered repository.

  • If the package is already installed but is not the one requested, the existing package is removed and the correct one installed.

  • For reasons unknown, npm will periodically throw an EBUSY error (-4082) when performing an install or link. This error is trapped and the command re-executed. The error rarely happens a second time and seems to always clear up.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

While they are not the same thing, in one sense DISTINCT implies a GROUP BY, because every DISTINCT could be re-written using GROUP BY instead. With that in mind, it doesn't make sense to order by something that's not in the aggregate group.

For example, if you have a table like this:

col1  col2
----  ----
 1     1
 1     2
 2     1
 2     2
 2     3
 3     1

and then try to query it like this:

SELECT DISTINCT col1 FROM [table] WHERE col2 > 2 ORDER BY col1, col2

That would make no sense, because there could end up being multiple col2 values per row. Which one should it use for the order? Of course, in this query you know the results wouldn't be that way, but the database server can't know that in advance.

Now, your case is a little different. You included all the columns from the order by clause in the select clause, and therefore it would seem at first glance that they were all grouped. However, some of those columns were included in a calculated field. When you do that in combination with distinct, the distinct directive can only be applied to the final results of the calculation: it doesn't know anything about the source of the calculation any more.

This means the server doesn't really know it can count on those columns any more. It knows that they were used, but it doesn't know if the calculation operation might cause an effect similar to my first simple example above.

So now you need to do something else to tell the server that the columns are okay to use for ordering. There are several ways to do that, but this approach should work okay:

SELECT rsc.RadioServiceCodeId,
            rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg 
    ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN 
    (SELECT val FROM dbo.fnParseArray(@RadioServiceGroup,','))
    OR @RadioServiceGroup IS NULL  
GROUP BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService

Git merge error "commit is not possible because you have unmerged files"

I've had a similar issue which boiled down to removing files under "unmerged paths"

Those files had to be removed using git rm

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

There is an alternative if you want to use of and not switch to in. You can use KeyValuePipe introduced in 6.1. You can easily iterate over an object:

<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>

What is monkey patching?

A MonkeyPatch is a piece of Python code which extends or modifies other code at runtime (typically at startup).

A simple example looks like this:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "ook ook eee eee eee!"

SomeClass.speak = speak

Source: MonkeyPatch page on Zope wiki.

Write Base64-encoded image to file

Assuming the image data is already in the format you want, you don't need image ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
    stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

How to Cast Objects in PHP

You can use above function for casting not similar class objects (PHP >= 5.3)

/**
 * Class casting
 *
 * @param string|object $destination
 * @param object $sourceObject
 * @return object
 */
function cast($destination, $sourceObject)
{
    if (is_string($destination)) {
        $destination = new $destination();
    }
    $sourceReflection = new ReflectionObject($sourceObject);
    $destinationReflection = new ReflectionObject($destination);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $sourceProperty->setAccessible(true);
        $name = $sourceProperty->getName();
        $value = $sourceProperty->getValue($sourceObject);
        if ($destinationReflection->hasProperty($name)) {
            $propDest = $destinationReflection->getProperty($name);
            $propDest->setAccessible(true);
            $propDest->setValue($destination,$value);
        } else {
            $destination->$name = $value;
        }
    }
    return $destination;
}

EXAMPLE:

class A 
{
  private $_x;   
}

class B 
{
  public $_x;   
}

$a = new A();
$b = new B();

$x = cast('A',$b);
$x = cast('B',$a);

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

Make a negative number positive

The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:

Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)

with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

How do I combine a background-image and CSS3 gradient on the same element?

I resolve the problem in that way. I define Gradient in HTML and background image in the Body

_x000D_
_x000D_
html {_x000D_
  background-image: -webkit-gradient(linear, left bottom, right top, color-stop(0.31, rgb(227, 227, 227)), color-stop(0.66, rgb(199, 199, 199)), color-stop(0.83, rgb(184, 184, 184)));_x000D_
  background-image: -moz-linear-gradient(left bottom, rgb(227, 227, 227) 31%, rgb(199, 199, 199) 66%, rgb(184, 184, 184) 83%);_x000D_
  height: 100%_x000D_
}_x000D_
body {_x000D_
  background: url("http://www.skrenta.com/images/stackoverflow.jpg");_x000D_
  height: 100%_x000D_
}
_x000D_
_x000D_
_x000D_

.setAttribute("disabled", false); changes editable attribute to false

Just set the property directly: .

eleman.disabled = false;

JPA CascadeType.ALL does not delete orphans

Just @OneToMany(cascade = CascadeType.ALL, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true).

Remove targetEntity = MyClass.class, it works great.

How to access host port from docker container

When you have two docker images "already" created and you want to put two containers to communicate with one-another.

For that, you can conveniently run each container with its own --name and use the --link flag to enable communication between them. You do not get this during docker build though.

When you are in a scenario like myself, and it is your

docker build -t "centos7/someApp" someApp/ 

That breaks when you try to

curl http://172.17.0.1:localPort/fileIWouldLikeToDownload.tar.gz > dump.tar.gz

and you get stuck on "curl/wget" returning no "route to host".

The reason is security that is set in place by docker that by default is banning communication from a container towards the host or other containers running on your host. This was quite surprising to me, I must say, you would expect the echosystem of docker machines running on a local machine just flawlessly can access each other without too much hurdle.

The explanation for this is described in detail in the following documentation.

http://www.dedoimedo.com/computers/docker-networking.html

Two quick workarounds are given that help you get moving by lowering down the network security.

The simplest alternative is just to turn the firewall off - or allow all. This means running the necessary command, which could be systemctl stop firewalld, iptables -F or equivalent.

Hope this information helps you.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

what about just store the output to the static table ? Like

-- SubProcedure: subProcedureName
---------------------------------
-- Save the value
DELETE lastValue_subProcedureName
INSERT INTO lastValue_subProcedureName (Value)
SELECT @Value
-- Return the value
SELECT @Value

-- Procedure
--------------------------------------------
-- get last value of subProcedureName
SELECT Value FROM lastValue_subProcedureName

its not ideal, but its so simple and you don't need to rewrite everything.

UPDATE: the previous solution does not work well with parallel queries (async and multiuser accessing) therefore now Iam using temp tables

-- A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. 
-- The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. 
-- The table cannot be referenced by the process that called the stored procedure that created the table.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NULL
CREATE TABLE #lastValue_spGetData (Value INT)

-- trigger stored procedure with special silent parameter
EXEC dbo.spGetData 1 --silent mode parameter

nested spGetData stored procedure content

-- Save the output if temporary table exists.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NOT NULL
BEGIN
    DELETE #lastValue_spGetData
    INSERT INTO #lastValue_spGetData(Value)
    SELECT Col1 FROM dbo.Table1
END

 -- stored procedure return
 IF @silentMode = 0
 SELECT Col1 FROM dbo.Table1

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

jQuery ajax post file field

I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)

function verify1() {
    jQuery.ajax({
        type: 'POST',
        url:"functions.php",
        data: new FormData($("#infoForm1")[0]),
        processData: false, 
        contentType: false, 
        success: function(returnval) {
             $("#show1").html(returnval);
             $('#show1').show();
         }
    });
}

Just print the file details and check. You will get Output. If error let me know.

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

In Linux Kernel, present pages are physical pages of RAM which kernel can see. Literally, present pages is total size of RAM in 4KB unit.

grep present /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

The 'MemTotal' form /proc/meminfo is the total size of memory managed by buddy system.And we can also compute it like this:

grep managed /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

jQuery check/uncheck radio button onclick

$(document).ready(function(){ $("input:radio:checked").data("chk",true);

$("input:radio").click(function(){
    $("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");

    $(this).data("chk",!$(this).data("chk"));

    $(this).prop("checked",$(this).data("chk"));
});

});

Iterate through every file in one directory

As others have said, Dir::foreach is a good option here. However, note that Dir::foreach and Dir::entries will always include . and .. (the current and parent directories). You will generally not want to work on them, so you can use Dir::each_child or Dir::children (as suggested by ma11hew28) or do something like this:

Dir.foreach('/path/to/dir') do |filename|
  next if filename == '.' or filename == '..'
  # Do work on the remaining files & directories
end

Dir::foreach and Dir::entries (as well as Dir::each_child and Dir::children) also include hidden files & directories. Often this is what you want, but if it isn't, you need to do something to skip over them.

Alternatively, you might want to look into Dir::glob which provides simple wildcard matching:

Dir.glob('/path/to/dir/*.rb') do |rb_filename|
  # Do work on files & directories ending in .rb
end

How do I get countifs to select all non-blank cells in Excel?

In Excel 2010, You have the countifS function.

I was having issues if I was trying to count the number of cells in a range that have a non0 value.

e.g. If you had a worksheet that in the range A1:A10 had values 1, 0, 2, 3, 0 and you wanted the answer 3.

The normal function =COUNTIF(A1:A10,"<>0") would give you 8 as it is counting the blank cells as 0s.

My solution to this is to use the COUNTIFS function with the same range but multiple criteria e.g.

=COUNTIFS(A1:A10,"<>0",A1:A10,"<>")

This effectively checks if the range is non 0 and is non blank.

Passing a string array as a parameter to a function java

look at familiar main method which takes string array as param

Automatic login script for a website on windows machine?

I used @qwertyjones's answer to automate logging into Oracle Agile with a public password.

I saved the login page as index.html, edited all the href= and action= fields to have the full URL to the Agile server.

The key <form> line needed to change from

<form autocomplete="off" name="MainForm" method="POST"
 action="j_security_check" 
 onsubmit="return false;" target="_top">

to

<form autocomplete="off" name="MainForm" method="POST"
 action="http://my.company.com:7001/Agile/default/j_security_check"   
 onsubmit="return false;" target="_top">

I also added this snippet to the end of the <body>

<script>
function checkCookiesEnabled(){ return true; }
document.MainForm.j_username.value = "joeuser";
document.MainForm.j_password.value = "abcdef";
submitLoginForm();
</script> 

I had to disable the cookie check by redefining the function that did the check, because I was hosting this from XAMPP and I didn't want to deal with it. The submitLoginForm() call was inspired by inspecting the keyPressEvent() function.

Chart won't update in Excel (2007)

This problem is ridiculous! No one's solution worked for me in 2010, but I based mine off of tpascale's:

Dim C As ChartObject
Set C = ActiveSheet.ChartObjects("CTR_Chart")
C.Chart.SetSourceData Source:=Range( _
    "KeywordBreakdown!$A$8:$A$12,KeywordBreakdown!$E$8:$E$12")

Simply redefined the Source Data range. If it's a named range, that could conceivably be reasonably clean. I guess the best solution to this is keep trying to modify different chart properties until it refreshes.

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Based on Kapitán Mlíko's answer with source above, I would change it to use the following:

Marlett Font Example

It's a better practice to use the Marlett font rather than Path Data points for the Minimize, Restore/Maximize and Close buttons.

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="0" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="3.5,0,0,3" />
        </Grid>
    </Button.Content>
</Button>
<Grid Margin="1,0,1,0">
    <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="30" Height="25" UseLayoutRounding="True">
                <TextBlock Text="2" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
    <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="31" Height="25">
                <TextBlock Text="1" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="r" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="0,0,0,1" />
        </Grid>
    </Button.Content>
</Button>

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

The official docker answer to Run multiple services in a container.

It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./my_wrapper_script.sh) or a supervisor like supervisord.

The && workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.

Navigation bar with UIImage for title

This worked for me... try it

let image : UIImage = UIImage(named: "LogoName")
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
imageView.contentMode = .scaleAspectFit
imageView.image = image
navigationItem.titleView = imageView

Could not load type 'XXX.Global'

This just happened to me and after trying everything else, I just happened to notice on the error message that the app pool was set to .Net 1.1. I upgraded the app to 2.0, converted to web application, but never changed the app pool:

Version Information: Microsoft .NET Framework Version:1.1.4322.2490; ASP.NET Version:1.1.4322.2494

How to comment multiple lines in Visual Studio Code?

For me it was ctrl + ' (I am using a swedish layout for the keyboard). Hope that helps anyone.

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

Chrome: console.log, console.debug are not working

This worked for me. In the console section, go to the settings on top right. There select preserve log and Log XMLHttpsRequests.

how to add background image to activity?

Nowadays we have to use match_parent :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="@drawable/background">
</RelativeLayout>

enter image description here

Convert Map<String,Object> to Map<String,String>

The following will transform your existing entries.

TransformedMap.decorateTransform(params, keyTransformer, valueTransformer)

Where as

MapUtils.transformedMap(java.util.Map map, keyTransformer, valueTransformer)

only transforms new entries into your map

get parent's view from a layout

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

Case statement in MySQL

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

This is the shorter version: Basically I try to get the difference between the post timestamp with the Date() now.

// MARK: - UPDATE Time Stamp
static func updateTimeStampPost(postTimeStamp: Date?, _ completion: (_ finalString: String?) -> Void) {
    // date in the current state
    let date = Date()
    let dateComponentFormatter = DateComponentsFormatter()

    // change the styling date, wether second minute or hour
    dateComponentFormatter.unitsStyle = .abbreviated
    dateComponentFormatter.allowedUnits = [.second, .minute, .hour, .day, .weekOfMonth]
    dateComponentFormatter.maximumUnitCount = 1

    // return the date new format as a string in the completion
    completion(dateComponentFormatter.string(from: postTimeStamp!, to: date))
}

What are the benefits of learning Vim?

I too put off learning vi or vim for many years. Matter of fact, I use to make fun of the "vi guys" who always seemed to be doing finger aerobics. Then, as I moved away from Windows and over to Linux as my primary OS, I had to become more familiar with vim. It was a learning curve and it still is. After 9 years of using vim on a daily basis I still find myself learning new and faster ways of doing things. What I use to think of as "finger aerobics" actually turned out to be an extremely efficient way of being productive. I can now do a whole lot more code development in a whole lot less time and effort than I ever did prior to vim. And as I'm sure you know vim runs on about every platform out there so you always have it when you need it. Also, if you like GUI's they have GUI versions for most platforms. Personally, just like the mouse, I don't want to see a menu bar, scroll bars, etc. cluttering up my editing window(s).

If you decide to give vim a whirl I would highly recommend the O'Reilly "vi Editor Pocket Reference" book. It's cheap and it's great if you're just learning vi (vim). The full blown vim books are also good but the pocket reference gives you all the basics to be productive quickly.

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

In Java, how do I parse XML as a String instead of a file?

One way is to use the version of parse that takes an InputSource rather than a file

A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader

So something like

parse(new InputSource(new StringReader(myString))) may work. 

How to hide first section header in UITableView (grouped style)

Swift3 : heightForHeaderInSection works with 0, you just have to make sure header is set to clipsToBounds.

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return 0
}

if you don't set clipsToBounds hidden header will be visible when scrolling.

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }

    header.clipsToBounds = true
}

Oracle TNS names not showing when adding new connection to SQL Developer

SQL Developer will look in the following location in this order for a tnsnames.ora file

  1. $HOME/.tnsnames.ora
  2. $TNS_ADMIN/tnsnames.ora
  3. TNS_ADMIN lookup key in the registry
  4. /etc/tnsnames.ora ( non-windows )
  5. $ORACLE_HOME/network/admin/tnsnames.ora
  6. LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME_KEY
  7. LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME

To see which one SQL Developer is using, issue the command show tns in the worksheet

If your tnsnames.ora file is not getting recognized, use the following procedure:

  1. Define an environmental variable called TNS_ADMIN to point to the folder that contains your tnsnames.ora file.

    In Windows, this is done by navigating to Control Panel > System > Advanced system settings > Environment Variables...

    In Linux, define the TNS_ADMIN variable in the .profile file in your home directory.

  2. Confirm the os is recognizing this environmental variable

    From the Windows command line: echo %TNS_ADMIN%

    From linux: echo $TNS_ADMIN

  3. Restart SQL Developer

  4. Now in SQL Developer right click on Connections and select New Connection.... Select TNS as connection type in the drop down box. Your entries from tnsnames.ora should now display here.

JQuery show and hide div on mouse click (animate)

Of course slideDown and slideUp don't do what you want, you said you want it to be left/right, not top/down.

If your edit to your question adding the jquery-ui tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide effect.

If not:

Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source

$(document).ready(function() {
    // Hide menu once we know its width
    $('#showmenu').click(function() {
        var $menu = $('.menu');
        if ($menu.is(':visible')) {
            // Slide away
            $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
                $menu.hide();
            });
        }
        else {
            // Slide in
            $menu.show().animate({left: 0});
        }
    });
});

You'll need to put position: relative on the menu element.

Note that I replaced your toggle with click, because that form of toggle was removed from jQuery.


If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.

This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
  <script>
    $(document).ready(function() {
        var first = true;

        // Hide menu once we know its width
        $('#showmenu').click(function() {
            var $menu = $('.menu');
            if ($menu.is(':visible')) {
                // Slide away
                $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
                    $menu.hide();
                });
            }
            else {
                // Slide in
                $menu.show().css("left", -($menu.outerWidth() + 10)).animate({left: 0});
            }
        });
    });
  </script>
</body>
</html>

Python foreach equivalent

Its also interesting to observe this

To iterate over the indices of a sequence, you can combine range() and len() as follows:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
  print(i, a[i])

output

0 Mary
1 had
2 a
3 little
4 lamb

Edit#1: Alternate way:

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
  print(i, v)

output

0 tic
1 tac
2 toe

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

How to dynamically change the color of the selected menu item of a web page?

Assuming you want to change the colour of the currently selected link/tab... you're best bet is to apply a class (say active) to the currently selected link/tab and then style this differently.

Example style could be:

li.active, a.active {
  background-color: #f90;
}

Writing BMP image in pure c/c++ without other libraries

Clean C Code for Bitmap (BMP) Image Generation

Generated Image:

bitmap image


The code does not use any library other than stdio.h. So, the code can be easily incorporated in other languages of C-Family, like- C++, C#, Java.


#include <stdio.h>

const int BYTES_PER_PIXEL = 3; /// red, green, & blue
const int FILE_HEADER_SIZE = 14;
const int INFO_HEADER_SIZE = 40;

void generateBitmapImage(unsigned char* image, int height, int width, char* imageFileName);
unsigned char* createBitmapFileHeader(int height, int stride);
unsigned char* createBitmapInfoHeader(int height, int width);


int main ()
{
    int height = 361;
    int width = 867;
    unsigned char image[height][width][BYTES_PER_PIXEL];
    char* imageFileName = (char*) "bitmapImage.bmp";

    int i, j;
    for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
            image[i][j][2] = (unsigned char) ( i * 255 / height );             ///red
            image[i][j][1] = (unsigned char) ( j * 255 / width );              ///green
            image[i][j][0] = (unsigned char) ( (i+j) * 255 / (height+width) ); ///blue
        }
    }

    generateBitmapImage((unsigned char*) image, height, width, imageFileName);
    printf("Image generated!!");
}


void generateBitmapImage (unsigned char* image, int height, int width, char* imageFileName)
{
    int widthInBytes = width * BYTES_PER_PIXEL;

    unsigned char padding[3] = {0, 0, 0};
    int paddingSize = (4 - (widthInBytes) % 4) % 4;

    int stride = (widthInBytes) + paddingSize;

    FILE* imageFile = fopen(imageFileName, "wb");

    unsigned char* fileHeader = createBitmapFileHeader(height, stride);
    fwrite(fileHeader, 1, FILE_HEADER_SIZE, imageFile);

    unsigned char* infoHeader = createBitmapInfoHeader(height, width);
    fwrite(infoHeader, 1, INFO_HEADER_SIZE, imageFile);

    int i;
    for (i = 0; i < height; i++) {
        fwrite(image + (i*widthInBytes), BYTES_PER_PIXEL, width, imageFile);
        fwrite(padding, 1, paddingSize, imageFile);
    }

    fclose(imageFile);
}

unsigned char* createBitmapFileHeader (int height, int stride)
{
    int fileSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + (stride * height);

    static unsigned char fileHeader[] = {
        0,0,     /// signature
        0,0,0,0, /// image file size in bytes
        0,0,0,0, /// reserved
        0,0,0,0, /// start of pixel array
    };

    fileHeader[ 0] = (unsigned char)('B');
    fileHeader[ 1] = (unsigned char)('M');
    fileHeader[ 2] = (unsigned char)(fileSize      );
    fileHeader[ 3] = (unsigned char)(fileSize >>  8);
    fileHeader[ 4] = (unsigned char)(fileSize >> 16);
    fileHeader[ 5] = (unsigned char)(fileSize >> 24);
    fileHeader[10] = (unsigned char)(FILE_HEADER_SIZE + INFO_HEADER_SIZE);

    return fileHeader;
}

unsigned char* createBitmapInfoHeader (int height, int width)
{
    static unsigned char infoHeader[] = {
        0,0,0,0, /// header size
        0,0,0,0, /// image width
        0,0,0,0, /// image height
        0,0,     /// number of color planes
        0,0,     /// bits per pixel
        0,0,0,0, /// compression
        0,0,0,0, /// image size
        0,0,0,0, /// horizontal resolution
        0,0,0,0, /// vertical resolution
        0,0,0,0, /// colors in color table
        0,0,0,0, /// important color count
    };

    infoHeader[ 0] = (unsigned char)(INFO_HEADER_SIZE);
    infoHeader[ 4] = (unsigned char)(width      );
    infoHeader[ 5] = (unsigned char)(width >>  8);
    infoHeader[ 6] = (unsigned char)(width >> 16);
    infoHeader[ 7] = (unsigned char)(width >> 24);
    infoHeader[ 8] = (unsigned char)(height      );
    infoHeader[ 9] = (unsigned char)(height >>  8);
    infoHeader[10] = (unsigned char)(height >> 16);
    infoHeader[11] = (unsigned char)(height >> 24);
    infoHeader[12] = (unsigned char)(1);
    infoHeader[14] = (unsigned char)(BYTES_PER_PIXEL*8);

    return infoHeader;
}

Eloquent get only one column as an array

I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().

// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();

These methods can also be called on a Collection for example

// <= Laravel 5.1
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->lists('word_one');

// >= Laravel 5.2
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->pluck('word_one');

Range of values in C Int and Long 32 - 64 bits

No, int in C is not defined to be 32 bits. int and long are not defined to be any specific size at all. The only thing the language guarantees is that sizeof(char)<=sizeof(short)<=sizeof(long).

Theoretically a compiler could make short, char, and long all the same number of bits. I know of some that actually did that for all those types save char.

This is why C now defines types like uint16_t and uint32_t. If you need a specific size, you are supposed to use one of those.

set up device for development (???????????? no permissions)

sudo usermod -aG plugdev $LOGNAME

This command worked for me

jquery variable syntax

This is pure JavaScript.

There is nothing special about $. It is just a character that may be used in variable names.

var $ = 1;
var $$ = 2;
alert($ + $$);

jQuery just assigns it's core function to a variable called $. The code you have assigns this to a local variable called self and the results of calling jQuery with this as an argument to a global variable called $self.

It's ugly, dirty, confusing, but $, self and $self are all different variables that happen to have similar names.

indexOf method in an object array?

I did some performance testing of various answers here, which anyone can run them self:

https://jsperf.com/find-index-of-object-in-array-by-contents

Based on my initial tests in Chrome, the following method (using a for loop set up inside a prototype) is the fastest:

Array.prototype.indexOfObject = function (property, value) {
    for (var i = 0, len = this.length; i < len; i++) {
        if (this[i][property] === value) return i;
    }
    return -1;
}

myArray.indexOfObject("hello", "stevie");

This code is a slightly modified version of Nathan Zaetta's answer.

In the performance benchmarks I tried it with both the target being in the middle (index 500) and very end (index 999) of a 1000 object array, and even if I put the target in as the very last item in the array (meaning that it it has to loop through every single item in the array before it's found) it still ends up the fastest.

This solution also has the benefit of being one of the most terse for repeatedly executing, since only the last line needs to be repeated:

myArray.indexOfObject("hello", "stevie");

AngularJS sorting rows by table header

Try this:

First change your controller

    yourModuleName.controller("yourControllerName", function ($scope) {
        var list = [
            { H1:'A', H2:'B', H3:'C', H4:'d' },
            { H1:'E', H2:'B', H3:'F', H4:'G' },
            { H1:'C', H2:'H', H3:'L', H4:'M' },
            { H1:'I', H2:'B', H3:'E', H4:'A' }
        ];

        $scope.list = list;

        $scope.headers = ["Header1", "Header2", "Header3", "Header4"];

        $scope.sortColumn = 'Header1';

        $scope.reverseSort = false;

        $scope.sortData = function (columnIndex) {
            $scope.reverseSort = ($scope.sortColumn == $scope.headers[columnIndex]) ? !$scope.reverseSort : false;

            $scope.sortColumn = $scope.headers[columnIndex];
        }

    });

then change code in html side like this

    <th ng-repeat= "header in headers">
            <a ng-click="sortData($index)"> {{headers[$index]}} </a>
    </th>
    <tr ng-repeat "result in results | orderBy : sortColumn : reverseSort">
        <td> {{results.h1}} </td>
        <td> {{results.h2}} </td>
        <td> {{results.h3}} </td>
        <td> {{results.h4}} </td>
    </tr>

Checking that a List is not empty in Hamcrest

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.

How do I tell Gradle to use specific JDK version?

To people ending up here when searching for the Gradle equivalent of the Maven property maven.compiler.source (or <source>1.8</source>):

In build.gradle you can achieve this with

apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8

See the Gradle documentation on this.