Programs & Examples On #Null pointer

In computing, a null pointer has a value reserved for indicating that the pointer does not refer to a valid object.

Is it safe to delete a NULL pointer?

Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either.

If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete at all.

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, Both are functionally the same thing. But in C++ you should switch to nullptr in the place of NULL;

How do we check if a pointer is NULL pointer?

The compiler must provide a consistent type system, and provide a set of standard conversions. Neither the integer value 0 nor the NULL pointer need to be represented by all-zero bits, but the compiler must take care of converting the "0" token in the input file to the correct representation for integer zero, and the cast to pointer type must convert from integer to pointer representation.

The implication of this is that

void *p;
memset(&p, 0, sizeof p);
if(p) { ... }

is not guaranteed to behave the same on all target systems, as you are making an assumption about the bit pattern here.

As an example, I have an embedded platform that has no memory protection, and keeps the interrupt vectors at address 0, so by convention, integers and pointers are XORed with 0x2000000 when converted, which leaves (void *)0 pointing at an address that generates a bus error when dereferenced, however testing the pointer with an if statement will return it to integer representation first, which is then all-zeros.

Can't find @Nullable inside javax.annotation.*

The artifact has been moved from net.sourceforge.findbugs to

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>3.0.0</version>
</dependency>

SQL error "ORA-01722: invalid number"

This happened to me too, but the problem was actually different: file encoding.

The file was correct, but the file encoding was wrong. It was generated by the export utility of SQL Server and I saved it as Unicode.

The file itself looked good in the text editor, but when I opened the *.bad file that the SQL*loader generated with the rejected lines, I saw it had bad characters between every original character. Then I though about the encoding.

I opened the original file with Notepad++ and converted it to ANSI, and everything loaded properly.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim myWb as Excel.Workbook

    Set myWb = ActiveWorkbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
    xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text

    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

Google Chrome redirecting localhost to https

I experienced the same problem in Chrome and I tried unsuccessfully to use BigJump's solution.

I fixed my problem by forcing a hard refresh, as shown in this blog (originally from this SuperUser answer).

Ensure your address bar is using the http scheme and then go through these steps, possibly a couple of times:

  1. Open the Developer Tools panel (CTRL+SHIFT+I)
  2. Click and hold the reload icon / Right click the reload icon.
  3. A menu will open.
  4. Choose the 3rd option from this menu ("Empty Cache and Hard Reload")

Java 8: Lambda-Streams, Filter by Method with Exception

It can be resolved by below simple code with Stream and Try in AbacusUtil:

Stream.of(accounts).filter(a -> Try.call(a::isActive)).map(a -> Try.call(a::getNumber)).toSet();

Disclosure: I'm the developer of AbacusUtil.

How to make div background color transparent in CSS

Opacity gives you translucency or transparency. See an example Fiddle here.

-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";       /* IE 8 */
filter: alpha(opacity=50);  /* IE 5-7 */
-moz-opacity: 0.5;          /* Netscape */
-khtml-opacity: 0.5;        /* Safari 1.x */
opacity: 0.5;               /* Good browsers */

Note: these are NOT CSS3 properties

See http://css-tricks.com/snippets/css/cross-browser-opacity/

Java 8 Streams FlatMap method example

Extract unique words sorted ASC from a list of phrases:

List<String> phrases = Arrays.asList(
        "sporadic perjury",
        "confounded skimming",
        "incumbent jailer",
        "confounded jailer");

List<String> uniqueWords = phrases
        .stream()
        .flatMap(phrase -> Stream.of(phrase.split("\\s+")))
        .distinct()
        .sorted()
        .collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);

... and the output:

Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

How do I empty an input value with jQuery?

A better way is:

$("#element").val(null);

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to phpMyAdmin/config.inc.php edit the line

$cfg['Servers'][$i]['password'] = '';

to

$cfg['Servers'][$i]['password'] = 'yourpassword';

This problem might occur due to setting of a password to root, thus phpmyadmin is not able to connect to the mysql database.

And the last thing change

$cfg['Servers'][$i]['extension'] = 'mysql';

to

$cfg['Servers'][$i]['extension'] = 'mysqli';

Now restart your server. and see.

Create a directory if it doesn't exist

#include <experimental/filesystem> // or #include <filesystem> for C++17 and up
    
namespace fs = std::experimental::filesystem;


if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
    fs::create_directory("src"); // create src folder
}

Remove certain characters from a string

You can use Replace function as;

REPLACE ('Your String with cityname here', 'cityname', 'xyz')
--Results
'Your String with xyz here'

If you apply this to a table column where stringColumnName, cityName both are columns of YourTable

SELECT REPLACE(stringColumnName, cityName, '')
FROM YourTable

Or if you want to remove 'cityName' string from out put of a column then

SELECT REPLACE(stringColumnName, 'cityName', '')
FROM yourTable

EDIT: Since you have given more details now, REPLACE function is not the best method to sort your problem. Following is another way of doing it. Also @MartinSmith has given a good answer. Now you have the choice to select again.

SELECT RIGHT (O.Ort, LEN(O.Ort) - LEN(C.CityName)-1) As WithoutCityName
FROM   tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004'

Get current domain

Try $_SERVER['SERVER_NAME'].

Tips: Create a PHP file that calls the function phpinfo() and see the "PHP Variables" section. There are a bunch of useful variables we never think of there.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

Had the same, and it was solved by running with the classpath defining the derby.jar location.

java -cp <path-to-derby.jar> <Program>

To be more precise:

java -cp "lib/*:." Program

