Programs & Examples On #Database dump

How to restore PostgreSQL dump file into Postgres databases?

You didn't mention how your backup was made, so the generic answer is: Usually with the psql tool.

Depending on what pg_dump was instructed to dump, the SQL file can have different sets of SQL commands. For example, if you instruct pg_dump to dump a database using --clean and --schema-only, you can't expect to be able to restore the database from that dump as there will be no SQL commands for COPYing (or INSERTing if --inserts is used ) the actual data in the tables. A dump like that will contain only DDL SQL commands, and will be able to recreate the schema but not the actual data.

A typical SQL dump is restored with psql:

psql (connection options here) database  < yourbackup.sql

or alternatively from a psql session,

psql (connection options here) database
database=# \i /path/to/yourbackup.sql

In the case of backups made with pg_dump -Fc ("custom format"), which is not a plain SQL file but a compressed file, you need to use the pg_restore tool.

If you're working on a unix-like, try this:

man psql
man pg_dump
man pg_restore

otherwise, take a look at the html docs. Good luck!

How do I create a MongoDB dump of my database?

You need to open command prompt as an administrator in a folder where your Mongo is installed (in my case: C:\Program Files\MongoDB\Server\3.4\bin). If you want to dump your whole database, you can just use:

mongodump --db database_name

You also have posibilities to dump only certain collection(s), or to dump all but certain collection(s).

If you want to dump only one collection (for example users):

mongodump  --db database_name --collection users

If you want to dump all but users collection:

mongodump  --db database_name --excludeCollection=users

It is also possible to output the dump to an archive file:

mongodump --archive=test.archive --db database_name

How to set Spinner default value to null?

My solution, in case you have a TextView as each row of the spinner:

    // TODO: add a fake item as the last one of "items"
    final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items) 
      {
      @Override
      public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
        {
        final View dropDownView=super.getDropDownView(position,convertView,parent);
        ((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
        dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
        return dropDownView;
        }
      }

    ...
    spinner.setAdapter(adapter);
    _actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);



  public static int getDimensionFromAttribute(final Context context,final int attr)
    {
    final TypedValue typedValue=new TypedValue();
    if(context.getTheme().resolveAttribute(attr,typedValue,true))
      return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
    return 0;
    }

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

Here is an awesome and precise explanation I found.

TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.

TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.

TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.

TIMESTAMP is 4 bytes and DATETIME is 8 bytes.

TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'

source: https://www.dbrnd.com/2015/09/difference-between-datetime-and-timestamp-in-mysql/#:~:text=DATETIME%20vs%20TIMESTAMP%3A,DATETIME%20is%20constant.

Also...

table with different column "date" types and corresponding rails migration types depending on the database

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

Mac install and open mysql using terminal

  1. install homebrew via terminal

  2. brew install mysql

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

Run script on mac prompt "Permission denied"

To run in the administrator mode in mac

sudo su

How do you count the number of occurrences of a certain substring in a SQL varchar?

DECLARE @records varchar(400)
SELECT @records = 'a,b,c,d'
select  LEN(@records) as 'Before removing Commas' , LEN(@records) - LEN(REPLACE(@records, ',', '')) 'After Removing Commans'

openssl s_client using a proxy

for anyone coming here as of post-May 2015: there's a new "-proxy" option that will be included in the next release of openssl: https://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest

How do I check if an element is really visible with JavaScript?

You can use the clientHeight or clientWidth properties

function isViewable(element){
  return (element.clientHeight > 0);
}

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

How to download Javadoc to read offline?

Links to access the JDK documentation

By the way, a history of Java SE versions.

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

It's not necessary to rewrite everything. I recommend doing this instead:

Post this inside your .m file of your custom cell.

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,32,32);
}

This should do the trick nicely. :]

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas

table.setWidths(anchoDeColumnas);

When a 'blur' event occurs, how can I find out which element focus went *to*?

This way:

<script type="text/javascript">
    function yourFunction(element) {
        alert(element);
    }
</script>
<input id="myinput" onblur="yourFunction(this)">

Or if you attach the listener via JavaScript (jQuery in this example):

var input = $('#myinput').blur(function() {
    alert(this);
});

Edit: sorry. I misread the question.

An Iframe I need to refresh every 30 seconds (but not the whole page)

Okay... so i know that i'm answering to a decade question, but wanted to add something! I wanted to add a google calendar with special iframe parameters. Problem is that the calendar didn't work without it. 30 seconds is a bit short for my use, so i changed that in my own file to 15 minutes This worked for me.

<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
 document.getElementById("calendar").src=calendar.src;
}
</script>

    <iframe id="calendar" src="[URL]" style="border-width:0" width=100% height=100% frameborder="0" scrolling="no"></iframe>

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

You either need to increase the max_connections configuration setting or (probably better) use connection pooling to route a large number of user requests through a smaller connection pool.

https://wiki.postgresql.org/wiki/Number_Of_Database_Connections

How to return value from an asynchronous callback function?

If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

jQuery: Currency Format Number

_x000D_
_x000D_
var input=950000; _x000D_
var output=parseInt(input).toLocaleString(); _x000D_
alert(output);
_x000D_
_x000D_
_x000D_

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

Most efficient way to convert an HTMLCollection to an Array

I suppose that calling Array.prototype functions on instances of HTMLCollection is a much better option than converting collections to arrays (e.g.,[...collection] or Array.from(collection)), because in the latter case a collection is unnecessarily implicitly iterated and a new array object is created, and this eats up additional resources. Array.prototype iterating functions can be safely called upon objects with consecutive numeric keys starting from [0] and a length property with a valid number value of such keys' quantity (including, e.g., instances of HTMLCollection and FileList), so it's a reliable way. Also, if there is a frequent need in such operations, an empty array [] can be used for quick access to Array.prototype functions; or a shortcut for Array.prototype can be created instead. A runnable example:

_x000D_
_x000D_
const _ = Array.prototype;
const collection = document.getElementById('ol').children;
alert(_.reduce.call(collection, (acc, { textContent }, i) => {
  return acc += `${i+1}) ${textContent}` + '\n';
}, ''));
_x000D_
<ol id="ol">
    <li>foo</li>
    <li>bar</li>
    <li>bat</li>
    <li>baz</li>
</ol>
_x000D_
_x000D_
_x000D_

How do I format a number to a dollar amount in PHP

If you just want something simple:

'$' . number_format($money, 2);

number_format()

Nginx location priority

There is a handy online tool for testing location priority now:
location priority testing online

INSERT VALUES WHERE NOT EXISTS

More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.

They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.

The example code used for each technique is as follows (straight copy/paste from their page) :

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

from jquery $.ajax to angular $http

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.data = response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.error = response.statusText;
});

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);

There are number of things to notice:

  • AngularJS version is more concise (especially using .post() method)
  • AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
  • Callback functions are named success and error respectively (also please note parameters of each callback) - Deprecated in angular v1.5
  • use then function instead.
  • More info of then usage can be found here

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

Unnamed/anonymous namespaces vs. static functions

Putting methods in an anonymous namespace prevents you from accidentally violating the One Definition Rule, allowing you to never worry about naming your helper methods the same as some other method you may link in.

And, as pointed out by luke, anonymous namespaces are preferred by the standard over static members.

Html table tr inside td

You cannot put tr inside td. You can see the allowed content from MDN web docs documentation about td. The relevant information is in the permitted content section.

Another way to achieve this is by using colspan and rowspan. Check this fiddle.

HTML:

<table width="100%">
 <tr>
  <td>Name 1</td>
  <td>Name 2</td>
  <td colspan="2">Name 3</td>
  <td>Name 4</td>
 </tr>

 <tr>
  <td rowspan="3">ITEM 1</td>
  <td rowspan="3">ITEM 2</td>
  <td>name1</td>
  <td>price1</td>
  <td rowspan="3">ITEM 4</td>
 </tr>

 <tr>
  <td>name2</td>
  <td>price2</td>
 </tr>
 <tr>
  <td>name3</td>
  <td>price3/td>
 </tr>
</table>

And some CSS:

table {
    border-collapse: collapse       
}

td {
   border: 1px solid #000000
}

How do I position a div relative to the mouse pointer using jQuery?

You don not need to create a $(document).mousemove( function(e) {}) to handle mouse x,y. Get the event in the $.hover function and from there it is possible to get x and y positions of the mouse. See the code below:

$('foo').hover(function(e){
    var pos = [e.pageX-150,e.pageY];
    $('foo1').dialog( "option", "position", pos );
    $('foo1').dialog('open');
},function(){
    $('foo1').dialog('close');
});

PHP: How do I display the contents of a textfile on my page?

I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:

$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);

echo '<code>';
echo '<pre>';

echo $a;

echo '</pre>';
echo '</code>';

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

How could I convert data from string to long in c#

This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.

Convert.ToInt64("1100.25")

Method signature from MSDN:

public static long ToInt64(
    string value
)

Failed to resolve: com.android.support:appcompat-v7:26.0.0

My issue got resolved with the help of following steps:

For gradle 3.0.0 and above version

  1. add google() below jcenter()
  2. Change the compileSdkVersion to 26 and buildToolsVersion to 26.0.2
  3. Change to gradle-4.2.1-all.zip in the gradle_wrapper.properties file

How to declare a constant in Java

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

Converting string format to datetime in mm/dd/yyyy

I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

Where is debug.keystore in Android Studio

If you find that you do not have JDK installed. Go to your android terminal and navigate to the bin folder of JRE that comes with Android Studio.

C:\Program Files\Android\Android Studio\jre\bin

and run the following command. Remember to replace USERNAME with your actual PC username.

keytool -list -v -keystore "C:\Users\USERNAME\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Android Call an method from another class

You should use the following code :

Class2 cls2 = new Class2();
cls2.UpdateEmployee();

In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.UpdateEmployee().

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

Fastest way to ping a network range and return responsive hosts?

This is python code for the ping in range of the 192.168.0.0-192.168.0.100. You can change for loop as you comfort.

# -*- coding: utf-8 -*-
import socket
import os
import sys

up_ip =[] #list to store the ip-addresses of server online
for x in range(100):  #here range is 0-100. You can change the range according to your comfort

    server_ip = '192.168.0.'+ str(x)
    print "Trying ,server_ip,... \n"

    rep = os.system('ping -c 1 ' + server_ip)

    if rep == 0:
        up_ip.append(server_ip)
        print '******************* Server Is Up **************** \n'
    else:
        print 'server is down \n'

print up_ip

Move all files except one

A quick way would be to modify the tux filename so that your move command will not match.

For example:

mv Tux.png .Tux.png

mv * ~/somefolder

mv .Tux.png Tux.png

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Like the rest, I went with callables too. But they have one downside: by default, you can't order on them. Fortunately, there is a solution for that:

Django >= 1.8

def author(self, obj):
    return obj.book.author
author.admin_order_field  = 'book__author'

Django < 1.8

def author(self):
    return self.book.author
author.admin_order_field  = 'book__author'

Random numbers with Math.random() in Java

Google is right :-)

Google's formula creates numbers between: min and max Your formula creates numbers between: min and (min+max)

How to add external fonts to android application

To implement you need use Typeface go through with sample below

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
   if (view instanceof TextView) 
   {
      TextView textView = (TextView) view;
      textView.setTypeface(typeface);
      }
   }
}

How to edit binary file on Unix systems

There's lightweight binary editor, check hexedit. http://www.linux.org/apps/AppId_6968.html. I tried using it for editing ELF binaries in Linux at least.

printf not printing on console

As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.

On unix-like systems, including macs, stdout has line-based buffering by default. This means that your program empties its stdout buffer as soon as it sees a newline.

However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.

So on windows, a good approach is to completely shut off stdout buffering like so:

setvbuf (stdout, NULL, _IONBF, 0);

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

You can replace IList<DzieckoAndOpiekun> resultV with var resultV.

Determine .NET Framework version for dll

"Detect It Easy" also known as DiE is a program for determining types of files. Works with .dll files or other (.exe) files. Absolute free for commercial and non-commercial use.

enter image description here

java.io.FileNotFoundException: the system cannot find the file specified

Try to create a file using the code, so you will get to know the path of the file where the system create

File test=new File("check.txt");
if (test.createNewFile()) {
    System.out.println("File created: " + test.getName());
  }

How to enable PHP short tags?

To set short tags to open from a Vagrant install script on Ubuntu:

sed -i "s/short_open_tag = .*/short_open_tag = On/" /etc/php5/apache2/php.ini

How to update the value of a key in a dictionary in Python?

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

Redirect all output to file using Bash on Linux?

you can use this syntax to redirect all output stderr and stdout to stdout.txt

<cmd> <args> > allout.txt 2>&1 

PostgreSQL: How to change PostgreSQL user password?

Go to your Postgresql Config and Edit pg_hba.conf

sudo vim /etc/postgresql/9.3/main/pg_hba.conf

Then Change this Line :

Database administrative login by Unix domain socket
local      all              postgres                                md5

to :

Database administrative login by Unix domain socket
local   all             postgres                                peer

then Restart the PostgreSQL service via SUDO command then

psql -U postgres

You will be now entered and will See the Postgresql terminal

then enter

\password

and enter the NEW Password for Postgres default user, After Successfully changing the Password again go to the pg_hba.conf and revert the change to "md5"

now you will be logged in as

psql -U postgres

with your new Password.

Let me know if you all find any issue in it.

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

What is the best way to delete a component with CLI

  1. Delete the folder containing this component.
  2. In the app.module.ts remove the import statement for this component and remove its name from the declaration section of @NgModule
  3. Remove the line with the export statement for this component from index.ts.

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

How to get a cookie from an AJAX response?

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!

For this to work you need to:

1) login with the ajax request from which you expect cookies to be returned:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie

C# code to validate email address

If you really and I mean really want to know if an email address is valid...ask the mail exchanger to prove it, no regex needed. I can provide the code if requested.

General steps are as follows: 1. does email address have a domain name part? (index of @ > 0) 2. using a DNS query ask if domain has a mail exchanger 3. open tcp connection to mail exchanger 4. using the smtp protocol, open a message to the server using the email address as the reciever 5. parse the server's response. 6. quit the message if you made it this far, everything is good.

This is as you can imagine, very expensive time wise and relies on smtp, but it does work.

Prevent PDF file from downloading and printing

Okay, I take back what I commented earlier. Just talked to one of the senior guys in my shop and he said it is possible to lock it down hard. What you can do is convert the pdf to an image/flash/whatever and wrap it in an iFrame. Then, you create another image with 100% transparency and lay it over top the iFrame (not in it) and set it to have a higher Z-value than the iFrame.

What this will do is that if they right click on the 'image' to save it, they will be saving the transparent image instead. And since the image 'overrides' the iFrame, any attempt to use print screen should be shielded by the image, and they should only be able to snapshot the image that doesn't actually exist.

That leaves only one or two ways to get at the file...which requires digging straight into the source code to find the image file inside the iFrame. Still not totally secure, but protected from your average user.

How to execute raw SQL in Flask-SQLAlchemy app

Have you tried using connection.execute(text( <sql here> ), <bind params here> ) and bind parameters as described in the docs? This can help solve many parameter formatting and performance problems. Maybe the gateway error is a timeout? Bind parameters tend to make complex queries execute substantially faster.

MySQL > Table doesn't exist. But it does (or it should)

Its possible you have a hidden character in your table name. Those don't show up when you do a show tables. Can you do a "SHOW CREATE TABLE TABLE_ONE" and tab complete the "TABLE_ONE" and see if it puts in any hidden characters. Also, have you tried dropping and remaking the tables. Just to make sure nothing is wrong with the privileges and that there are no hidden characters.

Git 'fatal: Unable to write new index file'

I think some background backup solutions like Google Backup and Sync block access to the index file. I closed the application and Sourcetree had no issues at all. Seems that Dropbox does the same (@tonymayoral).

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

    [HttpPost]
    public bool parseAllDocs([FromBody] IList<docObject> data)
    {
        // do stuff

    }

Zooming MKMapView to fit annotation pins?

Apple has added a new method for IOS 7 to simplify life a bit.

[mapView showAnnotations:yourAnnotationArray animated:YES];

You can easily pull from an array stored in the map view:

yourAnnotationArray = mapView.annotations;

and quickly adjust the camera too!

mapView.camera.altitude *= 1.4;

this won't work unless the user has iOS 7+ or OS X 10.9+ installed. check out custom animation here

WPF button click in C# code

The following should do the trick:

btn.Click += btn1_Click;

What does the "More Columns than Column Names" error mean?

It uses commas as separators. So you can either set sep="," or just use read.csv:

x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593      9

The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):

State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582

And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table with the default quote argument (but not read.csv):

01,089,24,033,MD,Prince George's County,13,30,1040

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

C: What is the difference between ++i and i++?

The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

int  i;
int  j;

Increment operators:

i = 1;
j = ++i;    // i is now 2, j is also 2
j = i++;    // i is now 3, j is 2

How can I delay a method call for 1 second?

There is a Swift 3 solution from the checked solution :

