Programs & Examples On #Exponential distribution

Anything related to the exponential probability distribution, i.e. a continuous probability distribution whose probability density function is a one-sided decreasing exponential function.

Configure apache to listen on port other than 80

If you are using Apache on Windows:

  1. Check the name of the Apache service with Win+R+services.msc+Enter (if it's not ApacheX.Y, it should have the name of the software you are using with apache, e.g.: "wampapache64");
  2. Start a command prompt as Administrator (using Win+R+cmd+Enter is not enough);
  3. Change to Apache's directory, e.g.: cd c:\wamp\bin\apache\apache2.4.9\bin;
  4. Check if the config file is OK with: httpd.exe -n "YourServiceName" -t (replace the service name by the one you found on step 1);
  5. Make sure that the service is stopped: httpd.exe -k stop -n "YourServiceName"
  6. Start it with: httpd.exe -k start -n "YourServiceName"
  7. If it starts alright, the problem is no longer there, but if you get:

    AH00072: make_sock: could not bind to address IP:PORT_NUMBER

    AH00451: no listening sockets available, shutting down

    If the port number is not the one you wanted to use, then open the Apache config file (e.g. C:\wamp\bin\apache\apache2.4.9\conf\httpd.conf open with a code editor or wordpad, but not notepad - it does not read new lines properly) and replace the number on the line that starts with Listen with the number of the port you want, save it and repeat step 6. If it is the one you wanted to use, then continue:

  8. Check the PID of the process that is using that port with Win+R+resmon+Enter, click on Network tab and then on Ports subtab;
  9. Kill it with: taskkill /pid NUMBER /f (/f forces it);
  10. Recheck resmon to confirm that the port is free now and repeat step 6.

This ensures that Apache's service was started properly, the configuration on virtual hosts config file as sarul mentioned (e.g.: C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf) is necessary if you are setting your files path in there and changing the port as well. If you change it again, remember to restart the service: httpd.exe -k restart -n "YourServiceName".

How to parse JSON to receive a Date object in JavaScript?

//
// formats a .net date into a javascript compatible date
//
function FormatJsonDate(jsonDt) 
{              
    var MIN_DATE = -62135578800000; // const

    var date = new Date(parseInt(jsonDt.substr(6, jsonDt.length-8)));                                                       
    return date.toString() == new Date(MIN_DATE).toString() ? "" : (date.getMonth() + 1) + "\\" + date.getDate() + "\\" + date.getFullYear(); 
}

Find mouse position relative to element

Based on @Spider's solution, my non JQuery version is this:

// Get the container element's bounding box
var sides = document.getElementById("container").getBoundingClientRect();

// Apply the mouse event listener
document.getElementById("canvas").onmousemove = (e) => {
  // Here 'self' is simply the current window's context
  var x = (e.clientX - sides.left) + self.pageXOffset;
  var y = (e.clientY - sides.top) + self.pageYOffset;
}

This works both with scrolling and zooming (in which case sometimes it returns floats).

AngularJS - Access to child scope

One possible workaround is inject the child controller in the parent controller using a init function.

Possible implementation:

<div ng-controller="ParentController as parentCtrl">
   ...

    <div ng-controller="ChildController as childCtrl" 
         ng-init="ChildCtrl.init()">
       ...
    </div>
</div>

Where in ChildController you have :

app.controller('ChildController',
    ['$scope', '$rootScope', function ($scope, $rootScope) {
    this.init = function() {
         $scope.parentCtrl.childCtrl = $scope.childCtrl;
         $scope.childCtrl.test = 'aaaa';
    };

}])

So now in the ParentController you can use :

app.controller('ParentController',
    ['$scope', '$rootScope', 'service', function ($scope, $rootScope, service) {

    this.save = function() {
        service.save({
            a:  $scope.parentCtrl.ChildCtrl.test
        });
     };

}])

Important:
To work properly you have to use the directive ng-controller and rename each controller using as like i did in the html eg.

Tips:
Use the chrome plugin ng-inspector during the process. It's going to help you to understand the tree.

Retrieve specific commit from a remote Git repository

If the requested commit is in the pull requests of the remote repo, you can get it by its ID:

# Add the remote repo path, let's call it 'upstream':
git remote add upstream https://github.com/repo/project.git

# checkout the pull ID, for example ID '60':
git fetch upstream pull/60/head && git checkout FETCH_HEAD

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

To add more information to the correct answer above, after reading an example from Android-er I found you can easily convert your preference activity into a preference fragment. If you have the following activity:

public class MyPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_preference_screen);
    }
}

The only changes you have to make is to create an internal fragment class, move the addPreferencesFromResources() into the fragment, and invoke the fragment from the activity, like this:

public class MyPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.my_preference_screen);
        }
    }
}

There may be other subtleties to making more complex preferences from fragments; if so, I hope someone notes them here.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.

actions.js:

export function addNewComponent() {
  return {
    type: ADD_NEW_COMPONENT,
  };
}

myComponent.js:

import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);

I've forgotten to dispatch the action function with (). So doing this solved my issue.

  useEffect(() => {
    dispatch(refreshAllComponents());
  }, []);

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.

Circle button css

For div tag there is already default property display:block given by browser. For anchor tag there is not display property given by browser. You need to add display property to it. That's why use display:block or display:inline-block. It will work.

_x000D_
_x000D_
.btn {_x000D_
  display:block;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  border-radius: 50%;_x000D_
  border: 1px solid red;_x000D_
  _x000D_
}
_x000D_
<a class="btn" href="#"><i class="ion-ios-arrow-down"></i></a>
_x000D_
_x000D_
_x000D_

Why use pointers?

One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.

Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

Many embedded devices still use this technique.

"Invalid signature file" when attempting to run a .jar

If you're getting this when trying to bind JAR files for a Xamarin.Android bindings project like so:

JARTOXML : warning J2XA006: missing class error was raised while reflecting com.your.class : Invalid signature file digest for Manifest main attributes

Just open the JAR files using Winzip and delete the meta-inf directories. Rebuild - job done

Convert a matrix to a 1 dimensional array

array(A) or array(t(A)) will give you a 1-d array.

What, exactly, is needed for "margin: 0 auto;" to work?

Off the top of my head:

  1. The element must be block-level, e.g. display: block or display: table
  2. The element must not float
  3. The element must not have a fixed or absolute position1

Off the top of other people's heads:

  1. The element must have a width that is not auto2

Note that all of these conditions must be true of the element being centered for it to work.


1 There is one exception to this: if your fixed or absolutely positioned element has left: 0; right: 0, it will center with auto margins.

2 Technically, margin: 0 auto does work with an auto width, but the auto width takes precedence over the auto margins, and the auto margins are zeroed out as a result, making it seem as though they "don't work".

javascript if number greater than number

Do this.

var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);

How to clear basic authentication details in chrome

Things changed a lot since the answer was posted. Now you will see a small key symbol on the right hand side of the URL bar.
Click the symbol and it will take you directly to the saved password dialog where you can remove the password.

Successfully tested in Chrome 49

Regex for empty string or white space

If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():

"    your string contents  ".trim();

// => "your string contents"

How to access property of anonymous type in C#?

You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

So something like:

foreach(object o in nodes)
{
    Type t = o.GetType();

    PropertyInfo[] pi = t.GetProperties(); 

    foreach (PropertyInfo p in pi)
    {
        if (p.Name=="Checked" && !(bool)p.GetValue(o))
            Console.WriteLine("awesome!");
    }
}

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

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

How can I set the color of a selected row in DataGrid

Some of the reason which I experienced the row selected event not working

  1. Style is set up for DataGridCell
  2. Using Templated columns
  3. Trigger is set up at the DataGridRow

This is what helped me. Setting the Style for DataGridCell

<Style TargetType="{x:Type DataGridCell}">
  <Style.Triggers>
    <Trigger Property="IsSelected" Value="True">
      <Setter Property="Background" Value="Green"/>
      <Setter Property="Foreground" Value="White"/>
    </Trigger>
  </Style.Triggers> 
</Style>

And since I was using a template column with a label inside, I bound the Foreground property to the container Foreground using RelativeSource binding:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Label Content="{Binding CategoryName,
                 Mode=TwoWay,
                 UpdateSourceTrigger=LostFocus}"
             Foreground="{Binding Foreground,
                 RelativeSource={RelativeSource Mode=FindAncestor,
                     AncestorLevel=1, 
                     AncestorType={x:Type DataGridCell}}}"
             Width="150"/>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

How can I create a correlation matrix in R?

An example,

 d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
cor(d) # get correlations (returns matrix)

Get filename from input [type='file'] using jQuery

Getting the file name is fairly easy. As matsko points out, you cannot get the full file path on the user's computer for security reasons.

var file = $('#image_file')[0].files[0]
if (file){
  console.log(file.name);
}

Detecting EOF in C

Another issue is that you're reading with scanf("%f", &input); only. If the user types something that can't be interpreted as a C floating-point number, like "pi", the scanf() call will not assign anything to input, and won't progress from there. This means it would attempt to keep reading "pi", and failing.

Given the change to while(!feof(stdin)) which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value of input and printing the prompt, but the program would never process any new input.

scanf() returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something like char string[100];scanf("%99s", string);. This will remove the next string from the input stream (up to 99 characters, anyway - the extra char is for the null terminator on the string).

You know, this is reminding me of all the reasons I hate scanf(), and why I use fgets() instead and then maybe parse it using sscanf().

Display all post meta keys and meta values of the same post ID in wordpress

