Programs & Examples On #Mfc

The Microsoft Foundation Class Library (MFC) is a C++ framework for Windows GUI programming.

Convert CString to const char*

I had a similar problem. I had a char* buffer with the .so name in it.
I could not convert the char* variable to LPCTSTR. Here's how I got around it...

char *fNam;
...
LPCSTR nam = fNam;
dll = LoadLibraryA(nam);

How do you convert CString and std::string std::wstring to each other?

One interesting approach is to cast CString to CStringA inside a string constructor. Unlike std::string s((LPCTSTR)cs); this will work even if _UNICODE is defined. However, if that is the case, this will perform conversion from Unicode to ANSI, so it is unsafe for higher Unicode values beyond the ASCII character set. Such conversion is subject to the _CSTRING_DISABLE_NARROW_WIDE_CONVERSION preprocessor definition. https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx

        CString s1("SomeString");
        string s2((CStringA)s1);

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

Convert MFC CString to integer

If you are using TCHAR.H routine (implicitly, or explicitly), be sure you use _ttoi() function, so that it compiles for both Unicode and ANSI compilations.

More details: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

connecting to phpMyAdmin database with PHP/MySQL

The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.

mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());

// now you are connected

How to persist data in a dockerized postgres database using volumes

I would avoid using a relative path. Remember that docker is a daemon/client relationship.

When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database is then relative to the daemon, not the client.

Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.

In short, don't use a relative path, use an absolute path.

Generating a WSDL from an XSD file

Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.

Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.

Check if value exists in the array (AngularJS)

You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';
}

More about indexOf:

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

How can I iterate through a string and also know the index (current position)?

For strings, you can use string.c_str() which will return you a const char*, which can be treated as an array, example:

const char* strdata = str.c_str();

for (int i = 0; i < str.length(); ++i)
    cout << i << strdata[i];

DLL load failed error when importing cv2

Please Remember if you want to install python package/libraries for windows,

you should always consider Python unofficial Binaries

Step 1:

Search for your package, download dependent version 2.7 or 3.6 you can find it under Downloads/your_package_version.whl its called python wheel

Step 2:

Now install using pip,

pip install ~/Downloads/your_packae_ver.whl

this will install without any error.

How to install SimpleJson Package for Python

I would recommend EasyInstall, a package management application for Python.

Once you've installed EasyInstall, you should be able to go to a command window and type:

easy_install simplejson

This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like C:\Python25\Scripts).

Rails ActiveRecord date between

I ran this code to see if the checked answer worked, and had to try swapping around the dates to get it right. This worked--

Day.where(:reference_date => 3.months.ago..Time.now).count
#=> 721

If you're thinking the output should have been 36, consider this, Sir, how many days is 3 days to 3 people?

What is the meaning of 'No bundle URL present' in react-native?

I have found the easiest/quickest way to bypass this is to exit the app within the simulator (2 x Cmd + Shift + H) and re-launch.

Radio button validation in javascript

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}?

See it in action: http://jsfiddle.net/FhgQS/

How can I add private key to the distribution certificate?

What i did is that , i created a new certificate for distribution form my Mac computer and gave signing identity from this Mac computer as well, and thats it

How to remove a package in sublime text 2

Just wanted to add, that after you remove the package in question you might also need to check to see if it's listed in the list of packages in the following area and manually remove its listing:

Preferences>Package Settings>Package Control>Settings - User

{
    "auto_upgrade_last_run": null,
    "installed_packages":
    [
        "AdvancedNewFile",
        "Emmet",
        "Package Control",
        "SideBarEnhancements",
        "Sublimerge"
    ]
}

In my instance, my trial period for "Sublimerge" had run out and I would get a popup every time I would start Sublime Text 2 saying:

"The package specified, Sublimerge, is not available"

I would have to close the event window out before being able to do anything in ST2.

But in my case, even after successfully removing the package through package control, I still received a event window popup message telling me "Sublimerge" wasn't available. This didn't make any sense as I had successfully removed the package.

It wasn't until I found this "auto_upgrade_last_run" file and manually removed the "Sublimerge" entry and saved my edit, did the message go away.

How to pass multiple parameters to a get method in ASP.NET Core

    public HttpResponseMessage Get(int id,string numb)
    {

        using (MarketEntities entities = new MarketEntities())
        {
          var ent=  entities.Api_For_Test.FirstOrDefault(e => e.ID == id && e.IDNO.ToString()== numb);
            if (ent != null)
            {
                return Request.CreateResponse(HttpStatusCode.OK, ent);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Applicant with ID " + id.ToString() + " not found in the system");
            }
        }
    }

Save multiple sheets to .pdf

In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.

Highest Salary in each department

Assuming SQL Server 2005+

WITH cteRowNum AS (
    SELECT DeptID, EmpName, Salary,
           DENSE_RANK() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum
        FROM EmpDetails
)
SELECT DeptID, EmpName, Salary
    FROM cteRowNum
    WHERE RowNum = 1;

How to run a PowerShell script without displaying a window?

Here is a working solution in windows 10 that does not include any third-party components. It works by wrapping the PowerShell script into VBScript.

Step 1: we need to change some windows features to allow VBScript to run PowerShell and to open .ps1 files with PowerShell by default.

-go to run and type "regedit". Click on ok and then allow it to run.

-paste this path "HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell" and press enter.

-now open the entry on the right and change the value to 0.

-open PowerShell as an administrator and type "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned", press enter and confirm the change with "y" and then enter.

Step 2: Now we can start wrapping our script.

-save your Powershell script as a .ps1 file.

-create a new text document and paste this script.

Dim objShell,objFSO,objFile

Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")

'enter the path for your PowerShell Script
 strPath="c:\your script path\script.ps1"

'verify file exists
 If objFSO.FileExists(strPath) Then
   'return short path name
   set objFile=objFSO.GetFile(strPath)
   strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
    objFile.ShortPath & "}" & Chr(34)
   'Uncomment next line for debugging
   'WScript.Echo strCMD

  'use 0 to hide window
   objShell.Run strCMD,0

Else

  'Display error message
   WScript.Echo "Failed to find " & strPath
   WScript.Quit

End If

-now change the file path to the location of your .ps1 script and save the text document.

-Now right-click on the file and go to rename. Then change the filename extension to .vbs and press enter and then click ok.

DONE! If you now open the .vbs you should see no console window while your script is running in the background.

make sure to upvote if this worked for you!

opening html from google drive

While drive allows you to edit plain text and HTML files I don't believe they allow the HTML to actually be displayed. I don't think they want people hosting websites from their drive space.

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

Javascript onclick hide div

If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like:

this.parentNode.style.display = 'none';

To remove it you use removeChild

this.parentNode.parentNode.removeChild(this.parentNode);

If you had a library like jQuery included then hiding or removing the div would be slightly easier:

$(this).parent().hide();
$(this).parent().remove();

One other thing, as your img is in an anchor the onclick event on the anchor is going to fire as well. As the href is set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its href you should set the onclick event to return false;

How to reload the current state?

You can use @Rohan answer https://stackoverflow.com/a/23609343/3297761

But if you want to make each controller reaload after a view change you can use

myApp.config(function($ionicConfigProvider) { $ionicConfigProvider.views.maxCache(0); ... }

How to remove a web site from google analytics

To delete a web property, you simply need to delete every profile within the property. Once the last profile has been deleted, the web property with cease to exist in the GA account. That's all there is to it! -- Source

how to destroy bootstrap modal window completely?

It works for Bootstrap v3.3.6

$('#dialog').modal()
.on('hide.bs.modal', function () {
    // Some Code
}).on('shown.bs.modal', function () {
    // Some Code
}).on('hidden.bs.modal', function () {
    $("#dialog").off();
});

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

NOTE: This is a recent answer based on recent SQL server, .NET stack updates

latitute and longitude from google Maps should be stored as Point(note capital P) data in SQL server under geography data type.

Assuming your current data is stored in a table Sample as varchar under columns lat and lon, below query will help you convert to geography

alter table Sample add latlong geography
go
update Sample set latlong= geography::Point(lat,lon,4326)
go

PS: Next time when you do a select on this table with geography data, apart from Results and Messages tab, you will also get Spatial results tab like below for visualization

SSMS geo results tab

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

Creating a new user and password with Ansible

If you read Ansible's manual for user module, it'll direct you to the Ansible-examples github repo for details how to use password parameter.

There you'll see that your password must be hashed.

- hosts: all
  user: root
  vars:
    # created with:
    # python -c 'import crypt; print crypt.crypt("This is my Password", "$1$SomeSalt$")'
    password: $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI.

  tasks:
    - user: name=tset password={{password}}

If your playbook or ansible command line has your password as-is in plain text, this means your password hash recorded in your shadow file is wrong. That means when you try to authenticate with your password its hash will never match.

Additionally, see Ansible FAQ regarding some nuances of password parameter and how to correctly use it.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

java.util.Date is independent of the timezone. When you print cal_Two though the Calendar instance has got its timezone set to UTC, cal_Two.getTime() would return a Date instance which does not have a timezone (and is always in the default timezone)

Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());

Output:

 Sat Jan 25 16:40:28 IST 2014
    sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] 

From the javadoc of TimeZone.setDefault()

Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.

Hence, moving your setDefault() before cal_Two is instantiated you would get the correct result.

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());

Output:

Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014

How to add empty spaces into MD markdown readme on GitHub?