self.perform(#selector(self.targetMethod), with: self, afterDelay: 1.0)

And there is the method

@objc fileprivate func targetMethod(){

}

IIS Express Windows Authentication

option-1:

edit \My Documents\IISExpress\config\applicationhost.config file and enable windowsAuthentication, i.e:

<system.webServer>
...
  <security>
...
    <authentication>
      <windowsAuthentication enabled="true" />
    </authentication>
...
  </security>
...
</system.webServer>

option-2:

Unlock windowsAuthentication section in \My Documents\IISExpress\config\applicationhost.config as follows

<add name="WindowsAuthenticationModule" lockItem="false" />

Alter override settings for the required authentication types to 'Allow'

<sectionGroup name="security">
    ...
    <sectionGroup name="system.webServer">
        ...
        <sectionGroup name="authentication">
            <section name="anonymousAuthentication" overrideModeDefault="Allow" />
            ...
            <section name="windowsAuthentication" overrideModeDefault="Allow" />
    </sectionGroup>
</sectionGroup>

Add following in the application's web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
      <security>
        <authentication>
          <windowsAuthentication enabled="true" />
        </authentication>
      </security>
    </system.webServer>
</configuration>

Below link may help: http://learn.iis.net/page.aspx/376/delegating-configuration-to-webconfig-files/

After installing VS 2010 SP1 applying option 1 + 2 may be required to get windows authentication working. In addition, you may need to set anonymous authentication to false in IIS Express applicationhost.config:

<authentication>

            <anonymousAuthentication enabled="false" userName="" />

for VS2015, the IIS Express applicationhost config file may be located here:

$(solutionDir)\.vs\config\applicationhost.config

and the <UseGlobalApplicationHostFile> option in the project file selects the default or solution-specific config file.

How do you attach and detach from Docker's process?

To detach the tty without exiting the shell, use the escape sequence Ctrl+P followed by Ctrl+Q. More details here.

Additional info from this source:

  • docker run -t -i ? can be detached with ^P^Qand reattached with docker attach
  • docker run -i ? cannot be detached with ^P^Q; will disrupt stdin
  • docker run ? cannot be detached with ^P^Q; can SIGKILL client; can reattach with docker attach

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

MySQL OPTIMIZE all tables?

You can use mysqlcheck to do this at the command line.

One database:

mysqlcheck -o <db_schema_name>

All databases:

mysqlcheck -o --all-databases

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

How to get just numeric part of CSS property with jQuery?

You can implement this very simple jQuery plugin:

Plugin Definition:

(function($) {
   $.fn.cssValue = function(p) {
      var result;
      return isNaN(result = parseFloat(this.css(p))) ? 0 : result;
   };
})(jQuery);

It is resistant to NaN values that may occur in old IE version (will return 0 instead)

Usage:

$(this).cssValue('marginBottom');

Enjoy! :)

Where does Git store files?

If you are looking for where the project folder was created. I noticed when I typed in the git bash.

$ git init projectName

it will tell me, where the project folder is for that project.

How to debug ORA-01775: looping chain of synonyms?

Try this select to find the problematic synonyms, it lists all synonyms that are pointing to an object that does not exist (tables,views,sequences,packages, procedures, functions)

SELECT *
FROM dba_synonyms
WHERE table_owner = 'USER'
    AND (
        NOT EXISTS (
            SELECT *
            FROM dba_tables
            WHERE dba_synonyms.table_name = dba_tables.TABLE_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_views
            WHERE dba_synonyms.table_name = dba_views.VIEW_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_sequences
            WHERE dba_synonyms.table_name = dba_sequences.sequence_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_dependencies
            WHERE type IN (
                    'PACKAGE'
                    ,'PROCEDURE'
                    ,'FUNCTION'
                    )
                AND dba_synonyms.table_name = dba_dependencies.NAME
            )
        )

Android - Dynamically Add Views into View

It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.

Take a look at these tutorials

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Swap x and y axis without manually swapping values

Microsoft Excel for Mac 2011 v 14.5.9

  • Click on the chart
  • Press the "Switch Plot" button under the "Charts" tab

How to import a .cer certificate into a java keystore?

Importing .cer certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security worked for me, as opposed to attemps to generate and use my own keystore.

  1. Go to your java_home\jre\lib\security
  2. (Windows) Open admin command line there using cmd and CTRL+SHIFT+ENTER
  3. Run keytool to import certificate:
    • (Replace yourAliasName and path\to\certificate.cer respectively)

 ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer

This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.

Set drawable size programmatically

i didn't have time to dig why the setBounds() method is not working on bitmap drawable as expected but i have little tweaked @androbean-studio solution to do what setBounds should do...

/**
 * Created by ceph3us on 23.05.17.
 * file belong to pl.ceph3us.base.android.drawables
 * this class wraps drawable and forwards draw canvas
 * on it wrapped instance by using its defined bounds
 */
public class WrappedDrawable extends Drawable {

    private final Drawable _drawable;
    protected Drawable getDrawable() {
        return _drawable;
    }

    public WrappedDrawable(Drawable drawable) {
        super();
        _drawable = drawable;
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        //update bounds to get correctly
        super.setBounds(left, top, right, bottom);
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setBounds(left, top, right, bottom);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setAlpha(alpha);
        }
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setColorFilter(colorFilter);
        }
    }

    @Override
    public int getOpacity() {
        Drawable drawable = getDrawable();
        return drawable != null
                ? drawable.getOpacity()
                : PixelFormat.UNKNOWN;
    }

    @Override
    public void draw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.draw(canvas);
        }
    }

    @Override
    public int getIntrinsicWidth() {
        Drawable drawable = getDrawable();
        return drawable != null
                ? drawable.getBounds().width()
                : 0;
    }

    @Override
    public int getIntrinsicHeight() {
        Drawable drawable = getDrawable();
        return drawable != null ?
                drawable.getBounds().height()
                : 0;
    }
}

usage:

// get huge drawable 
final Drawable drawable = resources.getDrawable(R.drawable.g_logo);
// create our wrapper           
WrappedDrawable wrappedDrawable = new WrappedDrawable(drawable);
// set bounds on wrapper 
wrappedDrawable.setBounds(0,0,32,32); 
// use wrapped drawable 
Button.setCompoundDrawablesWithIntrinsicBounds(wrappedDrawable ,null, null, null);

results

before: enter image description here after: enter image description here

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

I had the EXACT same issue as the OP. My configuration and situation were identical. I finally narrowed it down to being an issue in WCFStorm after creating a service reference in a test project in Visual Studio and confirming that the service was working. In Storm you need to click on the "Config" settings option (NOT THE "Client Config"). After clicking on that, click on the "Security" tab on the dialog that pops up. Make sure "Authentication Type" is set to "None" (The default is "Windows Authentication"). Presto, it works! I always test out my methods in WCFStorm as I'm building them out, but have never tried using it to connect to one that has already been set up on SSL. Hope this helps someone!

Why do I need 'b' to encode a string with Base64?

Short Answer

You need to push a bytes-like object (bytes, bytearray, etc) to the base64.b64encode() method. Here are two ways:

>>> import base64
>>> data = base64.b64encode(b'data to be encoded')
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'

Or with a variable:

>>> import base64
>>> string = 'data to be encoded'
>>> data = base64.b64encode(string.encode())
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'

Why?

In Python 3, str objects are not C-style character arrays (so they are not byte arrays), but rather, they are data structures that do not have any inherent encoding. You can encode that string (or interpret it) in a variety of ways. The most common (and default in Python 3) is utf-8, especially since it is backwards compatible with ASCII (although, as are most widely-used encodings). That is what is happening when you take a string and call the .encode() method on it: Python is interpreting the string in utf-8 (the default encoding) and providing you the array of bytes that it corresponds to.

Base-64 Encoding in Python 3

Originally the question title asked about Base-64 encoding. Read on for Base-64 stuff.