I use it in form of a meta box. Here is a function that dumps values of all the meta data for post.

    function dump_all_meta(){

        echo "<h3>All Post Meta</h3>";

        // Get all the data.
        $getPostCustom=get_post_custom();


        foreach( $getPostCustom as $name=>$value ) {

            echo "<strong>".$name."</strong>"."  =>  ";

            foreach($getPostCustom as $name=>$value) {

        echo "<strong>".$name."</strong>"."  =>  ";

        foreach($value as $nameAr=>$valueAr) {
                echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                echo $nameAr."  =>  ";
                echo var_dump($valueAr);
        }

        echo "<br /><br />";

        }
    } // Callback funtion ended.

Hope it helps. You can use it inside a meta box or at the front-end.

Is it possible to program iPhone in C++

Although Objective-C does indeed appear to be "insane" initially, I encourage you to stick with it. Once you have an "a-ha" moment, suddenly it all starts to make sense. For me it took about 2 weeks of focused Objective-C concentration to really understand the Cocoa frameworks, the language, and how it all fits together. But once I really "got" it, it was very very exciting.

It sounds cliché, but it's true. Stick it out.

Of course, if you're bringing in C++ libraries or existing C++ code, you can use those modules with Objective-C/Objective-C++.

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local, which is executed about last in init phase.

how to Call super constructor in Lombok

Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:

@AllArgsConstructor 
public class Parent {   
     private String a; 
}

public class Child extends Parent {
  private String b;

  @Builder
  public Child(String a, String b){
    super(a);
    this.b = b;   
  } 
} 

As a result you can then use the generated builder like this:

Child.builder().a("testA").b("testB").build(); 

The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.

I also found this works nicely with Spring Data JPA.

How do I add an active class to a Link from React Router?

One of the way you can use it

When you are using the Functional component then follow the instruction here.

  • add a variable in your component
  • create an event change browser URL change/or other change
  • re-assign the current path (URL)
  • use javascript match function and set active or others

Use the above code here.

import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';

const NavItems = () => {
    let pathname = window.location.pathname;
    useEffect(() => {
        pathname = window.location.pathname;
    }, [window.location.pathname]);

    return (
        <>
            <li className="px-4">
                <Link to="/home" className={`${pathname.match('/home') ? 'link-active' : ''}`}>Home</Link>
            </li>
            <li className="px-4">
                <Link to="/about-me" className={`${pathname.match('/about-me') ? 'link-active' : ''}`}>About-me</Link>
            </li>
            <li className="px-4">
                <Link to="/skill" className={`${pathname.match('/skill') ? 'link-active' : ''}`}>Skill</Link>
            </li>
            <li className="px-4">
                <Link to="/protfolio" className={`${pathname.match('/protfolio') ? 'link-active' : ''}`}>Protfolio</Link>
            </li>
            <li className="pl-4">
                <Link to="/contact" className={`${pathname.match('/contact') ? 'link-active' : ''}`}>Contact</Link>
            </li>
        </>
    );
}

export default NavItems;

--- Thanks ---

Multiple "order by" in LINQ

Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies 
             orderby row.Category, row.Name
             select row;

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies 
             orderby row.Category descending, row.Name
             select row;

java - path to trustStore - set property doesn't work?

Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.

System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");

should be:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Show Hide div if, if statement is true

You can use css or js for hiding a div. In else statement you can write it as:

else{
?>
<style type="text/css">#divId{
display:none;
}</style>
<?php
}

Or in jQuery

else{
?>
<script type="text/javascript">$('#divId').hide()</script>
<?php
}

Or in javascript

else{
?>
<script type="text/javascript">document.getElementById('divId').style.display = 'none';</script>
<?php
}

JQuery create new select option

A really simple way to do this...

// create the option
var opt = $("<option>").val("myvalue").text("my text");

//append option to the select element
$(#my-select).append(opt);

This could be done in lots of ways, even in a single line if really you want to.

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

What does the Excel range.Rows property really do?

Since the .Rows result is marked as consisting of rows, you can "For Each" it to deal with each row individually, like this:

Function Attendance(rng As Range) As Long
Attendance = 0
For Each rRow In rng.Rows
    If WorksheetFunction.Sum(rRow) > 0 Then
        Attendance = Attendance + 1
    End If
Next
End Function

I use this to check attendance in any of a few categories (different columns) for a list of people (different rows).

(And of course you could use .Columns to do a "For Each" over the columns in the range.)

Get source JARs from Maven repository

In eclipse - click on the project then:

enter image description here.

How to update nested state properties in React

This is clearly not the right or best way to do, however it is cleaner to my view:

this.state.hugeNestedObject = hugeNestedObject; 
this.state.anotherHugeNestedObject = anotherHugeNestedObject; 

this.setState({})

However, React itself should iterate thought nested objects and update state and DOM accordingly which is not there yet.

How do I create a new class in IntelliJ without using the mouse?

With Esc and Command + 1 you can navigate between project view and editor area - back and forward, in this way you can select the folder/location you need

With Control +Option + N you can trigger New file menu and select whatever you need, class, interface, file, etc. This works in editor as well in project view and it relates to the current selected location

// please consider that this is working with standard key mapping

Redeploy alternatives to JRebel

DCEVM supports enhanced class redefinitions and is available for current JDK7 and JDK8.

https://github.com/dcevm/dcevm/releases

HotswapAgent is an free JRebel alternative and supports DCEVM in various Frameworks.

http://hotswapagent.org/

How can I find the product GUID of an installed MSI setup?

For upgrade code retrieval: How can I find the Upgrade Code for an installed MSI file?


Short Version

The information below has grown considerably over time and may have become a little too elaborate. How to get product codes quickly? (four approaches):

1 - Use the Powershell "one-liner"

Scroll down for screenshot and step-by-step. Disclaimer also below - minor or moderate risks depending on who you ask. Works OK for me. Any self-repair triggered by this option should generally be possible to cancel. The package integrity checks triggered does add some event log "noise" though. Note! IdentifyingNumber is the ProductCode (WMI peculiarity).

get-wmiobject Win32_Product | Sort-Object -Property Name |Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

Quick start of Powershell: hold Windows key, tap R, type in "powershell" and press Enter

2 - Use VBScript (script on github.com)

Described below under "Alternative Tools" (section 3). This option may be safer than Powershell for reasons explained in detail below. In essence it is (much) faster and not capable of triggering MSI self-repair since it does not go through WMI (it accesses the MSI COM API directly - at blistering speed). However, it is more involved than the Powershell option (several lines of code).

3 - Registry Lookup

Some swear by looking things up in the registry. Not my recommended approach - I like going through proper APIs (or in other words: OS function calls). There are always weird exceptions accounted for only by the internals of the API-implementation:

  • HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
  • HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
  • HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall

4 - Original MSI File / WiX Source

You can find the Product Code in the Property table of any MSI file (and any other property as well). However, the GUID could conceivably (rarely) be overridden by a transform applied at install time and hence not match the GUID the product is registered under (approach 1 and 2 above will report the real product code - that is registered with Windows - in such rare scenarios).

You need a tool to view MSI files. See towards the bottom of the following answer for a list of free tools you can download (or see quick option below): How can I compare the content of two (or more) MSI files?

UPDATE: For convenience and need for speed :-), download SuperOrca without delay and fuss from this direct-download hotlink - the tool is good enough to get the job done - install, open MSI and go straight to the Property table and find the ProductCode row (please always virus check a direct-download hotlink - obviously - you can use virustotal.com to do so - online scan utilizing dozens of anti-virus and malware suites to scan what you upload).

Orca is Microsoft's own tool, it is installed with Visual Studio and the Windows SDK. Try searching for Orca-x86_en-us.msi - under Program Files (x86) and install the MSI if found.

  • Current path: C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x86
  • Change version numbers as appropriate

And below you will find the original answer which "organically grew" into a lot of detail.

Maybe see "Uninstall MSI Packages" section below if this is the task you need to perform.


Retrieve Product Codes

UPDATE: If you also need the upgrade code, check this answer: How can I find the Upgrade Code for an installed MSI file? (retrieves associated product codes, upgrade codes & product names in a table output - similar to the one below).

  • Can't use PowerShell? See "Alternative Tools" section below.
  • Looking to uninstall? See "Uninstall MSI packages" section below.

Fire up Powershell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK) and run the command below to get a list of installed MSI package product codes along with the local cache package path and the product name (maximize the PowerShell window to avoid truncated names).

Before running this command line, please read the disclaimer below (nothing dangerous, just some potential nuisances). Section 3 under "Alternative Tools" shows an alternative non-WMI way to get the same information using VBScript. If you are trying to uninstall a package there is a section below with some sample msiexec.exe command lines:

get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

The output should be similar to this:

enter image description here

Note! For some strange reason the "ProductCode" is referred to as "IdentifyingNumber" in WMI. So in other words - in the picture above the IdentifyingNumber is the ProductCode.

If you need to run this query remotely against lots of remote computer, see "Retrieve Product Codes From A Remote Computer" section below.

DISCLAIMER (important, please read before running the command!): Due to strange Microsoft design, any WMI call to Win32_Product (like the PowerShell command below) will trigger a validation of the package estate. Besides being quite slow, this can in rare cases trigger an MSI self-repair. This can be a small package or something huge - like Visual Studio. In most cases this does not happen - but there is a risk. Don't run this command right before an important meeting - it is not ever dangerous (it is read-only), but it might lead to a long repair in very rare cases (I think you can cancel the self-repair as well - unless actively prevented by the package in question, but it will restart if you call Win32_Product again and this will persist until you let the self-repair finish - sometimes it might continue even if you do let it finish: How can I determine what causes repeated Windows Installer self-repair?).