Instead of using HTML entities like &nbsp; and &emsp; (as others have suggested), you can use the Unicode em space (8195 in UTF-8) directly. Try copy-pasting the following into your README.md. The spaces at the start of the lines are em spaces.

The action of every agent <br />
  into the world <br />
starts <br />
  from their physical selves. <br />

Convert String XML fragment to Document Node in Java

Element node =  DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(new ByteArrayInputStream("<node>value</node>".getBytes()))
    .getDocumentElement();

Save file/open file dialog box, using Swing & Netbeans GUI editor

saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

JavaScript Loading Screen while page loads

You can wait until the body is ready:

_x000D_
_x000D_
function onReady(callback) {_x000D_
  var intervalId = window.setInterval(function() {_x000D_
    if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
      window.clearInterval(intervalId);_x000D_
      callback.call(this);_x000D_
    }_x000D_
  }, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
  document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
  setVisible('.page', true);_x000D_
  setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
  background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
  font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page    { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p  { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 100;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
  background-color: rgba(192, 192, 192, 0.5);_x000D_
  background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
  <h1>The standard Lorem Ipsum passage</h1>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
_x000D_
_x000D_

Here is a JSFiddle that demonstrates this technique.

how to send multiple data with $.ajax() jquery

Change var data = 'id='+ id & 'name='+ name; as below,

use this instead.....

var data = "id="+ id + "&name=" + name;

this will going to work fine:)

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

How do I output lists as a table in Jupyter notebook?

Ok, so this was a bit harder than I though:

def print_matrix(list_of_list):
    number_width = len(str(max([max(i) for i in list_of_list])))
    cols = max(map(len, list_of_list))
    output = '+'+('-'*(number_width+2)+'+')*cols + '\n'
    for row in list_of_list:
        for column in row:
            output += '|' + ' {:^{width}d} '.format(column, width = number_width)
        output+='|\n+'+('-'*(number_width+2)+'+')*cols + '\n'
    return output

This should work for variable number of rows, columns and number of digits (for numbers)

data = [[1,2,30],
        [4,23125,6],
        [7,8,999],
        ]
print print_matrix(data)
>>>>+-------+-------+-------+
    |   1   |   2   |  30   |
    +-------+-------+-------+
    |   4   | 23125 |   6   |
    +-------+-------+-------+
    |   7   |   8   |  999  |
    +-------+-------+-------+

Converting BigDecimal to Integer

I found that the above did not work for me. I was pulling a cell value from a JTable but could not cast to double or int etc. My solution:

Object obj = getTable().getValueAt(row, 0);

where row 0 would always be a number. Hope this helps anyone still scrolling!

How to convert comma-separated String to List?

You can use Guava to split the string, and convert it into an ArrayList. This works with an empty string as well, and returns an empty list.

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

String commaSeparated = "item1 , item2 , item3";

// Split string into list, trimming each item and removing empty items
ArrayList<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(commaSeparated));
System.out.println(list);

list.add("another item");
System.out.println(list);

outputs the following:

[item1, item2, item3]
[item1, item2, item3, another item]

How to get the row number from a datatable?

Why don't you try this

for(int i=0; i < dt.Rows.Count; i++)
{
  // u can use here the i
}

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You guys copied the wrong code.

Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)

Path.Combine for URLs?

You use Uri.TryCreate( ... ) :

Uri result = null;

if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
{
    Console.WriteLine(result);
}

Will return:

http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx

getting error while updating Composer

In php7.2 Ubuntu 18.04 LTS and ubuntu 19.04

sudo apt-get install php-gd php-xml php7.2-mbstring

Works like a Charm

Can I bind an array to an IN() condition?

As I know there is no any possibility to bind an array into PDO statement.

But exists 2 common solutions:

  1. Use Positional Placeholders (?,?,?,?) or Named Placeholders (:id1, :id2, :id3)

    $whereIn = implode(',', array_fill(0, count($ids), '?'));

  2. Quote array earlier

    $whereIn = array_map(array($db, 'quote'), $ids);

Both options are good and safe. I prefer second one because it's shorter and I can var_dump parameters if I need it. Using placeholders you must bind values and in the end your SQL code will be the same.

$sql = "SELECT * FROM table WHERE id IN ($whereIn)";

And the last and important for me is avoiding error "number of bound variables does not match number of tokens"

Doctrine it's great example of using positional placeholders, only because it has internal control over incoming parameters.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

You can suppress basic auth popup with request url looking like this:

https://username:[email protected]/admin/...

If you get 401 error (wrong username or password) it will be correctly handled with jquery error callback. It can cause some security issues (in case of http protocol instead of https), but it's works.

UPD: This solution support will be removed in Chrome 59

UTL_FILE.FOPEN() procedure not accepting path for directory?

Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.

The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...

UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');

The alternative approach is to declare a directory object.

create or replace directory temp_dir as 'C:\temp'
/

grant read, write on directory temp_dir to vineet
/

Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...

UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');

The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.

In either case, the oracle OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.


If the oracle OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:

ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7

The OERR text for this error is pretty clear:

29283 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

(grep) Regex to match non-ASCII characters?

To Validate Text Box Accept Ascii Only use this Pattern

[\x00-\x7F]+

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified. This makes it seem as if the array is passed by value when in actual fact it isn't.

For example, in this first case, even though you aren't defining your function to accept $my_array by reference (by using the & character in the parameter definition), it still gets passed by reference (ie: you don't waste memory with an unnecessary copy).

function handle_array($my_array) {  

    // ... read from but do not modify $my_array
    print_r($my_array);

    // ... $my_array effectively passed by reference since no copy is made
}

However if you modify the array, a copy of it is made first (which uses more memory but leaves your original array unaffected).

function handle_array($my_array) {

    // ... modify $my_array
    $my_array[] = "New value";

    // ... $my_array effectively passed by value since requires local copy
}

FYI - this is known as "lazy copy" or "copy-on-write".

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Update R using RStudio

Paste this into the console and run the commands:

## How to update R in RStudio using installr package (for Windows)
## paste this into the console and run the commands
## "The updateR() command performs the following: finding the latest R version, downloading it, running the installer, deleting the installation file, copy and updating old packages to the new R installation."
## more info here: https://cran.r-project.org/web/packages/installr/index.html

install.packages("installr")
library(installr)
updateR()

## Watch for small pop up windows. There will be many questions and they don't always pop to the front. 
## Note: It warns that it might work better in Rgui but I did it in Rstudio and it worked just fine. 

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

Strtotime() doesn't work with dd/mm/YYYY format

From the STRTOTIME writeup Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

It is as simple as that.

Can I specify multiple users for myself in .gitconfig?

If you do not want to have a default email address (email address links to a github user), you can configure that you want to be asked. How you can do that depends on the version of git you use, see below.

The (intended) drawback is that you have to configure your email address (and your name) once for every repository. So, you cannot forget to do it.

Version < 2.7.0

[user]
    name = Your name
    email = "(none)"

in your global configuration ~/.gitconfig as stated in a comment by Dan Aloni in Orr Sella's blog post. When trying to do the first commit in a repository, git fails with the nice message:

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got '(none)')

The name is taken from the global config when the email address is set locally (the message is not perfectly accurate).

2.7.0 = Version < 2.8.0

The behaviour in versions < 2.7.0 was not intended and fixed with 2.7.0. You can still use a pre-commit hook as described in Orr Sella's blog post. This solution works also for other versions, but the other solutions not for this version.

Version = 2.8.0

Dan Aloni added an option to achieve that behaviour (see release notes). Use it with:

[user]
    useConfigOnly = true

To make it work you may not give a name or email address in the global config. Then, at the first commit, you get an error message

fatal: user.useConfigOnly set but no name given

So the message is not very instructive, but since you set the option explicitly, you should know what to do. In contrast to the solution of versions < 2.7.0, you always have to set both name and email manually.

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

Retrieve column names from java.sql.ResultSet

I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData by label instead of index:

ResultSet resultSet = null;
DatabaseMetaData metaData = null;

    try {
        metaData  = connection.getMetaData();
        resultSet = metaData.getColumns(null, null, tableName, null);

        while (resultSet.next()){
            String name = resultSet.getString("COLUMN_NAME");
        }
    }

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

How can I represent an 'Enum' in Python?

While the original enum proposal, PEP 354, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a PEP 435 intended for inclusion in Python 3.4. The reference implementation of PEP 435 is flufl.enum.

As of April 2013, there seems to be a general consensus that something should be added to the standard library in 3.4—as long as people can agree on what that "something" should be. That's the hard part. See the threads starting here and here, and a half dozen other threads in the early months of 2013.

Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a PyPI search.

How do I redirect to the previous action in ASP.NET MVC?

In Mvc using plain html in View Page with java script onclick

<input type="button" value="GO BACK" class="btn btn-primary" 
onclick="location.href='@Request.UrlReferrer'" />

This works great. hope helps someone.

@JuanPieterse has already answered using @Html.ActionLink so if possible someone can comment or answer using @Url.Action

How do I concatenate two text files in PowerShell?

I think the "powershell way" could be :

set-content destination.log -value (get-content c:\FileToAppend_*.log )

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "os"
)

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

jQuery autohide element after 5 seconds

jQuery(".success_mgs").show(); setTimeout(function(){ jQuery(".success_mgs").hide();},5000);

Undoing a git rebase

Actually, rebase saves your starting point to ORIG_HEAD so this is usually as simple as:

git reset --hard ORIG_HEAD

However, the reset, rebase and merge all save your original HEAD pointer into ORIG_HEAD so, if you've done any of those commands since the rebase you're trying to undo then you'll have to use the reflog.