base64 encoding takes 6-bit binary chunks and encodes them using the characters A-Z, a-z, 0-9, '+', '/', and '=' (some encodings use different characters in place of '+' and '/'). This is a character encoding that is based off of the mathematical construct of radix-64 or base-64 number system, but they are very different. Base-64 in math is a number system like binary or decimal, and you do this change of radix on the entire number, or (if the radix you're converting from is a power of 2 less than 64) in chunks from right to left.

In base64 encoding, the translation is done from left to right; those first 64 characters are why it is called base64 encoding. The 65th '=' symbol is used for padding, since the encoding pulls 6-bit chunks but the data it is usually meant to encode are 8-bit bytes, so sometimes there are only two or 4 bits in the last chunk.

Example:

>>> data = b'test'
>>> for byte in data:
...     print(format(byte, '08b'), end=" ")
...
01110100 01100101 01110011 01110100
>>>

If you interpret that binary data as a single integer, then this is how you would convert it to base-10 and base-64 (table for base-64):

base-2:  01 110100 011001 010111 001101 110100 (base-64 grouping shown)
base-10:                            1952805748
base-64:  B      0      Z      X      N      0

base64 encoding, however, will re-group this data thusly:

base-2:  011101  000110  010101 110011 011101 00(0000) <- pad w/zeros to make a clean 6-bit chunk
base-10:     29       6      21     51     29      0
base-64:      d       G       V      z      d      A

So, 'B0ZXN0' is the base-64 version of our binary, mathematically speaking. However, base64 encoding has to do the encoding in the opposite direction (so the raw data is converted to 'dGVzdA') and also has a rule to tell other applications how much space is left off at the end. This is done by padding the end with '=' symbols. So, the base64 encoding of this data is 'dGVzdA==', with two '=' symbols to signify two pairs of bits will need to be removed from the end when this data gets decoded to make it match the original data.

Let's test this to see if I am being dishonest:

>>> encoded = base64.b64encode(data)
>>> print(encoded)
b'dGVzdA=='

Why use base64 encoding?

Let's say I have to send some data to someone via email, like this data:

>>> data = b'\x04\x6d\x73\x67\x08\x08\x08\x20\x20\x20'
>>> print(data.decode())
   
>>> print(data)
b'\x04msg\x08\x08\x08   '
>>>

There are two problems I planted:

  1. If I tried to send that email in Unix, the email would send as soon as the \x04 character was read, because that is ASCII for END-OF-TRANSMISSION (Ctrl-D), so the remaining data would be left out of the transmission.
  2. Also, while Python is smart enough to escape all of my evil control characters when I print the data directly, when that string is decoded as ASCII, you can see that the 'msg' is not there. That is because I used three BACKSPACE characters and three SPACE characters to erase the 'msg'. Thus, even if I didn't have the EOF character there the end user wouldn't be able to translate from the text on screen to the real, raw data.

This is just a demo to show you how hard it can be to simply send raw data. Encoding the data into base64 format gives you the exact same data but in a format that ensures it is safe for sending over electronic media such as email.

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

Comparing object properties in c#

Do you override .ToString() on all of your objects that are in the properties? Otherwise, that second comparison could come back with null.

Also, in that second comparison, I'm on the fence about the construct of !( A == B) compared to (A != B), in terms of readability six months/two years from now. The line itself is pretty wide, which is ok if you've got a wide monitor, but might not print out very well. (nitpick)

Are all of your objects always using properties such that this code will work? Could there be some internal, non-propertied data that could be different from one object to another, but all exposed data is the same? I'm thinking of some data which could change over time, like two random number generators that happen to hit the same number at one point, but are going to produce two different sequences of information, or just any data that doesn't get exposed through the property interface.

Update multiple columns in SQL

update T1
set T1.COST2=T1.TOT_COST+2.000,
T1.COST3=T1.TOT_COST+2.000,
T1.COST4=T1.TOT_COST+2.000,
T1.COST5=T1.TOT_COST+2.000,
T1.COST6=T1.TOT_COST+2.000,
T1.COST7=T1.TOT_COST+2.000,
T1.COST8=T1.TOT_COST+2.000,
T1.COST9=T1.TOT_COST+2.000,
T1.COST10=T1.TOT_COST+2.000,
T1.COST11=T1.TOT_COST+2.000,
T1.COST12=T1.TOT_COST+2.000,
T1.COST13=T1.TOT_COST+2.000
from DBRMAST T1 
inner join DBRMAST t2 on t2.CODE=T1.CODE

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Neither of the first two answers worked for me with multiple elements that can open dialogs that point to different pages.

This feels like the cleanest solution, only creates the dialog object once on load and then uses the events to open/close/display appropriately:

$(function () {
      var ajaxDialog = $('<div id="ajax-dialog" style="display:hidden"></div>').appendTo('body');
      ajaxDialog.dialog({autoOpen: false});
      $('a.ajax-dialog-opener').live('click', function() {
          // load remote content
          ajaxDialog.load(this.href);
          ajaxDialog.dialog("open");
          //prevent the browser from following the link
          return false;
      });
}); 

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals

$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');

SQL Server - boolean literal?

I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Create a shortcut on Desktop

I use "Windows Script Host Object Model" reference to create shortcut.

Adding "Windows Script Host Object Model" to project references

and to create shortcut on specific location:

    void CreateShortcut(string linkPath, string filename)
    {
        // Create shortcut dir if not exists
        if (!Directory.Exists(linkPath))
            Directory.CreateDirectory(linkPath);

        // shortcut file name
        string linkName = Path.ChangeExtension(Path.GetFileName(filename), ".lnk");

        // COM object instance/props
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkName);
        sc.Description = "some desc";
        //shortcut.IconLocation = @"C:\..."; 
        sc.TargetPath = linkPath;
        // save shortcut to target
        sc.Save();
    }

Is it possible to start a shell session in a running container (without ssh)

Just do

docker attach container_name

As mentioned in the comments, to detach from the container without stopping it, type Ctrlpthen Ctrlq.

Where do I find some good examples for DDD?

Code Camp Server, Jeffrey Palermo's sample code for the book ASP.NET MVC in Action. While the book is focused on the presentation layer, the application is modeled using DDD.

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

Selecting rows where remainder (modulo) is 1 after division by 2?

select * from table where value % 2 = 1 works fine in mysql.

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

CSS: Truncate table cells, but fit as much as possible

Simply add the following rules to your td:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
// These ones do the trick
width: 100%;
max-width: 0;

Example:

_x000D_
_x000D_
table {_x000D_
  width: 100%_x000D_
}_x000D_
_x000D_
td {_x000D_
  white-space: nowrap;_x000D_
}_x000D_
_x000D_
.td-truncate {_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  width: 100%;_x000D_
  max-width: 0;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
    <td>content</td>_x000D_
    <td class="td-truncate">long contenttttttt ttttttttt ttttttttttttttttttttttt tttttttttttttttttttttt ttt tttt ttttt ttttttt tttttttttttt ttttttttttttttttttttttttt</td>_x000D_
    <td>other content</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

PS: If you want to set a custom width to another td use property min-width.

Can't connect to MySQL server on 'localhost' (10061) after Installation

I had the same error. I resolved in this way

Go to start- MySQL Installer-community and run again the installer as a re-configuration(you will be asked so).

Once asked if you want make MySQL instance to run as a Windows service, check the box.

In case would do not work, try unistalling and installing again, and check the box to run MySQL as Windows service.

Unit testing click event in Angular

My objective is to check if the 'onEditButtonClick' is getting invoked when the user clicks the edit button and not checking just the console.log being printed.

You will need to first set up the test using the Angular TestBed. This way you can actually grab the button and click it. What you will do is configure a module, just like you would an @NgModule, just for the testing environment

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

describe('', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TestComponent ],
      providers: [  ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInstance;
    });
  }));
});

Then you need to spy on the onEditButtonClick method, click the button, and check that the method was called

it('should', async(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();

  fixture.whenStable().then(() => {
    expect(component.onEditButtonClick).toHaveBeenCalled();
  });
}));

Here we need to run an async test as the button click contains asynchronous event handling, and need to wait for the event to process by calling fixture.whenStable()

Update

It is now preferred to use fakeAsync/tick combo as opposed to the async/whenStable combo. The latter should be used if there is an XHR call made, as fakeAsync does not support it. So instead of the above code, refactored, it would look like

it('should', fakeAsync(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();
  tick();
  expect(component.onEditButtonClick).toHaveBeenCalled();

}));

Don't forget to import fakeAsync and tick.

See also:

How do I test if a string is empty in Objective-C?

You have 2 methods to check whether the string is empty or not:

Let's suppose your string name is NSString *strIsEmpty.

Method 1:

if(strIsEmpty.length==0)
{
    //String is empty
}

else
{
    //String is not empty
}

Method 2:

if([strIsEmpty isEqualToString:@""])
{
    //String is empty
}

else
{
    //String is not empty
}

Choose any of the above method and get to know whether string is empty or not.

HintPath vs ReferencePath in Visual Studio

According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/

There is a search order for assemblies when building. The search order is as follows:

  • Files from the current project – indicated by ${CandidateAssemblyFiles}.
  • $(ReferencePath) property that comes from .user/targets file.
  • %(HintPath) metadata indicated by reference item.
  • Target framework directory.
  • Directories found in registry that uses AssemblyFoldersEx Registration.
  • Registered assembly folders, indicated by ${AssemblyFolders}.
  • $(OutputPath) or $(OutDir)
  • GAC

So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.

Open URL in same window and in same tab

Exactly like this window.open("www.youraddress.com","_self")

"Sources directory is already netbeans project" error when opening a project from existing sources

If it helps anyone else, I had the same problem and the solution was to reinstall NetBeans.

I had tried all sorts of fixes: Deleting the NetBeansProjects folders, checking/unchecking "Put Netbeans metadata in a separate directory", killing/restarting NetBeans, restarting the system, etc. Nothing cleared the message...except the reinstall.

selecting rows with id from another table

SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

Vim for Windows - What do I type to save and exit from a file?

A faster way to

  • Save
  • and quit

would be

:x

If you have opened multiple files you may need to do a

:xa

Get number days in a specified month using JavaScript?

The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...

 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

Calling a JSON API with Node.js

Another solution is to user axios:

npm install axios

Code will be like:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

No module named MySQLdb

On my mac running Catalina v10.15.2, I had the following MySQLdb version conflict:

ImportError: this is MySQLdb version (1, 2, 5, 'final', 1), but _mysql is version (1, 4, 6, 'final', 0)

To resolve it, I did the following:

pip uninstall MySQL-python
pip install MySQL-python

How to find out if you're using HTTPS without $_SERVER['HTTPS']

Here is a re-usable function that I have been using for a while. HTH.

Note: The value of HTTPS_PORT (which is a custom constant in my code) may vary on your envrionment, for example it may be 443 or 81.