And just for the record: some people report their event logs filling up with MsiInstaller EventID 1035 entries (see code chief's answer) - apparently caused by WMI queries to the Win32_Product class (personally I have never seen this). This is not directly related to the Powershell command suggested above, it is in context of general use of the WIM class Win32_Product.

You can also get the output in list form (instead of table):

get-wmiobject -class Win32_Product

In this case the output is similar to this:

enter image description here


Retrieve Product Codes From A Remote Computer

In theory you should just be able to specify a remote computer name as part of the command itself. Here is the same command as above set up to run on the machine "RemoteMachine" (-ComputerName RemoteMachine section added):

get-wmiobject Win32_Product -ComputerName RemoteMachine | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

This might work if you are running with domain admin rights on a proper domain. In a workgroup environment (small office / home network), you probably have to add user credentials directly to the WMI calls to make it work.

Additionally, remote connections in WMI are affected by (at least) the Windows Firewall, DCOM settings, and User Account Control (UAC) (plus any additional non-Microsoft factors - for instance real firewalls, third party software firewalls, security software of various kinds, etc...). Whether it will work or not depends on your exact setup.

UPDATE: An extensive section on remote WMI running can be found in this answer: How can I find the Upgrade Code for an installed MSI file?. It appears a firewall rule and suppression of the UAC prompt via a registry tweak can make things work in a workgroup network environment. Not recommended changes security-wise, but it worked for me.


Alternative Tools

PowerShell requires the .NET framework to be installed (currently in version 3.5.1 it seems? October, 2017). The actual PowerShell application itself can also be missing from the machine even if .NET is installed. Finally I believe PowerShell can be disabled or locked by various system policies and privileges.

If this is the case, you can try a few other ways to retrieve product codes. My preferred alternative is VBScript - it is fast and flexible (but can also be locked on certain machines, and scripting is always a little more involved than using tools).

  1. Let's start with a built-in Windows WMI tool: wbemtest.exe.
  • Launch wbemtest.exe (Hold down the Windows key, tap R, release the Windows key, type in "wbemtest.exe" and press OK).
  • Click connect and then OK (namespace defaults to root\cimv2), and click "connect" again.
  • Click "Query" and type in this WQL command (SQL flavor): SELECT IdentifyingNumber,Name,Version FROM Win32_Product and click "Use" (or equivalent - the tool will be localized).
  • Sample output screenshot (truncated). Not the nicest formatting, but you can get the data you need. IdentifyingNumber is the MSI product code:

wbemtest.exe

  1. Next, you can try a custom, more full featured WMI tool such as WMIExplorer.exe
  • This is not included in Windows. It is a very good tool, however. Recommended.
  • Check it out at: https://github.com/vinaypamnani/wmie2/releases
  • Launch the tool, click Connect, double click ROOT\CIMV2
  • From the "Query tab", type in the following query SELECT IdentifyingNumber,Name,Version FROM Win32_Product and press Execute.
  • Screenshot skipped, the application requires too much screen real estate.
  1. Finally you can try a VBScript to access information via the MSI automation interface (core feature of Windows - it is unrelated to WMI).
  • Copy the below script and paste into a *.vbs file on your desktop, and try to run it by double clicking. Your desktop must be writable for you, or you can use any other writable location.
  • This is not a great VBScript. Terseness has been preferred over error handling and completeness, but it should do the job with minimum complexity.
  • The output file is created in the folder where you run the script from (folder must be writable). The output file is called msiinfo.csv.
  • Double click the file to open in a spreadsheet application, select comma as delimiter on import - OR - just open the file in Notepad or any text viewer.
  • Opening in a spreadsheet will allow advanced sorting features.
  • This script can easily be adapted to show a significant amount of further details about the MSI installation. A demonstration of this can be found here: how to find out which products are installed - newer product are already installed MSI windows.
' Retrieve all ProductCodes (with ProductName and ProductVersion)
Set fso = CreateObject("Scripting.FileSystemObject")
Set output = fso.CreateTextFile("msiinfo.csv", True, True)
Set installer = CreateObject("WindowsInstaller.Installer")

On Error Resume Next ' we ignore all errors

For Each product In installer.ProductsEx("", "", 7)
   productcode = product.ProductCode
   name = product.InstallProperty("ProductName")
   version=product.InstallProperty("VersionString")
   output.writeline (productcode & ", " & name & ", " & version)
Next

output.Close

I can't think of any further general purpose options to retrieve product codes at the moment, please add if you know of any. Just edit inline rather than adding too many comments please.

You can certainly access this information from within your application by calling the MSI automation interface (COM based) OR the C++ MSI installer functions (Win32 API). Or even use WMI queries from within your application like you do in the samples above using PowerShell, wbemtest.exe or WMIExplorer.exe.


Uninstall MSI Packages

If what you want to do is to uninstall the MSI package you found the product code for, you can do this as follows using an elevated command prompt (search for cmd.exe, right click and run as admin):

Option 1: Basic, interactive uninstall without logging (quick and easy):

msiexec.exe /x {00000000-0000-0000-0000-00000000000C}

Quick Parameter Explanation:

/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall

You can also enable (verbose) logging and run in silent mode if you want to, leading us to option 2:

Option 2: Silent uninstall with verbose logging (better for batch files):

msiexec.exe /x {00000000-0000-0000-0000-00000000000C} /QN /L*V "C:\My.log" REBOOT=ReallySuppress

Quick Parameter Explanation:

/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
/QN = run completely silently
/L*V "C:\My.log"= verbose logging at specified path
REBOOT=ReallySuppress = avoid unexpected, sudden reboot

There is a comprehensive reference for MSI uninstall here (various different ways to uninstall MSI packages): Uninstalling an MSI file from the command line without using msiexec. There is a plethora of different ways to uninstall.

If you are writing a batch file, please have a look at section 3 in the above, linked answer for a few common and standard uninstall command line variants.

And a quick link to msiexec.exe (command line options) (overview of the command line for msiexec.exe from MSDN). And the Technet version as well.


Retrieving other MSI Properties / Information (f.ex Upgrade Code)

UPDATE: please find a new answer on how to find the upgrade code for installed packages instead of manually looking up the code in MSI files. For installed packages this is much more reliable. If the package is not installed, you still need to look in the MSI file (or the source file used to compile the MSI) to find the upgrade code. Leaving in older section below:

If you want to get the UpgradeCode or other MSI properties, you can open the cached installation MSI for the product from the location specified by "LocalPackage" in the image show above (something like: C:\WINDOWS\Installer\50c080ae.msi - it is a hex file name, unique on each system). Then you look in the "Property table" for UpgradeCode (it is possible for the UpgradeCode to be redefined in a transform - to be sure you get the right value you need to retrieve the code programatically from the system - I will provide a script for this shortly. However, the UpgradeCode found in the cached MSI is generally correct).

To open the cached MSI files, use Orca or another packaging tool. Here is a discussion of different tools (any of them will do): What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc. If you don't have such a tool installed, your fastest bet might be to try Super Orca (it is simple to use, but not extensively tested by me).

UPDATE: here is a new answer with information on various free products you can use to view MSI files: How can I compare the content of two (or more) MSI files?

If you have Visual Studio installed, try searching for Orca-x86_en-us.msi - under Program Files (x86) - and install it (this is Microsoft's own, official MSI viewer and editor). Then find Orca in the start menu. Go time in no time :-). Technically Orca is installed as part of Windows SDK (not Visual Studio), but Windows SDK is bundled with the Visual Studio install. If you don't have Visual Studio installed, perhaps you know someone who does? Just have them search for this MSI and send you (it is a tiny half mb file) - should take them seconds. UPDATE: you need several CAB files as well as the MSI - these are found in the same folder where the MSI is found. If not, you can always download the Windows SDK (it is free, but it is big - and everything you install will slow down your PC). I am not sure which part of the SDK installs the Orca MSI. If you do, please just edit and add details here.



Similar topics (for reference and easy access - I should clean this list up):

Nginx - Customizing 404 page

Be careful with the syntax! Great Turtle used them interchangeably, but:

error_page 404 = /404.html;

Will return the 404.html page with a status code of 200 (because = has relayed that to this page)

error_page 404 /404.html;

Will return the 404.html page with a (the original) 404 error code.

https://serverfault.com/questions/295789/nginx-return-correct-headers-with-custom-error-documents

Is there a way to do repetitive tasks at intervals?

I use the following code:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    fmt.Println("\nToday:", now)

    after := now.Add(1 * time.Minute)
    fmt.Println("\nAdd 1 Minute:", after)

    for {
        fmt.Println("test")
        time.Sleep(10 * time.Second)

        now = time.Now()

        if now.After(after) {
            break
        }
    }

    fmt.Println("done")
}

It is more simple and works fine to me.

Arduino COM port doesn't work

This fix / solution worked for me: Device Manager --> Ports --> right click on Arduino Uno --> Update Driver Software --> Search automatically for updated driver software

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

fatal: The current branch master has no upstream branch

If you are trying to push your code direct to the master branch then use command

git push origin master

It helps me.

AutoComplete TextBox in WPF

Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"

  1. Install nuget package for project in Visual Studio

  2. Add a reference to the library in the xaml:
    xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"

  3. Create a textbox and bind the AutoCompleteBehaviour to List<String> (TestItems):
    <TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />

IMHO this is much easier to get started and manage than the other options listed above.

Exercises to improve my Java programming skills

My recommendation is to solve problems that you're interested in, writing code that might be useful to you.

Java is a huge box. It's got a lot of computer science inside: graphics, scientific computing, relational databases, user interfaces for desktop and web, messaging and queuing, multi-threading, security, and more. Each area has their own "beginner problem". Which one do you mean?

How do you define "beginner problem"? Maybe you're having trouble because you aren't narrowing your search enough.

If your imagination is lacking, your best bet is to Google something like "java beginner practice problems" and investigate what you get back.

Or start with Sun's on-line Java tutorial and work you way all the way through it. You'll know a fair amount about Java when you're done.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.

  1. Install anaconda. Latest version can be found here
  2. Open the navigator by typing anaconda-navigator in terminal
  3. Open environments. Click on create and then choose your python version in that.
  4. Now new environment will be created for your python version and you can install the IDE's(which are listed there) just by clicking install in that.
  5. Launch the IDE in your environment so that that IDE will use the specified version for that environment.

Hope it helps!!

Throw keyword in function's signature

To add a bit more value to all the other answer's to this question, one should invest a few minutes in the question: What is the output of the following code?

#include <iostream>
void throw_exception() throw(const char *)
{
    throw 10;
}
void my_unexpected(){
    std::cout << "well - this was unexpected" << std::endl;
}
int main(int argc, char **argv){
    std::set_unexpected(my_unexpected);
    try{
        throw_exception();
    }catch(int x){
        std::cout << "catch int: " << x << std::endl;
    }catch(...){
        std::cout << "catch ..." << std::endl;
    }
}

Answer: As noted here, the program calls std::terminate() and thus none of the exception handlers will get called.

Details: First my_unexpected() function is called, but since it doesn't re-throw a matching exception type for the throw_exception() function prototype, in the end, std::terminate() is called. So the full output looks like this:

user@user:~/tmp$ g++ -o except.test except.test.cpp
user@user:~/tmp$ ./except.test
well - this was unexpected
terminate called after throwing an instance of 'int'
Aborted (core dumped)

How do you rename a Git tag?

You can also rename remote tags without checking them out, by duplicate the old tag/branch to a new name and delete the old one, in a single git push command.

Remote tag rename / Remote branch ? tag conversion: (Notice: :refs/tags/)

git push <remote_name> <old_branch_or_tag>:refs/tags/<new_tag> :<old_branch_or_tag>

Remote branch rename / Remote tag ? branch conversion: (Notice: :refs/heads/)

git push <remote_name> <old_branch_or_tag>:refs/heads/<new_branch> :<old_branch_or_tag>

Output renaming a remote tag:

D:\git.repo>git push gitlab App%2012.1%20v12.1.0.23:refs/tags/App_12.1_v12.1.0.23 :App%2012.1%20v12.1.0.23

Total 0 (delta 0), reused 0 (delta 0)
To https://gitlab.server/project/repository.git
 - [deleted]               App%2012.1%20v12.1.0.23
 * [new tag]               App%2012.1%20v12.1.0.23 -> App_12.1_v12.1.0.23

How do I read an attribute on a class at runtime?

When you have Overridden Methods with same Name Use the helper below

public static TValue GetControllerMethodAttributeValue<T, TT, TAttribute, TValue>(this T type, Expression<Func<T, TT>> exp, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
        {
            var memberExpression = exp?.Body as MethodCallExpression;

            if (memberExpression.Method.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault() is TAttribute attr && valueSelector != null)
            {
                return valueSelector(attr);
            }

            return default(TValue);
        }

Usage: var someController = new SomeController(Some params); var str = typeof(SomeController).GetControllerMethodAttributeValue(x => someController.SomeMethod(It.IsAny()), (RouteAttribute routeAttribute) => routeAttribute.Template);

CSS fill remaining width

I know its quite late to answer this, but I guess it will help anyone ahead.

Well using CSS3 FlexBox. It can be acheived. Make you header as display:flex and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part. apply justify-content: between to the header container and flex-grow:1 to the searchbar. That's it. The sample code is below.

_x000D_
_x000D_
#header {_x000D_
  background-color: #323C3E;_x000D_
  justify-content: space-between;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
  align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
  flex-grow:1;_x000D_
  background-color: orange;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
  padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
  display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
    <img src="img/logo.png" />_x000D_
    <div id="searchBar">_x000D_
      <input type="text" />_x000D_
    </div>_x000D_
    <div class="buttonsHolder">_x000D_
      <div class="button orange inline" id="myAccount">_x000D_
        My Account_x000D_
      </div>_x000D_
      <div class="button red inline" id="basket">_x000D_
        Basket (2)_x000D_
      </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I find all of the distinct file extensions in a folder hierarchy?

I've found it simple and fast...

   # find . -type f -exec basename {} \; | awk -F"." '{print $NF}' > /tmp/outfile.txt
   # cat /tmp/outfile.txt | sort | uniq -c| sort -n > tmp/outfile_sorted.txt

How can I do factory reset using adb in android?

I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)

Here is steps:

# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache 
# reboot device
fastboot reboot

window.onload vs $(document).ready()

The $(document).ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window.onload event occurs later, when everything including images on the page loaded.

Also window.onload is a pure javascript event in the DOM, while the $(document).ready() event is a method in jQuery.

$(document).ready() is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...

Look at to jQuery source code to understand how it's working:

jQuery.ready.promise = function( obj ) {
    if ( !readyList ) {

        readyList = jQuery.Deferred();

        // Catch cases where $(document).ready() is called after the browser event has already occurred.
        // we once tried to use readyState "interactive" here, but it caused issues like the one
        // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", completed, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", completed, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", completed );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", completed );

            // If IE and not a frame
            // continually check to see if the document is ready
            var top = false;

            try {
                top = window.frameElement == null && document.documentElement;
            } catch(e) {}

            if ( top && top.doScroll ) {
                (function doScrollCheck() {
                    if ( !jQuery.isReady ) {

                        try {
                            // Use the trick by Diego Perini
                            // http://javascript.nwbox.com/IEContentLoaded/
                            top.doScroll("left");
                        } catch(e) {
                            return setTimeout( doScrollCheck, 50 );
                        }

                        // detach all dom ready events
                        detach();

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

Also I have created the image below as a quick references for both:

enter image description here

How to return a table from a Stored Procedure?

It's VERY important to include:

 SET NOCOUNT ON;

into SP, In First line, if you do INSERT in SP, the END SELECT can't return values.

THEN, in vb60 you can:

SET RS = CN.EXECUTE(SQL)

OR:

RS.OPEN CN, RS, SQL

how to end ng serve or firebase serve

If ctrl + c doesn't work use this:

ctrl +shift+ c

Sometimes people change the behaviour of ctrl + c for copy/pasting so you may need this.

Of course, you should also ensure that the terminal window has keyboard focus, ctrl + c won't work if your browser window has focus.

Extract regression coefficient values

Just pass your regression model into the following function:

    plot_coeffs <- function(mlr_model) {
      coeffs <- coefficients(mlr_model)
      mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
      lablist <- names(coeffs)
      text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
    }

Use as follows:

model <- lm(Petal.Width ~ ., data = iris)

plot_coeffs(model)

enter image description here

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

Write bytes to file

If I understand you correctly, this should do the trick. You'll need add using System.IO at the top of your file if you don't already have it.

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
    try
    {
        using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in process: {0}", ex);
        return false;
    }
}

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Here's a good post that shows how to do it.

If you want to read the values from a file other than the app.config, you need to load it into the ConfigurationManager.

Try this method: ConfigurationManager.OpenMappedExeConfiguration()

There's an example of how to use it in the MSDN article.

Cut off text in string after/before separator in powershell

Using regex, the result is in $matches[1]:

$str = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$str -match "^(.*?)\s\;"
$matches[1]
test.txt

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Yes, this is possible. As previously noted by multiple users, there seems to be a problem with excel reading the correct Byte Order Mark when the file is encoded in UTF-8. With UTF-16 it does not seem to have a problem, so it is endemic to UTF-8. The solution I use for this is adding the BOM, TWICE. For this I execute the following sed command twice:

sed -I '1s/^/\xef\xbb\xbf/' *.csv

, where the wildcard can be replaced with any file name. However, this leads to a mutation of the sep= at the beginning of the .csv file. The .csv file will then open normally in excel, but with an extra row with "sep=" in the first cell. The "sep=" can also be removed in the source .csv itself, but when opening the file with VBA the delimiter should be specified:

Workbooks.Open(name, Format:=6, Delimiter:=";", Local:=True)

Format 6 is the .csv format. Set Local to true, in case there are dates in the file. If Local is not set to true the dates will be Americanized, which in some cases will corrupt the .csv format.

Detecting touch screen devices with Javascript

This works for me:

function isTouchDevice(){
    return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

What are naming conventions for MongoDB?

DATABASE

  • camelCase
  • append DB on the end of name
  • make singular (collections are plural)

MongoDB states a nice example:

To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:

use myDB
use myNewDB

Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases

COLLECTIONS

  • Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.

  • Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"

  • >No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
    firstname). This one is up for debate according to a few people
    around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
    readability of your collection name by adding underscores or
    camelCasing your collection name is probably too long or should use
    periods as appropriate which is the standard for collection
    categorization.

  • Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.

Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html

For collections I'm following these suggested patterns until I find official MongoDB documentation.

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

jQuery .scrollTop(); + animation

Try this instead:

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}

PHP: Calling another class' method

If they are separate classes you can do something like the following:

class A
{
    private $name;

    public function __construct()
    {
        $this->name = 'Some Name';
    }

    public function getName()
    {
        return $this->name;
    }
}

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    function getNameOfA()
    {
        return $this->a->getName();
    }
}

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

$b->getNameOfA();

What I have done in this example is first create a new instance of the A class. And after that I have created a new instance of the B class to which I pass the instance of A into the constructor. Now B can access all the public members of the A class using $this->a.

Also note that I don't instantiate the A class inside the B class because that would mean I tighly couple the two classes. This makes it hard to:

  1. unit test your B class
  2. swap out the A class for another class

C error: Expected expression before int

{ } -->

defines scope, so if(a==1) { int b = 10; } says, you are defining int b, for {}- this scope. For

if(a==1)
  int b =10;

there is no scope. And you will not be able to use b anywhere.

How to give a pattern for new line in grep?

Thanks to @jarno I know about the -z option and I found out that when using GNU grep with the -P option, matching against \n is possible. :)

Example:

grep -zoP 'foo\n\K.*'<<<$'foo\nbar'

Prints bar

Get HTML code from website in C#

Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.

You need to stream the page into an HtmlDocument object and then select your required element.

// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;

try
{
    var webRequest = HttpWebRequest.Create(pageUrl);
    Stream stream = webRequest.GetResponse().GetResponseStream();
    doc.Load(stream);
    stream.Close();
}
catch (System.UriFormatException uex)
{
    Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
    throw;
}
catch (System.Net.WebException wex)
{
    Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
    throw;
}

//get the div by id and then get the inner text 
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();

[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.

Code sample directly from their site:

using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;

//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
    var title = item.QuerySelector("h3:not(.share)").InnerText;
    var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
    var description = item.QuerySelector("span:has(b)").InnerHtml;
}

I don't think it can get any simpler than that.

Can't find the 'libpq-fe.h header when trying to install pg gem

I have tried all solutions but only works below command

pip install psycopg2-binary

The import com.google.android.gms cannot be resolved

Another way is to let Eclipse do the import work for you. Hover your mouse over the com.google.android.gms import that can not be resolved and towards the bottom of the popup menu, select the Fix project setup... option as below. Then it'll prompt to import the google play services library. Select that and you should be good to go.

enter image description here

How to export/import PuTTy sessions list?

An improvement to the solution of bumerang to import data to PuTTY portable.

Simply moving exported putty.reg (with m0nhawk solution) to PuTTYPortable\Data\settings\ didn't work. PuTTY Portable backup the file and create a new empty one.

To workaround this issue, merge both putty.reg copying manually the config you want to migrate from your exported putty.reg to the newly created PuTTYPortable\Data\settings\putty.reg below following lines.

REGEDIT4

[HKEY_CURRENT_USER\Software\SimonTatham\PuTTY]
"RandSeedFile"="D:\\Programme\\PuTTYPortable\\Data\\settings\\PUTTY.RND"

Sending cookies with postman

Enable intercepter in this way

Basically it is a chrome plug in. After installing the extention, you also need to make sure the extention is enabled from chrome side.

enter image description here

Differences between key, superkey, minimal superkey, candidate key and primary key

I have always found it difficult to remember all the keys; so I keep the below notes handy, hope they help someone! Let me know if it can be improved.

  • Key: An attribute or combination of attributes that uniquely identify an entity/record in a relational table.

  • PK: A single key that is unique and not-null. It is one of the candidate keys.

  • Foreign Key: FK is a key in one table (child) that uniquely identifies a row of another table (parent). A FK is not-unique in the child table. It is a candidate key in the parent table. Referential integrity is maintained as the value in FK is present as a value in PK in parent table else it is NULL.

  • Unique Key: A unique key that may or may not be NULL

  • Natural key: PK in OLTP. It may be a PK in OLAP.

  • Surrogate Key: It is the Surrogate PK in OLAP acting as the substitute of the PK in OLTP. Artificial key generated internally in OLAP.

  • Composite Key: PK made up of multiple attributes

  • SuperKey: A key that can be uniquely used to identify a database record, that may contain extra attributes that are not necessary to uniquely identify records.

  • Candidate Key: A candidate key can be uniquely used to identify a database record without any extraneous data. They are Not Null and unique. It is a minimal super-key.

  • Alternate Key: A candidate key that is not the primary key is called an alternate key.

  • Candidate Key/s with Extraneous data: Consider that can be used to identify a record in the Employee table but candidate key alone is sufficient for this task. So becomes the extraneous data.

Note that the PK, Foreign Key, Unique Key, Natural key, Surrogate Key, Composite Key are defined as Database objects; where the Natural key is a PK in the OLTP and could be a PK in the target OLAP. For the rest of the keys, it's up to the DB designer/architect to decide whether unique/not-null/referential integrity constraints need to enforced or not.

Below I have tried to use set theory to simplify the representation of the membership of the keys w.r.t. each other.

key = { All of the below keys   }
PK  = { PK  }
Foreign Key = { Key with Not Null constraint    }
Unique Key  = { {Candidate Key/s}, {attributes containing NULL} }
Natural key = { PK  }
Surrogate Key   = { PK  }
Composite Key   = { PK  }
Super Key   = { {Candidate Key/s}, {Candidate Key/s with Extraneous data}   }
Candidate Key   = { PK, {Alternate Key/s}   }
Alternate Key   = { {Candidate Keys} - PK   }
Candidate Key/s with Extraneous data    = {     }

I have summarized it below:

Database Keys

Notes: an-overview-of-the-database-keys-primary-key-composite-key-surrogate-key-et-al

How to write and read java serialized objects into a file

As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.

In that case the serialization code becomes

ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
    fout = new FileOutputStream("G:\\address.ser", true);
    oos = new ObjectOutputStream(fout);
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    if(oos != null){
        oos.close();
    } 
}

And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):

ObjectInputStream objectinputstream = null;
try {
    FileInputStream streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
    recordList.add(readCase);
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

You can also deserialize several objects from a file, as you intended to:

ObjectInputStream objectinputstream = null;
try {
    streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    MyClass readCase = null;
    do {
        readCase = (MyClass) objectinputstream.readObject();
        if(readCase != null){
            recordList.add(readCase);
        } 
    } while (readCase != null)        
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

Please do not forget to close stream objects in a finally clause (note: it can throw exception).

EDIT

As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.

Here is the list serialization :

try(
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
){
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
}

How to set image button backgroundimage for different state?

Hi try the following code it will be useful to you,

((ImageView)findViewById(R.id.ImageViewButton)).setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_over);

        if(event.getAction() == MotionEvent.ACTION_UP)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_normal);

        return false;
    }
});

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Cannot invoke an expression whose type lacks a call signature