How can I display a tooltip message on hover using jQuery?

Following will work like a charm (assuming you have div/span/table/tr/td/etc with "id"="myId")

    $("#myId").hover(function() {
        $(this).css('cursor','pointer').attr('title', 'This is a hover text.');
    }, function() {
        $(this).css('cursor','auto');
    });

As a complimentary, .css('cursor','pointer') will change the mouse pointer on hover.

Where are the recorded macros stored in Notepad++?

Hit F6

Insert::

npp_open $(PLUGINS_CONFIG_DIR)\..\..\shortcuts.xml

Click OK

You now have the file opened in your editor.


Before altering things checkout the related docs:

How to fix "unable to write 'random state' " in openssl

It may also be that you need to run the console as an administrator. On windows 7, hold ctrl+shift when you launch the console window.

Linux configure/make, --prefix?

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

How to manually deploy artifacts in Nexus Repository Manager OSS 3

To use mvn deploy:deploy-file, must add ~./m2/settings.xml

<settings>
  <servers>
    <server>
      <id>nexus-repo</id>
      <username>admin</username>
      <password>admin123</password>
    </server>
  </servers>
</settings>

command:

mvn deploy:deploy-file -DgroupId=com.example \
                                       -DartifactId=my-app \
                                       -Dversion=2.0.0 \
                                       -Dpackaging=jar \
                                       -Dfile=my-app.jar \
                                       -DgeneratePom=true \
                                       -DrepositoryId=nexus-repo \
                                       -Durl=http://localhost:8081/repository/maven-releases/

Bootstrap radio button "checked" flag

You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.

How to stop PHP code execution?

Please see the following information from user Pekka ?

According to the manual, destructors are executed even if the script gets terminated using die() or exit():

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).

The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)

The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different

It does not get executed on parse errors (because the whole script won't be interpreted)

The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.

Referenced in this question Are there any instances when the destructor in PHP is NOT called?

Serializing a list to JSON

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

or this call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

Is there "\n" equivalent in VBscript?

I think it's vbcrlf.

replace(s, vbcrlf, "<br />")

Excel VBA to Export Selected Sheets to PDF

this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)

' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir

Sub luxation2()
    Dim Filename As String
    Filename = "temp201"



Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"


    ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False

End Sub

Execution failed app:processDebugResources Android Studio

In my Case Problem solved with Instant Run Disable in Android Studio 3.1.2 Android Instant Raun Disable

json_decode to array

Try like this:

$json_string = 'https://example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj->Result);
foreach($obj->Result as $value){
  echo $value->id; //change accordingly
}

Using an image caption in Markdown Jekyll

There are two semantically correct solutions to this question:

  1. Using a plugin
  2. Creating a custom include

1. Using a plugin

I've tried a couple of plugins doing this and my favourite is jekyll-figure.

1.1. Install jekyll-figure

One way to install jekyll-figure is to add gem "jekyll-figure" to your Gemfile in your plugins group.

Then run bundle install from your terminal window.

1.2. Use jekyll-figure

Simply wrap your markdown in {% figure %} and {% endfigure %} tags.

You caption goes in the opening {% figure %} tag, and you can even style it with markdown!

Example:

{% figure caption:"Le logo de **Jekyll** et son clin d'oeil à Robert Louis Stevenson" %}
    ![Le logo de Jekyll](/assets/images/2018-08-07-jekyll-logo.png)
{% endfigure %}

1.3. Style it

Now that your images and captions are semantically correct, you can apply CSS as you wish to:

  • figure (for both image and caption)
  • figure img (for image only)
  • figcaption (for caption only)

2. Creating a custom include

You'll need to create an image.html file in your _includes folder, and include it using Liquid in Markdown.

2.1. Create _includes/image.html

Create the image.html document in your _includes folder :

<!-- _includes/image.html -->
<figure>
    {% if include.url %}
    <a href="{{ include.url }}">
    {% endif %}
    <img
        {% if include.srcabs %}
            src="{{ include.srcabs }}"
        {% else %}
            src="{{ site.baseurl }}/assets/images/{{ include.src }}"
        {% endif %}
    alt="{{ include.alt }}">
    {% if include.url %}
    </a>
    {% endif %}
    {% if include.caption %}
        <figcaption>{{ include.caption }}</figcaption>
    {% endif %}
</figure>

2.2. In Markdown, include an image using Liquid

An image in /assets/images with a caption:

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="jekyll-logo.png" <!-- image filename (placed in /assets/images) -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

An (external) image using an absolute URL: (change src="" to srcabs="")

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    srcabs="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

A clickable image: (add url="" argument)

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    url="https://jekyllrb.com" <!-- destination url -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

An image without a caption:

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    alt="Jekyll's logo" <!-- alt text -->
%}

2.3. Style it

Now that your images and captions are semantically correct, you can apply CSS as you wish to:

  • figure (for both image and caption)
  • figure img (for image only)
  • figcaption (for caption only)

How to validate an e-mail address in swift?

Here is a very simple way available in current Swiftmailer. Most of the other answers are old and reinvent the wheel.

As per Swiftmailer documentation: https://swiftmailer.symfony.com/docs/messages.html#quick-reference

use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;

$validator = new EmailValidator();
$validator->isValid("[email protected]", new RFCValidation()); //true

This is by far the simplest and most robust approach, imo. Just install via Composer the Egulias\EmailValidator library which should already be brought in as a dependency of SwiftMailer anyway.

Remove CSS class from element with JavaScript (no jQuery)

The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:

ELEMENT.classList.remove("CLASS_NAME");

_x000D_
_x000D_
remove.onclick = () => {_x000D_
  const el = document.querySelector('#el');_x000D_
  if (el.classList.contains("red")) {_x000D_
    el.classList.remove("red");_x000D_
_x000D_
  }_x000D_
}
_x000D_
.red {_x000D_
  background: red_x000D_
}
_x000D_
<div id='el' class="red"> Test</div>_x000D_
<button id='remove'>Remove Class</button>
_x000D_
_x000D_
_x000D_

Documentation: https://developer.mozilla.org/en/DOM/element.classList

How to reverse an std::string?

Try

string reversed(temp.rbegin(), temp.rend());

EDIT: Elaborating as requested.

string::rbegin() and string::rend(), which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the "next" element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator>
string(Iterator first, Iterator last);

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

Where do I find the definition of size_t?

size_t is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. The value of the result is implementation-de?ned, and its type (an unsigned integer type) is size_t (ISO C99 Section 6.5.3.4.)

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

docker-compose up for only certain containers

You usually don't want to do this. With Docker Compose you define services that compose your app. npm and manage.py are just management commands. You don't need a container for them. If you need to, say create your database tables with manage.py, all you have to do is:

docker-compose run client python manage.py create_db

Think of it as the one-off dynos Heroku uses.

If you really need to treat these management commands as separate containers (and also use Docker Compose for these), you could create a separate .yml file and start Docker Compose with the following command:

docker-compose up -f my_custom_docker_compose.yml

Spring Boot Rest Controller how to return different HTTP status codes?

One of the way to do this is you can use ResponseEntity as a return object.

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)

public ResponseEntity<?> create(@RequestBody String data) {

if(everything_fine)
    return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);

}

How to install pip3 on Windows?

There is another way to install the pip3: just reinstall 3.6.

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

I actually tried to implement connection pooling on the django end using:

https://github.com/gmcguire/django-db-pool

but I still received this error, despite lowering the number of connections available to below the standard development DB quota of 20 open connections.

There is an article here about how to move your postgresql database to the free/cheap tier of Amazon RDS. This would allow you to set max_connections higher. This will also allow you to pool connections at the database level using PGBouncer.

https://www.lewagon.com/blog/how-to-migrate-heroku-postgres-database-to-amazon-rds

UPDATE:

Heroku responded to my open ticket and stated that my database was improperly load balanced in their network. They said that improvements to their system should prevent similar problems in the future. Nonetheless, support manually relocated my database and performance is noticeably improved.

Get the client's IP address in socket.io

In version v2.3.0

this work for me :

socket.handshake.headers['x-forwarded-for'].split(',')[0]

How to create a inset box-shadow only on one side?

Literally you can't do such a thing, but you should try this CSS trick:

box-shadow: inset 0 3vw 6vw rgba(0,0,0,0.6), inset 0 -3vw 6vw rgba(0,0,0,0.6);

How to write and save html file in python?

You can try:

colour = ["red", "red", "green", "yellow"]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<table>')

    s = '1234567890'
    for i in range(0, len(s), 60):
        myFile.write('<tr><td>%04d</td>' % (i+1));
    for j, k in enumerate(s[i:i+60]):
        myFile.write('<td><font style="background-color:%s;">%s<font></td>' % (colour[j %len(colour)], k));


    myFile.write('</tr>')
    myFile.write('</table>')
    myFile.write('</body>')
    myFile.write('</html>')

Jupyter/IPython Notebooks: Shortcut for "run all"?

Jupyter Lab 1.0.4:

  1. In the top menu, go to: Settings->Advanced Settings Editor->Keyboard Shortcuts

  2. Paste this code in the User Preferences window:

{
    "shortcuts": [
        {
            "command": "runmenu:run-all",
            "keys": [
                "R",
                "R"
            ],
            "selector": "[data-jp-kernel-user]:focus"
        }
    ]
}
  1. Save (top right of the user-preferences window)