Where :. includes the current directory. And the lib/* does not include the jar extension (lib/*.jar).

How to include duplicate keys in HashMap?

Use Map<Integer, List<String>>:

Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();

map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...

To add a new key/value pair in this map:

public void add(Integer key, String newValue) {
    List<String> currentValue = map.get(key);
    if (currentValue == null) {
        currentValue = new ArrayList<String>();
        map.put(key, currentValue);
    }
    currentValue.add(newValue);
}

C++ class forward declaration

To do anything other than declare a pointer to an object, you need the full definition.

The best solution is to move the implementation in a separate file.

If you must keep this in a header, move the definition after both declarations:

class tile_tree_apple;

class tile_tree : public tile
{
  public:
      tile onDestroy();
      tile tick();
      void onCreate();        
};

class tile_tree_apple : public tile
{
  public:
      tile onDestroy();
      tile tick();
      void onCreate(); 
      tile onUse();       
};

tile tile_tree::onDestroy() {return *new tile_grass;};
tile tile_tree::tick() {if (rand()%20==0) return *new tile_tree_apple;};
void tile_tree::onCreate() {health=rand()%5+4; type=TILET_TREE;};        

tile tile_tree_apple::onDestroy() {return *new tile_grass;};
tile tile_tree_apple::tick() {if (rand()%20==0) return *new tile_tree;};
void tile_tree_apple::onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;}; 
tile tile_tree_apple::onUse() {return *new tile_tree;};       

Important

You have memory leaks:

tile tile_tree::onDestroy() {return *new tile_grass;};

will create an object on the heap, which you can't destroy afterwards, unless you do some ugly hacking. Also, your object will be sliced. Don't do this, return a pointer.

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Toggle input disabled attribute using jQuery


    $('#checkbox').click(function(){
        $('#submit').attr('disabled', !$(this).attr('checked'));
    });

Where does mysql store data?

In mysql server 8.0, on Windows, the location is C:\ProgramData\MySQL\MySQL Server 8.0\Data

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

This problem occurs if there are different jar versions. Especially versions of httpcore and httpclient. Use same versions of httpcore and httpclient.

Adding a slide effect to bootstrap dropdown

For Bootstrap 3, this variation on the answers above makes the mobile slideUp() animation smoother; the answers above have choppy animation because Bootstrap removes the .open class from the toggle's parent immediately, so this code restores the class until the slideUp() animation is finished.

// Add animations to topnav dropdowns
// based on https://stackoverflow.com/a/19339162
// and https://stackoverflow.com/a/52231970

$('.dropdown')
  .on('show.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
  })
  .on('hide.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, false).slideUp(300, function() {
      $(this).parent().removeClass('open');
    });
  })
  .on('hidden.bs.dropdown', function() {
    $(this).addClass('open');
  });

Key differences:

  • In the hide.bs.dropdown event handler I'm using .stop()'s default value (false) for its second argument (jumpToEnd)
  • The hidden.bs.dropdown event handler restores the .open class to the dropdown toggle's parent, and it does this pretty much immediately after the class has been first removed. Meanwhile the slideUp() animation is still running, and just like in the answers above, its "the-animation-is-completed" callback is responsible for finally removing the .open class from its parent.
  • Methods are chained together because the selector for each event handler is the same

How to loop through all elements of a form jQuery

What happens, if you do this way:-

$('#new_user_form input, #new_user_form select').each(function(key, value) {

Refer LIVE DEMO

Implements vs extends: When to use? What's the difference?

Extends is used when you want attributes of parent class/interface in your child class/interface and implements is used when you want attributes of an interface in your class.

Example:

  1. Extends using class

    class Parent{

    }

    class Child extends Parent{

    }

  2. Extends using interface

    interface Parent{

    }

    interface Child extends Parent{

    }

  3. Implements

interface A{

}

class B implements A{

}

Combination of extends and implements

interface A{

}

class B

{

}

class C implements A,extends B{

}

Writing image to local server

Cleanest way of saving image locally using request:

const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))

If you need to add authentication token in headers do this:

const request = require('request');
request({
        url: 'http://link/to/your/image/file.png',
        headers: {
            "X-Token-Auth": TOKEN,
        }
    }).pipe(fs.createWriteStream('filename.png'))                    

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

How can I post data as form data instead of a request payload?

These answers look like insane overkill, sometimes, simple is just better:

$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
                     "&password=" + encodeURIComponent(password) +
                     "&grant_type=password"
).success(function (data) {
//...

Creating an empty file in C#

System.IO.File.Create(@"C:\Temp.txt");

As others have pointed out, you should dispose of this object or wrap it in an empty using statement.

using (System.IO.File.Create(@"C:\Temp.txt"));

How to chain scope queries with OR instead of AND?

Update for Rails4

requires no 3rd party gems

a = Person.where(name: "John") # or any scope 
b = Person.where(lastname: "Smith") # or any scope 
Person.where([a, b].map{|s| s.arel.constraints.reduce(:and) }.reduce(:or))\
  .tap {|sc| sc.bind_values = [a, b].map(&:bind_values) }

Old answer

requires no 3rd party gems

Person.where(
    Person.where(:name => "John").where(:lastname => "Smith")
      .where_values.reduce(:or)
)

Revert to Eclipse default settings

Open any java class -> Right clic -> Checkstyle -> Clear Checkstyle vilolations. It works for me.

SQL Server PRINT SELECT (Print a select query result)?

set @n = (select sum(Amount) from Expense)
print 'n=' + @n

HTML: How to limit file upload to be only images?

HTML5 File input has accept attribute and also multiple attribute. By using multiple attribute you can upload multiple images in an instance.

<input type="file" multiple accept="image/*">

You can also limit multiple mime types.

<input type="file" multiple accept="image/*,audio/*,video/*">

and another way of checking mime type using file object.

file object gives you name,size and type.

var files=e.target.files;

var mimeType=files[0].type; // You can get the mime type

You can also restrict the user for some file types to upload by the above code.

"Items collection must be empty before using ItemsSource."

Perhaps not such an useful answer, but I had the same problem when changing column order and made mistake like the one in the following sample. Having a lot of columns, I reordered them and somehow pasted one after closing tag /DataGrid.Columns:

       <DataGridTemplateColumn x:Name="addedDateColumn" Header="Added Date" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=AddedDate}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
            <DataGridTemplateColumn x:Name="rowguidColumn" Header="rowguid" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=rowguid}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    </DataGrid>

Anyway, lost half an hour because of this. Hope this helps others.

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Java 6 ships the javax.xml.bind.DatatypeConverter. This class provides two static methods that support the same decoding & encoding:

parseBase64Binary() / printBase64Binary()

Update: Since Java 8 we now have a much better Base64 Support.

Use this and you will not need an extra library, like Apache Commons Codec.

How do I declare class-level properties in Objective-C?

As seen on WWDC 2016/XCode 8 (what's new in LLVM session @5:05). Class properties can be declared as follows

@interface MyType : NSObject
@property (class) NSString *someString;
@end

NSLog(@"format string %@", MyType.someString);

Note that class properties are never synthesized

@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end

How do I get AWS_ACCESS_KEY_ID for Amazon?

  1. Go to: http://aws.amazon.com/
  2. Sign Up & create a new account (they'll give you the option for 1 year trial or similar)
  3. Go to your AWS account overview
  4. Account menu in the upper-right (has your name on it)
  5. sub-menu: Security Credentials

Select first row in each GROUP BY group?

In Postgres you can use array_agg like this:

SELECT  customer,
        (array_agg(id ORDER BY total DESC))[1],
        max(total)
FROM purchases
GROUP BY customer

This will give you the id of each customer's largest purchase.

Some things to note:

  • array_agg is an aggregate function, so it works with GROUP BY.
  • array_agg lets you specify an ordering scoped to just itself, so it doesn't constrain the structure of the whole query. There is also syntax for how you sort NULLs, if you need to do something different from the default.
  • Once we build the array, we take the first element. (Postgres arrays are 1-indexed, not 0-indexed).
  • You could use array_agg in a similar way for your third output column, but max(total) is simpler.
  • Unlike DISTINCT ON, using array_agg lets you keep your GROUP BY, in case you want that for other reasons.

How to finish Activity when starting other activity in Android?

  1. Make your activity A in manifest file: launchMode = "singleInstance"
  2. When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.
  3. When the user clicks modify, call the new Intent or simply finish activity B.

What do Push and Pop mean for Stacks?

Hopefully this will help you visualize a Stack, and how it works.

Empty Stack:

|     |
|     |
|     |
-------

After Pushing A, you get:

|     |
|     |
|  A  |
-------

After Pushing B, you get:

|     |
|  B  |
|  A  |
-------

After Popping, you get:

|     |
|     |
|  A  |
-------

After Pushing C, you get:

|     |
|  C  |
|  A  |
-------

After Popping, you get:

|     |
|     |
|  A  |
-------

After Popping, you get:

|     |
|     |
|     |
-------

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

How to enable/disable bluetooth programmatically in android

To Enable the Bluetooth you could use either of the following functions:

 public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        // The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() 
        // implementation as the requestCode parameter. 
        int REQUEST_ENABLE_BT = 1;
        startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
        }
  }

The second function is:

public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.enable();
    }
}

The difference is that the first function makes the app ask the user a permission to turn on the Bluetooth or to deny. The second function makes the app turn on the Bluetooth directly.

To Disable the Bluetooth use the following function:

public void disableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.disable();
    }
}

NOTE/ The first function needs only the following permission to be defined in the AndroidManifest.xml file:

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

While, the second and third functions need the following permissions:

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

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

Uses of content-disposition in an HTTP response header

Well, it seems that the Content-Disposition header was originally created for e-mail, not the web. (Link to relevant RFC.)

I'm guessing that web browsers may respond to

Response.AppendHeader("content-disposition", "inline; filename=" + fileName);

when saving, but I'm not sure.

How to get row number in dataframe in Pandas?

To get all indices that matches 'Smith'

>>> df[df['LastName'] == 'Smith'].index
Int64Index([1], dtype='int64')

or as a numpy array

>>> df[df['LastName'] == 'Smith'].index.to_numpy()  # .values on older versions
array([1])

or if there is only one and you want the integer, you can subset

>>> df[df['LastName'] == 'Smith'].index[0]
1

You could use the same boolean expressions with .loc, but it is not needed unless you also want to select a certain column, which is redundant when you only want the row number/index.

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

Unable to open a file with fopen()

In addition to the above, you might be interested in displaying your current directory:

int MAX_PATH_LENGTH = 80;
char* path[MAX_PATH_LENGTH];
getcwd(path, MAX_PATH_LENGTH);
printf("Current Directory = %s", path);

This should work without issue on a gcc/glibc platform. (I'm most familiar with that type of platform). There was a question posted here that talked about getcwd & Visual Studio if you're on a Windows type platform.

SQL Query with Join, Count and Where

I have used sub-query and it worked great!

SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories

How to make a div center align in HTML

I think that the the align="center" aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.

text-align is doing a similar sort of thing.

left:50% is ignored unless you set the div's position to be something like relative or absolute.

The generally accepted methods is to use the following properties

width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;

the margins being auto means they grow/shrink to match the browser window (or parent div)

UPDATE

Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.

margin:0 auto;

this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

SQL How to Select the most recent date item

You haven't specified what the query should return if more than one document is added at the same time, so this query assumes you want all of them returned:

SELECT t.ID,
       t.USER_ID,
       t.DATE_ADDED,
       t.DATE_VIEWED,
       t.DOCUMENT_ID,
       t.URL,
       t.DOCUMENT_TITLE,
       t.DOCUMENT_DATE
FROM (
  SELECT test_table.*,
         RANK()
         OVER (ORDER BY DOCUMENT_DATE DESC) AS the_rank
  FROM   test_table
  WHERE  user_id = value
  )
WHERE the_rank = 1;

This query will only make one pass through the data.

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar issue and using %in% operator instead of the == (equality) operator was the solution:

# %in%

Hope it helps.

Pass Javascript Array -> PHP

You can transfer array from javascript to PHP...

Javascript... ArraySender.html

<script language="javascript">

//its your javascript, your array can be multidimensional or associative

plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info'; 
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3'; 
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4'; 
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5'; 

function convertJsArr2Php(JsArr){
    var Php = '';
    if (Array.isArray(JsArr)){  
        Php += 'array(';
        for (var i in JsArr){
            Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
            if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
                Php += ', ';
            }
        }
        Php += ')';
        return Php;
    }
    else{
        return '\'' + JsArr + '\'';
    }
}


function ajaxPost(str, plArrayC){
    var xmlhttp;
    if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
    else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    xmlhttp.open("POST",str,true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send('Array=' + plArrayC);
}

ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>

and PHP Code... ArrayReader.php

<?php 

eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);

?>

How do I write a "tab" in Python?

Assume I have a variable named file that contains a file. Then I could use file.write("hello\talex").

  1. file.write("hello means I'm starting to write to this file.
  2. \t means a tab
  3. alex") is the rest I'm writing

How to get value of Radio Buttons?

You need to check one if you have two

if(rbMale.Checked)
{

}
else
{

}

You need to check all the checkboxes if more then two

if(rb1.Checked)
{

}
else if(rb2.Checked)
{

}
else if(rb3.Checked)
{

}

How can I get session id in php and show it?

if(isset($_POST['submit']))
   {  
 if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
    {
     $uname = $_POST['login_username'];
     $pass = $_POST['login_password'];
     $res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and  password='$pass' ";
$query=mysql_query($res)or die (mysql_error());  

list($result,$uname,$role) = mysql_fetch_row($query);   
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
 if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
 {
 if($result>0)
      {
       header ('Location:Dashboard.php');
      }
      else
      {
         header ('Location:loginform.php');
      }
 }

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

jquery - How to determine if a div changes its height or any css attribute?

For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.

Here is a link to the caniuse js MutationObserver

Simple usage with powerful results.

    var observer = new MutationObserver(function (mutations) {
        //your action here
    });

    //set up your configuration
    //this will watch to see if you insert or remove any children
    var config = { subtree: true, childList: true };

    //start observing
    observer.observe(elementTarget, config);

When you don't need to observe any longer just disconnect.

    observer.disconnect();

Check out the MDN documentation for more information

how to change attribute "hidden" in jquery

You can use jquery attr method

$("#delete").attr("hidden",true);

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

Mysql database sync between two databases

SymmetricDS is the answer. It supports multiple subscribers with one direction or bi-directional asynchronous data replication. It uses web and database technologies to replicate tables between relational databases, in near real time if desired.

Comprehensive and robust Java API to suit your needs.

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

integrating barcode scanner into php application?

PHP can be easily utilized for reading bar codes printed on paper documents. Connecting manual barcode reader to the computer via USB significantly extends usability of PHP (or any other web programming language) into tasks involving document and product management, like finding a book records in the database or listing all bills for a particular customer.

Following sections briefly describe process of connecting and using manual bar code reader with PHP.

The usage of bar code scanners described in this article are in the same way applicable to any web programming language, such as ASP, Python or Perl. This article uses only PHP since all tests have been done with PHP applications.

What is a bar code reader (scanner)

Bar code reader is a hardware pluggable into computer that sends decoded bar code strings into computer. The trick is to know how to catch that received string. With PHP (and any other web programming language) the string will be placed into focused input HTML element in browser. Thus to catch received bar code string, following must be done:

just before reading the bar code, proper input element, such as INPUT TEXT FIELD must be focused (mouse cursor is inside of the input field). once focused, start reading the code when the code is recognized (bar code reader usually shortly beeps), it is send to the focused input field. By default, most of bar code readers will append extra special character to decoded bar code string called CRLF (ENTER). For example, if decoded bar code is "12345AB", then computer will receive "12345ABENTER". Appended character ENTER (or CRLF) emulates pressing the key ENTER causing instant submission of the HTML form:

<form action="search.php" method="post">
    <input name="documentID" onmouseover="this.focus();" type="text">
</form>

Choosing the right bar code scanner

When choosing bar code reader, one should consider what types of bar codes will be read with it. Some bar codes allow only numbers, others will not have checksum, some bar codes are difficult to print with inkjet printers, some barcode readers have narrow reading pane and cannot read for example barcodes with length over 10 cm. Most of barcode readers support common barcodes, such as EAN8, EAN13, CODE 39, Interleaved 2/5, Code 128 etc.

For office purposes, the most suitable barcodes seem to be those supporting full range of alphanumeric characters, which might be:

  • code 39 - supports 0-9, uppercased A-Z, and few special characters (dash, comma, space, $, /, +, %, *)
  • code 128 - supports 0-9, a-z, A-Z and other extended characters

Other important things to note:

  • make sure all standard barcodes are supported, at least CODE39, CODE128, Interleaved25, EAN8, EAN13, PDF417, QRCODE.
  • use only standard USB plugin cables. RS232 interfaces are meant for industrial usage, rather than connecting to single PC.
  • the cable should be long enough, at least 1.5 m - the longer the better.
  • bar code reader plugged into computer should not require other power supply - it should power up simply by connecting to PC via USB.
  • if you also need to print bar code into generated PDF documents, you can use TCPDF open source library that supports most of common 2D bar codes.

Installing scanner drivers

Installing manual bar code reader requires installing drivers for your particular operating system and should be normally supplied with purchased bar code reader.

Once installed and ready, bar code reader turns on signal LED light. Reading the barcode starts with pressing button for reading.

Scanning the barcode - how does it work?

STEP 1 - Focused input field ready for receiving character stream from bar code scanner:

step 1

STEP 2 - Received barcode string from bar code scanner is immediatelly submitted for search into database, which creates nice "automated" effect:

step 2

STEP 3 - Results returned after searching the database with submitted bar code:

step 3

Conclusion

It seems, that utilization of PHP (and actually any web programming language) for scanning the bar codes has been quite overlooked so far. However, with natural support of emulated keypress (ENTER/CRLF) it is very easy to automate collecting & processing recognized bar code strings via simple HTML (GUI) fomular.

The key is to understand, that recognized bar code string is instantly sent to the focused HTML element, such as INPUT text field with appended trailing character ASCII 13 (=ENTER/CRLF, configurable option), which instantly sends input text field with populated received barcode as a HTML formular to any other script for further processing.

Reference: http://www.synet.sk/php/en/280-barcode-reader-scanner-in-php

Hope this helps you :)

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

There is an easy way without the need to use an external tool - it runs fine with Windows 7, 8, 8.1 and 10 and is backwards-compatible too (Windows XP doesn't have any UAC, thus elevation is not needed - in that case the script just proceeds).

Check out this code (I was inspired by the code by NIronwolf posted in the thread Batch File - "Access Denied" On Windows 7?), but I've improved it - in my version there isn't any directory created and removed to check for administrator privileges):

::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
 @echo off
 CLS
 ECHO.
 ECHO =============================
 ECHO Running Admin shell
 ECHO =============================

:init
 setlocal DisableDelayedExpansion
 set cmdInvoke=1
 set winSysFolder=System32
 set "batchPath=%~0"
 for %%k in (%0) do set batchName=%%~nk
 set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
 setlocal EnableDelayedExpansion

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
  if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
  ECHO.
  ECHO **************************************
  ECHO Invoking UAC for Privilege Escalation
  ECHO **************************************

  ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
  ECHO args = "ELEV " >> "%vbsGetPrivileges%"
  ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
  ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
  ECHO Next >> "%vbsGetPrivileges%"

  if '%cmdInvoke%'=='1' goto InvokeCmd 

  ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
  goto ExecElevation

:InvokeCmd
  ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
  ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"

:ExecElevation
 "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
 exit /B

:gotPrivileges
 setlocal & cd /d %~dp0
 if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)

 ::::::::::::::::::::::::::::
 ::START
 ::::::::::::::::::::::::::::
 REM Run shell as admin (example) - put here code as you like
 ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9
 cmd /k

The script takes advantage of the fact that NET FILE requires administrator privilege and returns errorlevel 1 if you don't have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the administrator account and password.

I have tested it with Windows 7, 8, 8.1, 10 and with Windows XP - it works fine for all. The advantage is, after the start point you can place anything that requires system administrator privileges, for example, if you intend to re-install and re-run a Windows service for debugging purposes (assumed that mypackage.msi is a service installer package):

msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice

Without this privilege elevating script, UAC would ask you three times for your administrator user and password - now you're asked only once at the beginning, and only if required.


If your script just needs to show an error message and exit if there aren't any administrator privileges instead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:

@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
  ECHO "RUN AS ADMINISTRATOR"  to run this batch. Exiting... & ECHO. &
  PAUSE & EXIT /D)
REM ... proceed here with admin rights ...

This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects administrator rights, otherwise exit with an error. If you don't require the PAUSE, just remove it. Important: NET FILE [...] EXIT /D) must be on the same line. It is displayed here in multiple lines for better readability!


On some machines, I've encountered issues, which are solved in the new version above already. One was due to different double quote handling, and the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.

I have fixed this now by stripping the quotes in the path and re-adding them later, and I've added an extra parameter which is added when the script re-launches with elevated rights.

The double quotes are removed by the following (details are here):

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion

You can then access the path by using !batchPath!. It doesn't contain any double quotes, so it is safe to say "!batchPath!" later in the script.

The line

if '%1'=='ELEV' (shift & goto gotPrivileges)

checks if the script has already been called by the VBScript script to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.


Update:

  • To avoid having to register the .vbs extension in Windows 10, I have replaced the line
    "%temp%\OEgetPrivileges.vbs"
    by
    "%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
    in the script above; also added cd /d %~dp0 as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.

  • Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.

  • According to Artjom B.'s hint, I analyzed it and have replaced SHIFT by SHIFT /1, which preserves the file name for the %0 parameter

  • Added del "%temp%\OEgetPrivileges_%batchName%.vbs" to the :gotPrivileges section to clean up (as mlt suggested). Added %batchName% to avoid impact if you run different batches in parallel. Note that you need to use for to be able to take advantage of the advanced string functions, such as %%~nk, which extracts just the filename.

  • Optimized script structure, improvements (added variable vbsGetPrivileges which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs file if batch needed to be elevated)

  • In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
    set cmdInvoke=0
    set winSysFolder=System32
    Either change the 1st parameter to set cmdInvoke=1 and check if that already fixes the issue. It will add cmd.exe to the script performing the elevation.
    Or try to change the 2nd parameter to winSysFolder=Sysnative, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).

  • To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files".

  • If you want to debug the VBS script, you can add the //X parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).

Useful links:

What is the meaning of "this" in Java?

this refers to the current object.

Each non-static method runs in the context of an object. So if you have a class like this:

public class MyThisTest {
  private int a;

  public MyThisTest() {
    this(42); // calls the other constructor
  }

  public MyThisTest(int a) {
    this.a = a; // assigns the value of the parameter a to the field of the same name
  }

  public void frobnicate() {
    int a = 1;

    System.out.println(a); // refers to the local variable a
    System.out.println(this.a); // refers to the field a
    System.out.println(this); // refers to this entire object
  }

  public String toString() {
    return "MyThisTest a=" + a; // refers to the field a
  }
}

Then calling frobnicate() on new MyThisTest() will print

1
42
MyThisTest a=42

So effectively you use it for multiple things:

  • clarify that you are talking about a field, when there's also something else with the same name as a field
  • refer to the current object as a whole
  • invoke other constructors of the current class in your constructor

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

How to synchronize or lock upon variables in Java?

For this functionality you are better off not using a lock at all. Try an AtomicReference.

public class Sample {
    private final AtomicReference<String> msg = new AtomicReference<String>();

    public void setMsg(String x) {
        msg.set(x);
    }

    public String getMsg() {
        return msg.getAndSet(null);
    }
}

No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

As previously answered (and retracted). To get the base directory, as in the location of the running assembly, don't use Directory.GetCurrentDirectory(), rather get it from IHostingEnvironment.ContentRootPath.

private IHostingEnvironment _hostingEnvironment;
    private string projectRootFolder;
    public Program(IHostingEnvironment env)
    {
        _hostingEnvironment = env;
        projectRootFolder = env.ContentRootPath.Substring(0,
            env.ContentRootPath.LastIndexOf(@"\ProjectRoot\", StringComparison.Ordinal) + @"\ProjectRoot\".Length);
    }

However I made an additional error: I had set the ContentRoot Directory to Directory.GetCurrentDirectory() at startup undermining the default value which I had so desired! Here I commented out the offending line:

 public static void Main(string[] args)
    {
        var host = new WebHostBuilder().UseKestrel()
           // .UseContentRoot(Directory.GetCurrentDirectory()) //<== The mistake
            .UseIISIntegration()
            .UseStartup<Program>()
            .Build();
        host.Run();
    }

Now it runs correctly - I can now navigate to sub folders of my projects root with:

var pathToData = Path.GetFullPath(Path.Combine(projectRootFolder, "data"));

I realised my mistake by reading BaseDirectory vs. Current Directory and @CodeNotFound founds answer (which was retracted because it didn't work because of the above mistake) which basically can be found here: Getting WebRoot Path and Content Root Path in Asp.net Core

oracle SQL how to remove time from date

We can use TRUNC function in Oracle DB. Here is an example.

SELECT TRUNC(TO_DATE('01 Jan 2018 08:00:00','DD-MON-YYYY HH24:MI:SS')) FROM DUAL

Output: 1/1/2018

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

How can I compile LaTeX in UTF8?

Save your file in UTF8 format.

Verify the file format using the following (UNIX) command:

file -bi filename.tex 

You should see:

text/x-tex; charset=utf-8

Convert the file using iconv if it is not UTF8:

iconv --from-code=ISO-8859-1 --to-code=UTF-8 filename.txt > filename-utf.txt

Using Case/Switch and GetType to determine the object

You can do this:

if (node is CasusNodeDTO)
{
    ...
}
else if (node is BucketNodeDTO)
{
    ...
}
...

While that would be more elegant, it's possibly not as efficient as some of the other answers here.

How to get the ActionBar height?

i think the safest way would be :

private int getActionBarHeight() {
    int actionBarHeight = getSupportActionBar().getHeight();
    if (actionBarHeight != 0)
        return actionBarHeight;
    final TypedValue tv = new TypedValue();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    } else if (getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true))
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    return actionBarHeight;
}

Download File Using jQuery

If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.

Reading output of a command into an array in Bash

The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *, ?, [...].

To get the output of a command in an array, with one line per element, there are essentially 3 ways:

  1. With Bash=4 use mapfile—it's the most efficient:

    mapfile -t my_array < <( my_command )
    
  2. Otherwise, a loop reading the output (slower, but safe):

    my_array=()
    while IFS= read -r line; do
        my_array+=( "$line" )
    done < <( my_command )
    
  3. As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:

    IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
    

    Please make sure you use exactly this form, i.e., make sure you have the following:

    • IFS=$'\n' on the same line as the read statement: this will only set the environment variable IFS for the read statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read to break the stream at the EOL character \n.
    • -r: this is important. It tells read to not interpret the backslashes as escape sequences.
    • -d '': please note the space between the -d option and its argument ''. If you don't leave a space here, the '' will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read to stop reading at the nil byte. Some people write it as -d $'\0', but it is not really necessary. -d '' is better.
    • -a my_array tells read to populate the array my_array while reading the stream.
    • You must use the printf '\0' statement after my_command, so that read returns 0; it's actually not a big deal if you don't (you'll just get an return code 1, which is okay if you don't use set -e – which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf '', which doesn't output anything. printf '\0' prints a null byte, needed by read to happily stop reading there (remember the -d '' option?).

If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.

If you want to use read, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]} in the example I gave).

Note that mapfile provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile and the options -C and -c therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).


Now I'm going to tell you why the following method:

my_array=( $( my_command) )

is broken when there are spaces:

$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!

Then some people will then recommend using IFS=$'\n' to fix it:

$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!

But now let's use another command, with globs:

$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?

That's because I have a file called t in the current directory… and this filename is matched by the glob [three four]… at this point some people would recommend using set -f to disable globbing: but look at it: you have to change IFS and use set -f to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.

$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'

here we're working with the shell!

Chrome hangs after certain amount of data transfered - waiting for available socket

Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.

The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.

As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.

Trim spaces from start and end of string

This is what is suggested by JavaScript Architect/Guru Douglas Crockford.

String.method('trim', function (  ) {
    return this.replace(/^\s+|\s+$/g, '');
});

Note: you have to define "method" for Function.prototype.

Alternatively

String.prototype.trim = function () {
   return this.replace(/^\s+|\s+$/g, '');
};

title.trim();    // returns trimmed title

Observation

In recent browsers, the trim method is included by default. So you don't have to add it explicitly.

Major browsers Chrome, Firefox, Safari etc. supports trim method. Checked in Chrome 55.0.2883.95 (64-bit), Firefox 51.0.1 (64-bit), Safari 10.0 (12602.1.50.0.10).

Simple way to calculate median with MySQL

I just found another answer online in the comments:

For medians in almost any SQL:

SELECT x.val from data x, data y
GROUP BY x.val
HAVING SUM(SIGN(1-SIGN(y.val-x.val))) = (COUNT(*)+1)/2

Make sure your columns are well indexed and the index is used for filtering and sorting. Verify with the explain plans.

select count(*) from table --find the number of rows

Calculate the "median" row number. Maybe use: median_row = floor(count / 2).

Then pick it out of the list:

select val from table order by val asc limit median_row,1

This should return you one row with just the value you want.

Jacob

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

What is a 'Closure'?

Closures Whenever we have a function defined inside another function, the inner function has access to the variables declared in the outer function. Closures are best explained with examples. In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term closure. The concept in itself is simple enough and fairly intuitive.

Listing 2-18:
    function outerFunction(arg) {
     var variableInOuterFunction = arg;

     function bar() {
             console.log(variableInOuterFunction); // Access a variable from the outer scope
     }
     // Call the local function to demonstrate that it has access to arg
     bar(); 
    }
    outerFunction('hello closure!'); // logs hello closure!

source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf

programmatically add column & rows to WPF Datagrid

If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)

option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)

xaml.cs

DataContext = myCollection;

//myCollection is a `ICollection<YourType>` preferably
`ObservableCollection<YourType>

 - option 2) Declare the name of the Datagrid in xaml

        <WpfToolkit:DataGrid Name=dataGrid}>

in xaml.cs

CollectionView myCollectionView = 
      (CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
dataGrid.ItemsSource = myCollectionView;

If your type has a property FirstName defined, you can then do what John Myczek pointed out.

DataGridTextColumn textColumn = new DataGridTextColumn(); 
dataColumn.Header = "First Name"; 
dataColumn.Binding = new Binding("FirstName"); 
dataGrid.Columns.Add(textColumn); 

This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.

How to execute AngularJS controller function on page load?

Found Dmitry Evseev answer quite useful.

Case 1 : Using angularJs alone:
To execute a method on page load, you can use ng-init in the view and declare init method in controller, having said that use of heavier function is not recommended, as per the angular Docs on ng-init:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

HTML:

<div ng-controller="searchController()">
    <!-- renaming view code here, including the search box and the buttons -->
</div>

Controller:

app.controller('SearchCtrl', function(){

    var doSearch = function(keyword){
        //Search code here
    }

    doSearch($routeParams.searchKeyword);
})

Warning : Do not use this controller for another view meant for a different intention as it will cause the search method be executed there too.

Case 2 : Using Ionic:
The above code will work, just make sure the view cache is disabled in the route.js as:

route.js

.state('app', {
    url           : '/search',
    cache         : false, //disable caching of the view here
    templateUrl   : 'templates/search.html'   ,
    controller    : 'SearchCtrl'
  })

Hope this helps

How to sign in kubernetes dashboard?

A self-explanatory simple one-liner to extract token for kubernetes dashboard login.

kubectl describe secret -n kube-system | grep deployment -A 12

Copy the token and paste it on the kubernetes dashboard under token sign in option and you are good to use kubernetes dashboard

How to get the current taxonomy term ID (not the slug) in WordPress?

Nevermind! I found it :)

get_queried_object()->term_id;

row-level trigger vs statement-level trigger

if you want to execute the statement when number of rows are modified then it can be possible by statement level triggers.. viseversa... when you want to execute your statement each modification on your number of rows then you need to go for row level triggers..

for example: statement level triggers works for when table is modified..then more number of records are effected. and row level triggers works for when each row updation or modification..

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

You can wrap the inputs in col-* classes

<form name="registration_form" id="registration_form" class="form-horizontal">
     <div class="form-group">
           <div class="col-sm-6">
             <label for="firstname" class="sr-only"></label>
             <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
           </div>       
           <div class="col-sm-6">
             <label for="lastname" class="sr-only"></label>
             <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
           </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
          <label for="username" class="sr-only"></label>
          <input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
        </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
        <label for="password" class="sr-only"></label>
        <input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
        </div>
    </div><!--/form-group-->
 </form>

http://bootply.com/127825

View more than one project/solution in Visual Studio

You can create a new blank solution and add your different projects to it.

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

How to get the concrete class name as a string?

you can also create a dict with the classes themselves as keys, not necessarily the classnames

typefunc={
    int:lambda x: x*2,
    str:lambda s:'(*(%s)*)'%s
}

def transform (param):
    print typefunc[type(param)](param)

transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

How do I make a Mac Terminal pop-up/alert? Applescript?

I made a script to solve this which is here. You don't need any extra software for this. Installation:
brew install akashaggarwal7/tools/tsay
Usage:
sleep 5; tsay

Feel free to contribute!

How to change the cursor into a hand when a user hovers over a list item?

Just for completeness:

cursor: -webkit-grab;

It also gives a hand, the one you know when moving the view of an image around.

It is quite useful if you want to emulate grab behavior using jQuery and mousedown.

Enter image description here

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:

TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();

How to exit a 'git status' list in a terminal?

If you are facing this?

enter image description here Sometimes it is possible that while writing in Gitbash you get into > and you just can not get out of that.
It happens with me quite often while I type ' by mistake in Gitbash(See in the image).

How to solve this in Mac?

control + C

I have not checked it in Windows. But if it does please edit that in my answer.

Parse query string in JavaScript

Me too! http://jsfiddle.net/drzaus/8EE8k/

(Note: without fancy nested or duplicate checking)

deparam = (function(d,x,params,p,i,j) {
return function (qs) {
    // start bucket; can't cheat by setting it in scope declaration or it overwrites
    params = {};
    // remove preceding non-querystring, correct spaces, and split
    qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
    // march and parse
    for (i = qs.length; i > 0;) {
        p = qs[--i];
        // allow equals in value
        j = p.indexOf('=');
        // what if no val?
        if(j === -1) params[d(p)] = undefined;
        else params[d(p.substring(0,j))] = d(p.substring(j+1));
    }

    return params;
};//--  fn  deparam
})(decodeURIComponent, /\+/g);

And tests:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';

var $output = document.getElementById('output');
function output(msg) {
    msg = Array.prototype.slice.call(arguments, 0).join("\n");
    if($output) $output.innerHTML += "\n" + msg + "\n";
    else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
    var q = deparam(test);
    results[msg] = q;
    output(msg, test, JSON.stringify(q), $.param(q));
    output('-------------------');
});

output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
    output(msg, JSON.stringify(result));
    output('-------------------');
});

Results in:

simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"}   <-- it's there, i swear!
qux=quux&baz=&foo=bar        <-- ...see, jQuery found it
-------------------

Fill username and password using selenium in python

I am new to selenium and I tried all solutions above but they don't work. Finally, I tried this manually by

driver = webdriver.Firefox()
import time

driver.get(url)

time.sleep(20)

print (driver.page_source.encode("utf-8"))

Then I could get contents from web.

Chosen Jquery Plugin - getting selected values

This worked for me

$(".chzn-select").chosen({

     disable_search_threshold: 10

}).change(function(event){

     if(event.target == this){
        alert($(this).val());
     }

});

HTTPS using Jersey Client

For Jersey 2 you'd need to modify the code:

        return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();

https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html

Converting map to struct

Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

The second result parameter has to be an address of the struct.

Update MongoDB field using value of another field

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:

// { firstName: "Hello", lastName: "World" }
db.collection.update(
  {},
  [{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
  { multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
  • The first part {} is the match query, filtering which documents to update (in our case all documents).

  • The second part [{ $set: { name: { ... } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields.

  • Don't forget { multi: true }, otherwise only the first matching document will be updated.

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

Min and max value of input in angular4 application

I succeeded by using a form control. This is my html code :

<md-input-container>
    <input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl">
    <md-error>Please enter a value between 0 and 100</md-error>
</md-input-container>

And in my Typescript code, I have :

this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])

So, if we enter a value higher than 100 or smaller than 0, the material design input become red and the field is not validate. So after, if the value is not good, I don't save when I click on the save button.

Convert Json string to Json object in Swift 4

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

Call Python script from bash with argument

Print all args without the filename:

for i in range(1, len(sys.argv)):
print(sys.argv[i])

passing several arguments to FUN of lapply (and others *apply)

You can do it in the following way:

 myfxn <- function(var1,var2,var3){
      var1*var2*var3

    }

    lapply(1:3,myfxn,var2=2,var3=100)

and you will get the answer:

[[1]] [1] 200

[[2]] [1] 400

[[3]] [1] 600

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

Find empty or NaN entry in Pandas Dataframe

np.where(pd.isnull(df)) returns the row and column indices where the value is NaN:

In [152]: import numpy as np
In [153]: import pandas as pd
In [154]: np.where(pd.isnull(df))
Out[154]: (array([2, 5, 6, 6, 7, 7]), array([7, 7, 6, 7, 6, 7]))

In [155]: df.iloc[2,7]
Out[155]: nan

In [160]: [df.iloc[i,j] for i,j in zip(*np.where(pd.isnull(df)))]
Out[160]: [nan, nan, nan, nan, nan, nan]

Finding values which are empty strings could be done with applymap:

In [182]: np.where(df.applymap(lambda x: x == ''))
Out[182]: (array([5]), array([7]))

Note that using applymap requires calling a Python function once for each cell of the DataFrame. That could be slow for a large DataFrame, so it would be better if you could arrange for all the blank cells to contain NaN instead so you could use pd.isnull.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

How to discard uncommitted changes in SourceTree?

On SourceTree for Mac, right click the files you want to discard (in the Files in the working tree list), and choose Reset.

On SourceTree for Windows, right click the files you want to discard (in the Working Copy Changes list), and choose Discard.

On git, you'd simply do:

git reset --hard to discard changes made to versioned files;

git clean -xdf to erase new (untracked) files, including ignored ones (the x option). d is to also remove untracked directories and f to force.

what is the differences between sql server authentication and windows authentication..?

I don't know SQLServer as well as other DBMS' but I imagine the benefit is the same as with DB2 and Oracle. If you use Windows authentication, you only have to maintain one set of users and/or passwords, that of Windows, which is already done for you.

DBMS authentication means having a separate set of users and/or passwords which must be maintained.

In addition, Windows passwords allow them to be configured centrally for the enterprise (Active Directory) whereas SQLServer has to maintain one set for each DBMS instance.

Android Pop-up message

Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:

Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {            
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}

What is the best open-source java charting library? (other than jfreechart)

You can try Jzy3d. It helps drawing simple 3d charts (surfaces, scatters, bars, etc), and has lot of options for customizing layout of axes, ticks, etc. There are lot of examples and a documentation on the wiki.

It's free and open source.

Cheers,

Martin

How to know the size of the string in bytes?

From MSDN:

A String object is a sequential collection of System.Char objects that represent a string.

So you can use this:

var howManyBytes = yourString.Length * sizeof(Char);

What's causing my java.net.SocketException: Connection reset?

This error occurs on the server side when the client closed the socket connection before the response could be returned over the socket. In a web app scenario not all of these are dangerous, since they can be created manually. For example, by quitting the browser before the reponse was retrieved.

How to get a list column names and datatypes of a table in PostgreSQL?

To make this topic 'more complete'.

I required the column names and data types on a SELECT statement (not a table).

If you want to do this on a SELECT statement instead of an actual existing table, you can do the following:

DROP TABLE IF EXISTS abc;
CREATE TEMPORARY TABLE abc AS
-- your select statement here!
SELECT 
    *
FROM foo
-- end your select statement
;

select column_name, data_type 
from information_schema.columns 
where table_name = 'abc';
DROP IF EXISTS abc;

Short explanation, it makes a (temp) table of your select statement, which you can 'call' upon via the query provided by (among others) @a_horse_with_no_name and @selva.

Hope this helps.

Why doesn't TFS get latest get the latest?

WHen I run into this problem with it not getting latest and version mismatches I first do a "Get Specific Version" set it to changeset and put in 1. This will then remove all the files from your local workspace (for that project, folder, file, etc) and it will also have TFS update so that it knows you now have NO VERSION DOWNLOADED. You can then do a "Get Latest" and viola, you will actually have the latest

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I had this problem, except the type it couldn't load was System.Reflection.AssemblyMetadataAttribute. The web application was built on a machine with .NET 4.5 installed (runs fine there), with 4.0 as the target framework, but the error presented itself when it was run on a web server with only 4.0 installed. I then tried it on a web server with 4.5 installed and there was no error. So, as others have said, this is all due to the screwy way Microsoft released 4.5, which basically is an upgrade to (and overwrite of) version 4.0. The System.Reflection assembly references a type that doesn't exist in 4.0 (AssemblyMetadataAttribute) so it will fail if you don't have the new System.Reflection.dll.

You can either install .NET 4.5 on the target web server, or build the application on a machine that does not have 4.5 installed. Far from an ideal resolution.

Insert the same fixed value into multiple rows

To update the content of existing rows use the UPDATE statement:

UPDATE table_name SET table_column = 'test';

Real differences between "java -server" and "java -client"?

Last time I had a look at this, (and admittedly it was a while back) the biggest difference I noticed was in the garbage collection.

IIRC:

  • The server heap VM has a differnt number of generations than the Client VM, and a different garbage collection algorithm. This may not be true anymore
  • The server VM will allocate memory and not release it to the OS
  • The server VM will use more sophisticated optimisation algorithms, and hence have bigger time and memory requirements for optimisation

If you can compare two java VMs, one client, one server using the jvisualvm tool, you should see a difference in the frequency and effect of the garbage collection, as well as in the number of generations.

I had a pair of screenshots that showed the difference really well, but I can't reproduce as I have a 64 bit JVM which only implements the server VM. (And I can't be bothered to download and wrangle the 32 bit version on my system as well.)

This doesn't seem to be the case anymore, having tried running some code on windows with both server and client VMs, I seem to get the same generation model for both...

matplotlib: how to draw a rectangle on image

You can add a Rectangle patch to the matplotlib Axes.

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

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

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

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

# Display the image
ax.imshow(im)

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

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

plt.show()

enter image description here

how to assign a block of html code to a javascript variable

 var test = "<div class='saved' >"+
 "<div >test.test</div> <div class='remove'>[Remove]</div></div>";

You can add "\n" if you require line-break.

Javascript add method to object

You can make bar a function making it a method.

Foo.bar = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean

Foo.bar = "a place";

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.

For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.

Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.

Remove xticks in a matplotlib plot?

Here is an alternative solution that I found on the matplotlib mailing list:

import matplotlib.pylab as plt

x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none') 

graph

Make child visible outside an overflow:hidden parent

This is an old question but encountered it myself.

I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")

If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.

If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.

Here is a crappy example just post into a html file to view.

<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
    <div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
        <div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
    </div>
</div>

Can I get "&&" or "-and" to work in PowerShell?

Just install PowerShell 7 (go here, and scroll and expand the assets section). This release has implemented the pipeline chain operators.

Check if a Windows service exists and delete in PowerShell

There's no harm in using the right tool for the job, I find running (from Powershell)

sc.exe \\server delete "MyService" 

the most reliable method that does not have many dependencies.

How to check if the URL contains a given string?

It will be a good practice if you convert your string to lower or uppercase as indexof() method is case sensitive.

This will be if your search isn't case sensitive you can simply use indexOf() method without converting the orignal string to lowercase or uppercase:

var string= location.href;
var convertedString= string.toLowerCase();

if(convertedString.indexOf('franky') != -1)
{
    alert("url has franky");
}
else
{
    alert("url has no franky");
}

Switching the order of block elements with CSS

Hows this for low tech...

put the ad at the top and bottom and use media queries to display:none as appropriate.

If the ad wasn't too big, it wouldn't add too much size to the download, you could even customise where the ad sent you for iPhone/pc.

C++ deprecated conversion from string constant to 'char*'

I solve this problem by adding this macro in the beginning of the code, somewhere. Or add it in <iostream>, hehe.

 #define C_TEXT( text ) ((char*)std::string( text ).c_str())

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to get MAC address of your machine using a C program?

  1. On Linux, use the service of "Network Manager" over the DBus.

  2. There is also good'ol shell program which can be invoke and the result grabbed (use an exec function under C):

$ /sbin/ifconfig | grep HWaddr

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Today represents the current system date with the time part set to 00:00:00

and

DateTime.Now represents the current system date and time

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

You can not add ON DELETE CASCADE to an already existing constraint. You will have to drop and re-create the constraint. The documentation shows that the MODIFY CONSTRAINT clause can only modify the state of a constraint (i-e: ENABLED/DISABLED...).

hexadecimal string to byte array in python

Assuming you have a byte string like so

"\x12\x45\x00\xAB"

and you know the amount of bytes and their type you can also use this approach

import struct

bytes = '\x12\x45\x00\xAB'
val = struct.unpack('<BBH', bytes)

#val = (18, 69, 43776)

As I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.

0x12 = 18

0x45 = 69

0xAB00 = 43776

B is equal to one byte (8 bit) unsigned

H is equal to two bytes (16 bit) unsigned

More available characters and byte sizes can be found here

The advantages are..

You can specify more than one byte and the endian of the values

Disadvantages..

You really need to know the type and length of data your dealing with

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

Editable 'Select' element

_x000D_
_x000D_
A bit more universal <select name="env" style="width: 200px; position:absolute;" onchange="this.nextElementSibling.value=this.value">_x000D_
    <option></option>_x000D_
    <option>1</option>_x000D_
    <option>2</option>_x000D_
    <option>3</option> _x000D_
</select>_x000D_
<input style="width: 178px; margin-top: 1px; border: none; position:relative; left:1px; margin-right: 25px;" value="123456789012345678901234"/>layout ...
_x000D_
_x000D_
_x000D_

C# equivalent of C++ vector, with contiguous memory?

First of all, stay away from Arraylist or Hashtable. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.

Now, what you are looking for is the List<T> class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.

Most efficient way to reverse a numpy array

Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use

np.flipud(your_array) 

if it is a 1d array (column array).

With matrizes do

fliplr(matrix)

if you want to reverse rows and flipud(matrix) if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.

Killing a process using Java

Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().

import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);

And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:

Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
    Field f = proc.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    int pid = f.get(proc);
}

GIT clone repo across local file system in windows

After clone, for me push wasn't working.

Solution: Where repo is cloned open .git folder and config file.

For remote origin url set value:

[remote "origin"]
    url = file:///C:/Documentation/git_server/kurmisoftware

What does %~dp0 mean, and how does it work?

The variable %0 in a batch script is set to the name of the executing batch file.

The ~dp special syntax between the % and the 0 basically says to expand the variable %0 to show the drive letter and path, which gives you the current directory containing the batch file!

Help = Link

Chrome, Javascript, window.open in new tab

Clear mini-solution $('<form action="http://samedomainurl.com/" target="_blank"></form>').submit()

Check a radio button with javascript

Today, in the year 2016, it is save to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):

document.querySelector("input[name=main-categories]:checked").value

How to delete selected text in the vi editor

When using a terminal like PuTTY, usually mouse clicks and selections are not transmitted to the remote system. So, vi has no idea that you just selected some text. (There are exceptions to this, but in general mouse actions aren't transmitted.)

To delete multiple lines in vi, use something like 5dd to delete 5 lines.

If you're not using Vim, I would strongly recommend doing so. You can use visual selection, where you press V to start a visual block, move the cursor to the other end, and press d to delete (or any other editing command, such as y to copy).

React Native Change Default iOS Simulator Device

As answered by Ian L, I also use NPM to manage my scripts.

Example:

_x000D_
_x000D_
{_x000D_
  "scripts": {_x000D_
    "ios": "react-native run-ios --simulator=\"iPad Air 2\"",_x000D_
    "devices": "xcrun simctl list devices"_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

This way, I can quickly get what I need:

  1. List all devices: npm run devices
  2. Run the default simulator: npm run ios

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

How to get character array from a string?

simple answer:

_x000D_
_x000D_
let str = 'this is string, length is >26';_x000D_
_x000D_
console.log([...str]);
_x000D_
_x000D_
_x000D_

java.lang.ClassCastException

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;
}

How do I access refs of a child component in the parent component

First of all, I want to say a big screw you to React for designing an interface that doesn't let us access 'ref' on the instantiated child components, in whatever context, without having to use the 'forwardRef' "hack" (which technically only works on specific/single instances, and not dynamic collections). Thanks for making our lives harder with your proprietary hook crap and now forcing us to use functional components (which can't inherit base functionality without more hacks). Why did JavaScript add class support to begin with? Right...

With that said, here is how I solve the problem for dynamic components:

On the parent, dynamically create references to the child components, for example:

class Form extends Component {
    fieldRefs: [];

    componentWillMount = () => {
        this.fieldRefs = [];
        for(let f of this.props.children) {
            if (f && f.type.name == 'FormField') {
                f.ref = createRef();
                this.fieldRefs.push(f);
            }
        }
    }

    public getFields = () => {
        let data = {};

        for(let r of this.fieldRefs) {
            let f = r.ref.current;
            data[f.props.id] = f.field.current.value;
        }

        return data;
    }
}

The Child component (ie <FormField />) implements it's own 'field' ref, to be referred to from the parent:

class FormField extends Component {
    field = createRef();
    
    render() {
        return(
            <input ref={this.field} type={type} />
        );
    }
}

Then in your main page, "Parent Parent" component, you can get the field values from the reference with:

class Page extends Component {
    form = createRef();

    onSubmit = () => {
        let fields = this.form.current.getFields();
    }

    render() {
        return (
            <Form ref={this.form}>
                <FormField id="email" type="email" autoComplete="email" label="E-mail" />
                <FormField id="password" type="password" autoComplete="password" label="Password" />

                <div class="button" onClick={this.onSubmit}>Submit</div>
            </Form>
        );
    }
}

I implemented this because I wanted to encapsulate all generic form functionality from a main <Form /> component, and the only way to be able to have the main client/page component set and style its own inner components was to use child components (ie. <FormField /> items within the parent <Form />, which is inside some other <Page /> component).

So, while some might consider this a hack, it's just as hackey as React's attempts to block the actual 'ref' from any parent, which I think is a ridiculous design, however they want to rationalize it.

Also wtf SO. It's 2021 and we still don't have get proper code-editing tools in your editor. Ffs.

How to pass the password to su/sudo/ssh without overriding the TTY?

When there's no better choice (as suggested by others), then man socat can help:

   (sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) |
   socat - EXEC:'ssh -l user server',pty,setsid,ctty

          EXEC’utes an ssh session to server. Uses a pty for communication
          between socat and ssh, makes it ssh’s  controlling  tty  (ctty),
          and makes this pty the owner of a new process group (setsid), so
          ssh accepts the password from socat.

All of the pty,setsid,ctty complexity is necessary and, while you might not need to sleep as long, you will need to sleep. The echo=0 option is worth a look too, as is passing the remote command on ssh's command line.

How to combine date from one field with time from another field - MS SQL Server

simply concatenate both , but cast them first as below

select cast(concat(Cast(DateField as varchar), ' ', Cast(TimeField as varchar)) as datetime) as DateWithTime from TableName;

SQL Greater than, Equal to AND Less Than

declare @starttime datetime = '2012-03-07 22:58:00'

SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60

Reverse of JSON.stringify?

You need to JSON.parse() the string.

_x000D_
_x000D_
var str = '{"hello":"world"}';
try {
  var obj = JSON.parse(str); // this is how you parse a string into JSON 
  document.body.innerHTML += obj.hello;
} catch (ex) {
  console.error(ex);
}
_x000D_
_x000D_
_x000D_

How do I import/include MATLAB functions?

You have to set the path. See here.

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How to set background color of a View

try to add:

setBackgroundColor(Color.parseColor("#FF0000"));

Installing tkinter on ubuntu 14.04

In Ubuntu 14.04.2 LTS:

  1. Go to Software Center and remove "IDLE(using Python-2.7)".

  2. Install "IDLE(using Python-3.4)".

Try again. This step worked for me.

Show hide fragment in android

Try this:

MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.mapview);
mapFragment.getView().setVisibility(View.GONE);

How can I easily view the contents of a datatable or dataview in the immediate window

To beautify adinas's debugger output I made some simple formattings:

    public void DebugTable(DataTable table)
    {
        Debug.WriteLine("--- DebugTable(" + table.TableName + ") ---");
        int zeilen = table.Rows.Count;
        int spalten = table.Columns.Count;

        // Header
        for (int i = 0; i < table.Columns.Count; i++)
        {
            string s = table.Columns[i].ToString();
            Debug.Write(String.Format("{0,-20} | ", s));
        }
        Debug.Write(Environment.NewLine);
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);

        // Data
        for (int i = 0; i < zeilen; i++)
        {
            DataRow row = table.Rows[i];
            //Debug.WriteLine("{0} {1} ", row[0], row[1]);
            for (int j = 0; j < spalten; j++)
            {
                string s = row[j].ToString();
                if (s.Length > 20) s = s.Substring(0, 17) + "...";
                Debug.Write(String.Format("{0,-20} | ", s));
            }
            Debug.Write(Environment.NewLine);
        }
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);
    }

Best of this solution: You don't need Visual Studio! Here my example output:

SELECT PackKurz, PackName, PackGewicht FROM verpackungen

PackKurz             | PackName             | PackGewicht          | 
---------------------|----------------------|----------------------|-
BB205                | BigBag 205 kg        | 205                  | 
BB300                | BigBag 300 kg        | 300                  | 
BB365                | BigBag 365 kg        | 365                  | 
CO                   | Container, Alteru... |                      | 
EP                   | Palette              |                      | 
IBC                  | Chemikaliengefäß ... |                      | 
lose                 | nicht verpackungs... | 0                    | 
---------------------|----------------------|----------------------|-

Create an array of integers property in Objective-C

You can put this in your .h file for your class and define it as property, in XCode 7:

@property int  (*stuffILike) [10];

Swift add icon/image in UITextField

enter image description here
Another way to set placeholder icon & set padding to TextField.

let userIcon = UIImage(named: "ImageName") 
setPaddingWithImage(image: userIcon, textField: txtUsername)

func setPaddingWithImage(image: UIImage, textField: UITextField){
    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 50))
    imageView.frame = CGRect(x: 13.0, y: 13.0, width: 24.0, height: 24.0)
    //For Setting extra padding other than Icon.
    let seperatorView = UIView(frame: CGRect(x: 50, y: 0, width: 10, height: 50))
    seperatorview.backgroundColor = UIColor(red: 80/255, green: 89/255, blue: 94/255, alpha: 1)
    view.addSubview(seperatorView)
    textField.leftViewMode = .always
    view.addSubview(imageView)
    view.backgroundColor = .darkGray
    textField.leftViewMode = UITextFieldViewMode.always
    textField.leftView = view
}

Select 2 columns in one and combine them

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

Error: Can't set headers after they are sent to the client

error find by itself after a RND :

1) my error code :

return res.sendStatus(200).json({ data: result });

2) my success code

return res.status(200).json({ data: result });

the difference is that i used sendStatus() instead of status().

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

Autocompletion in Vim

You can start from built-in omnifunc setting.

Just put:

filetype plugin on
au FileType php setl ofu=phpcomplete#CompletePHP
au FileType ruby,eruby setl ofu=rubycomplete#Complete
au FileType html,xhtml setl ofu=htmlcomplete#CompleteTags
au FileType c setl ofu=ccomplete#CompleteCpp
au FileType css setl ofu=csscomplete#CompleteCSS

on the bottom of your .vimrc, then type <Ctrl-X><Ctrl-O> in insert mode.

I always rely on this CSS completion.

ToList()-- does it create a new list?

The accepted answer correctly addresses the OP's question based on his example. However, it only applies when ToList is applied to a concrete collection; it does not hold when the elements of the source sequence have yet to be instantiated (due to deferred execution). In case of the latter, you might get a new set of items each time you call ToList (or enumerate the sequence).

Here is an adaptation of the OP's code to demonstrate this behaviour:

public static void RunChangeList()
{
    var objs = Enumerable.Range(0, 10).Select(_ => new MyObject() { SimpleInt = 0 });
    var whatInt = ChangeToList(objs);   // whatInt gets 0
}

public static int ChangeToList(IEnumerable<MyObject> objects)
{
    var objectList = objects.ToList();
    objectList.First().SimpleInt = 5;
    return objects.First().SimpleInt;
}

Whilst the above code may appear contrived, this behaviour can appear as a subtle bug in other scenarios. See my other example for a situation where it causes tasks to get spawned repeatedly.

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

Which MySQL data type to use for storing boolean values

After reading the answers here I decided to use bit(1) and yes, it is somehow better in space/time, BUT after a while I changed my mind and I will never use it again. It complicated my development a lot, when using prepared statements, libraries etc (php).

Since then, I always use tinyint(1), seems good enough.

Getting started with Haskell

These are my favorite

Haskell: Functional Programming with Types

Joeri van Eekelen, et al. | Wikibooks
       Published in 2012, 597 pages

Real World Haskell

   B. O'Sullivan, J. Goerzen, D. Stewart | OReilly Media, Inc.
   Published in 2008, 710 pages

In Java what is the syntax for commenting out multiple lines?

As @kgrad says, /* */ does not nest and can cause errors. A better answer is:

// LINE *of code* I WANT COMMENTED 
// LINE *of code* I WANT COMMENTED 
// LINE *of code* I WANT COMMENTED 

Most IDEs have a single keyboard command for doing/undoing this, so there's really no reason to use the other style any more. For example: in eclipse, select the block of text and hit Ctrl+/
To undo that type of comment, use Ctrl+\

UPDATE: The Sun coding convention says that this style should not be used for block text comments:

// Using the slash-slash
// style of comment as shown
// in this paragraph of non-code text is 
// against the coding convention.

but // can be used 3 other ways:

  1. A single line comment
  2. A comment at the end of a line of code
  3. Commenting out a block of code

How to copy directories with spaces in the name

There's no need to add space before closing quote if path doesn't contain trailing backslash, so following command should work:

robocopy "C:\Source Path" "C:\Destination Path" /option1 /option2...

But, following will not work:

robocopy "C:\Source Path\" "C:\Destination Path\" /option1 /option2...

This is due to the escaping issue that is described here:

The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the closing quote " at the end of the line will be escaped \".

MySQL my.ini location

I met with the same problem when I did MSI install of MySQL and there were no my-medium.ini files too when I tried the above steps. Only installing the ZIP file of MySQL helped me. So, I suggest you to uninstall the MSI installed folder and reinstall using the ZIP file.

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