As mentioned in the github issue originally linked by @peter in the comments:

const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);

How can I get a list of Git branches, ordered by most recent commit?

This is based on saeedgnu's version, but with the current branch shown with a star and in color, and only showing anything that is not described as "months" or "years" ago:

current_branch="$(git symbolic-ref --short -q HEAD)"
git for-each-ref --sort=committerdate refs/heads \
  --format='%(refname:short)|%(committerdate:relative)' \
  | grep -v '\(year\|month\)s\? ago' \
  | while IFS='|' read branch date
    do
      start='  '
      end=''
      if [[ $branch = $current_branch ]]; then
        start='* \e[32m'
        end='\e[0m'
      fi
      printf "$start%-30s %s$end\\n" "$branch" "$date"
    done

How to force a hover state with jQuery?

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

How do you turn a Mongoose document into a plain object?

A better way of tackling an issue like this is using doc.toObject() like this

doc.toObject({ getters: true })

other options include:

  • getters: apply all getters (path and virtual getters)
  • virtuals: apply virtual getters (can override getters option)
  • minimize: remove empty objects (defaults to true)
  • transform: a transform function to apply to the resulting document before returning
  • depopulate: depopulate any populated paths, replacing them with their original refs (defaults to false)
  • versionKey: whether to include the version key (defaults to true)