This will be effective immediately. Here, two consecutive 'R' presses runs all cells (just like two '0' for kernel restart). Notably, system defaults has empty templates for all menu commands, including this code (search for run-all). The selector was copied from kernelmenu:restart, to allow printing r within cells. This system defaults copy-paste can be generalized to any command.

How do I read input character-by-character in Java?

If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.

Bulk Record Update with SQL

You can do this through a regular UPDATE with a JOIN

UPDATE T1
SET Description = T2.Description
   FROM Table1 T1
      JOIN Table2 T2
         ON T2.ID = T1.DescriptionId

ASP.NET Web API session or something?

In WebApi 2 you can add this to global.asax

protected void Application_PostAuthorizeRequest() 
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

Then you could access the session through:

HttpContext.Current.Session

Why use static_cast<int>(x) instead of (int)x?

  1. Allows casts to be found easily in your code using grep or similar tools.
  2. Makes it explicit what kind of cast you are doing, and engaging the compiler's help in enforcing it. If you only want to cast away const-ness, then you can use const_cast, which will not allow you to do other types of conversions.
  3. Casts are inherently ugly -- you as a programmer are overruling how the compiler would ordinarily treat your code. You are saying to the compiler, "I know better than you." That being the case, it makes sense that performing a cast should be a moderately painful thing to do, and that they should stick out in your code, since they are a likely source of problems.

See Effective C++ Introduction

How to get the selected radio button value using js

Hy, you have to do it this way.

function checkRadio () {
    if(document.getElementById('user1').checked) {
        return $('#user1').val();
    }else if(document.getElementById('user2').checked) {
        return $('#user2').val();
    }
}

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

How do you configure HttpOnly cookies in tomcat / java webapps?

For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.

To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:

org.apache.catalina.connector.Request.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.connectorResponse.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}

jQuery change input text value

Best practice is using the identify directly:

$('#id').val('xxx');

How to check if a process is running via a batch script

Just mentioning, if your task name is really long then it won't appear in its entirety in the tasklist result, so it might be safer (other than localization) to check for the opposite.

Variation of this answer:

:: in case your task name is really long, check for the 'opposite' and find  the message when it's not there
tasklist /fi "imagename eq yourreallylongtasknamethatwontfitinthelist.exe" 2>NUL | find /I /N "no tasks are running">NUL
if "%errorlevel%"=="0" (
    echo Task Found
) else (
    echo Not Found Task
)

Send Email Intent

None of these solutions were working for me. Here's a minimal solution that works on Lollipop. On my device, only Gmail and the native email apps appear in the resulting chooser list.

Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
                                Uri.parse("mailto:" + Uri.encode(address)));

emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(emailIntent, "Send email via..."));

How to prevent vim from creating (and leaving) temporary files?

I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.

set undofile
set undolevels=1000         " How many undos
set undoreload=10000        " number of lines to save for undo

set backup                        " enable backups
set swapfile                      " enable swaps
set undodir=$HOME/.vim/tmp/undo     " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap   " swap files

" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")
endif

Changing the browser zoom level

You can use the CSS3 zoom function, but I have not tested it yet with jQuery. Will try now and let you know. UPDATE: tested it, works but it's fun

Is there a RegExp.escape function in JavaScript?

Most of the expressions here solve single specific use cases.

That's okay, but I prefer an "always works" approach.

function regExpEscape(literal_string) {
    return literal_string.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
}

This will "fully escape" a literal string for any of the following uses in regular expressions:

  • Insertion in a regular expression. E.g. new RegExp(regExpEscape(str))
  • Insertion in a character class. E.g. new RegExp('[' + regExpEscape(str) + ']')
  • Insertion in integer count specifier. E.g. new RegExp('x{1,' + regExpEscape(str) + '}')
  • Execution in non-JavaScript regular expression engines.

Special Characters Covered:

  • -: Creates a character range in a character class.
  • [ / ]: Starts / ends a character class.
  • { / }: Starts / ends a numeration specifier.
  • ( / ): Starts / ends a group.
  • * / + / ?: Specifies repetition type.
  • .: Matches any character.
  • \: Escapes characters, and starts entities.
  • ^: Specifies start of matching zone, and negates matching in a character class.
  • $: Specifies end of matching zone.
  • |: Specifies alternation.
  • #: Specifies comment in free spacing mode.
  • \s: Ignored in free spacing mode.
  • ,: Separates values in numeration specifier.
  • /: Starts or ends expression.
  • :: Completes special group types, and part of Perl-style character classes.
  • !: Negates zero-width group.
  • < / =: Part of zero-width group specifications.

Notes:

  • / is not strictly necessary in any flavor of regular expression. However, it protects in case someone (shudder) does eval("/" + pattern + "/");.
  • , ensures that if the string is meant to be an integer in the numerical specifier, it will properly cause a RegExp compiling error instead of silently compiling wrong.
  • #, and \s do not need to be escaped in JavaScript, but do in many other flavors. They are escaped here in case the regular expression will later be passed to another program.

If you also need to future-proof the regular expression against potential additions to the JavaScript regex engine capabilities, I recommend using the more paranoid:

function regExpEscapeFuture(literal_string) {
    return literal_string.replace(/[^A-Za-z0-9_]/g, '\\$&');
}

This function escapes every character except those explicitly guaranteed not be used for syntax in future regular expression flavors.


For the truly sanitation-keen, consider this edge case:

var s = '';
new RegExp('(choice1|choice2|' + regExpEscape(s) + ')');

This should compile fine in JavaScript, but will not in some other flavors. If intending to pass to another flavor, the null case of s === '' should be independently checked, like so:

var s = '';
new RegExp('(choice1|choice2' + (s ? '|' + regExpEscape(s) : '') + ')');

What are the advantages of NumPy over regular Python lists?

Here's a nice answer from the FAQ on the scipy.org website:

What advantages do NumPy arrays offer over (nested) Python lists?

Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.

How to check if string input is a number?

I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):

This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)

a=(raw_input("Amount:"))

try:
    int(a)
except ValueError:
    try:
        float(a)
    except ValueError:
        print "This is not a number"
        a=0


if a==0:
    a=0
else:
    print a
    #Do stuff

Turn off constraints temporarily (MS SQL)

-- Disable the constraints on a table called tableName:
ALTER TABLE tableName NOCHECK CONSTRAINT ALL

-- Re-enable the constraints on a table called tableName:
ALTER TABLE tableName WITH CHECK CHECK CONSTRAINT ALL
---------------------------------------------------------

-- Disable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'

-- Re-enable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
---------------------------------------------------------

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):

    mWebView = (WebView) findViewById(R.id.web_view);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if( url.startsWith("http:") || url.startsWith("https:") ) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            return true;
        }
    });
    mWebView.loadUrl(url);

Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.

"Too many values to unpack" Exception

try unpacking in one variable,

python will handle it as a list,

then unpack from the list

def returnATupleWithThreeValues():
    return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

How to export SQL Server database to MySQL?

I used the below connection string on the Advanced tab of MySQL Migration Tool Kit to connect to SQL Server 2008 instance:

jdbc:jtds:sqlserver://"sql_server_ip_address":1433/<db_name>;Instance=<sqlserver_instanceName>;user=sa;password=PASSWORD;namedPipe=true;charset=utf-8;domain= 

Usually the parameter has "systemName\instanceName". But in the above, do not add "systemName\" (use only InstanceName).

To check what the instanceName should be, go to services.msc and check the DisplayName of the MSSQL instance. It shows similar to MSSQL$instanceName.

Hope this help in MSSQL connectivity from mysql migration toolKit.

How do I tell if an object is a Promise?

In case you are using Typescript, I'd like to add that you can use the "type predicate" feature. Just should wrap the logical verification in a function that returns x is Promise<any> and you won't need to do typecasts. Below on my example, c is either a promise or one of my types which I want to convert into a promise by calling the c.fetch() method.

export function toPromise(c: Container<any> | Promise<any>): Promise<any> {
    if (c == null) return Promise.resolve();
    return isContainer(c) ? c.fetch() : c;
}

export function isContainer(val: Container<any> | Promise<any>): val is Container<any> {
    return val && (<Container<any>>val).fetch !== undefined;
}

export function isPromise(val: Container<any> | Promise<any>): val is Promise<any> {
    return val && (<Promise<any>>val).then !== undefined;
}

More info: https://www.typescriptlang.org/docs/handbook/advanced-types.html

Testing if a checkbox is checked with jQuery

Just use $(selector).is(':checked')

It returns a boolean value.

Changing WPF title bar background color

Here's an example on how to achieve this:

    <Grid DockPanel.Dock="Right"
      HorizontalAlignment="Right">

        <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Right"
                VerticalAlignment="Center">

            <Button x:Name="MinimizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MinimizeWindow"
                Style="{StaticResource MinimizeButton}" 
                Template="{StaticResource MinimizeButtonControlTemplate}" />

            <Button x:Name="MaximizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MaximizeClick"
                Style="{DynamicResource MaximizeButton}" 
                Template="{DynamicResource MaximizeButtonControlTemplate}" />

            <Button x:Name="CloseButton"
                KeyboardNavigation.IsTabStop="False"
                Command="{Binding ApplicationCommands.Close}"
                Style="{DynamicResource CloseButton}" 
                Template="{DynamicResource CloseButtonControlTemplate}"/>

        </StackPanel>
    </Grid>
</DockPanel>

Handle Click Events in the code-behind.

For MouseDown -

App.Current.MainWindow.DragMove();

For Minimize Button -

App.Current.MainWindow.WindowState = WindowState.Minimized;