How can I rename a single column in a table at select?

If, like me, you are doing this for a column which then goes through COALESCE / array_to_json / ARRAY_AGG / row_to_json (PostgreSQL) and want to keep the capitals in the column name, double quote the column name, like so:

SELECT a.price AS "myFirstPrice", b.price AS "mySecondPrice"

Without the quotes (and when using those functions), my column names in camelCase would lose the capital letters.

Convert pyQt UI to python

Quickest way to convert .ui to .py is from terminal:

pyuic4 -x input.ui -o output.py

Make sure you have pyqt4-dev-tools installed.

How to get a random value from dictionary?

I am assuming that you are making a quiz kind of application. For this kind of application I have written a function which is as follows:

def shuffle(q):
"""
The input of the function will 
be the dictionary of the question
and answers. The output will
be a random question with answer
"""
selected_keys = []
i = 0
while i < len(q):
    current_selection = random.choice(q.keys())
    if current_selection not in selected_keys:
        selected_keys.append(current_selection)
        i = i+1
        print(current_selection+'? '+str(q[current_selection]))

If I will give the input of questions = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'} and call the function shuffle(questions) Then the output will be as follows:

VENEZUELA? CARACAS
CANADA? TORONTO

You can extend this further more by shuffling the options also

Any way to exit bash script, but not quitting the terminal