so for example you can say

Model.findOne().exec((err, doc) => {
   if (!err) {
      doc.toObject({ getters: true })
      console.log('doc _id:', doc._id)
   }
})

and now it will work.

For reference, see: http://mongoosejs.com/docs/api.html#document_Document-toObject

Adding/removing items from a JavaScript object with jQuery

Keep things simple :)

var my_form_obj = {};
my_form_obj.name = "Captain America";
my_form_obj.weapon = "Shield";

Hope this helps!

How to make a checkbox checked with jQuery?

I think you should use prop(), if you are using jQuery 1.6 onwards.

To check it you should do:

$('#test').prop('checked', true);

to uncheck it:

$('#test').prop('checked', false);

Resizing Images in VB.NET

    Dim x As Integer = 0
    Dim y As Integer = 0
    Dim k = 0
    Dim l = 0
    Dim bm As New Bitmap(p1.Image)
    Dim om As New Bitmap(p1.Image.Width, p1.Image.Height)
    Dim r, g, b As Byte
    Do While x < bm.Width - 1
        y = 0
        l = 0
        Do While y < bm.Height - 1
            r = 255 - bm.GetPixel(x, y).R
            g = 255 - bm.GetPixel(x, y).G
            b = 255 - bm.GetPixel(x, y).B
            om.SetPixel(k, l, Color.FromArgb(r, g, b))
            y += 3
            l += 1
        Loop
        x += 3
        k += 1
    Loop
    p2.Image = om

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

How to randomize (or permute) a dataframe rowwise and columnwise?

If the goal is to randomly shuffle each column, some of the above answers don't work since the columns are shuffled jointly (this preserves inter-column correlations). Others require installing a package. Yet a one-liner exist:

df2 = lapply(df1, function(x) { sample(x) })

Equivalent VB keyword for 'break'

Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

How do you replace all the occurrences of a certain character in a string?

The problem is you're not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.

line[8] = line[8].replace(letter, "")

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

Print current call stack from a method in Python code

Here's a variation of @RichieHindle's excellent answer which implements a decorator that can be selectively applied to functions as desired. Works with Python 2.7.14 and 3.6.4.

from __future__ import print_function
import functools
import traceback
import sys

INDENT = 4*' '

def stacktrace(func):
    @functools.wraps(func)
    def wrapped(*args, **kwds):
        # Get all but last line returned by traceback.format_stack()
        # which is the line below.
        callstack = '\n'.join([INDENT+line.strip() for line in traceback.format_stack()][:-1])
        print('{}() called:'.format(func.__name__))
        print(callstack)
        return func(*args, **kwds)

    return wrapped

@stacktrace
def test_func():
    return 42

print(test_func())

Output from sample:

test_func() called:
    File "stacktrace_decorator.py", line 28, in <module>
    print(test_func())
42

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

Line Break in XML formatting?

Also you can add <br> instead of \n.

And then you can add text to TexView:

articleTextView.setText(Html.fromHtml(textForTextView));

How to break out of multiple loops?

You can define a variable( for example break_statement ), then change it to a different value when two-break condition occurs and use it in if statement to break from second loop also.

while True:
    break_statement=0
    while True:
        ok = raw_input("Is this ok? (y/n)")
        if ok == "n" or ok == "N": 
            break
        if ok == "y" or ok == "Y": 
            break_statement=1
            break
    if break_statement==1:
        break

Freemarker iterating over hashmap keys

Edit: Don't use this solution with FreeMarker 2.3.25 and up, especially not .get(prop). See other answers.

You use the built-in keys function, e.g. this should work:

<#list user?keys as prop>
    ${prop} = ${user.get(prop)}
</#list>  

Set an empty DateTime variable

Option 1: Use a nullable DateTime?

Option 2: Use DateTime.MinValue

Personally, I'd prefer option 1.

Responsive font size in CSS

After many conclusions I ended up with this combination:

@media only screen and (max-width: 730px) {

    h2 {
        font-size: 4.3vw;
    }
}

Load jQuery with Javascript and use jQuery

There is an other way to load jQuery dynamically (source). You could also use

document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');

It's considered bad practice to use document.write, but for sake of completion it's good to mention it.

See Why is document.write considered a "bad practice"? for the reasons. The pro is that document.write does block your page from loading other assests, so there is no need to create a callback function.

How to change the session timeout in PHP?

You can override values in php.ini from your PHP code using ini_set().

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

I've tried all examples, posted here, but they do not work without extra CSS. Try this:

<a href="http://www.google.com"><button type="button" class="btn btn-success">Google</button></a>

Works perfectly without any extra CSS.

How can I change the default width of a Twitter Bootstrap modal box?

Preserve the responsive design, set the width to what you desire.

.modal-content {
  margin-left: auto;
  margin-right: auto;
  max-width: 360px;
}

Keep it simple.

replace String with another in java