/**
 * Determine if this is a secure HTTPS connection
 * 
 * @return  bool    True if it is a secure HTTPS connection, otherwise false.
 */
function isSSL()
{
    if (isset($_SERVER['HTTPS'])) {
        if ($_SERVER['HTTPS'] == 1) {
            return true;
        } elseif ($_SERVER['HTTPS'] == 'on') {
            return true;
        }
    } elseif ($_SERVER['SERVER_PORT'] == HTTPS_PORT) {
        return true;
    }

    return false;
}

Passing a 2D array to a C++ function

Fixed Size

1. Pass by reference

template <size_t rows, size_t cols>
void process_2d_array_template(int (&array)[rows][cols])
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < rows; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < cols; ++j)
            std::cout << array[i][j] << '\t';
        std::cout << std::endl;
    }
}

In C++ passing the array by reference without losing the dimension information is probably the safest, since one needn't worry about the caller passing an incorrect dimension (compiler flags when mismatching). However, this isn't possible with dynamic (freestore) arrays; it works for automatic (usually stack-living) arrays only i.e. the dimensionality should be known at compile time.

2. Pass by pointer

void process_2d_array_pointer(int (*array)[5][10])
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < 5; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < 10; ++j)
            std::cout << (*array)[i][j] << '\t';
        std::cout << std::endl;
    }    
}

The C equivalent of the previous method is passing the array by pointer. This should not be confused with passing by the array's decayed pointer type (3), which is the common, popular method, albeit less safe than this one but more flexible. Like (1), use this method when all the dimensions of the array is fixed and known at compile-time. Note that when calling the function the array's address should be passed process_2d_array_pointer(&a) and not the address of the first element by decay process_2d_array_pointer(a).

Variable Size

These are inherited from C but are less safe, the compiler has no way of checking, guaranteeing that the caller is passing the required dimensions. The function only banks on what the caller passes in as the dimension(s). These are more flexible than the above ones since arrays of different lengths can be passed to them invariably.

It is to be remembered that there's no such thing as passing an array directly to a function in C [while in C++ they can be passed as a reference (1)]; (2) is passing a pointer to the array and not the array itself. Always passing an array as-is becomes a pointer-copy operation which is facilitated by array's nature of decaying into a pointer.

3. Pass by (value) a pointer to the decayed type

// int array[][10] is just fancy notation for the same thing
void process_2d_array(int (*array)[10], size_t rows)
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < rows; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < 10; ++j)
            std::cout << array[i][j] << '\t';
        std::cout << std::endl;
    }
}

Although int array[][10] is allowed, I'd not recommend it over the above syntax since the above syntax makes it clear that the identifier array is a single pointer to an array of 10 integers, while this syntax looks like it's a 2D array but is the same pointer to an array of 10 integers. Here we know the number of elements in a single row (i.e. the column size, 10 here) but the number of rows is unknown and hence to be passed as an argument. In this case there's some safety since the compiler can flag when a pointer to an array with second dimension not equal to 10 is passed. The first dimension is the varying part and can be omitted. See here for the rationale on why only the first dimension is allowed to be omitted.

4. Pass by pointer to a pointer

// int *array[10] is just fancy notation for the same thing
void process_pointer_2_pointer(int **array, size_t rows, size_t cols)
{
    std::cout << __func__ << std::endl;
    for (size_t i = 0; i < rows; ++i)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < cols; ++j)
            std::cout << array[i][j] << '\t';
        std::cout << std::endl;
    }
}

Again there's an alternative syntax of int *array[10] which is the same as int **array. In this syntax the [10] is ignored as it decays into a pointer thereby becoming int **array. Perhaps it is just a cue to the caller that the passed array should have at least 10 columns, even then row count is required. In any case the compiler doesn't flag for any length/size violations (it only checks if the type passed is a pointer to pointer), hence requiring both row and column counts as parameter makes sense here.

Note: (4) is the least safest option since it hardly has any type check and the most inconvenient. One cannot legitimately pass a 2D array to this function; C-FAQ condemns the usual workaround of doing int x[5][10]; process_pointer_2_pointer((int**)&x[0][0], 5, 10); as it may potentially lead to undefined behaviour due to array flattening. The right way of passing an array in this method brings us to the inconvenient part i.e. we need an additional (surrogate) array of pointers with each of its element pointing to the respective row of the actual, to-be-passed array; this surrogate is then passed to the function (see below); all this for getting the same job done as the above methods which are more safer, cleaner and perhaps faster.

Here's a driver program to test the above functions:

#include <iostream>

// copy above functions here

int main()
{
    int a[5][10] = { { } };
    process_2d_array_template(a);
    process_2d_array_pointer(&a);    // <-- notice the unusual usage of addressof (&) operator on an array
    process_2d_array(a, 5);
    // works since a's first dimension decays into a pointer thereby becoming int (*)[10]

    int *b[5];  // surrogate
    for (size_t i = 0; i < 5; ++i)
    {
        b[i] = a[i];
    }
    // another popular way to define b: here the 2D arrays dims may be non-const, runtime var
    // int **b = new int*[5];
    // for (size_t i = 0; i < 5; ++i) b[i] = new int[10];
    process_pointer_2_pointer(b, 5, 10);
    // process_2d_array(b, 5);
    // doesn't work since b's first dimension decays into a pointer thereby becoming int**
}

ReactJS: setTimeout() not working?

setTimeout(() => {
  this.setState({ position: 1 });
}, 3000);

The above would also work because the ES6 arrow function does not change the context of this.

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

When to use std::size_t?

size_t is an unsigned integral type, that can represent the largest integer on you system. Only use it if you need very large arrays,matrices etc.

Some functions return an size_t and your compiler will warn you if you try to do comparisons.

Avoid that by using a the appropriate signed/unsigned datatype or simply typecast for a fast hack.

Set keyboard caret position in html textbox

I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.

function setCaretPosition(elem, caretPos) {
    var range;

    if (elem.createTextRange) {
        range = elem.createTextRange();
        range.move('character', caretPos);
        range.select();
    } else {
        elem.focus();
        if (elem.selectionStart !== undefined) {
            elem.setSelectionRange(caretPos, caretPos);
        }
    }
}

How to prevent auto-closing of console after the execution of batch file

In Windows/DOS batch files:

pause

This prints a nice "Press any key to continue . . . " message

Or, if you don't want the "Press any key to continue . . ." message, do this instead:

pause >nul

How do I set a fixed background image for a PHP file?

I found my answer.

<?php
$profpic = "bg.jpg";
?>

<html>
<head>
<style type="text/css">

body {
background-image: url('<?php echo $profpic;?>');
}
</style>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>

How do I limit the number of rows returned by an Oracle query after ordering?

For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.

  SELECT * FROM sometable1 so
    WHERE so.id IN (
    SELECT so2.id from sometable2 so2
    WHERE ROWNUM <=5
    )
    AND ORDER BY so.somefield AND ROWNUM <= 100 

I have implemented this in oracle server 11.2.0.1.0

List of IP addresses/hostnames from local network in Python

If you know the names of your computers you can use:

import socket
IP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer
IP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer

Otherwise you will have to scan for all the IP addresses that follow the same mask as your local computer (IP1), as stated in another answer.

How do I bottom-align grid elements in bootstrap fluid layout

Just set the parent to display:flex; and the child to margin-top:auto. This will place the child content at the bottom of the parent element, assuming the parent element has a height greater than the child element.

There is no need to try and calculate a value for margin-top when you have a height on your parent element or another element greater than your child element of interest within your parent element.

How to create a list of objects?

You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass

objs = [MyClass() for i in range(10)]

print(objs)

How to set a cookie for another domain

You can't, but... If you own both pages then...

1) You can send the data via query params (http://siteB.com/?key=value)

2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)

How to Completely Uninstall Xcode and Clear All Settings

FOR UNINSTALLING AND THEN BEING ABLE TO REINSTALL XCODE 9 CORRECTLY

I followed the topmost answer for deleting Xcode 7 and found a major error, deleting ~/Library/Developer will delete an important folder called PrivateFrameworks, which will actually crash Xcode everytime you reinstall and force you to have to get your friends to send you the PrivateFrameworks folder again, a complete waste of time seeing if you needed to uninstall and reinstall Xcode urgently for immediate work purposes.

I have tried editing the topmost answer but see no changes so below is the modified steps you should take for Xcode 9:

Delete

/Applications/Xcode.app

~/Library/Preferences/com.apple.dt.* (Generally anything with com.apple.dt. as prefix is removable in the Preferences folder)

~/Library/Caches/com.apple.dt.Xcode

~/Library/Application Support/Xcode

Everything in /Library/Developer directory except for /Library/Developer/PrivateFrameworks

hasNext in Python iterators?

The way I solved my problem is to keep the count of the number of objects iterated over, so far. I wanted to iterate over a set using calls to an instance method. Since I knew the length of the set, and the number of items counted so far, I effectively had an hasNext method.

A simple version of my code:

class Iterator:
    # s is a string, say
    def __init__(self, s):
        self.s = set(list(s))
        self.done = False
        self.iter = iter(s)
        self.charCount = 0

    def next(self):
        if self.done:
            return None
        self.char = next(self.iter)
        self.charCount += 1
        self.done = (self.charCount < len(self.s))
        return self.char

    def hasMore(self):
        return not self.done

Of course, the example is a toy one, but you get the idea. This won't work in cases where there is no way to get the length of the iterable, like a generator etc.

What command means "do nothing" in a conditional in Bash?

The no-op command in shell is : (colon).

if [ "$a" -ge 10 ]
then
    :
elif [ "$a" -le 5 ]
then
    echo "1"
else
    echo "2"
fi

From the bash manual:

: (a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.

WCF Service , how to increase the timeout?

In your binding configuration, there are four timeout values you can tweak:

<bindings>
  <basicHttpBinding>
    <binding name="IncreasedTimeout"
             sendTimeout="00:25:00">
    </binding>
  </basicHttpBinding>

The most important is the sendTimeout, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds in your settings - in my sample, I set the timeout to 25 minutes.

The openTimeout as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.

The receiveTimeout is a bit like a mirror for the sendTimeout - while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout is the amount of time you'll give you client to receive and process the response from the server.

In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.

There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.

To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:

Learning WCF http://ecx.images-amazon.com/images/I/51GNuqUJq%2BL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!

For more advanced topics I recommend that you check out Juwal Lowy's Programming WCF Services book.

Programming WCF http://ecx.images-amazon.com/images/I/41odWcLoGAL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

How do you remove a specific revision in the git history?

If all you want to do is remove the changes made in revision 3, you might want to use git revert.

Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.

What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.

This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.

css 100% width div not taking up full width of parent

html, body{ 
  width:100%;
}

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

html, body{ 
  min-width:100%;
}

So it will be 100% as a minimum, bot more if needed.

Multiple bluetooth connection

Please take a look at the Android documentation.

Using the Bluetooth APIs, an Android application can perform the following:

  • Scan for other Bluetooth devices
  • Query the local Bluetooth adapter for paired Bluetooth devices
  • Establish RFCOMM channels
  • Connect to other devices through service discovery
  • Transfer data to and from other devices
  • Manage multiple connections

How to set thousands separator in Java?

As mentioned above, the following link gives you the specific country code to allow Java to localize the number. Every country has its own style.

In the link above you will find the country code which should be placed in here:

...(new Locale(<COUNTRY CODE HERE>));

Switzerland for example formats the numbers as follows:

1000.00 --> 1'000.00

country code

To achieve this, following codes works for me:

NumberFormat nf = NumberFormat.getNumberInstance(new Locale("de","CH"));
nf.setMaximumFractionDigits(2);
DecimalFormat df = (DecimalFormat)nf;
System.out.println(df.format(1000.00));

Result is as expected:

1'000.00

Response.Redirect with POST instead of Get?

Thought it might interesting to share that heroku does this with it's SSO to Add-on providers

An example of how it works can be seen in the source to the "kensa" tool:

https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb

And can be seen in practice if you turn of javascript. Example page source:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Heroku Add-ons SSO</title>
  </head>

  <body>
    <form method="POST" action="https://XXXXXXXX/sso/login">

        <input type="hidden" name="email" value="XXXXXXXX" />

        <input type="hidden" name="app" value="XXXXXXXXXX" />

        <input type="hidden" name="id" value="XXXXXXXX" />

        <input type="hidden" name="timestamp" value="1382728968" />

        <input type="hidden" name="token" value="XXXXXXX" />

        <input type="hidden" name="nav-data" value="XXXXXXXXX" />

    </form>

    <script type="text/javascript">
      document.forms[0].submit();
    </script>
  </body>
</html>

How do I check if a file exists in Java?

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

    new File("/path/to/file").exists();
    
  2. Check for file

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isFile()) {}
    
  3. Check for Directory.

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isDirectory()) {}
    
  4. Java 7 way.

    Path path = Paths.get("/path/to/file");
    Files.exists(path)  // Existence 
    Files.isDirectory(path)  // is Directory
    Files.isRegularFile(path)  // Regular file 
    Files.isSymbolicLink(path)  // Symbolic Link
    

Reading images in python

If you just want to read an image in Python using the specified libraries only, I will go with matplotlib

In matplotlib :

import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')

Intel's HAXM equivalent for AMD on Windows OS

From the Android docs (March 2016):

Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:

  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

Note: Virtualization extensions are typically enabled through your computer's BIOS and are frequently turned off by default. Check the documentation for your system's motherboard to find out how to enable virtualization extensions.

Most people talk about Genymotion being faster, and I have never heard anyone say it's slower. I definitely think it's faster, and it will be worth the ~20 minutes it will take to set up just to try it.

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

How to validate email id in angularJs using ng-pattern

Spend some time to make it working for me.

Requirement:

single or comma separated list of e-mails with domains ending [email protected] or [email protected]

Controller:

$scope.email = {
   EMAIL_FORMAT:  /^\w+([\.-]?\w+)*@(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*@(list.)?gmail.com)*$/,
   EMAIL_FORMAT_HELP: "format as '[email protected]' or comma separated '[email protected], [email protected]'"
};

HTML:

<ng-form name="emailModal">
    <div class="form-group row mb-3">
        <label for="to" class="col-sm-2 text-right col-form-label">
            <span class="form-required">*</span>
            To
        </label>
        <div class="col-sm-9">
            <input class="form-control" id="to"
                   name="To"
                   ng-required="true"
                   ng-pattern="email.EMAIL_FORMAT"
                   placeholder="{{email.EMAIL_FORMAT_HELP}}"
                   ng-model="mail.to"/>
            <small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
        </div>
    </div>
</ng-form>

I found good online regex testing tool. Covered my regex with tests:

https://regex101.com/r/Dg2iAZ/6/tests

How do I monitor all incoming http requests?

What you need to do is configure Fiddler to work as a "reverse proxy"

There are instructions on 2 different ways you can do this on Fiddler's website. Here is a copy of the steps:


Step #0

Before either of the following options will work, you must enable other computers to connect to Fiddler. To do so, click Tools > Fiddler Options > Connections and tick the "Allow remote computers to connect" checkbox. Then close Fiddler.

Option #1: Configure Fiddler as a Reverse-Proxy

Fiddler can be configured so that any traffic sent to http://127.0.0.1:8888 is automatically sent to a different port on the same machine. To set this configuration:

  1. Start REGEDIT
  2. Create a new DWORD named ReverseProxyForPort inside HKCU\SOFTWARE\Microsoft\Fiddler2.
  3. Set the DWORD to the local port you'd like to re-route inbound traffic to (generally port 80 for a standard HTTP server)
  4. Restart Fiddler
  5. Navigate your browser to http://127.0.0.1:8888

Option #2: Write a FiddlerScript rule

Alternatively, you can write a rule that does the same thing.

Say you're running a website on port 80 of a machine named WEBSERVER. You're connecting to the website using Internet Explorer Mobile Edition on a Windows SmartPhone device for which you cannot configure the web proxy. You want to capture the traffic from the phone and the server's response.

  1. Start Fiddler on the WEBSERVER machine, running on the default port of 8888.
  2. Click Tools | Fiddler Options, and ensure the "Allow remote clients to connect" checkbox is checked. Restart if needed.
  3. Choose Rules | Customize Rules.
  4. Inside the OnBeforeRequest handler, add a new line of code:
    if (oSession.host.toLowerCase() == "webserver:8888") oSession.host = "webserver:80";
  5. On the SmartPhone, navigate to http://webserver:8888

Requests from the SmartPhone will appear in Fiddler. The requests are forwarded from port 8888 to port 80 where the webserver is running. The responses are sent back through Fiddler to the SmartPhone, which has no idea that the content originally came from port 80.

How to create friendly URL in php?

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

Reading numbers from a text file into an array in C

for (i = 0; i < 16; i++)
{
    fscanf(myFile, "%d", &numberArray[i]);
}

This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

5 6 2 3 ...

Disable browser's back button

<body onLoad="if(history.length>0)history.go(+1)">

Checking to see if one array's elements are in another array in PHP

if 'empty' is not the best choice, what about this:

if (array_intersect($people, $criminals)) {...} //when found

or

if (!array_intersect($people, $criminals)) {...} //when not found

CSS3 Spin Animation

@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}

this will make you to answer the question

How do getters and setters work?

1. The best getters / setters are smart.

Here's a javascript example from mozilla:

var o = { a:0 } // `o` is now a basic object

Object.defineProperty(o, "b", { 
    get: function () { 
        return this.a + 1; 
    } 
});

console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)

I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.

2. Getters / setters in php

Example from sof

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

citings:

Update int column in table with unique incrementing values

simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1

SET @a  = 50000835 ;  
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
WHERE external_identifier IS NULL;

How to set a value to a file input in HTML?

As everyone else here has stated: You cannot upload just any file automatically with JavaScript.

HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.

What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...