For DoubleClick and MaximizeClick

if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
    App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
    App.Current.MainWindow.WindowState = WindowState.Maximized;
}

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

git replacing LF with CRLF

Removing the below from the ~/.gitattributes file

* text=auto

will prevent git from checking line-endings in the first-place.

How to load all modules in a folder?

This is the best way i've found so far:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

how to add background image to activity?

use the android:background attribute in your xml. Easiest way if you want to apply it to a whole activity is to put it in the root of your layout. So if you have a RelativeLayout as the start of your xml, put it in here:

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

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link generally means, the resource object of the established mysqli connection to query the database.

So there are two ways of solving this problem

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

Or, Using mysql_query() (This is now obselete)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .

Tensorflow installation error: not a supported wheel on this platform

I was trying to install CPU TF on Ubuntu 18.04, and the best way (for me...) I found for it was using it on top of Conda, for that:

  1. To create Conda ‘tensorflow’ env. Follow https://linuxize.com/post/how-to-install-anaconda-on-ubuntu-18-04/

  2. After all installed see https://conda.io/projects/conda/en/latest/user-guide/getting-started.html And use it according to https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#managing-environments

  3. conda create --name tensorflow

  4. source activate tensorflow

  5. pip install --upgrade pip

  6. pip uninstall tensorflow

  7. For CPU: pip install tensorflow-cpu, for GPU: pip install tensorflow

  8. pip install --ignore-installed --upgrade tensorflow

  9. Test TF E.g. on 'Where' with:

python

import tensorflow as tf

tf.where([[True, False], [False, True]])

expected result:

<tf.Tensor: shape=(2, 2), dtype=int64, numpy=
array([[0, 0],
       [1, 1]])>
  • After Conda upgrade I got: DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.

So you should use:

‘conda activate tensorflow’ / ‘conda deactivate’

How to convert std::string to lower case?

Boost provides a string algorithm for this:

#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str

Or, for non-in-place:

#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);

Each for object?

A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work

$.each(object, function(index, value) {
    console.log(value);
}); 

Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this

Object.keys(object).map(function(objectKey, index) {
    var value = object[objectKey];
    console.log(value);
});

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.

But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.


Right, so also pointed out in other answers, a plain Javascript alternative would be

for(var index in object) { 
    var attr = object[index]; 
}

There are two potential issues with this:

1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var attr = object[index];
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.

The jQuery.each and Object.keys functions take care of this automatically.

2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:

<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>

var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) { 
   if (messagesByButtonId.hasOwnProperty(buttonId)) {
       $('#'+buttonId).click(function() {
           var message = messagesByButtonId[buttonId];
           console.log(message);
       });
   }
}

If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.

Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.

How can I simulate a print statement in MySQL?

If you do not want to the text twice as column heading as well as value, use the following stmt!

SELECT 'some text' as '';

Example:

mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)

How to prevent scrollbar from repositioning web page?

Expanding on the answer using this:

body {
    width: calc(100vw - 17px);
}

One commentor suggested adding left-padding as well to maintain the centering:

body {
    padding-left: 17px;
    width: calc(100vw - 17px);
}

But then things don't look correct if your content is wider than the viewport. To fix that, you can use media queries, like this:

@media screen and (min-width: 1058px) {
    body {
        padding-left: 17px;
        width: calc(100vw - 17px);
    }
}

Where the 1058px = content width + 17 * 2

This lets a horizontal scrollbar handle the x overflow and keeps the centered content centered when the viewport is wide enough to contain your fixed-width content

How to ignore SSL certificate errors in Apache HttpClient 4.0

Tested on 4.5.4:

            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();

            CloseableHttpClient httpClient = HttpClients
                    .custom()
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .setSSLContext(sslContext)
                    .build();

How to get overall CPU usage (e.g. 57%) on Linux

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:

$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%

This will use awk to print out 100 minus the 12th field (idle), with a percentage sign after it. awk will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/).

You can also average five samples, one second apart:

$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'

Test it like this:

$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'

Entity Framework - Code First - Can't Store List<String>

Just to simplify -

Entity framework doesn't support primitives. You either create a class to wrap it or add another property to format the list as a string:

public ICollection<string> List { get; set; }
public string ListString
{
    get { return string.Join(",", List); }
    set { List = value.Split(',').ToList(); }
}

Convert timestamp to readable date/time PHP

$epoch = 1483228800;
$dt = new DateTime("@$epoch");  // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00

In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:

Format Output

r              -----    Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c              -----    2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y          -----    Mar/15/2017
d-m-Y          -----    15-03-2017
Y-m-d H:i:s    -----    2017-03-15 12:00:00

How to compare two dates in Objective-C

NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [NSDate dateWithString:@"xxxxxx"]; // your date 

NSComparisonResult result; 
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending

result = [today compare:newDate]; // comparing two dates

if(result==NSOrderedAscending)
    NSLog(@"today is less");
else if(result==NSOrderedDescending)
    NSLog(@"newDate is less");
else
    NSLog(@"Both dates are same");

There are other ways that you may use to compare an NSDate objects. Each of the methods will be more efficient at certain tasks. I have chosen the compare method because it will handle most of your basic date comparison needs.

Disable same origin policy in Chrome

FOR MAC USER ONLY

open -n -a /Applications/Google\ Chrome.app --args --user-data-dir="/tmp/someFolderName" --disable-web-security

Using ALTER to drop a column if it exists in MySQL

I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

  1. get a new sql editor and execute SHOW TABLES to get a list of your tables
  2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
  3. paste the list of names into another editor tab
  4. write your query, ie ALTER TABLE x DROP a;
  5. do some copying and pasting, so you end up with separate query for each table
  6. Toggle whether the workbench should stop when an error occurs
  7. Hit execute and look through the output log

any tables which had the table now haven't any tables which didn't will have shown an error in the logs

then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

How to restore the menu bar in Visual Studio Code

You have two options.

Option 1

Make the menu bar temporarily visible.

  • press Alt key and you will be able to see the menu bar

Option 2

Make the menu bar permanently visible.

Steps:

  1. Press F1
  2. Type user settings
  3. Press Enter
  4. Click on the { } (top right corner of the window) to open settings.json file see the screenshot
  5. Then in the settings.json file, change the value to the default "window.menuBarVisibility": "default" you can see a sample here (or remove this line from JSON file. If you remove any value from the settings.json file then it will use the default settings for those entries. So if you want to make everything to default settings then remove all entries in the settings.json file).

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

PHP: Split string

explode('.', $string)

If you know your string has a fixed number of components you could use something like

list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;

Prints:

object
attribute

Setting the selected attribute on a select list using jQuery

This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })

MVC Razor Radio Button

MVC Razor provides one elegant Html Helper called RadioButton with two parameters (this is general, But we can overload it uptil five parameters) i.e. one with the group name and other being the value

<div class="col-md-10">
    Male:   @Html.RadioButton("Gender", "Male")
    Female: @Html.RadioButton("Gender", "Female")
</div>                         

Python "expected an indented block"

Your last for statement is missing a body.

Python expects an indented block to follow the line with the for, or to have content after the colon.

The first style is more common, so it says it expects some indented code to follow it. You have an elif at the same indent level.

How to install pywin32 module in windows 7

Quoting the README at https://github.com/mhammond/pywin32:

By far the easiest way to use pywin32 is to grab binaries from the most recent release

Just download the installer for your version of Python from https://github.com/mhammond/pywin32/releases and run it, and you're done.

Facebook API error 191

I have noticed also that even if you specify your website under secion - Website With Facebook Login -> Site url as e.g. http://example.com, but if your App Domains section is empty, and you open website as www.example.com you will get this error, too. To avoid it in "App Domains" section write example.com, that will allow subdomains, like www.example.com, something.example.com etc

What is the best JavaScript code to create an img element

Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...

document.getElementById("image-holder").innerHTML = "<img src='image.png' alt='The Image' />";

By the way, innerHTML is not that bad