Another suggestion, Let's say you have two same words in the String

String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.

replace function will change every string is given in the first parameter to the second parameter

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

and you can use also replaceAll method for the same result

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

if you want to change just the first string which is positioned earlier,

System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.

How to wrap text around an image using HTML/CSS

Addition to BeNdErR's answer:
The "other TEXT" element should have float:none, like:

_x000D_
_x000D_
    <div style="width:100%;">_x000D_
        <div style="float:left;width:30%; background:red;">...something something something  random text</div>_x000D_
        <div style="float:none; background:yellow;"> text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text  </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

Hibernate: flush() and commit()

session.flush() is synchronise method means to insert data in to database sequentially.if we use this method data will not store in database but it will store in cache,if any exception will rise in middle we can handle it. But commit() it will store data in database,if we are storing more amount of data then ,there may be chance to get out Of Memory Exception,As like in JDBC program in Save point topic

ImportError: No module named request

from @Zzmilanzz's answer I used

try: #python3
    from urllib.request import urlopen
except: #python2
    from urllib2 import urlopen

How to create a windows service from java app

Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.

How to make a <div> appear in front of regular text/tables

Use the display property in CSS:

<body> 
    <div id="invisible" style="display:none;">Invisible DIV</div>  
    <div>Another DIV 
        <button onclick="document.getElementById('invisible').style.display='block'">
            Button
        </button>  
    </div>  
</body>

When the the display of the first div is set back to block it will appear and shift the second div down.

How to use the priority queue STL for objects?

This piece of code may help..

#include <bits/stdc++.h>
using namespace std;    

class node{
public:
    int age;
    string name;
    node(int a, string b){
        age = a;
        name = b;
    }
};

bool operator<(const node& a, const node& b) {

    node temp1=a,temp2=b;
    if(a.age != b.age)
        return a.age > b.age;
    else{
        return temp1.name.append(temp2.name) > temp2.name.append(temp1.name);
    }
}

int main(){
    priority_queue<node> pq;
    node b(23,"prashantandsoon..");
    node a(22,"prashant");
    node c(22,"prashantonly");
    pq.push(b);
    pq.push(a);
    pq.push(c);

    int size = pq.size();
    for (int i = 0; i < size; ++i)
    {
        cout<<pq.top().age<<" "<<pq.top().name<<"\n";
        pq.pop();
    }
}

Output:

22 prashantonly
22 prashant
23 prashantandsoon..

How do you convert WSDLs to Java classes using Eclipse?

In Eclipse Kepler it is very easy to generate Web Service Client classes,You can achieve this by following steps .

RightClick on any Project->Create New Other ->Web Services->Web Service Client->Then paste the wsdl url(or location) in Service Definition->Next->Finish

You will see the generated classes are inside your src folder.

NOTE :Without eclipse also you can generate client classes from wsdl file by using wsimport command utility which ships with JDK.

refer this link Create Web service client using wsdl

How to allow Cross domain request in apache2

In httpd.conf

  1. Make sure these are loaded:
LoadModule headers_module modules/mod_headers.so

LoadModule rewrite_module modules/mod_rewrite.so
  1. In the target directory:
<Directory "**/usr/local/PATH**">
    AllowOverride None
    Require all granted

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
    Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
    Header always set Access-Control-Max-Age "600"

    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]

</Directory>

If running outside container, you may need to restart apache service.

MySQL config file location - redhat linux server

The information you want can be found by running

mysql --help

or

mysqld --help --verbose

I tried this :

    mysql --help | grep Default -A 1

And the output:

                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash 
--
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers 
--
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names 
--
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
--
  --default-auth=name Default authentication client-side plugin to use.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
--
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 

How is using OnClickListener interface different via XML and Java code?

using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener then add the variable Button button1; then add this to your onCreate()

button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);

when you implement OnClickListener you need to add the inherited method onClick() where you will handle your clicks

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

A one line solution. Add this anywhere before calling the server on the client side:

System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

This should only be used for testing purposes because the client will skip SSL/TLS security checks.

getting the reason why websockets closed with close code 1006

I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy

And sending just some "ping" message from server to client every x second resolved problem

What is wrong with my SQL here? #1089 - Incorrect prefix key

It works for me:

CREATE TABLE `users`(
    `user_id` INT(10) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`user_id`)
) ENGINE = MyISAM;       

Python, add items from txt file into a list

f = open('file.txt','r')

for line in f:
    myNames.append(line.strip()) # We don't want newlines in our list, do we?

Can I get the name of the currently running function in JavaScript?

All what you need is simple. Create function:

function getFuncName() {
   return getFuncName.caller.name
}

After that whenever you need, you simply use:

function foo() { 
  console.log(getFuncName())
}

foo() 
// Logs: "foo"

response.sendRedirect() from Servlet to JSP does not seem to work

Instead of using

response.sendRedirect("/demo.jsp");

Which does a permanent redirect to an absolute URL path,

Rather use RequestDispatcher. Example:

RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);

How to prevent ENTER keypress to submit a web form?

How about:

<script>
function isok(e) {
  var name = e.explicitOriginalTarget.name;
  if (name == "button") {
    return true
  }
  return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>

And just name your button right and it will still submit, but text fields i.e. the explicitOriginalTarget when you hit return in one, will not have the right name.

Python: get key of index in dictionary

Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.

You can only do this in a loop:

[k for (k, v) in i.iteritems() if v == 0]

Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0} is perfectly legal.

If you want ordering you either need to use a list or a OrderedDict instance instead:

items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0]         # gives 'a'

Python locale error: unsupported locale setting

If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html

I got the same issue here using Docker, I've tried every single step and didn't work well, always getting locale error, so I decided to use BABEL, and everything worked well.

Conditional Count on a field

Using ANSI SQL-92 CASE Statements, you could do something like this (derived table plus case):

 SELECT jobId, jobName, SUM(Priority1)
 AS Priority1, SUM(Priority2) AS
 Priority2, SUM(Priority3) AS
 Priority3, SUM(Priority4) AS
 Priority4,  SUM(Priority5) AS
 Priority5 FROM (
     SELECT jobId, jobName,
     CASE WHEN Priority = 1 THEN 1 ELSE 0 END AS Priority1,
     CASE WHEN Priority = 2 THEN 1 ELSE 0 END AS Priority2,
     CASE WHEN Priority = 3 THEN 1 ELSE 0 END AS Priority3,
     CASE WHEN Priority = 4 THEN 1 ELSE 0 END AS Priority4,
     CASE WHEN Priority = 5 THEN 1 ELSE 0 END AS Priority5
     FROM TableName


)

Manually put files to Android emulator SD card

One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)enter image description here

Passing an Array as Arguments, not an Array, in PHP

As has been mentioned, as of PHP 5.6+ you can (should!) use the ... token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:

<?php
function variadic($arg1, $arg2)
{
    // Do stuff
    echo $arg1.' '.$arg2;
}

$array = ['Hello', 'World'];

// 'Splat' the $array in the function call
variadic(...$array);

// 'Hello World'

Note: array items are mapped to arguments by their position in the array, not their keys.

As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array.

Aside

Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.

(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)

This is great for making sure an array contains items of a specific type:

<?php

// Define the function...

function variadic($var, SomeClass ...$items)
{
    // $items will be an array of objects of type `SomeClass`
}

// Then you can call...

variadic('Hello', new SomeClass, new SomeClass);

// or even splat both ways

$items = [
    new SomeClass,
    new SomeClass,
];

variadic('Hello', ...$items);

How to get relative path of a file in visual studio?

When it is the case that you want to use any kind of external file, there is certainly a way to put them in a folder within your project, but not as valid as getting them from resources. In a regular Visual Studio project, you should have a Resources.resx file under the Properties section, if not, you can easily add your own Resource.resx file. And add any kind of file in it, you can reach the walkthrough for adding resource files to your project here.

After having resource files in your project, calling them is easy as this:

var myIcon = Resources.MyIconFile;

Of course you should add the using Properties statement like this:

using <namespace>.Properties;

Fully custom validation error message with Rails

In the custom validation method use:

errors.add(:base, "Custom error message")

as add_to_base has been deprecated.

errors.add_to_base("Custom error message")

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

The openssl extension is required for SSL/TLS protection

After trying everything, I finally managed to get this sorted. None of the above suggested solutions worked for me. My system is A PC Windows 10. In order to get this sorted I had to change the config.json file located here C:\Users\[Your User]\AppData\Roaming\Composer\. In there, you will find:

{
    "config": {
        "disable-tls": true},
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "http://repo.packagist.org" // this needs to change to 'https'
        }
    }
}

where you need to update the packagist repo url to point to the 'https' url version.

I am aware that the above selected solution will work for 95% of the cases, but as I said, that did not work for me. Hope this helps someone.

Happy coding!

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

@Html.Partial returns view in HTML-encoded string and use same view TextWriter object. @Html.RenderPartial this method return void. @Html.RenderPartial is faster than @Html.Partial

The syntax for PartialView:

 [HttpGet] 
 public ActionResult AnyActionMethod
 {
     return PartialView();
 }

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Just for kicks, here's the functions I wrote to do it before I had the .PadRight bit:

    public string insertSpacesAtEnd(string input, int longest)
    {
        string output = input;
        string spaces = "";
        int inputLength = input.Length;
        int numToInsert = longest - inputLength;

        for (int i = 0; i < numToInsert; i++)
        {
            spaces += " ";
        }

        output += spaces;

        return output;
    }

    public int findLongest(List<Results> theList)
    {
        int longest = 0;

        for (int i = 0; i < theList.Count; i++)
        {
            if (longest < theList[i].title.Length)
                longest = theList[i].title.Length;
        }
        return longest;
    }

    ////Usage////
    for (int i = 0; i < storageList.Count; i++)
    {
        output += insertSpacesAtEnd(storageList[i].title, longest + 5) +   storageList[i].rank.Trim() + "     " + storageList[i].term.Trim() + "         " + storageList[i].name + "\r\n";
    }

CSS: Set a background color which is 50% of the width of the window

Older Browser Support

If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare div element:

#background {
    position: fixed;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    background-color: pink; 
}

Example: http://jsfiddle.net/PLfLW/1704/