if your terminal emulator doesn't have -hold you can sanitize a sourced script and hold the terminal with:

#!/bin/sh
sed "s/exit/return/g" script >/tmp/script
. /tmp/script
read

otherwise you can use $TERM -hold -e script

comma separated string of selected values in mysql

Use group_concat() function of mysql.

SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;

It'll give you concatenated string like :

5,6,9,10,12,14,15,17,18,779 

How to append elements at the end of ArrayList in Java?

I know this is an old question, but I wanted to make an answer of my own. here is another way to do this if you "really" want to add to the end of the list instead of using list.add(str) you can do it this way, but I don't recommend.

 String[] items = new String[]{"Hello", "World"};
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, items);
        int endOfList = list.size();
        list.add(endOfList, "This goes end of list");
        System.out.println(Collections.singletonList(list));

this is the 'Compact' way of adding the item to the end of list. here is a safer way to do this, with null checking and more.

String[] items = new String[]{"Hello", "World"};
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, items);
        addEndOfList(list, "Safer way");
        System.out.println(Collections.singletonList(list));

 private static void addEndOfList(List<String> list, String item){
            try{
                list.add(getEndOfList(list), item);
            } catch (IndexOutOfBoundsException e){
                System.out.println(e.toString());
            }
        }

   private static int getEndOfList(List<String> list){
        if(list != null) {
            return list.size();
        }
        return -1;
    }