function uploadFile (data) {
        // define data and connections
    var blob = new Blob([JSON.stringify(data)]);
    var url = URL.createObjectURL(blob);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'myForm.php', true);
    
        // define new form
    var formData = new FormData();
    formData.append('someUploadIdentifier', blob, 'someFileName.json');
        
        // action after uploading happens
    xhr.onload = function(e) {
        console.log("File uploading completed!");
    };
    
        // do the uploading
    console.log("File uploading started!");
    xhr.send(formData);
}

    // This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});

So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.

How to Animate Addition or Removal of Android ListView Rows

Just sharing another approach:

First set the list view's android:animateLayoutChanges to true:

<ListView
        android:id="@+id/items_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"/>

Then I use a handler to add items and update the listview with delay:

Handler mHandler = new Handler();
    //delay in milliseconds
    private int mInitialDelay = 1000;
    private final int DELAY_OFFSET = 1000;


public void addItem(final Integer item) {
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mDataSet.add(item);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }).start();

        }
    }, mInitialDelay);
    mInitialDelay += DELAY_OFFSET;
}

Android load from URL to Bitmap

Follow method to get url to bitmap in android just pass link of this image and get bitmap.

public static Bitmap getBitmapFromURL(String imgUrl) {
    try {
        URL url = new URL(imgUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}

Method List in Visual Studio Code

For find method in all files you can press CTRL + P and then start search with #

example : #signin

enter image description here

How do I copy a version of a single file from one git branch to another?

What about using checkout command :

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"

Specify the from user when sending email using the mail command

Most people need to change two values when trying to correctly forge the from address on an email. First is the from address and the second is the orig-to address. Many of the solutions offered online only change one of these values.

If as root, I try a simple mail command to send myself an email it might look like this. echo "test" | mail -s "a test" [email protected]

And the associated logs: Feb 6 09:02:51 myserver postfix/qmgr[28875]: B10322269D: from=<[email protected]>, size=437, nrcpt=1 (queue active) Feb 6 09:02:52 myserver postfix/smtp[19848]: B10322269D: to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=0.34, delays=0.1/0/0.11/0.13, dsn=2.0.0, status=sent (250 Ok 0000014b5f678593-a0e399ef-a801-4655-ad6b-19864a220f38-000000)

Trying to change the from address with -- echo "test" | mail -s "a test" [email protected] -- [email protected]

This changes the orig-to value but not the from value: Feb 6 09:09:09 myserver postfix/qmgr[28875]: 6BD362269D: from=<[email protected]>, size=474, nrcpt=2 (queue active) Feb 6 09:09:09 myserver postfix/smtp[20505]: 6BD362269D: to=<me@noone>, orig_to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=0.31, delays=0.06/0/0.09/0.15, dsn=2.0.0, status=sent (250 Ok 0000014b5f6d48e2-a98b70be-fb02-44e0-8eb3-e4f5b1820265-000000)

Next trying it with a -r and a -- to adjust the from and orig-to. echo "test" | mail -s "a test" -r [email protected] [email protected] -- [email protected]

And the logs: Feb 6 09:17:11 myserver postfix/qmgr[28875]: E3B972264C: from=<[email protected]>, size=459, nrcpt=2 (queue active) Feb 6 09:17:11 myserver postfix/smtp[21559]: E3B972264C: to=<[email protected]>, orig_to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=1.1, delays=0.56/0.24/0.11/0.17, dsn=2.0.0, status=sent (250 Ok 0000014b5f74a2c0-c06709f0-4e8d-4d7e-9abf-dbcea2bee2ea-000000)

This is how it's working for me. Hope this helps someone.

Command to run a .bat file

Can refer to here: https://ss64.com/nt/start.html

start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Storing Python dictionaries

My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.

To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list or an object as root. So I considered that my JSON file always has a list of objects and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w):

def saveJson(url,sc): # This function writes the two values to the file
    newdata = {'url':url,'sc':sc}
    json_path = "db/file.json"

    old_list= []
    with open(json_path) as myfile:  # Read the contents first
        old_list = json.load(myfile)
    old_list.append(newdata)

    with open(json_path,"w") as myfile:  # Overwrite the whole content
        json.dump(old_list, myfile, sort_keys=True, indent=4)

    return "success"

The new JSON file will look something like this:

[
    {
        "sc": "a11",
        "url": "www.google.com"
    },
    {
        "sc": "a12",
        "url": "www.google.com"
    },
    {
        "sc": "a13",
        "url": "www.google.com"
    }
]

NOTE: It is essential to have a file named file.json with [] as initial data for this approach to work

PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.

matplotlib: how to draw a rectangle on image

You can add a Rectangle patch to the matplotlib Axes.

For example (using the image from the tutorial here):

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image

im = Image.open('stinkbug.png')

# Create figure and axes
fig, ax = plt.subplots()

# Display the image
ax.imshow(im)

# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

plt.show()

enter image description here

Execute a SQL Stored Procedure and process the results

From MSDN

To execute a stored procedure returning rows programmatically using a command object

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

Invalid length parameter passed to the LEFT or SUBSTRING function

Something else you can use is isnull:

isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)

How to block until an event is fired in c#

If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:

public class Foo
{
    public delegate void MyEventHandler(object source, MessageEventArgs args);
    public event MyEventHandler _event;
    public string ReadLine()
    {
        return Observable
            .FromEventPattern<MyEventHandler, MessageEventArgs>(
                h => this._event += h,
                h => this._event -= h)
            .Select(ep => ep.EventArgs.Message)
            .First();
    }
    public void SendLine(string message)
    {
        _event(this, new MessageEventArgs() { Message = message });
    }
}

public class MessageEventArgs : EventArgs
{
    public string Message;
}

I can use it like this:

var foo = new Foo();

ThreadPoolScheduler.Instance
    .Schedule(
        TimeSpan.FromSeconds(5.0),
        () => foo.SendLine("Bar!"));

var resp = foo.ReadLine();

Console.WriteLine(resp);

I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.