The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.

If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.


Modern Browsers

If newer browsers are your only concern, there are a couple other methods you can use:

Linear Gradient:

This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.

body {
    height: 100%;
    background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%);
}

This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.

Example: http://jsfiddle.net/v14m59pq/2/

Multiple Backgrounds with background-size:

You can apply a background color to the html element, and then apply a background-image to the body element and use the background-size property to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.

html {
    height: 100%;
    background-color: cyan;
}

body {
    height: 100%;
    background-image: url('http://i.imgur.com/9HMnxKs.png');
    background-repeat: repeat-y;
    background-size: 50% auto;
}

Example: http://jsfiddle.net/6vhshyxg/2/


EXTRA NOTE: Notice that both the html and body elements are set to height: 100% in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.

Import Excel spreadsheet columns into SQL Server database

First of all, try the 32 Bit Version of the Import Wizard. This shows a lot more supported import formats.

Background: All depends on your Office (Runtimes Engines) installation.

If you dont't have Office 2007 or greater installed, the Import Wizard (32 Bit) only allows you to import Excel 97-2003 (.xls) files.

If you have the Office 2010 and geater (comes also in 64 Bit, not recommended) installed, the Import Wizard also supports Excel 2007+ (.xlsx) files.

To get an overview on the runtimes see 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Jump into interface implementation in Eclipse IDE

Press Ctrl + T on the method name (rather than F3). This gives the type hierarchy as a pop-up so is slightly faster than using F4 and the type hierarchy view.

Also, when done on a method, subtypes that don't implement/override the method will be greyed out, and when you double click on a class in the list it will take you straight to the method in that class.

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

How to split a file into equal parts, without breaking individual lines?

split was updated in coreutils release 8.8 (announced 22 Dec 2010) with the --number option to generate a specific number of files. The option --number=l/n generates n files without splitting lines.

http://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html#split-invocation http://savannah.gnu.org/forum/forum.php?forum_id=6662

Using String Format to show decimal up to 2 places or simple integer

try

double myPrice = 123.0;

String.Format(((Math.Round(myPrice) == myPrice) ? "{0:0}" : "{0:0.00}"), myPrice);

What is a quick way to force CRLF in C# / .NET?

Environment.NewLine;

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

Export DataBase with MySQL Workbench with INSERT statements

For the latest version of MySql Workbench

  1. Click on the Server menu in the top menu bar
  2. Select 'Data Export' submenu
  3. It will open up the Object Selection window where you can select the appropriate database which has the desired tables
  4. Once you select the database in the left side all the tables will appear in the right side with radio buttons
  5. Select the radio buttons in front of needed tables
  6. Just below the table selection you can see a dropdown to select Dump Structure Only or Data only or Structure & Data
  7. Under Objects to Export tick the box if you need stored procedures or events also. If you don't need those then untick those
  8. Under export option change the exporting file name and path
  9. If you want to create the schema once you import the dump file then tick include create schema
  10. Press Start Export button in the right-hand side corner. once it successful the summary will be showing in the Export progress tab

Display last git commit comment

I just found out a workaround with shell by retrieving the previous command.

Press Ctrl-R to bring up reverse search command:

reverse-i-search

Then start typing git commit -m, this will add this as search command, and this brings the previous git commit with its message:

reverse-i-search`git commit -m`: git commit -m "message"

Enter. That's it!

(tested in Ubuntu shell)

Return multiple values from a function, sub or type?

You can also use a variant array as the return result to return a sequence of arbitrary values:

Function f(i As Integer, s As String) As Variant()
    f = Array(i + 1, "ate my " + s, Array(1#, 2#, 3#))
End Function

Sub test()
    result = f(2, "hat")
    i1 = result(0)
    s1 = result(1)
    a1 = result(2)
End Sub

Ugly and bug prone because your caller needs to know what's being returned to use the result, but occasionally useful nonetheless.

Where am I? - Get country

/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        }
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    }
    catch (Exception e) { }
    return null;
}

How to verify if a file exists in a batch file?

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

MYOTHERBATFILE.BAT sync.bat myprogram.ini

How do I rename a local Git branch?

In PhpStorm:

VCS ? Git ? Branches... ? Local Branches ? _your_branch_ ? Rename

How to disable/enable select field using jQuery?

Just simply use:

var update_pizza = function () {
     $("#pizza_kind").prop("disabled", !$('#pizza').prop('checked'));
};

update_pizza();
$("#pizza").change(update_pizza);

DEMO ?

Jenkins not executing jobs (pending - waiting for next executor)

I ran into a similar problem because my master was set to " # of executor (The maximum number of concurrent builds that Jenkins may perform on this agent).

Go to Jenkins --> Manage Jenkins --> Manage Nodes, and click on the configure button of your master node (increase the number of executor to run mutiple jobs at a time).

What is difference between functional and imperative programming languages?

Functional Programming is a form of declarative programming, which describe the logic of computation and the order of execution is completely de-emphasized.

Problem: I want to change this creature from a horse to a giraffe.

  • Lengthen neck
  • Lengthen legs
  • Apply spots
  • Give the creature a black tongue
  • Remove horse tail

Each item can be run in any order to produce the same result.

Imperative Programming is procedural. State and order is important.

Problem: I want to park my car.

  1. Note the initial state of the garage door
  2. Stop car in driveway
  3. If the garage door is closed, open garage door, remember new state; otherwise continue
  4. Pull car into garage
  5. Close garage door

Each step must be done in order to arrive at desired result. Pulling into the garage while the garage door is closed would result in a broken garage door.

Android: Internet connectivity change listener

Here's the Java code using registerDefaultNetworkCallback (and registerNetworkCallback for API < 24):

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    connectivityManager.registerNetworkCallback(request, networkCallback);
}

Check if multiple strings exist in another string

You can use any:

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

Similarly to check if all the strings from the list are found, use all instead of any.

How to make (link)button function as hyperlink?

You can use OnClientClick event to call a JavaScript function:

<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />

JavaScript code:

function redirect() {
  location.href = 'page.aspx';
}

But i think the best would be to style a hyperlink with css.

Example :

.button {
  display: block;
  height: 25px;
  background: #f1f1f1;
  padding: 10px;
  text-align: center;
  border-radius: 5px;
  border: 1px solid #e1e1e2;
  color: #000;
  font-weight: bold;
}

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

In my case the only work solution was:

  1. CREATE TABLE bad_table ENGINE=MyISAM ...
  2. rm bad_table.ibd
  3. DROP TABLE bad_table

WPF: Grid with column/row margin/padding?

You could use something like this:

<Style TargetType="{x:Type DataGridCell}">
  <Setter Property="Padding" Value="4" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type DataGridCell}">
        <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
          <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>

Or if you don't need the TemplateBindings:

<Style TargetType="{x:Type DataGridCell}">
   <Setter Property="Template">
      <Setter.Value>
          <ControlTemplate TargetType="{x:Type DataGridCell}">
              <Border Padding="4">
                  <ContentPresenter />
              </Border>
          </ControlTemplate>
      </Setter.Value>
  </Setter>
</Style>

How to change the URI (URL) for a remote Git repository?

Switching remote URLs

Open Terminal.

Ist Step:- Change the current working directory to your local project.

2nd Step:- List your existing remotes in order to get the name of the remote you want to change.

git remote -v

origin  https://github.com/USERNAME/REPOSITORY.git (fetch)

origin  https://github.com/USERNAME/REPOSITORY.git (push)

Change your remote's URL from HTTPS to SSH with the git remote set-url command.

3rd Step:- git remote set-url origin [email protected]:USERNAME/REPOSITORY.git

4th Step:- Now Verify that the remote URL has changed.

git remote -v Verify new remote URL

origin  [email protected]:USERNAME/REPOSITORY.git (fetch)
origin  [email protected]:USERNAME/REPOSITORY.git (push)

How to check if an int is a null

You have to access to your class atributes.

To access to it atributes, you have to do:

person.id
person.name

where

person

is an instance of your class Person.

This can be done if the attibutes can be accessed, if not, you must use setters and getters...

Comments in Android Layout xml

The World Wide Web Consortium (W3C) actually defined a comment interface. The definition says all the characters between the starting ' <!--' and ending '-->' form a part of comment content and no lexical check is done on the content of a comment.

More details are available on developer.android.com site.

So you can simply add your comment in between any starting and ending tag. In Eclipse IDE simply typing <!-- would auto complete the comment for you. You can then add your comment text in between.

For example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".TicTacToe" >

 <!-- This is a comment -->

</LinearLayout>

Purpose of specifically mentioning in between is because you cannot use it inside a tag.

For example:

<TextView 
    android:text="@string/game_title"
    <!-- This is a comment -->
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"/>

is wrong and will give following error

 Element type "TextView" must be followed by either attribute specifications, ">" or "/>".

NPM: npm-cli.js not found when running npm

I know it is an older post but as I write this the version of Node js is 12.13.1. People face this generally because they might have already installed a previous version of Node js which added the following to the system path.

C:\Program Files\nodejs\node_modules\npm\bin

However, the newer versions need to add the following:-

C:\Program Files\nodejs

I mean to say the path where you installed the Nodejs. The default is

C:\Program Files\nodejs

However, if you gave a different location you should point it to that.

Django optional url parameters

Thought I'd add a bit to the answer.

If you have multiple URL definitions then you'll have to name each of them separately. So you lose the flexibility when calling reverse since one reverse will expect a parameter while the other won't.

Another way to use regex to accommodate the optional parameter:

r'^project_config/(?P<product>\w+)/((?P<project_id>\w+)/)?$'

FileNotFoundException while getting the InputStream object from HttpURLConnection

The solution:
just change localhost for the IP of your PC
if you want to know this: Windows+r > cmd > ipconfig
example: http://192.168.0.107/directory/service/program.php?action=sendSomething
just replace 192.168.0.107 for your own IP (don't try 127.0.0.1 because it's same as localhost)

How can I create download link in HTML?

A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:

<a href="path to resource.name of file">Link</a>

<a href="files/installer.exe">Link to installer</a>

How to install the JDK on Ubuntu Linux

The following used to work before the Oracle Java license changes in early 2019.

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