Heres another way to add items to the end of list, happy coding :)

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

What is the default root pasword for MySQL 5.7

To do it in non interactive mode (from a script):

systemctl start mysqld
MYSQL_ROOT_TMP_PSW=$(grep 'temporary password' $logpath/mysqld.log |sed "s|.*: ||")

## POPULATE SCHEMAS WITH ROOT USER
/usr/bin/mysql --connect-expired-password -u root -p${MYSQL_ROOT_TMP_PSW} < "$mysql_init_script"

Here's the head of the init script

SET GLOBAL validate_password_policy=LOW;
FLUSH privileges;

SET PASSWORD = PASSWORD('MYSQL_ROOT_PSW');
FLUSH privileges;

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
FLUSH privileges;

...

Then restart the service systemctl restart mysqld

Camera access through browser

In iOS6, Apple supports this via the <input type="file"> tag. I couldn't find a useful link in Apple's developer documentation, but there's an example here.

It looks like overlays and more advanced functionality is not yet available, but this should work for a lot of use cases.

EDIT: The w3c has a spec that iOS6 Safari seems to implement a subset of. The capture attribute is notably missing.

using favicon with css

You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.

If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.

ASP.NET MVC: What is the purpose of @section?

@section is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).

You might find Scott Gu's write up on this very interesting.