WCF Service, the type provided as the service attribute values…could not be found

  1. When you create an IIS application only the /bin or /App_Code folder is in the root directory of the IIS app. So just remember put all the code in the root /bin or /App_code directory (see http://blogs.msdn.com/b/chrsmith/archive/2006/08/10/wcf-service-nesting-in-iis.aspx).

  2. Make sure that the service name and the contract contain full name(e.g namespace.ClassName), and the service name and interface is the same as the name attribute of the service tag and contract of endpoint in web.config.

MySQL Removing Some Foreign keys

Check what's the CONSTRAINT name and the FOREIGN KEY name:

SHOW CREATE TABLE table_name;

Remove both the CONSTRAINT name and the FOREIGN KEY name:

ALTER TABLE table_name
  DROP FOREIGN KEY the_name_after_CONSTRAINT,
  DROP KEY the_name_after_FOREIGN_KEY;

Hope this helps!

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

Input button target="_blank" isn't causing the link to load in a new window/tab

Another solution, using JQUERY, would be to write a function that is invoked when the user clicks the button. This function creates a new <A> element, with target='blank', appends this to the document, 'clicks' it then removes it.

So as far as the user is concerned, they clicked a button, but behind the scenes, an <A> element with target='_blank' was clicked.

<input type="button" id='myButton' value="facebook">

$(document).on('ready', function(){
     $('#myButton').on('click',function(){
         var link = document.createElement("a");
         link.href = 'http://www.facebook.com/';
         link.style = "visibility:hidden";
         link.target = "_blank";
         document.body.appendChild(link);
         link.click();
         document.body.removeChild(link); 
     });
});

JsFiddle : https://jsfiddle.net/ragDaniel/tf991u4g/2/

Submit form without page reloading

It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.

First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().

event.preventDefault()

Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.

Example:

Form:

<form id="form-id" onsubmit="func()">
    <input id="input-id" type="text">
</form>

Javascript:

function func(){
    event.preventDefault();
    var newValue = $('#input-field-id').val();
    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
}

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

How to use @Nullable and @Nonnull annotations more effectively?

I think this original question indirectly points to a general recommendation that run-time null-pointer check is still needed, even though @NonNull is used. Refer to the following link:

Java 8's new Type Annotations

In the above blog, it is recommended that:

Optional Type Annotations are not a substitute for runtime validation Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification. Your code should still perform runtime validation.

PHP Array to JSON Array using json_encode();

If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index

How to display default text "--Select Team --" in combo box on pageload in WPF?

EDIT: Per comments below, this is not a solution. Not sure how I had it working, and can't check that project.

It's time to update this answer for the latest XAML.

Finding this SO question searching for a solution to this question, I then found that the updated XAML spec has a simple solution.

An attribute called "Placeholder" is now available to accomplish this task. It is as simple as this (in Visual Studio 2015):

<ComboBox x:Name="Selection" PlaceholderText="Select...">
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
</ComboBox>

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

Copying files from server to local computer using SSH

Make sure the scp command is available on both sides - both on the client and on the server.

BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found or something similar even though though you have it all configured locally.

Oracle date function for the previous month

The trunc() function truncates a date to the specified time period; so trunc(sysdate,'mm') would return the beginning of the current month. You can then use the add_months() function to get the beginning of the previous month, something like this:

select count(distinct switch_id)   
  from [email protected]  
 where dealer_name =  'XXXX'    
   and creation_date >= add_months(trunc(sysdate,'mm'),-1) 
   and creation_date < trunc(sysdate, 'mm')

As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g. DATE 2012-08-31, or the to_date() function, for example to_date('2012-08-31','YYYY-MM-DD'). If you don't then you are bound to get this wrong at some point.

You would not use sysdate - 15 as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not using trunc().


Just as a little demonstration of what trunc(<date>,'mm') does:

select sysdate
     , case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as gt
     , case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as lt
     , case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as eq
  from dual
       ;

SYSDATE                   GT         LT         EQ
----------------- ---------- ---------- ----------
20120911 19:58:51                                1

Event handlers for Twitter Bootstrap dropdowns?

Try this:

$('div.btn-group ul.dropdown-menu li a').click(function (e) {
    var $div = $(this).parent().parent().parent(); 
    var $btn = $div.find('button');
    $btn.html($(this).text() + ' <span class="caret"></span>');
    $div.removeClass('open');
    e.preventDefault();
    return false;
});

csv.Error: iterator should return strings, not bytes

Your problem is you have the b in the open flag. The flag rt (read, text) is the default, so, using the context manager, simply do this:

with open('sample.csv') as ifile:
    read = csv.reader(ifile) 
    for row in read:
        print (row)  

The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.

The above is the same as:

with open('sample.csv', 'r') as ifile:
    ...

or

with open('sample.csv', 'rt') as ifile:
    ...

Why would an Enum implement an Interface?

Since Enums can implement interfaces they can be used for strict enforcing of the singleton pattern. Trying to make a standard class a singleton allows...

  • for the possibility of using reflection techniques to expose private methods as public
  • for inheriting from your singleton and overriding your singleton's methods with something else

Enums as singletons help to prevent these security issues. This might have been one of the contributing reasons to let Enums act as classes and implement interfaces. Just a guess.

See https://stackoverflow.com/questions/427902/java-enum-singleton and Singleton class in java for more discussion.

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

Script to Change Row Color when a cell changes text

I used GENEGC's script, but I found it quite slow.

It is slow because it scans whole sheet on every edit.

So I wrote way faster and cleaner method for myself and I wanted to share it.

function onEdit(e) {
    if (e) { 
        var ss = e.source.getActiveSheet();
        var r = e.source.getActiveRange(); 

        // If you want to be specific
        // do not work in first row
        // do not work in other sheets except "MySheet"
        if (r.getRow() != 1 && ss.getName() == "MySheet") {

            // E.g. status column is 2nd (B)
            status = ss.getRange(r.getRow(), 2).getValue();

            // Specify the range with which You want to highlight
            // with some reading of API you can easily modify the range selection properties
            // (e.g. to automatically select all columns)
            rowRange = ss.getRange(r.getRow(),1,1,19);

            // This changes font color
            if (status == 'YES') {
                rowRange.setFontColor("#999999");
            } else if (status == 'N/A') {
                rowRange.setFontColor("#999999");
            // DEFAULT
            } else if (status == '') { 
                rowRange.setFontColor("#000000");
            }   
        }
    }
}

Cancel split window in Vim

To close all splits, I usually place the cursor in the window that shall be the on-ly visible one and then do :on which makes the current window the on-ly visible window. Nice mnemonic to remember.


Edit: :help :on showed me that these commands are the same:

  • :on
  • :only
  • CTRL-w CTRL-o
  • And yes, also CTRL-W o has the same effect (as Nathan answered).

Each of these four closes all windows except the active one.

Flutter: Setting the height of the AppBar

At the time of writing this, I was not aware of PreferredSize. Cinn's answer is better to achieve this.

You can create your own custom widget with a custom height:

import "package:flutter/material.dart";

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Column(children : <Widget>[new CustomAppBar("Custom App Bar"), new Container()],);
  }
}


class CustomAppBar extends StatelessWidget {

  final String title;
  final double barHeight = 50.0; // change this for different heights 

  CustomAppBar(this.title);

  @override
  Widget build(BuildContext context) {
    final double statusbarHeight = MediaQuery
        .of(context)
        .padding
        .top;

    return new Container(
      padding: new EdgeInsets.only(top: statusbarHeight),
      height: statusbarHeight + barHeight,
      child: new Center(
        child: new Text(
          title,
          style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

Count length of array and return 1 if it only contains one element

Instead of writing echo $cars.length write echo @($cars).length

How do I pass a URL with multiple parameters into a URL?

In your example parts of your passed-in URL are not URL encoded (for example the colon should be %3A, the forward slashes should be %2F). It looks like you have encoded the parameters to your parameter URL, but not the parameter URL itself. Try encoding it as well. You can use encodeURIComponent.

How can I tell when a MySQL table was last updated?

I would create a trigger that catches all updates/inserts/deletes and write timestamp in custom table, something like tablename | timestamp

Just because I don't like the idea to read internal system tables of db server directly

jQuery Call to WebService returns "No Transport" error

None of the proposed answers completely worked for me. My use case is slightly different (doing an ajax get to an S3 .json file in IE9). Setting jQuery.support.cors = true; got rid of the No Transport error but I was still getting Permission denied errors.

What did work for me was to use the jQuery-ajaxTransport-XDomainRequest to force IE9 to use XDomainRequest. Using this did not require setting jQuery.support.cors = true;

Center a button in a Linear layout

easy with this

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:visibility="visible" 
        android:gravity="center"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/pbEndTrip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Gettings" />
    </LinearLayout>

Google Chromecast sender error if Chromecast extension is not installed or using incognito

By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.

Do you know the Maven profile for mvnrepository.com?

Place this in the ~/.m2/settings.xml or custom file to be run with $ mvn -s custom-settings.xml install

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>${user.home}/.m2/repository</localRepository>
<interactiveMode/>
<offline/>
<pluginGroups/>
<profiles>
    <profile>
        <repositories>
            <repository>
                <id>mvnrepository</id>
                <name>mvnrepository</name>
                <url>http://www.mvnrepository.com</url>
            </repository>
        </repositories>
    </profile>
</profiles>
<activeProfiles>
    <activeProfile>mvnrepository</activeProfile>
</activeProfiles>
</settings>

How to convert a multipart file to File?

if you don't want to use MultipartFile.transferTo(). You can write file like this

    val dir = File(filePackagePath)
    if (!dir.exists()) dir.mkdirs()

    val file = File("$filePackagePath${multipartFile.originalFilename}").apply {
        createNewFile()
    }

    FileOutputStream(file).use {
        it.write(multipartFile.bytes)
    }

Find the directory part (minus the filename) of a full path in access 97

I always used the FileSystemObject for this sort of thing. Here's a little wrapper function I used. Be sure to reference the Microsoft Scripting Runtime.

Function StripFilename(sPathFile As String) As String

'given a full path and file, strip the filename off the end and return the path

Dim filesystem As New FileSystemObject

StripFilename = filesystem.GetParentFolderName(sPathFile) & "\"

Exit Function

End Function

How to manually reload Google Map with JavaScript

map.setZoom(map.getZoom());

For some reasons, resize trigger did not work for me, and this one worked.

Java HashMap performance optimization / alternative

In Effective Java: Programming Language Guide (Java Series)

Chapter 3 you can find good rules to follow when computing hashCode().

Specially:

If the field is an array, treat it as if each element were a separate field. That is, compute a hash code for each significant element by applying these rules recursively, and combine these values per step 2.b. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.

Call a global variable inside module

Sohnee solutions is cleaner, but you can also try

window["bootbox"]

find a minimum value in an array of floats

Python has a min() built-in function:

>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828

Convert Unix timestamp to a date string

As @TomMcKenzie says in a comment to another answer, date -r 123456789 is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there's no universal guaranteed portable solution.

The -d option on many types of systems means something entirely different than GNU Date's --date extension. Sadly GNU Date doesn't interpret -r the same as these other implementations. So unfortunately you have to know which version of date you're using, and many older Unix date commands don't support either option.

Even worse, POSIX date recognizes neither -d nor -r and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime()). (You can't use touch -t and ls because the former does not accept a time given as seconds since the Unix Epoch.)

Note though The One True Awk available direct from Brian Kernighan does now have the strftime() function built-in as well as a systime() function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.

How do I check form validity with angularjs?

You can also use myform.$invalid

E.g.

if($scope.myform.$invalid){return;}

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

Simple way to measure cell execution time in ipython notebook

Sometimes the formatting is different in a cell when using print(res), but jupyter/ipython comes with a display. See an example of the formatting difference using pandas below.

%%time
import pandas as pd 
from IPython.display import display

df = pd.DataFrame({"col0":{"a":0,"b":0}
              ,"col1":{"a":1,"b":1}
              ,"col2":{"a":2,"b":2}
             })

#compare the following
print(df)
display(df)

The display statement can preserve the formatting. screenshot