How to implement a binary search tree in Python?

    def BinaryST(list1,key):
    start = 0
    end = len(list1)
    print("Length of List: ",end)

    for i in range(end):
        for j in range(0, end-i-1):
            if(list1[j] > list1[j+1]):
                temp = list1[j]
                list1[j] = list1[j+1]
                list1[j+1] = temp

    print("Order List: ",list1)

    mid = int((start+end)/2)
    print("Mid Index: ",mid)

    if(key == list1[mid]):
        print(key," is on ",mid," Index")

    elif(key > list1[mid]):
        for rindex in range(mid+1,end):
            if(key == list1[rindex]):
                print(key," is on ",rindex," Index")
                break
            elif(rindex == end-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue

    elif(key < list1[mid]):
        for lindex in range(0,mid):
            if(key == list1[lindex]):
                print(key," is on ",lindex," Index")
                break
            elif(lindex == mid-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue


size = int(input("Enter Size of List: "))
list1 = []
for e in range(size):
    ele = int(input("Enter Element in List: "))
    list1.append(ele)

key = int(input("\nEnter Key for Search: "))

print("\nUnorder List: ",list1)
BinaryST(list1,key)

Spring Security exclude url patterns in security annotation configurartion

Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

The following is working for me.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()
        .antMatchers("/static/**").permitAll()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
                .usernameParameter("username").passwordParameter("password")
        .and()
            .logout().logoutSuccessUrl("/login?logout")
        .and()
            .exceptionHandling().accessDeniedPage("/403")
        .and()
            .csrf();

}

NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()

Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")

Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

DynamoDB vs MongoDB NoSQL

I have worked on both and kind of fan of both.

But you need to understand when to use what and for what purpose.

I don't think It's a great idea to move all your database to DynamoDB, reason being querying is difficult except on primary and secondary keys, Indexing is limited and scanning in DynamoDB is painful.

I would go for a hybrid sort of DB, where extensive query-able data should be there is MongoDB, with all it's feature you would never feel constrained to provide enhancements or modifications.

DynamoDB is lightning fast (faster than MongoDB) so DynamoDB is often used as an alternative to sessions in scalable applications. DynamoDB best practices also suggests that if there are plenty of data which are less being used, move it to other table.

So suppose you have a articles or feeds. People are more likely to look for last week stuff or this month's stuff. chances are really rare for people to visit two year old data. For these purposes DynamoDB prefers to have data stored by month or years in different tables.

DynamoDB is seemlessly scalable, something you will have to do manually in MongoDB. however you would lose on performance of DynamoDB, if you don't understand about throughput partition and how scaling works behind the scene.

DynamoDB should be used where speed is critical, MongoDB on the other hand has too many hands and features, something DynamoDB lacks.

for example, you can have a replica set of MongoDB in such a way that one of the replica holds data instance of 8(or whatever) hours old. Really useful, if you messed up something big time in your DB and want to get the data as it is before.

That's my opinion though.

how to check for datatype in node js- specifically for integer

_x000D_
_x000D_
var val = ... //the value you want to check_x000D_
if(Number.isNaN(Number(val))){_x000D_
  console.log("This is NOT a number!");_x000D_
}else{_x000D_
  console.log("This IS a number!");_x000D_
}
_x000D_
_x000D_
_x000D_

What does the keyword Set actually do in VBA?

Set is used for setting object references, as opposed to assigning a value.

Passing environment-dependent variables in webpack

Just another option, if you want to use only a cli interface, just use the define option of webpack. I add the following script in my package.json :

"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"

So I just have to run npm run build-production.

Get int value from enum in C#

Use:

Question question = Question.Role;
int value = Convert.ToInt32(question);

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

<ng-container> vs <template>

A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

Using -XX:+UseParNewGC along with -XX:+UseConcMarkSweepGC, will cause higher pause time for Minor GCs, when compared to -XX:+UseParallelGC.

This is because, promotion of objects from Young to Old Generation will require running a Best-Fit algorithm (due to old generation fragmentation) to find an address for this object.
Running such an algorithm is not required when using -XX:+UseParallelGC, as +UseParallelGC can be configured only with MarkandCompact Collector, in which case there is no fragmentation.

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

Be aware that when you do press your <leader> key you have only 1000ms (by default) to enter the command following it.

This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader> key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.

If you add set showcmd to your vimrc then you will see your <leader> key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.

The length of the timeout can also be set in your vimrc, see :help timeoutlen for more information.

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

php: check if an array has duplicates

$duplicate = false;

 if(count(array) != count(array_unique(array))){
   $duplicate = true;
}

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

1.0 includes a http server & util for serving files with a few lines of code.

package main

import (
    "fmt"; "log"; "net/http"
)

func main() {
    fmt.Println("Serving files in the current directory on port 8080")
    http.Handle("/", http.FileServer(http.Dir(".")))
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

Run this source using go run myserver.go or to build an executable go build myserver.go

How to replace (null) values with 0 output in PIVOT

You cannot place the IsNull() until after the data is selected so you will place the IsNull() around the final value in the SELECT:

SELECT CLASS,
  IsNull([AZ], 0) as [AZ],
  IsNull([CA], 0) as [CA],
  IsNull([TX], 0) as [TX]
FROM #TEMP
PIVOT 
(
  SUM(DATA)
  FOR STATE IN ([AZ], [CA], [TX])
) AS PVT
ORDER BY CLASS

Use of for_each on map elements

Just an example:

template <class key, class value>
class insertIntoVec
{
public:
    insertIntoVec(std::vector<value>& vec_in):m_vec(vec_in)
    {}

    void operator () (const std::pair<key, value>& rhs)  
    {   
        m_vec.push_back(rhs.second);
    }

private:
    std::vector<value>& m_vec;
};

int main()
{
std::map<int, std::string> aMap;
aMap[1] = "test1";
aMap[2] = "test2";
aMap[3] = "test3";
aMap[4] = "test4";

std::vector<std::string> aVec;

aVec.reserve(aMap.size());
std::for_each(aMap.begin(), aMap.end(),
          insertIntoVec<int, std::string>(aVec) 
    );

}

IF a cell contains a string

You can use OR() to group expressions (as well as AND()):

=IF(OR(condition1, condition2), true, false)

=IF(AND(condition1, condition2), true, false)

So if you wanted to test for "cat" and "22":

=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

It appears to only be availabe using the mysqlnd driver.
Try replacing it with the integer it represents; 1002, if I am not mistaken.

Can I export a variable to the environment from a bash script without sourcing it?

Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

Quick answer: No.

But there are several possible workarounds.

The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:

$ cat set-vars1.sh 
export FOO=BAR
$ . set-vars1.sh 
$ echo $FOO
BAR

Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:

$ cat set-vars2.sh
#!/bin/bash
echo export FOO=BAR
$ eval "$(./set-vars2.sh)"
$ echo "$FOO"
BAR

A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:

$ cat set-vars3.sh
#!/bin/bash
export FOO=BAR
exec "$@"
$ ./set-vars3.sh printenv | grep FOO
FOO=BAR

This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).

In C++, what is a virtual base class?

In addition to what has already been said about multiple and virtual inheritance(s), there is a very interesting article on Dr Dobb's Journal: Multiple Inheritance Considered Useful

Use different Python version with virtualenv

As already mentioned in multiple answers, using virtualenv is a clean solution. However a small pitfall that everyone should be aware of is that if an alias for python is set in bash_aliases like:

python=python3.6

this alias will also be used inside the virtual environment. So in this scenario running python -V inside the virtual env will always output 3.6 regardless of what interpreter is used to create the environment:

virtualenv venv --python=pythonX.X

Error: fix the version conflict (google-services plugin)

install or update google play services. Secondly, check your 'com.google.gms:google-services:3.0.0' version . Check , this by upgrading it if still not work to 3.1.0

python replace single backslash with double backslash

Maybe a syntax error in your case, you may change the line to:

directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')

which give you the right following output:

C:\\Users\\Josh\\Desktop\\20130216

Reverse a string in Java

public class StringReverse1 {

public static void main(String[] args) {
    String name = "Vaquar khan";

    char array[] = name.toCharArray();
    System.out.println(name);
    System.out.println(reverseString(array));
}

private static String reverseString(char[] array) {
    String reverse = "";
    ///
    for (int i = array.length - 1; i >= 0; i--) {
        //System.out.println(array[i]);
        //
        reverse += array[i];
    }
    return reverse;

}

}

Results :

      Vaquar khan

      nahk rauqaV

What is the difference between user variables and system variables?

Right-click My Computer and go to Properties->Advanced->Environmental Variables...

What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.

If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

Get current value when change select option - Angular2

There is a way to get the value from different options. check this plunker

component.html

<select class="form-control" #t (change)="callType(t.value)">
  <option *ngFor="#type of types" [value]="type">{{type}}</option>
</select>

component.ts

this.types = [ 'type1', 'type2', 'type3' ];

callType(value) {
  console.log(value);
  this.order.type = value;
}

Mysql - How to quit/exit from stored procedure

To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:

CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
     IF tablename IS NOT NULL THEN
         CALL SP_Reporting_2(tablename);
     END IF;
END;

CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
     #proceed with code
END;

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

Python Graph Library

I second zweiterlinde's suggestion to use python-graph. I've used it as the basis of a graph-based research project that I'm working on. The library is well written, stable, and has a good interface. The authors are also quick to respond to inquiries and reports.

dataframe: how to groupBy/count then filter on count in Scala

So, is that a behavior to expect, a bug

Truth be told I am not sure. It looks like parser is interpreting count not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.

is there a canonical way to go around?

Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:

import org.apache.spark.sql.functions.count

df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt"  > 2)

Share data between html pages

I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:

var val = sessionStorage.myValue

in place of getItem and

sessionStorage.myValue = 'value'

in place of setItem.

Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:

sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object

The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.

Get the closest number out of an array

Works with unsorted arrays

While there were some good solutions posted here, JavaScript is a flexible language that gives us tools to solve a problem in many different ways. It all comes down to your style, of course. If your code is more functional, you'll find the reduce variation suitable, i.e.:

  arr.reduce(function (prev, curr) {
    return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  });

However, some might find that hard to read, depending on their coding style. Therefore I propose a new way of solving the problem:

  var findClosest = function (x, arr) {
    var indexArr = arr.map(function(k) { return Math.abs(k - x) })
    var min = Math.min.apply(Math, indexArr)
    return arr[indexArr.indexOf(min)]
  }

  findClosest(80, [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]) // Outputs 82

Contrary to other approaches finding the minimum value using Math.min.apply, this one doesn't require the input array arr to be sorted. We don't need to care about the indexes or sort it beforehand.

I'll explain the code line by line for clarity:

  1. arr.map(function(k) { return Math.abs(k - x) }) Creates a new array, essentially storing the absolute values of the given numbers (number in arr) minus the input number (x). We'll look for the smallest number next (which is also the closest to the input number)
  2. Math.min.apply(Math, indexArr) This is a legit way of finding the smallest number in the array we've just created before (nothing more to it)
  3. arr[indexArr.indexOf(min)] This is perhaps the most interesting part. We have found our smallest number, but we're not sure if we should add or subtract the initial number (x). That's because we used Math.abs() to find the difference. However, array.map creates (logically) a map of the input array, keeping the indexes in the same place. Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr.indexOf(min).

I've created a bin demonstrating it.

"Debug certificate expired" error in Eclipse Android plugins

After you install the Android SDK in Eclipse, it generates a debug signing certificate for you in a keystore called debug.keystore. The Eclipse plug-in uses this certificate to sign each application build that is generated.

Now, the problem with this debug certificate is that it is only valid for a year, or 365 days. If your Eclipse IDE uses an expired debug certificate, you will not be able to create and/or deploy an Android app.

To fix this problem all you need to do is delete the debug.keystore file.

  1. Go to Preferences
  2. Android
  3. Build
  4. Default debug keystore

There you should see the folder where the file is located. Simply delete that file and you are good to go.

For more info. you can visit

http://developer.android.com/tools/publishing/app-signing.html

How do I disable the resizable property of a textarea?

With @style, you can give it a custom size and disable the resize feature (resize: none;).

@Html.TextAreaFor(model => model.YourProperty, new { @style = "width: 90%; height: 180px; resize: none;" })

Is there Java HashMap equivalent in PHP?

$fruits = array (
    "fruits"  => array("a" => "Orange", "b" => "Banana", "c" => "Apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);

echo $fruits["fruits"]["b"]

outputs 'Banana'

taken from http://in2.php.net/manual/en/function.array.php

How does the ARM architecture differ from x86?

The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.

Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.

But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.

So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)

Version vs build in Xcode

(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:

- (NSString*) version {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

In Swift

func version() -> String {
    let dictionary = NSBundle.mainBundle().infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as? String
    let build = dictionary["CFBundleVersion"] as? String
    return "\(version) build \(build)"
}

Is there a TRY CATCH command in Bash

Below is an example of a script which implements try/catch/finally in bash.

Like other answers to this question, exceptions must be caught after exiting a subprocess.

The example scripts start by creating an anonymous fifo, which is used to pass string messages from a command exception or throw to end of the closest try block. Here the messages are removed from the fifo and placed in an array variable. The status is returned through return and exit commands and placed in a different variable. To enter a catch block, this status must not be zero. Other requirements to enter a catch block are passed as parameters. If the end of a catch block is reached, then the status is set to zero. If the end of the finally block is reached and the status is still nonzero, then an implicit throw containing the messages and status is executed. The script requires the calling of the function trycatchfinally which contains an unhandled exception handler.

The syntax for the trycatchfinally command is given below.

trycatchfinally [-cde] [-h ERR_handler] [-k] [-o debug_file] [-u unhandled_handler] [-v variable] fifo function

The -c option adds the call stack to the exception messages.
The -d option enables debug output.
The -e option enables command exceptions.
The -h option allows the user to substitute their own command exception handler.
The -k option adds the call stack to the debug output.
The -o option replaces the default output file which is /dev/fd/2.
The -u option allows the user to substitute their own unhandled exception handler.
The -v option allows the user the option to pass back values though the use of Command Substitution.
The fifo is the fifo filename.
The function function is called by trycatchfinally as a subprocess.

Note: The cdko options were removed to simplify the script.

The syntax for the catch command is given below.

catch [[-enoprt] list ...] ...

The options are defined below. The value for the first list is the status. Subsquent values are the messages. If the there are more messages than lists, then the remaining messages are ignored.

-e means [[ $value == "$string" ]] (the value has to match at least one string in the list)
-n means [[ $value != "$string" ]] (the value can not match any of the strings in the list)
-o means [[ $value != $pattern ]] (the value can not match any of the patterns in the list)
-p means [[ $value == $pattern ]] (the value has to match at least one pattern in the list)
-r means [[ $value =~ $regex ]] (the value has to match at least one extended regular expression in the list)
-t means [[ ! $value =~ $regex ]] (the value can not match any of the extended regular expressions in the list)

The try/catch/finally script is given below. To simplify the script for this answer, most of the error checking was removed. This reduced the size by 64%. A complete copy of this script can be found at my other answer.

shopt -s expand_aliases
alias try='{ common.Try'
alias yrt='EchoExitStatus; common.yrT; }'
alias catch='{ while common.Catch'
alias hctac='common.hctaC; done; }'
alias finally='{ common.Finally'
alias yllanif='common.yllaniF; }'

DefaultErrHandler() {
    echo "Orginal Status: $common_status"
    echo "Exception Type: ERR"
}

exception() {
    let "common_status = 10#$1"
    shift
    common_messages=()
    for message in "$@"; do
        common_messages+=("$message")
    done
}

throw() {
    local "message"
    if [[ $# -gt 0 ]]; then
        let "common_status = 10#$1"
        shift
        for message in "$@"; do
            echo "$message" >"$common_fifo"
        done
    elif [[ ${#common_messages[@]} -gt 0 ]]; then
        for message in "${common_messages[@]}"; do
            echo "$message" >"$common_fifo"
        done
    fi
    chmod "0400" "$common_fifo"
    exit "$common_status"
}

common.ErrHandler() {
    common_status=$?
    trap ERR
    if [[ -w "$common_fifo" ]]; then
        if [[ $common_options != *e* ]]; then
            common_status="0"
            return
        fi
        eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
        chmod "0400" "$common_fifo"
    fi
    if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
        return   
    else
        exit "$common_status"
    fi
}

common.Try() {
    common_status="0"
    common_subshell="$common_trySubshell"
    common_trySubshell="$BASH_SUBSHELL"
    common_messages=()
}

common.yrT() {
    local "status=$?"
    if [[ common_status -ne 0 ]]; then    
        local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
        chmod "0600" "$common_fifo"
        echo "$eof" >"$common_fifo"
        common_messages=()
        while read "message"; do
            [[ $message != *$eof ]] || break
            common_messages+=("$message")
        done <"$common_fifo"
    fi
    common_trySubshell="$common_subshell"
}

common.Catch() {
    [[ common_status -ne 0 ]] || return "1"
    local "parameter" "pattern" "value"
    local "toggle=true" "compare=p" "options=$-"
    local -i "i=-1" "status=0"
    set -f
    for parameter in "$@"; do
        if "$toggle"; then
            toggle="false"
            if [[ $parameter =~ ^-[notepr]$ ]]; then
                compare="${parameter#-}"
                continue 
            fi
        fi
        toggle="true"
        while "true"; do
            eval local "patterns=($parameter)"
            if [[ ${#patterns[@]} -gt 0 ]]; then
                for pattern in "${patterns[@]}"; do
                    [[ i -lt ${#common_messages[@]} ]] || break
                    if [[ i -lt 0 ]]; then
                        value="$common_status"
                    else
                        value="${common_messages[i]}"
                    fi
                    case $compare in
                    [ne]) [[ ! $value == "$pattern" ]] || break 2;;
                    [op]) [[ ! $value == $pattern ]] || break 2;;
                    [tr]) [[ ! $value =~ $pattern ]] || break 2;;
                    esac
                done
            fi
            if [[ $compare == [not] ]]; then
                let "++i,1"
                continue 2
            else
                status="1"
                break 2
            fi
        done
        if [[ $compare == [not] ]]; then
            status="1"
            break
        else
            let "++i,1"
        fi
    done
    [[ $options == *f* ]] || set +f
    return "$status"
} 

common.hctaC() {
    common_status="0"
}

common.Finally() {
    :
}

common.yllaniF() {
    [[ common_status -eq 0 ]] || throw
}

caught() {
    [[ common_status -eq 0 ]] || return 1
}

EchoExitStatus() {
    return "${1:-$?}"
}

EnableThrowOnError() {
    [[ $common_options == *e* ]] || common_options+="e"
}

DisableThrowOnError() {
    common_options="${common_options/e}"
}

GetStatus() {
    echo "$common_status"
}

SetStatus() {
    let "common_status = 10#$1"
}

GetMessage() {
    echo "${common_messages[$1]}"
}

MessageCount() {
    echo "${#common_messages[@]}"
}

CopyMessages() {
    if [[ ${#common_messages} -gt 0 ]]; then
        eval "$1=(\"\${common_messages[@]}\")"
    else
        eval "$1=()"
    fi
}

common.GetOptions() {
    local "opt"
    let "OPTIND = 1"
    let "OPTERR = 0"
    while getopts ":cdeh:ko:u:v:" opt "$@"; do
        case $opt in
        e)  [[ $common_options == *e* ]] || common_options+="e";;
        h)  common_errHandler="$OPTARG";;
        u)  common_unhandled="$OPTARG";;
        v)  common_command="$OPTARG";;
        esac
    done
    shift "$((OPTIND - 1))"
    common_fifo="$1"
    shift
    common_function="$1"
    chmod "0600" "$common_fifo"
}

DefaultUnhandled() {
    local -i "i"
    echo "-------------------------------------------------"
    echo "TryCatchFinally: Unhandeled exception occurred"
    echo "Status: $(GetStatus)"
    echo "Messages:"
    for ((i=0; i<$(MessageCount); i++)); do
        echo "$(GetMessage "$i")"
    done
    echo "-------------------------------------------------"
}

TryCatchFinally() {
    local "common_errHandler=DefaultErrHandler"
    local "common_unhandled=DefaultUnhandled"
    local "common_options="
    local "common_fifo="
    local "common_function="
    local "common_flags=$-"
    local "common_trySubshell=-1"
    local "common_subshell"
    local "common_status=0"
    local "common_command="
    local "common_messages=()"
    local "common_handler=$(trap -p ERR)"
    [[ -n $common_handler ]] || common_handler="trap ERR"
    common.GetOptions "$@"
    shift "$((OPTIND + 1))"
    [[ -z $common_command ]] || common_command+="=$"
    common_command+='("$common_function" "$@")'
    set -E
    set +e
    trap "common.ErrHandler" ERR
    try
        eval "$common_command"
    yrt
    catch; do
        "$common_unhandled" >&2
    hctac
    [[ $common_flags == *E* ]] || set +E
    [[ $common_flags != *e* ]] || set -e
    [[ $common_flags != *f* || $- == *f* ]] || set -f
    [[ $common_flags == *f* || $- != *f* ]] || set +f
    eval "$common_handler"
}

Below is an example, which assumes the above script is stored in the file named simple. The makefifo file contains the script described in this answer. The assumption is made that the file named 4444kkkkk does not exist, therefore causing an exception to occur. The error message output from the ls 4444kkkkk command is automatically suppressed until inside the appropriate catch block.

#!/bin/bash
#

if [[ $0 != ${BASH_SOURCE[0]} ]]; then
    bash "${BASH_SOURCE[0]}" "$@"
    return
fi

source simple
source makefifo

MyFunction3() {
    echo "entered MyFunction3" >&4
    echo "This is from MyFunction3"
    ls 4444kkkkk
    echo "leaving MyFunction3" >&4
}

MyFunction2() {
    echo "entered MyFunction2" >&4
    value="$(MyFunction3)"
    echo "leaving MyFunction2" >&4
}

MyFunction1() {
    echo "entered MyFunction1" >&4
    local "flag=false"
    try 
    (
        echo "start of try" >&4
        MyFunction2
        echo "end of try" >&4
    )
    yrt
    catch "[1-3]" "*" "Exception\ Type:\ ERR"; do
        echo 'start of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
        local -i "i"
        echo "-------------------------------------------------"
        echo "Status: $(GetStatus)"
        echo "Messages:"
        for ((i=0; i<$(MessageCount); i++)); do
            echo "$(GetMessage "$i")"
        done
        echo "-------------------------------------------------"
        break
        echo 'end of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
    hctac >&4
    catch "1 3 5" "*" -n "Exception\ Type:\ ERR"; do
        echo 'start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
        echo "-------------------------------------------------"
        echo "Status: $(GetStatus)"
        [[ $(MessageCount) -le 1 ]] || echo "$(GetMessage "1")"
        echo "-------------------------------------------------"
        break
        echo 'end of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
    hctac >&4
    catch; do
        echo 'start of catch' >&4
        echo "failure"
        flag="true"
        echo 'end of catch' >&4
    hctac
    finally
        echo "in finally"
    yllanif >&4
    "$flag" || echo "success"
    echo "leaving MyFunction1" >&4
} 2>&6

ErrHandler() {
    echo "EOF"
    DefaultErrHandler "$@"
    echo "Function: $3"
    while read; do
        [[ $REPLY != *EOF ]] || break
        echo "$REPLY"
    done
}

set -u
echo "starting" >&2
MakeFIFO "6"
TryCatchFinally -e -h ErrHandler -o /dev/fd/4 -v result /dev/fd/6 MyFunction1 4>&2
echo "result=$result"
exec >&6-

The above script was tested using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17). The output, from running this script, is shown below.

starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "[1-3]" "*" "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 1
Messages:
Orginal Status: 1
Exception Type: ERR
Function: MyFunction3
ls: 4444kkkkk: No such file or directory
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure

Another example which uses a throw can be created by replacing function MyFunction3 with the script shown below.

MyFunction3() {
    echo "entered MyFunction3" >&4
    echo "This is from MyFunction3"
    throw "3" "Orginal Status: 3" "Exception Type: throw"
    echo "leaving MyFunction3" >&4
}

The syntax for the throw command is given below. If no parameters are present, then status and messages stored in the variables are used instead.

throw [status] [message ...]

The output, from executing the modified script, is shown below.

starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 3
Exception Type: throw
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure

get everything between <tag> and </tag> with php

this function worked for me

<?php

function everything_in_tags($string, $tagname)
{
    $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

?>

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

In scikit version 0.22, you can do it like this

from sklearn.metrics import multilabel_confusion_matrix

y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]

mcm = multilabel_confusion_matrix(y_true, y_pred,labels=["ant", "bird", "cat"])

tn = mcm[:, 0, 0]
tp = mcm[:, 1, 1]
fn = mcm[:, 1, 0]
fp = mcm[:, 0, 1]

sed edit file in place

You didn't specify what shell you are using, but with zsh you could use the =( ) construct to achieve this. Something along the lines of:

cp =(sed ... file; sync) file

=( ) is similar to >( ) but creates a temporary file which is automatically deleted when cp terminates.

How to click an element in Selenium WebDriver using JavaScript

Here is the code using JavaScript to click the button in WebDriver:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('gbqfb').click();");

Remove the newline character in a list read from a file

str.strip() returns a string with leading+trailing whitespace removed, .lstrip and .rstrip for only leading and trailing respectively.

grades.append(lists[i].rstrip('\n').split(','))

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

Replace whitespaces with tabs in linux

Download and run the following script to recursively convert soft tabs to hard tabs in plain text files.

Place and execute the script from inside the folder which contains the plain text files.

#!/bin/bash

find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
    echo "Converting... "$file"";
    data=$(unexpand --first-only -t 4 "$file");
    rm "$file";
    echo "$data" > "$file";
}; done;

How to extract duration time from ffmpeg output?

ffmpeg -i abc.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed s/,//

gives output

HH:MM:SS.milisecs

printing all contents of array in C#

The easiest one e.g. if you have a string array declared like this string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));

How to tell if JRE or JDK is installed

according to JAVA documentation, the JDK should be installed in this path:

/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk

See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html

So if you can find such folder then the JDK is installed

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Came across this issue when using Bootstrap 3. My solution was to add the carousel-fade class to the carousel main DIV and slot the following CSS in, somewhere after the Bootstrap CSS is included:

.carousel-fade .item {
  opacity: 0;
  -webkit-transition: opacity 2s ease-in-out;
  -moz-transition: opacity 2s ease-in-out;
  -ms-transition: opacity 2s ease-in-out;
  -o-transition: opacity 2s ease-in-out;
  transition: opacity 2s ease-in-out;
  left: 0 !important;
}

.carousel-fade .active {
  opacity: 1 !important;
}

.carousel-fade .left {
  opacity: 0 !important;
  -webkit-transition: opacity 0.5s ease-in-out !important;
  -moz-transition: opacity 0.5s ease-in-out !important;
  -ms-transition: opacity 0.5s ease-in-out !important;
  -o-transition: opacity 0.5s ease-in-out !important;
  transition: opacity 0.5s ease-in-out !important;
}

.carousel-fade .carousel-control {
  opacity: 1 !important;
}

The style transitions that Bootstrap applies mean that you have to have the mid-stride transitions (active left, next left) quickly, otherwise the item just ends up disappearing (hence the 1/2 second transition time).

I haven't experimented with adjusting the .item and .left transition times, but they will probably need adjusting proportionally to keep the effect looking nice.

When is "java.io.IOException:Connection reset by peer" thrown?

For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java

// The remote forcibly closed the connection, cancel

// the selection key and close the channel.

    private void read(SelectionKey key) throws IOException {
            SocketChannel socketChannel = (SocketChannel) key.channel();

            // Clear out our read buffer so it's ready for new data
            this.readBuffer.clear();

            // Attempt to read off the channel
            int numRead;
            try {
                numRead = socketChannel.read(this.readBuffer);
            } catch (IOException e) {
                // The remote forcibly closed the connection, cancel
                // the selection key and close the channel.
                key.cancel();
                socketChannel.close();
                return;
            }

            if (numRead == -1) {
                // Remote entity shut the socket down cleanly. Do the
                // same from our end and cancel the channel.
                key.channel().close();
                key.cancel();
                return;
            }
...

C# RSA encryption/decryption with transmission

I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:

        ...
        var signature = Get(url); // base64_encoded signature received from server
        var inputtext= "inputtext"; // this is main text signature was created for
        bool result = VerifySignature(inputtext, signature);
        ...

    private bool VerifySignature(string input, string signature)
    {
        var result = false;
        using (var cps=new RSACryptoServiceProvider())
        {
            // converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
            byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
            byte[] signatureBytes  = Convert.FromBase64String(signature);

            cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
            result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes  );
        }

        return result;
    }

Add list to set?

Sets can't have mutable (changeable) elements/members. A list, being mutable, cannot be a member of a set.

As sets are mutable, you cannot have a set of sets! You can have a set of frozensets though.

(The same kind of "mutability requirement" applies to the keys of a dict.)

Other answers have already given you code, I hope this gives a bit of insight. I'm hoping Alex Martelli will answer with even more details.

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.

SomeDate.Value.GetDateTimeFormats()[5]

GetDateTimeFormats

Regex to match words of a certain length

Length of characters to be matched.

{n,m}  n <= length <= m
{n}    length == n
{n,}   length >= n

And by default, the engine is greedy to match this pattern. For example, if the input is 123456789, \d{2,5} will match 12345 which is with length 5.

If you want the engine returns when length of 2 matched, use \d{2,5}?