Edit: Based on additional question clarification

The @RenderSection syntax goes into the Shared View, such as:

<div id="sidebar">
    @RenderSection("Sidebar", required: false)
</div>

This would then be placed in your view with @Section syntax:

@section Sidebar{
    <!-- Content Here -->
}

In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.

Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.

@{
    ViewBag.Title = "Corporate Homepage";
    ViewBag.BodyID = "page-home";
    Layout = "~/Views/Shared/_Layout2.cshtml";
}

There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.

How do you find what version of libstdc++ library is installed on your linux machine?

What exactly do you want to know?

The shared library soname? That's part of the filename, libstdc++.so.6, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname.

The minor revision number? You should be able to get that by simply checking what the symlink points to:

$ ls -l  /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16

That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6 version, which corresponds to the GLIBCXX_3.4.16 symbol versions.

Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++ and libstdc++.so you can get that from:

$ g++ -dumpversion
4.6.3

Or, on most distros, you can just ask the package manager. On my Fedora host that's

$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686

As other answers have said, you can map releases to library versions by checking the ABI docs

How to minify php page html output?

I have a GitHub gist contains PHP functions to minify HTML, CSS and JS files → https://gist.github.com/taufik-nurrohman/d7b310dea3b33e4732c0

Here’s how to minify the HTML output on the fly with output buffer:

<?php

include 'path/to/php-html-css-js-minifier.php';

ob_start('minify_html');

?>

<!-- HTML code goes here ... -->

<?php echo ob_get_clean(); ?>

Radio/checkbox alignment in HTML/CSS

The following works in Firefox and Opera (sorry, I do not have access to other browsers at the moment):

<div class="form-field">
    <input id="option1" type="radio" name="opt"/>
    <label for="option1">Option 1</label>
</div>

The CSS:

.form-field * {
    vertical-align: middle;
}

How to get directory size in PHP

Regarding Johnathan Sampson's Linux example, watch out when you are doing an intval on the outcome of the "du" function, if the size is >2GB, it will keep showing 2GB.

Replace:

$totalSize = intval(fgets($io, 80));

by:

strtok(fgets($io, 80), " ");

supposed your "du" function returns the size separated with space followed by the directory/file name.

Jump to function definition in vim

g* does a decent job without ctags being set up.

That is, type g,* (or just * - see below) to search for the word under the cursor (in this case, the function name). Then press n to go to the next (or Shift-n for previous) occurrence.

It doesn't jump directly to the definition, given that this command just searches for the word under the cursor, but if you don't want to deal with setting up ctags at the moment, you can at least save yourself from having to re-type the function name to search for its definition.

--Edit-- Although I've been using g* for a long time, I've recently discovered two shortcuts for these shortcuts!

(a) * will jump to the next occurrence of the word under the cursor. (No need to type the g, the 'goto' command in vi).

(b) # goes to the previous occurrence, in similar fashion.

N and n still work, but '#' is often very useful to start the search initially in the reverse direction, for example, when looking for the declaration of a variable under the cursor.

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

Sublime Text 3, convert spaces to tabs

On the bottom right-hand corner of your Sublime Text window, you'll see an indentation indicator that looks a lot like this:

Indentation options menu

Clicking it will open a menu with options to adjust your indentation preferences, and more importantly, Convert Indentation to Tabs/Spaces.

enter image description here

The same menu is listed under View -> Indentation.

How to properly create an SVN tag from trunk?

Try this. It works for me:

mkdir <repos>/tags/Release1.0
svn commit <repos>/tags/Release1.0 
svn copy <repos>/trunk/* <repos>/tag/Release1.0
svn commit <repos/tags/Release1.0 -m "Tagging Release1.0"