The PPA is discontinued, until the author finds a workaround for the license issues.

How to check if variable is array?... or something array-like

If you are using foreach inside a function and you are expecting an array or a Traversable object you can type hint that function with:

function myFunction(array $a)
function myFunction(Traversable)

If you are not using foreach inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:

if (is_array($a) or ($a instanceof Traversable))

Order by descending date - month, day and year

what is the type of the field EventDate, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort

How to specify a multi-line shell variable?

Use read with a heredoc as shown below:

read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF

echo "$sql"

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

Android - Package Name convention

Generally the first 2 package "words" are your web address in reverse. (You'd have 3 here as convention, if you had a subdomain.)

So something stackoverflow produces would likely be in package com.stackoverflow.whatever.customname

something asp.net produces might be called net.asp.whatever.customname.omg.srsly

something from mysubdomain.toplevel.com would be com.toplevel.mysubdomain.whatever

Beyond that simple convention, the sky's the limit. This is an old linux convention for something that I cannot recall exactly...

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json) and it worked, as you can see on the image below

My Code

How do I discard unstaged changes in Git?

Just use:

git stash -u

Done. Easy.

If you really care about your stash stack then you can follow with git stash drop. But at that point you're better off using (from Mariusz Nowak):

git checkout -- .
git clean -df

Nonetheless, I like git stash -u the best because it "discards" all tracked and untracked changes in just one command. Yet git checkout -- . only discards tracked changes, and git clean -df only discards untracked changes... and typing both commands is far too much work :)

Rename all files in a folder with a prefix in a single command

Situation:

We have certificate.key certificate.crt inside /user/ssl/

We want to rename anything that starts with certificate to certificate_OLD

We are now located inside /user

First, you do a dry run with -n:

rename -n "s/certificate/certificate_old/" ./ssl/*

Which returns:

rename(./ssl/certificate.crt, ./ssl/certificate_OLD.crt) rename(./ssl/certificate.key, ./ssl/certificate_OLD.key)

Your files will be unchanged this is just a test run.

Solution:

When your happy with the result of the test run it for real:

rename "s/certificate/certificate_OLD/" ./ssl/*

What it means:

`rename "s/ SOMETHING / SOMETING_ELSE " PATH/FILES

Tip:

If you are already on the path run it like this:

rename "s/certificate/certificate_OLD/" *

Or if you want to do this in any sub-directory starting with ss do:

rename -n "s/certificat/certificate_old/" ./ss*/*

You can also do:

rename -n "s/certi*/certificate_old/" ./ss*/*

Which renames anything starting with certi in any sub-directory starting with ss.

The sky is the limit.

Play around with regex and ALWAYS test this BEFORE with -n.

WATCH OUT THIS WILL EVEN RENAME FOLDER NAMES THAT MATCH. Better cd into the directory and do it there. USE AT OWN RISK.

Enable PHP Apache2

You can use a2enmod or a2dismod to enable/disable modules by name.

From terminal, run: sudo a2enmod php5 to enable PHP5 (or some other module), then sudo service apache2 reload to reload the Apache2 configuration.

How to get the start time of a long-running Linux process?

As a follow-up to Adam Matan's answer, the /proc/<pid> directory's time stamp as such is not necessarily directly useful, but you can use

awk -v RS=')' 'END{print $20}' /proc/12345/stat

to get the start time in clock ticks since system boot.1

This is a slightly tricky unit to use; see also convert jiffies to seconds for details.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat

This should give you seconds, which you can pass to strftime() to get a (human-readable, or otherwise) timestamp.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat

Updated with some fixes from Stephane Chazelas in the comments; thanks as always!

If you only have Mawk, maybe try

awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
  NR==1 { now=$1; next }
  END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}

1 man proc; search for starttime.

How to change color of Toolbar back button in Android?

use this style

<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
    <item name="android:homeAsUpIndicator">@drawable/back_button_image</item>
</style>

PowerShell - Start-Process and Cmdline Switches

you are going to want to separate your arguments into separate parameter

$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe"
$arguments = "/v:q /nologo"
start-process $msbuild $arguments 

Cross-Origin Request Blocked

You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}

How do I use a C# Class Library in a project?

You need to add a reference to your class library from your project. Right click on the references folder and click add reference. You can either browse for the DLL or, if your class libaray is a project in your solution you can add a project reference.

Storing money in a decimal column - what precision and scale?

I would think that for a large part your or your client's requirements should dictate what precision and scale to use. For example, for the e-commerce website I am working on that deals with money in GBP only, I have been required to keep it to Decimal( 6, 2 ).

How to fill DataTable with SQL Table

You can fill your data table like the below code.I am also fetching the connections at runtime using a predefined XML file that has all the connection.

  public static DataTable Execute_Query(string connection, string query)
    {
        Logger.Info("Execute Query has been called for connection " + connection);
        connection = "Data Source=" + Connections.run_singlevalue(connection, "server") + ";Initial Catalog=" + Connections.run_singlevalue(connection, "database") + ";User ID=" + Connections.run_singlevalue(connection, "username") + ";Password=" + Connections.run_singlevalue(connection, "password") + ";Connection Timeout=30;";
        DataTable dt = new DataTable();
        try
        {
            using (SqlConnection con = new SqlConnection(connection))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    con.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.SelectCommand.CommandTimeout = 1800;
                        da.Fill(dt);
                    }
                    con.Close();
                }
            }
            Logger.Info("Execute Query success");
            return dt;
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
            return null;
        }
    }   

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Based on this page:

  • Run regedit (remember to run it as the administrator)
  • Expand HKEY_LOCAL_MACHINE
  • Expand SOFTWARE
  • Expand Microsoft
  • Expand Windows
  • Expand CurrentVersion
  • Expand App Paths
  • At App Paths, add a new KEY called sqldeveloper.exe
  • Expand sqldeveloper.exe
  • Modify the (DEFAULT) value to the full pathway to the sqldeveloper executable (See example below step 11)
  • Create a new STRING VALUE called PATH and set it value to the sqldeveloper pathway + \jdk\jre\bin

Hive query output to file

I agree with tnguyen80's response. Please note that when there is a specific string value in query better to given entire query in double quotes.

For example:

$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv

Python: finding lowest integer

To find the minimum value of a list, you might just as well use min:

x = min(float(s) for s in l) # min of a generator

Or, if you want the result as a string, rather than a float, use a key function:

x = min(l, key=float)

HTTP POST with URL query parameters -- good idea or not?

I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

'if' in prolog?

There are essentially three different ways how to express something like if-then-else in Prolog. To compare them consider char_class/2. For a and b the class should be ab and other for all other terms. One could write this clumsily like so:

char_class(a, ab).
char_class(b, ab).
char_class(X, other) :-
   dif(X, a),
   dif(X, b).

?- char_class(Ch, Class).
   Ch = a, Class = ab
;  Ch = b, Class = ab
;  Class = other,
   dif(Ch, a), dif(Ch, b).

To write things more compactly, an if-then-else construct is needed. Prolog has a built-in one:

?- ( ( Ch = a ; Ch = b ) -> Class = ab ; Class = other ).
   Ch = a, Class = ab.

While this answer is sound, it is incomplete. Just the first answer from ( Ch = a ; Ch = b ) is given. The other answers are chopped away. Not very relational, indeed.

A better construct, often called a "soft cut" (don't believe the name, a cut is a cut is a cut), gives slightly better results (this is in YAP):

?- ( ( Ch = a ; Ch = b ) *-> Class = ab ; Class = other ).
   Ch = a, Class = ab
;  Ch = b, Class = ab.

Alternatively, SICStus has if/3 with very similar semantics:

?- if( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
   Ch = a, Class = ab
;  Ch = b, Class = ab.

So the last answer is still suppressed. Now enter library(reif) for SICStus, YAP, and SWI. Install it and say:

?- use_module(library(reif)).

?- if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
   Ch = a, Class = ab
;  Ch = b, Class = ab
;  Class = other,
   dif(Ch, a), dif(Ch, b).

Note that all the if_/3 is compiled away to a wildly nested if-then-else for

char_class(Ch, Class) :-
   if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).

which expands in YAP 6.3.4 to:

char_class(A,B) :-
   ( A\=a
   ->
     ( A\=b
     ->
       B=other
     ;
       ( A==b
       ->
         B=ab
       )
     ;
       A=b,
       B=ab
     ;
       dif(A,b),
       B=other
     )
   ;
     ( A==a
     ->
       B=ab
     )
   ;
     A=a,
     B=ab
   ;
     dif(A,a),
     ( A\=b
     ->
       B=other
     ;
       ( A==b
       ->
         B=ab
       )
     ;
       A=b,
       B=ab
     ;
       dif(A,b),
       B=other
     )
   ).

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

Tracking CPU and Memory usage per process

maybe you can use this. It should work for you and will report processor time for the specified process.

@echo off
: Rich Kreider <[email protected]>
: report processor time for given process until process exits (could be expanded to use a PID to be more
: precise)
: Depends:  typeperf
: Usage:  foo.cmd <processname>

set process=%~1
echo Press CTRL-C To Stop...
:begin
for /f "tokens=2 delims=," %%c in ('typeperf "\Process(%process%)\%% Processor Time" -si 1 -sc 1 ^| find /V "\\"') do (
if %%~c==-1 (
goto :end
) else (
echo %%~c%%
goto begin
)
)

:end
echo Process seems to have terminated.

jquery how to get the page's current screen top position?

Use this to get the page scroll position.

var screenTop = $(document).scrollTop();

$('#content').css('top', screenTop);

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

Print an integer in binary format in Java

You can use bit mask (1<< k) and do AND operation with number! 1 << k has one bit at k position!

private void printBits(int x) {
    for(int i = 31; i >= 0; i--) {
        if((x & (1 << i)) != 0){
            System.out.print(1);
        }else {
            System.out.print(0);
        }
    }
    System.out.println();
}

System.BadImageFormatException: Could not load file or assembly

My cause was different I referenced a web service then I got this message.

Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.

hope this helps!

How to get the class of the clicked element?

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

You can emulate classList in older browsers using myClass.split(/\s+/);

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.