Programs & Examples On #Savepoints

A **savepoint** is a way of implementing subtransactions (also known as nested transactions) within a relational database management system by indicating a point within a transaction that can be "rolled back to" without affecting any work done in the transaction before the savepoint was created.

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

How can javascript upload a blob?

I was able to get @yeeking example to work by not using FormData but using javascript object to transfer the blob. Works with a sound blob created using recorder.js. Tested in Chrome version 32.0.1700.107

function uploadAudio( blob ) {
  var reader = new FileReader();
  reader.onload = function(event){
    var fd = {};
    fd["fname"] = "test.wav";
    fd["data"] = event.target.result;
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: fd,
      dataType: 'text'
    }).done(function(data) {
        console.log(data);
    });
  };
  reader.readAsDataURL(blob);
}

Contents of upload.php

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

How to send authorization header with axios

Install the cors middleware. We were trying to solve it with our own code, but all attempts failed miserably.

This made it work:

cors = require('cors')
app.use(cors());

Original link

Font-awesome, input type 'submit'

use button type="submit" instead of input

<button type="submit" class="btn btn-success">
    <i class="fa fa-arrow-circle-right fa-lg"></i> Next
</button>

for Font Awesome 3.2.0 use

<button type="submit" class="btn btn-success">
    <i class="icon-circle-arrow-right icon-large"></i> Next
</button>

How to find duplicate records in PostgreSQL

From "Find duplicate rows with PostgreSQL" here's smart solution:

select * from (
  SELECT id,
  ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
  FROM tbl
) dups
where 
dups.Row > 1

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

How to restrict the selectable date ranges in Bootstrap Datepicker?

Most answers and explanations are not to explain what is a valid string of endDate or startDate. Danny gave us two useful example.

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

But why?let's take a look at the source code at bootstrap-datetimepicker.js. There are some code begin line 1343 tell us how does it work.

if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
            var part_re = /([-+]\d+)([dmwy])/,
                parts = date.match(/([-+]\d+)([dmwy])/g),
                part, dir;
            date = new Date();
            for (var i = 0; i < parts.length; i++) {
                part = part_re.exec(parts[i]);
                dir = parseInt(part[1]);
                switch (part[2]) {
                    case 'd':
                        date.setUTCDate(date.getUTCDate() + dir);
                        break;
                    case 'm':
                        date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
                        break;
                    case 'w':
                        date.setUTCDate(date.getUTCDate() + dir * 7);
                        break;
                    case 'y':
                        date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
                        break;
                }
            }
            return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
        }

There are four kinds of expressions.

  • w means week
  • m means month
  • y means year
  • d means day

Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$. You can do more than these -0d or +1m.

Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator , could be one of [\f\n\r\t\v,]

How to insert a string which contains an "&"

An alternate solution, use concatenation and the chr function:

select 'J' || chr(38) || 'J Construction' from dual;

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine

Specifically I would point out the following

Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.

So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.

++i or i++ in for loops ??

With integers, it's preference.

If the loop variable is a class/object, it can make a difference (only profiling can tell you if it's a significant difference), because the post-increment version requires that you create a copy of that object that gets discarded.

If creating that copy is an expensive operation, you're paying that expense once for every time you go through the loop, for no reason at all.

If you get into the habit of always using ++i in for loops, you don't need to stop and think about whether what you're doing in this particular situation makes sense. You just always are.

Event handlers for Twitter Bootstrap dropdowns?

In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.

click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown

etc

linux find regex

Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.  
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"

Return from a promise then()

What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

// new answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // do something with the output :)
  })
  .catch(err => {
    console.log(err);
  });

Hope this helps!

// old answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // do something with the output :)
    }

Auto start node.js server on boot

Copied directly from this answer:

You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder

How to search by key=>value in a multidimensional array in PHP

I think the easiest way is using php array functions if you know your key.

function search_array ( $array, $key, $value )
{
   return array_search($value,array_column($array,$key));
}

this return an index that you could find your desired data by this like below:

$arr = array(0 => array('id' => 1, 'name' => "cat 1"),
  1 => array('id' => 2, 'name' => "cat 2"),
  2 => array('id' => 3, 'name' => "cat 1")
);

echo json_encode($arr[search_array($arr,'name','cat 2')]);

this output will:

{"id":2,"name":"cat 2"}

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

Excel compare two columns and highlight duplicates

Don't wana do soo much work guyss.. Just Press Ctr and select Colum one and Press Ctr and select colum two. Then click conditional formatting -> Highlight Cell Rules -> Equel To.

and thats it. your done. :)

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

The original answer by Adam Batkin will lead you to a solution, but if you redeploy your webapp (without restarting your web container), you should run into the following error:

java.lang.UnsatisfiedLinkError: Native Library "foo" already loaded in another classloader
   at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1715)
   at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1646)
   at java.lang.Runtime.load0(Runtime.java:787)
   at java.lang.System.load(System.java:1022)

This happens because the ClassLoader that originally loaded your DLL still references this DLL. However, your webapp is now running with a new ClassLoader, and because the same JVM is running and a JVM won't allow 2 references to the same DLL, you can't reload it. Thus, your webapp can't access the existing DLL and can't load a new one. So.... you're stuck.

Tomcat's ClassLoader documentation outlines why your reloaded webapp runs in a new isolated ClassLoader and how you can work around this limitation (at a very high level).

The solution is to extend Adam Batkin's solution a little:

   package awesome;

   public class Foo {

        static {
            System.loadLibrary('foo');
        }

        // required to work with JDK 6 and JDK 7
        public static void main(String[] args) {
        }

    }

Then placing a jar containing JUST this compiled class into the TOMCAT_HOME/lib folder.

Now, within your webapp, you just have to force Tomcat to reference this class, which can be done as simply as this:

  Class.forName("awesome.Foo");

Now your DLL should be loaded in the common classloader, and can be referenced from your webapp even after being redeployed.

Make sense?

A working reference copy can be found on google code, static-dll-bootstrapper .

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

What do *args and **kwargs mean?

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

def my_sum(*args):
    return sum(args)

It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

The official Python documentation has a more in-depth look.

Run an OLS regression with Pandas Data Frame

Statsmodels kan build an OLS model with column references directly to a pandas dataframe.

Short and sweet:

model = sm.OLS(df[y], df[x]).fit()


Code details and regression summary:

# imports
import pandas as pd
import statsmodels.api as sm
import numpy as np

# data
np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('ABC'))

# assign dependent and independent / explanatory variables
variables = list(df.columns)
y = 'A'
x = [var for var in variables if var not in y ]

# Ordinary least squares regression
model_Simple = sm.OLS(df[y], df[x]).fit()

# Add a constant term like so:
model = sm.OLS(df[y], sm.add_constant(df[x])).fit()

model.summary()

Output:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                 -0.001
Method:                 Least Squares   F-statistic:                    0.9409
Date:                Thu, 14 Feb 2019   Prob (F-statistic):              0.394
Time:                        08:35:04   Log-Likelihood:                -484.49
No. Observations:                 100   AIC:                             975.0
Df Residuals:                      97   BIC:                             982.8
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         43.4801      8.809      4.936      0.000      25.996      60.964
B              0.1241      0.105      1.188      0.238      -0.083       0.332
C             -0.0752      0.110     -0.681      0.497      -0.294       0.144
==============================================================================
Omnibus:                       50.990   Durbin-Watson:                   2.013
Prob(Omnibus):                  0.000   Jarque-Bera (JB):                6.905
Skew:                           0.032   Prob(JB):                       0.0317
Kurtosis:                       1.714   Cond. No.                         231.
==============================================================================

How to directly get R-squared, Coefficients and p-value:

# commands:
model.params
model.pvalues
model.rsquared

# demo:
In[1]: 
model.params
Out[1]:
const    43.480106
B         0.124130
C        -0.075156
dtype: float64

In[2]: 
model.pvalues
Out[2]: 
const    0.000003
B        0.237924
C        0.497400
dtype: float64

Out[3]:
model.rsquared
Out[2]:
0.0190

What is the purpose of flush() in Java streams?

For performance issue, first data is to be written into Buffer. When buffer get full then data is written to output (File,console etc.). When buffer is partially filled and you want to send it to output(file,console) then you need to call flush() method manually in order to write partially filled buffer to output(file,console).

How to make a radio button look like a toggle button

Here's my version of that nice CSS solution JS Fiddle example posted above.

http://jsfiddle.net/496c9/

HTML

<div id="donate">
    <label class="blue"><input type="radio" name="toggle"><span>$20</span></label>
    <label class="green"><input type="radio" name="toggle"><span>$50</span></label>
    <label class="yellow"><input type="radio" name="toggle"><span>$100</span></label>
    <label class="pink"><input type="radio" name="toggle"><span>$500</span></label>
    <label class="purple"><input type="radio" name="toggle"><span>$1000</span></label>
</div>

CSS

body {
    font-family:sans-serif;
}

#donate {
    margin:4px;

    float:left;
}

#donate label {
    float:left;
    width:170px;
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid #D0D0D0;
    overflow:auto;

}

#donate label span {
    text-align:center;
    font-size: 32px;
    padding:13px 0px;
    display:block;
}

#donate label input {
    position:absolute;
    top:-20px;
}

#donate input:checked + span {
    background-color:#404040;
    color:#F7F7F7;
}

#donate .yellow {
    background-color:#FFCC00;
    color:#333;
}

#donate .blue {
    background-color:#00BFFF;
    color:#333;
}

#donate .pink {
    background-color:#FF99FF;
    color:#333;
}

#donate .green {
    background-color:#A3D900;
    color:#333;
}
#donate .purple {
    background-color:#B399FF;
    color:#333;
}

Styled with coloured buttons :)

Finding the second highest number in array

I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:

 static int secondHighest(int... nums) {
    int high1 = Integer.MIN_VALUE;
    int high2 = Integer.MIN_VALUE;
    for (int num : nums) {
      if (num > high1) {
        high2 = high1;
        high1 = num;
      } else if (num > high2) {
        high2 = num;
      }
    }
    return high2;
 }

This is O(N) in one pass. If you want to accept ties, then change to if (num >= high1), but as it is, it will return Integer.MIN_VALUE if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE if the array contains only the same number.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory ** This is a solution if you are using Audit table.@Audit

Use:- @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.

Get file content from URL?

Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

Python group by

I also liked pandas simple grouping. it's powerful, simple and most adequate for large data set

result = pandas.DataFrame(input).groupby(1).groups

How can I cast int to enum?

I prefer a short way using a nullable enum type variable.

var enumValue = (MyEnum?)enumInt;

if (!enumValue.HasValue)
{
    throw new ArgumentException(nameof(enumValue));
}

Turn off deprecated errors in PHP 5.3

You can do it in code by calling the following functions.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

or

error_reporting(E_ALL ^ E_DEPRECATED);

Dependency injection with Jersey 2.0

Oracle recommends to add the @Path annotation to all types to be injected when combining JAX-RS with CDI: http://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced004.htm Though this is far from perfect (e.g. you will get warning from Jersey on startup), I decided to take this route, which saves me from maintaining all supported types within a binder.

Example:

@Singleton
@Path("singleton-configuration-service")
public class ConfigurationService {
  .. 
}

@Path("my-path")
class MyProvider {
  @Inject ConfigurationService _configuration;

  @GET
  public Object get() {..}
}

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

Does a finally block always get executed in Java?

The finally block is always executed unless there is abnormal program termination, either resulting from a JVM crash or from a call to System.exit(0).

On top of that, any value returned from within the finally block will override the value returned prior to execution of the finally block, so be careful of checking all exit points when using try finally.

Are strongly-typed functions as parameters possible in TypeScript?

Because you can't easily union a function definition and another data type, I find having these types around useful to strongly type them. Based on Drew's answer.

type Func<TArgs extends any[], TResult> = (...args: TArgs) => TResult; 
//Syntax sugar
type Action<TArgs extends any[]> = Func<TArgs, undefined>; 

Now you can strongly type every parameter and the return type! Here's an example with more parameters than what is above.

save(callback: Func<[string, Object, boolean], number>): number
{
    let str = "";
    let obj = {};
    let bool = true;
    let result: number = callback(str, obj, bool);
    return result;
}

Now you can write a union type, like an object or a function returning an object, without creating a brand new type that may need to be exported or consumed.

//THIS DOESN'T WORK
let myVar1: boolean | (parameters: object) => boolean;

//This works, but requires a type be defined each time
type myBoolFunc = (parameters: object) => boolean;
let myVar1: boolean | myBoolFunc;

//This works, with a generic type that can be used anywhere
let myVar2: boolean | Func<[object], boolean>;

CSS Circular Cropping of Rectangle Image

You need to use jQuery to do this. This approach gives you the abbility to have dynamic images and do them round no matter the size.

My demo has one flaw right now I don't center the image in the container, but ill return to it in a minute (need to finish a script I'm working on).

DEMO

<div class="container">
    <img src="" class="image" alt="lambo" />
</div>

//script
var container = $('.container'),
    image = container.find('img');

container.width(image.height());


//css    
.container {
    height: auto;
    overflow: hidden;
    border-radius: 50%;    
}

.image {
    height: 100%;    
    display: block;    
}

How to change the status bar background color and text color on iOS 7?

The below code snippet should work with Objective C.

   if (@available(iOS 13.0, *)) {
      UIView *statusBar = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
      statusBar.backgroundColor = [UIColor whiteColor];
      [[UIApplication sharedApplication].keyWindow addSubview:statusBar];
  } else {
      // Fallback on earlier versions

       UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
          if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
              statusBar.backgroundColor = [UIColor whiteColor];//set whatever color you like
      }
  }

GCC -fPIC option

The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.


There are two commonly used methods for dealing with this problem:

1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.

2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.


The name "position-independent code" actually implies following:

  • The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.

  • The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.

  • All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.


This so-called symbol interposition is intended to mimic the behavior of static libraries.

A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.

p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.

You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf

The result of a query cannot be enumerated more than once

Try explicitly enumerating the results by calling ToList().

Change

foreach (var item in query)

to

foreach (var item in query.ToList())

connecting to mysql server on another PC in LAN

Users who can Install MySQL Workbench on MySQL Server Machine

If you use or have MySQL Workbench on the MySQL Server PC you can do this with just a few clicks. Recommend only for development environment.

  1. Connect to MySQL Server

Connect to MySQL Server with MySQL Workbench

  1. Find this option Users and Privileges from Navigator and click on it.

Users and Privileges - MySQL Workbench

  1. Select root user and change value for Limit to Hosts Matching to %.

Users and Privileges - MySQL Workbench

  1. The click Apply at the bottom.

This should enable root user to access MySQL Server from remote machine.

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

MySQL set current date in a DATETIME field on insert

Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.

  1. http://www.mysqltutorial.org/sql-triggers.aspx
  2. http://www.tutorialspoint.com/plsql/plsql_triggers.htm

These two toturial will help to implement the trigger.

How do I wait for a promise to finish before returning the variable of a function?

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

When does Java's Thread.sleep throw InterruptedException?

If an InterruptedException is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt() method. The wait method detects that and throws an InterruptedException so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.

If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:

} catch (InterruptedException e) {
  Thread.currentThread().interrupt();
  // code for stopping current task so thread stops
}

Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.

What might be better is to add this:

} catch (InterruptedException e) {
  throw new RuntimeException("Unexpected interrupt", e);
}

...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.

Word-wrap in an HTML table

It appears you need to set word-wrap:break-word; on a block element (div), with specified (non relative) width. Ex:

_x000D_
_x000D_
<table style="width: 100%;"><tr>_x000D_
    <td><div style="display:block; word-wrap: break-word; width: 40em;">loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</div></td>_x000D_
    <td><span style="display: inline;">Foo</span></td>_x000D_
</tr></table>
_x000D_
_x000D_
_x000D_

or using word-break:break-all per Abhishek Simon's suggestion.

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

sorting and paging with gridview asp.net

More simple way...:

    Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
    Dim dv As New DataView(dt)

    If GridView1.Attributes("dir") = SortDirection.Ascending Then
        dv.Sort = e.SortExpression & " DESC" 
        GridView1.Attributes("dir") = SortDirection.Descending

    Else
        GridView1.Attributes("dir") = SortDirection.Ascending
        dv.Sort = e.SortExpression & " ASC"

    End If

    GridView1.DataSource = dv
    GridView1.DataBind()

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

Is there an easy way to check the .NET Framework version?

Not sure why nobody suggested following the official advice from Microsoft right here.

This is the code they recommend. Sure it's ugly, but it works.

For .NET 1-4

private static void GetVersionFromRegistry()
{
     // Opens the registry key for the .NET Framework entry. 
        using (RegistryKey ndpKey = 
            RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
            OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5  
            // or later, you can use: 
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,  
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        foreach (string versionKeyName in ndpKey.GetSubKeyNames())
        {
            if (versionKeyName.StartsWith("v"))
            {

                RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                string name = (string)versionKey.GetValue("Version", "");
                string sp = versionKey.GetValue("SP", "").ToString();
                string install = versionKey.GetValue("Install", "").ToString();
                if (install == "") //no install info, must be later.
                    Console.WriteLine(versionKeyName + "  " + name);
                else
                {
                    if (sp != "" && install == "1")
                    {
                        Console.WriteLine(versionKeyName + "  " + name + "  SP" + sp);
                    }

                }
                if (name != "")
                {
                    continue;
                }
                foreach (string subKeyName in versionKey.GetSubKeyNames())
                {
                    RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                    name = (string)subKey.GetValue("Version", "");
                    if (name != "")
                        sp = subKey.GetValue("SP", "").ToString();
                    install = subKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                        Console.WriteLine(versionKeyName + "  " + name);
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            Console.WriteLine("  " + subKeyName + "  " + name + "  SP" + sp);
                        }
                        else if (install == "1")
                        {
                            Console.WriteLine("  " + subKeyName + "  " + name);
                        }

                    }

                }

            }
        }
    }

}

For .NET 4.5 and later

// Checking the version using >= will enable forward compatibility, 
// however you should always compile your code on newer versions of
// the framework to ensure your app works the same.
private static string CheckFor45DotVersion(int releaseKey)
{
   if (releaseKey >= 393295) {
      return "4.6 or later";
   }
   if ((releaseKey >= 379893)) {
        return "4.5.2 or later";
    }
    if ((releaseKey >= 378675)) {
        return "4.5.1 or later";
    }
    if ((releaseKey >= 378389)) {
        return "4.5 or later";
    }
    // This line should never execute. A non-null release key should mean
    // that 4.5 or later is installed.
    return "No 4.5 or later version detected";
}

private static void Get45or451FromRegistry()
{
    using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) {
        if (ndpKey != null && ndpKey.GetValue("Release") != null) {
            Console.WriteLine("Version: " + CheckFor45DotVersion((int) ndpKey.GetValue("Release")));
        }
      else {
         Console.WriteLine("Version 4.5 or later is not detected.");
      } 
    }
}

How do I insert values into a Map<K, V>?

The syntax is

data.put("John","Taxi driver");

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

Auto select file in Solution Explorer from its open tab

I've put in a feature request for this very feature. Although I know this isn't an answer in itself it is a step in the direction of being able to get this feature implemented. Any votes it it may help to get Microsoft's attention.

As far as I'm aware of though there is no way to do this other than possibly writing a macro or creating your own add-in/extension to Visual Studio.

how to upload a file to my server using html

<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
   <input id="fileupload" name="myfile" type="file" />
   <input type="submit" value="submit" id="submit" />
</form>

To upload a file, it is essential to set enctype="multipart/form-data" on your form

You need that form type and then some php to process the file :)

You should probably check out Uploadify if you want something very customisable out of the box.

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

How to get disk capacity and free space of remote computer

There are two issues I encountered with the other suggestions

    1) Drive mappings are not supported if you run the powershell under task scheduler
    2) You may get Access is denied errors errors trying to used "get-WmiObject" on remote computers (depending on your infrastructure setup, of course)

The alternative that doesn't suffer from these issues is to use GetDiskFreeSpaceEx with a UNC path:

function getDiskSpaceInfoUNC($p_UNCpath, $p_unit = 1tb, $p_format = '{0:N1}')
{
    # unit, one of --> 1kb, 1mb, 1gb, 1tb, 1pb
    $l_typeDefinition = @' 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        [return: MarshalAs(UnmanagedType.Bool)] 
        public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, 
            out ulong lpFreeBytesAvailable, 
            out ulong lpTotalNumberOfBytes, 
            out ulong lpTotalNumberOfFreeBytes); 
'@
    $l_type = Add-Type -MemberDefinition $l_typeDefinition -Name Win32Utils -Namespace GetDiskFreeSpaceEx -PassThru

    $freeBytesAvailable     = New-Object System.UInt64 # differs from totalNumberOfFreeBytes when per-user disk quotas are in place
    $totalNumberOfBytes     = New-Object System.UInt64
    $totalNumberOfFreeBytes = New-Object System.UInt64

    $l_result = $l_type::GetDiskFreeSpaceEx($p_UNCpath,([ref]$freeBytesAvailable),([ref]$totalNumberOfBytes),([ref]$totalNumberOfFreeBytes)) 

    $totalBytes     = if($l_result) { $totalNumberOfBytes    /$p_unit } else { '' }
    $totalFreeBytes = if($l_result) { $totalNumberOfFreeBytes/$p_unit } else { '' }

    New-Object PSObject -Property @{
        Success   = $l_result
        Path      = $p_UNCpath
        Total     = $p_format -f $totalBytes
        Free      = $p_format -f $totalFreeBytes
    } 
}

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

What are bitwise shift (bit-shift) operators and how do they work?

Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.

For example:

(long) 4 >> 65

equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:

(long) 4 >> (65 % 64)

This is true for <<, >>, and >>>. I have not tried it out in other languages.

Getter and Setter?

You can use php magic methods __get and __set.

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

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

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

    return $this;
  }
}
?>

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

Just go to References and add "System.IO.Compression.FileSystem".

How do I increase memory on Tomcat 7 when running as a Windows Service?

If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8

08/14/2019  10:24 PM           116,648 Tomcat-Custom.exe
08/14/2019  10:24 PM           119,720 Tomcat-Customw.exe
               2 File(s)        236,368 bytes

Running the "w" terminated executable will let you configure Xmx in the Java tab
enter image description here

Trying to load local JSON file to show data in a html page using JQuery

Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
<script type="text/javascript" language="javascript" src="priorities.json"></script> 

<script type="text/javascript">
   $(document).ready(function(e) {
         alert(jsonObject.start.count);
   });
</script>

Your priorities.json file:

var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
     <script type="text/javascript">
           $(document).ready(function(e) {

           });

           function jsonCallback(jsonObject){
               alert(jsonObject.start.count);
           }
        </script>

 <script type="text/javascript" language="javascript" src="priorities.json"></script> 

Your priorities.json file:

jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

How do I remove a submodule?

Simple steps

  1. Remove config entries:
    git config -f .git/config --remove-section submodule.$submodulename
    git config -f .gitmodules --remove-section submodule.$submodulename
  2. Remove directory from index:
    git rm --cached $submodulepath
  3. Commit
  4. Delete unused files:
    rm -rf $submodulepath
    rm -rf .git/modules/$submodulename

Please note: $submodulepath doesn't contain leading or trailing slashes.

Background

When you do git submodule add, it only adds it to .gitmodules, but once you did git submodule init, it added to .git/config.

So if you wish to remove the modules, but be able to restore it quickly, then do just this:

git rm --cached $submodulepath
git config -f .git/config --remove-section submodule.$submodulepath

It is a good idea to do git rebase HEAD first and git commit at the end, if you put this in a script.

Also have a look at an answer to Can I unpopulate a Git submodule?.

Check if a value exists in ArrayList

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

Get the index of a certain value in an array in PHP

The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

$list = ['string1', 'string2', 'string3'];
$index = array_search('string2',array_values($list));

Setting a max height on a table

NOTE this answer is now incorrect. I may get back to it at a later time.

As others have pointed out, you can't set the height of a table unless you set its display to block, but then you get a scrolling header. So what you're looking for is to set the height and display:block on the tbody alone:

<table style="border: 1px solid red">
    <thead>
        <tr>
            <td>Header stays put, no scrolling</td>
        </tr>
    </thead>
    <tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
        <tr>
            <td>cell 1/1</td>
            <td>cell 1/2</td>
        </tr>
        <tr>
            <td>cell 2/1</td>
            <td>cell 2/2</td>
        </tr>
        <tr>
            <td>cell 3/1</td>
            <td>cell 3/2</td>
        </tr>
    </tbody>
</table>

Here's the fiddle.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

SOLUTIONS

  1. Sometimes the project is created before installing g++. So install g++ first and then recreate your project. This worked for me.
  2. Paste the following line in CMakeCache.txt: CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++

Note the path to g++ depends on OS. I have used my fedora path obtained using which g++

CentOS: Enabling GD Support in PHP Installation

CentOs 6.5+ & PHP 5.6:

sudo yum install php56-gd

service httpd restart

Detect page change on DataTable

I got it working using:

$('#id-of-table').on('draw.dt', function() {
    // do action here
});

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

Simple function:

CREATE FUNCTION [dbo].[RemoveAlphaCharacters](@InputString VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
  WHILE PATINDEX('%[^0-9]%',@InputString)>0
        SET @InputString = STUFF(@InputString,PATINDEX('%[^0-9]%',@InputString),1,'')     
  RETURN @InputString
END

GO

How to position three divs in html horizontally?

You can use floating elements like so:

<div id="the whole thing" style="height:100%; width:100%; overflow: hidden;">
    <div id="leftThing" style="float: left; width:25%; background-color:blue;">Left Side Menu</div>
    <div id="content" style="float: left; width:50%; background-color:green;">Random Content</div>
    <div id="rightThing" style="float: left; width:25%; background-color:yellow;">Right Side Menu</div>
</div>

Note the overflow: hidden; on the parent container, this is to make the parent grow to have the same dimensions as the child elements (otherwise it will have a height of 0).

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Reminder: If you do combine multiple contexts make sure you cut n paste all the functionality in your various RealContexts.OnModelCreating() into your single CombinedContext.OnModelCreating().

I just wasted time hunting down why my cascade delete relationships weren't being preserved only to discover that I hadn't ported the modelBuilder.Entity<T>()....WillCascadeOnDelete(); code from my real context into my combined context.

The backend version is not supported to design database diagrams or tables

You only get that message if you try to use Designer or diagrams. If you use t-SQL it works fine:

Select * 

into newdb.dbo.newtable
from olddb.dbo.yourtable

where olddb.dbo.yourtable has been created in 2008 exactly as you want the table to be in 2012

How do I copy the contents of a String to the clipboard in C#?

Use try-catch, even if it has an error it will still copy.

Try
   Clipboard.SetText("copy me to clipboard")
Catch ex As Exception

End Try

If you use a message box to capture the exception, it will show you error, but the value is still copied to clipboard.

Ansible: Set variable to file content

You can use lookups in Ansible in order to get the contents of a file, e.g.

user_data: "{{ lookup('file', user_data_file) }}"

Caveat: This lookup will work with local files, not remote files.

Here's a complete example from the docs:

- hosts: all
  vars:
     contents: "{{ lookup('file', '/etc/foo.txt') }}"
  tasks:
     - debug: msg="the value of foo.txt is {{ contents }}"

Why can't I have abstract static methods in C#?

This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to type instances. They can also be used as bounds for generic parameters; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.

In this context you may want to do something like this:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = TAnimal.ScientificName; // abstract static property
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

And here the capacity to express static members that can be specialized by subclasses totally makes sense!

Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can emulate them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.

The main idea is to associate an abstract companion class (here SpeciesFor<TAnimal>) to the one that should contain abstract members (here Animal):

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal
{
    public static SpeciesFor<TAnimal> Instance { get { … } }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

public abstract class Animal { … }

Now we would like to make this work:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

Of course we have two problems to solve:

  1. How do we allow and force an implementer of a subclass of Animal to associate a specific instance of SpeciesFor<TAnimal> to this subclass?
  2. How does the property SpeciesFor<TAnimal>.Instance retrieve this information?

Here is how we can solve 1:

public abstract class Animal<TSelf> where TSelf : Animal<TSelf>
{
    private Animal(…) {}
    
    public abstract class OfSpecies<TSpecies> : Animal<TSelf>
        where TSpecies : SpeciesFor<TSelf>, new()
    {
        protected OfSpecies(…) : base(…) { }
    }
    
    …
}

By making the constructor of Animal<TSelf> private we make sure that all its subclasses are also subclasses of inner class Animal<TSelf>.OfSpecies<TSpecies>. So these subclasses must specify a TSpecies type that has a new() bound.

For 2 we can provide the following implementation:

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>
{
    private static SpeciesFor<TAnimal> _instance;

    public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();

    private static SpeciesFor<TAnimal> MakeInstance()
    {
        Type t = typeof(TAnimal);
        while (true)
        {
            if (t.IsConstructedGenericType
                    && t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))
                return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);
            t = t.BaseType;
            if (t == null)
                throw new InvalidProgramException();
        }
    }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

How can we be sure that the reflection code inside MakeInstance() never throws? As we've already said, almost all classes within the hierarchy of Animal<TSelf> are also subclasses of Animal<TSelf>.OfSpecies<TSpecies>. So we know that for these classes a specific TSpecies must be provided. This type is also necessarily constructible thanks to constraint : new(). But this still leaves abstract types like Animal<Something> that have no associated species. Now we can convince ourself that the curiously recurring template pattern where TAnimal : Animal<TAnimal> makes it impossible to write SpeciesFor<Animal<Something>>.Instance as type Animal<Something> is never a subtype of Animal<Animal<Something>>.

Et voilà:

public class CatSpecies : SpeciesFor<Cat>
{
    // overriden "static" members

    public override string ScientificName => "Felis catus";
    public override Cat CreateInVivoFromDnaTrappedInAmber() { … }
    public override Cat Clone(Cat a) { … }
    public override Cat Breed(Cat a1, Cat a2) { … }
}

public class Cat : Animal<Cat>.OfSpecies<CatSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class DogSpecies : SpeciesFor<Dog>
{
    // overriden "static" members

    public override string ScientificName => "Canis lupus familiaris";
    public override Dog CreateInVivoFromDnaTrappedInAmber() { … }
    public override Dog Clone(Dog a) { … }
    public override Dog Breed(Dog a1, Dog a2) { … }
}

public class Dog : Animal<Dog>.OfSpecies<DogSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class Program
{
    public static void Main()
    {
        ConductCrazyScientificExperimentsWith<Cat>();
        ConductCrazyScientificExperimentsWith<Dog>();
        ConductCrazyScientificExperimentsWith<Tyranosaurus>();
        ConductCrazyScientificExperimentsWith<Wyvern>();
    }
    
    public static void ConductCrazyScientificExperimentsWith<TAnimal>()
        where TAnimal : Animal<TAnimal>
    {
        // Look Ma! No animal instance polymorphism!
        
        TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);
        TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);
        TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);
        
        Console.WriteLine(
            "The confederation of mad scientists is happy to announce the birth " +
            $"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.");
    }
}

A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary Mammal class associated to a MammalClass companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.

what is the difference between json and xml

The difference between XML and JSON is that XML is a meta-language/markup language and JSON is a lightweight data-interchange. That is, XML syntax is designed specifically to have no inherent semantics. Particular element names don't mean anything until a particular processing application processes them in a particular way. By contrast, JSON syntax has specific semantics built in stuff between {} is an object, stuff between [] is an array, etc.

A JSON parser, therefore, knows exactly what every JSON document means. An XML parser only knows how to separate markup from data. To deal with the meaning of an XML document, you have to write additional code.

To illustrate the point, let me borrow Guffa's example:

{   "persons": [
  {
    "name": "Ford Prefect",
    "gender": "male"
 },
 {
   "name": "Arthur Dent",
   "gender": "male"
  },
  {
    "name": "Tricia McMillan",
    "gender": "female"
  }   ] }

The XML equivalent he gives is not really the same thing since while the JSON example is semantically complete, the XML would require to be interpreted in a particular way to have the same effect. In effect, the JSON is an example uses an established markup language of which the semantics are already known, whereas the XML example creates a brand new markup language without any predefined semantics.

A better XML equivalent would be to define a (fictitious) XJSON language with the same semantics as JSON, but using XML syntax. It might look something like this:

<xjson>   
  <object>
    <name>persons</name>
    <value>
      <array>
         <object>
            <value>Ford Prefect</value>
            <gender>male</gender>
         </object>
         <object>
            <value>Arthur Dent</value>
            <gender>male</gender>
         </object>
         <object>
            <value>Tricia McMillan</value>
            <gender>female</gender>
         </object>
      </array>
    </value>   
  </object> 
 </xjson>

Once you wrote an XJSON processor, it could do exactly what JSON processor does, for all the types of data that JSON can represent, and you could translate data losslessly between JSON and XJSON.

So, to complain that XML does not have the same semantics as JSON is to miss the point. XML syntax is semantics-free by design. The point is to provide an underlying syntax that can be used to create markup languages with any semantics you want. This makes XML great for making up ad-hoc data and document formats, because you don't have to build parsers for them, you just have to write a processor for them.

But the downside of XML is that the syntax is verbose. For any given markup language you want to create, you can come up with a much more succinct syntax that expresses the particular semantics of your particular language. Thus JSON syntax is much more compact than my hypothetical XJSON above.

If follows that for really widely used data formats, the extra time required to create a unique syntax and write a parser for that syntax is offset by the greater succinctness and more intuitive syntax of the custom markup language. It also follows that it often makes more sense to use JSON, with its established semantics, than to make up lots of XML markup languages for which you then need to implement semantics.

It also follows that it makes sense to prototype certain types of languages and protocols in XML, but, once the language or protocol comes into common use, to think about creating a more compact and expressive custom syntax.

It is interesting, as a side note, that SGML recognized this and provided a mechanism for specifying reduced markup for an SGML document. Thus you could actually write an SGML DTD for JSON syntax that would allow a JSON document to be read by an SGML parser. XML removed this capability, which means that, today, if you want a more compact syntax for a specific markup language, you have to leave XML behind, as JSON does.

Setting unique Constraint with fluent API?

As an addition to Yorro's answer, it can also be done by using attributes.

Sample for int type unique key combination:

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }

If the data type is string, then MaxLength attribute must be added:

[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }

[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }

If there is a domain/storage model separation concern, using Metadatatype attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396


A quick console app example:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace EFIndexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
                context.UserSet.Add(newUser);
                context.SaveChanges();
            }
        }
    }

    [MetadataType(typeof(UserMetadata))]
    public class User
    {
        public int Id { get; set; }
        public int UniqueKeyIntPart1 { get; set; }
        public int UniqueKeyIntPart2 { get; set; }
        public string UniqueKeyStringPart1 { get; set; }
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class UserMetadata
    {
        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
        public int UniqueKeyIntPart1 { get; set; }

        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
        public int UniqueKeyIntPart2 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
        [MaxLength(50)]
        public string UniqueKeyStringPart1 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
        [MaxLength(50)]
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public virtual DbSet<User> UserSet { get; set; }
    }
}

Get the filePath from Filename using Java

You can use the Path api:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();

Add newline to VBA or Visual Basic 6

Visual Basic has built-in constants for newlines:

vbCr = Chr$(13) = CR (carriage-return character) - used by Mac OS and Apple II family

vbLf = Chr$(10) = LF (line-feed character) - used by Linux and Mac OS X

vbCrLf = Chr$(13) & Chr$(10) = CRLF (carriage-return followed by line-feed) - used by Windows

vbNewLine = the same as vbCrLf

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

Adding another use case where I found this happening. I was using a ADF Fusion application and the column type being used was a varchar2(4000) which could not accommodate the text and hence this error.

How to select multiple files with <input type="file">?

Thats easy ...

<input type='file' multiple>
$('#file').on('change',function(){
     _readFileDataUrl(this,function(err,files){
           if(err){return}
           console.log(files)//contains base64 encoded string array holding the 
           image data 
     });
});
var _readFileDataUrl=function(input,callback){
    var len=input.files.length,_files=[],res=[];
    var readFile=function(filePos){
        if(!filePos){
            callback(false,res);
        }else{
            var reader=new FileReader();
            reader.onload=function(e){              
                res.push(e.target.result);
                readFile(_files.shift());
            };
            reader.readAsDataURL(filePos);
        }
    };
    for(var x=0;x<len;x++){
        _files.push(input.files[x]);
    }
    readFile(_files.shift());
};

How do I clone a generic List in Java?

This is the code I use for that:

ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);

Hope is usefull for you

How to kill all processes matching a name?

If you're using cygwin or some minimal shell that lacks killall you can just use this script:

killall.sh - Kill by process name.

#/bin/bash
ps -W | grep "$1" | awk '{print $1}' | xargs kill --

Usage:

$ killall <process name>

Disabling tab focus on form elements

You have to disable or enable the individual elements. This is how I did it:

$(':input').keydown(function(e){
     var allowTab = true; 
     var id = $(this).attr('name');

     // insert your form fields here -- (:'') is required after
     var inputArr = {username:'', email:'', password:'', address:''}

     // allow or disable the fields in inputArr by changing true / false
     if(id in inputArr) allowTab = false; 

     if(e.keyCode==9 && allowTab==false) e.preventDefault();
});

How to specify legend position in matplotlib in graph coordinates

The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.
Therefore, when specifying bbox_to_anchor, always specify loc as well.

The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

enter image description here

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()    
plt.show()

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .


If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How do I check if file exists in Makefile so I can delete it?

Or just put it on one line, as make likes it:

if [ -a myApp ]; then rm myApp; fi;

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>

Include php files when they are in different folders

If I understand you correctly, You have two folders, one houses your php script that you want to include into a file that is in another folder?

If this is the case, you just have to follow the trail the right way. Let's assume your folders are set up like this:

root
    includes
        php_scripts
            script.php
    blog
        content
            index.php

If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:

include("../../../includes/php_scripts/script.php");

The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.

Is there a unique Android device ID?

Get Device UUID, model number with brand name and its version number with the help of below function.

Work in Android 10 perfectly and no need to allow read phone state permission.

Code Snippets:

private void fetchDeviceInfo() {
    String uniquePseudoID = "35" +
            Build.BOARD.length() % 10 +
            Build.BRAND.length() % 10 +
            Build.DEVICE.length() % 10 +
            Build.DISPLAY.length() % 10 +
            Build.HOST.length() % 10 +
            Build.ID.length() % 10 +
            Build.MANUFACTURER.length() % 10 +
            Build.MODEL.length() % 10 +
            Build.PRODUCT.length() % 10 +
            Build.TAGS.length() % 10 +
            Build.TYPE.length() % 10 +
            Build.USER.length() % 10;

    String serial = Build.getRadioVersion();
    String uuid=new UUID(uniquePseudoID.hashCode(), serial.hashCode()).toString();
    String brand=Build.BRAND;
    String modelno=Build.MODEL;
    String version=Build.VERSION.RELEASE;
    Log.e(TAG, "fetchDeviceInfo: \n "+
            "\n uuid is : "+uuid+
            "\n brand is: "+brand+
            "\n model is: "+modelno+
            "\n version is: "+version);
}

Call Above function and to check output of above code. please see your log cat in android studio. It look likes below:

enter image description here

SQL query: Delete all records from the table except latest N?

You cannot delete the records that way, the main issue being that you cannot use a subquery to specify the value of a LIMIT clause.

This works (tested in MySQL 5.0.67):

DELETE FROM `table`
WHERE id NOT IN (
  SELECT id
  FROM (
    SELECT id
    FROM `table`
    ORDER BY id DESC
    LIMIT 42 -- keep this many records
  ) foo
);

The intermediate subquery is required. Without it we'd run into two errors:

  1. SQL Error (1093): You can't specify target table 'table' for update in FROM clause - MySQL doesn't allow you to refer to the table you are deleting from within a direct subquery.
  2. SQL Error (1235): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' - You can't use the LIMIT clause within a direct subquery of a NOT IN operator.

Fortunately, using an intermediate subquery allows us to bypass both of these limitations.


Nicole has pointed out this query can be optimised significantly for certain use cases (such as this one). I recommend reading that answer as well to see if it fits yours.

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

Programmatically set image to UIImageView with Xcode 6.1/Swift

With swift syntax this worked for me :

    let leftImageView = UIImageView()
    leftImageView.image = UIImage(named: "email")

    let leftView = UIView()
    leftView.addSubview(leftImageView)

    leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
    leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
    userNameTextField.leftViewMode = .always
    userNameTextField.leftView = leftView

How to compile or convert sass / scss to css with node-sass (no Ruby)?

In Windows 10 using node v6.11.2 and npm v3.10.10, in order to execute directly in any folder:

> node-sass [options] <input.scss> [output.css]

I only followed the instructions in node-sass Github:

  1. Add node-gyp prerequisites by running as Admin in a Powershell (it takes a while):

    > npm install --global --production windows-build-tools
    
  2. In a normal command-line shell (Win+R+cmd+Enter) run:

    > npm install -g node-gyp
    > npm install -g node-sass
    

    The -g places these packages under %userprofile%\AppData\Roaming\npm\node_modules. You may check that npm\node_modules\node-sass\bin\node-sass now exists.

  3. Check if your local account (not the System) PATH environment variable contains:

    %userprofile%\AppData\Roaming\npm
    

    If this path is not present, npm and node may still run, but the modules bin files will not!

Close the previous shell and reopen a new one and run either > node-gyp or > node-sass.

Note:

  • The windows-build-tools may not be necessary (if no compiling is done? I'd like to read if someone made it without installing these tools), but it did add to the admin account the GYP_MSVS_VERSION environment variable with 2015 as a value.
  • I am also able to run directly other modules with bin files, such as > uglifyjs main.js main.min.js and > mocha

How to display alt text for an image in chrome

To display the Alt text of missing images, we have to add a style like this. I think, there is no need to add extra javascript for this.

.Your_Image_Class_Name {
  font-size: 14px;
}

It's work for me. Enjoy!!!!

check output from CalledProcessError

If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

import subprocess

command = ["ls", "-l"]
try:
    output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
    success = True 
except subprocess.CalledProcessError as e:
    output = e.output.decode()
    success = False

print(output)

This is Python 2 and 3 compatible.

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

This means that the first parameter you passed is a boolean (true or false).

The first parameter is $result, and it is false because there is a syntax error in the query.

" ... WHERE PartNumber = $partid';"

You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)

You should escape the variable:

" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"

Or better, use Prepared Statements.

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

What is the purpose of "&&" in a shell command?

command-line - what is the purpose of &&?

In shell, when you see

$ command one && command two

the intent is to execute the command that follows the && only if the first command is successful. This is idiomatic of Posix shells, and not only found in Bash.

It intends to prevent the running of the second process if the first fails.

You may notice I've used the word "intent" - that's for good reason. Not all programs have the same behavior, so for this to work, you need to understand what the program considers a "failure" and how it handles it by reading the documentation and, if necessary, the source code.

Your shell considers a return value of 0 for true, other positive numbers for false

Programs return a signal on exiting. They should return 0 if they exit successfully, or greater than zero if they do not. This allows a limited amount of communication between processes.

The && is referred to as AND_IF in the posix shell grammar, which is part of an and_or list of commands, which also include the || which is an OR_IF with similar semantics.

Grammar symbols, quoted from the documentation:

%token  AND_IF    OR_IF    DSEMI
/*      '&&'      '||'     ';;'    */

And the Grammar (also quoted from the documentation), which shows that any number of AND_IFs (&&) and/or OR_IFs (||) can be be strung together (as and_or is defined recursively):

and_or           :                         pipeline
                 | and_or AND_IF linebreak pipeline
                 | and_or OR_IF  linebreak pipeline

Both operators have equal precedence and are evaluated left to right (they are left associative). As the docs say:

An AND-OR list is a sequence of one or more pipelines separated by the operators "&&" and "||" .

A list is a sequence of one or more AND-OR lists separated by the operators ';' and '&' and optionally terminated by ';', '&', or .

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output:

$ false && echo foo || echo bar
$ true || echo foo && echo bar
  1. In the first case, the false is a command that exits with the status of 1

    $ false
    $ echo $?
    1
    

    which means echo foo does not run (i.e., shortcircuiting echo foo). Then the command echo bar is executed.

  2. In the second case, true exits with a code of 0

    $ true
    $ echo $?
    0
    

    and therefore echo foo is not executed, then echo bar is executed.

How to convert an object to JSON correctly in Angular 2 with TypeScript

Because you're encapsulating the product again. Try to convert it like so:

let body = JSON.stringify(product); 

How to get child element by ID in JavaScript?

Using jQuery

$('#note textarea');

or just

$('#textid');

How to drop all tables from the database with manage.py CLI in Django?

The command ./manage.py sqlclear or ./manage.py sqlflush seems to clear the table and not delete them, however if you want to delete the complete database try this : manage.py flush.

Warning: this will delete your database completely and you will lose all your data, so if that not important go ahead and try it.

Connecting to SQL Server Express - What is my server name?

Instead of giving:

./SQLEXPRESS //in the Server Name

I put this:

.\SQLEXPRESS //which solved my problem

GIT clone repo across local file system in windows

You can specify the remote’s URL by applying the UNC path to the file protocol. This requires you to use four slashes:

git clone file:////<host>/<share>/<path>

For example, if your main machine has the IP 192.168.10.51 and the computer name main, and it has a share named code which itself is a git repository, then both of the following commands should work equally:

git clone file:////main/code
git clone file:////192.168.10.51/code

If the Git repository is in a subdirectory, simply append the path:

git clone file:////main/code/project-repository
git clone file:////192.168.10.51/code/project-repository

How do I make a new line in swift

Also useful:

let multiLineString = """
                  Line One
                  Line Two
                  Line Three
                  """
  • Makes the code read more understandable
  • Allows copy pasting

Use YAML with variables

if your requirement is like parsing an replacing multiple variable and then use it as a hash/or anything then you can do something like this

require 'yaml'
require 'json'
yaml = YAML.load_file("xxxx.yaml")
blueprint = yaml.to_json % { var_a: "xxxx", var_b: "xxxx"}
hash = JSON.parse(blueprint)

inside the yaml just put variables like this

"%{var_a}"

how does array[100] = {0} set the entire array to 0?

It depends where you put this initialisation.

If the array is static as in

char array[100] = {0};

int main(void)
{
...
}

then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.

If your array is auto, then it is another story.

int foo(void)
{
char array[100] = {0};
...
}

In this case at every call of the function foo you will have a hidden memset.

The code above is equivalent to

int foo(void)
{ 
char array[100];

memset(array, 0, sizeof(array));
....
}

and if you omit the initializer your array will contain random data (the data of the stack).

If your local array is declared static like in

int foo(void)
{ 
static char array[100] = {0};
...
}

then it is technically the same case as the first one.

Iterating over dictionaries using 'for' loops

This is a very common looping idiom. in is an operator. For when to use for key in dict and when it must be for key in dict.keys() see David Goodger's Idiomatic Python article (archived copy).

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

Disable browser cache for entire ASP.NET website

I implemented all the previous answers and still had one view that did not work correctly.

It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.

After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.

Hiding table data using <div style="display:none">

Yes, you can hide only the rows that you want to hide. This can be helpful if you want to show rows only when some condition is satisfied in the rows that are currently being shown. The following worked for me.

<table>
  <tr><th>Sample Table</th></tr>  
  <tr id="row1">
    <td><input id="data1" type="text" name="data1" /></td>
  </tr>
 <tr id="row2" style="display: none;">
    <td><input id="data2" type="text" name="data2" /></td>
 </tr>
 <tr id="row3" style="display: none;">
    <td><input id="data3" type="text" name="data3" /></td>
 </tr>
</table>

In CSS, do the following:

#row2{
    display: none;
}

#row3{
    display: none;
}

In JQuery, you might have something like the following to show the desired rows.

$(document).ready(function(){
    if($("#row1").val() === "sometext"){  //your desired condition
        $("#row2").show();
    }

    if($("#row2").val() !== ""){   //your desired condition
        $("#row3").show();
    }
});

Set and Get Methods in java?

Setters and getters are used to replace directly accessing member variables from external classes. if you use a setter and getter in accessing a property, you can include initialization, error checking, complex transformations, etc. Some examples:

private String x;

public void setX(String newX) {
    if (newX == null) {
        x = "";
    } else {
        x = newX;
    }
}

public String getX() {
    if (x == null) {
        return "";
    } else {
       return x;
    }
}

Postgres FOR LOOP

I just ran into this question and, while it is old, I figured I'd add an answer for the archives. The OP asked about for loops, but their goal was to gather a random sample of rows from the table. For that task, Postgres 9.5+ offers the TABLESAMPLE clause on WHERE. Here's a good rundown:

https://www.2ndquadrant.com/en/blog/tablesample-in-postgresql-9-5-2/

I tend to use Bernoulli as it's row-based rather than page-based, but the original question is about a specific row count. For that, there's a built-in extension:

https://www.postgresql.org/docs/current/tsm-system-rows.html

CREATE EXTENSION tsm_system_rows;

Then you can grab whatever number of rows you want:

select * from playtime tablesample system_rows (15);

How to send FormData objects with Ajax-requests in jQuery?

You can use the $.ajax beforeSend event to manipulate the header.

beforeSend: function(xhr) { 
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
}

See this link for additional information: http://msdn.microsoft.com/en-us/library/ms536752(v=vs.85).aspx

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

How can Bash execute a command in a different directory context?

You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

# do something with /etc as the working directory
cd /etc
:

# do something with /tmp as the working directory
cd /tmp
:

You use the builtins just like any other command, and can change directory context as many times as you like in a script.

disable a hyperlink using jQuery

function EnableHyperLink(id) {
        $('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u 
        $('#' + id).addClass('enable-link');
        $('#' + id).removeClass('disable-link');
    }

    function DisableHyperLink(id) {
        $('#' + id).addClass('disable-link');
        $('#' + id).removeClass('enable-link');
        $('#' + id).removeAttr('onclick');
    }

.disable-link
{
    text-decoration: none !important;
    color: black !important;
    cursor: default;
}
.enable-link
{
    text-decoration: underline !important;
    color: #075798 !important;
    cursor: pointer !important;
}

Does C have a "foreach" loop construct?

C doesn't have a foreach, but macros are frequently used to emulate that:

#define for_each_item(item, list) \
    for(T * item = list->head; item != NULL; item = item->next)

And can be used like

for_each_item(i, processes) {
    i->wakeup();
}

Iteration over an array is also possible:

#define foreach(item, array) \
    for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
        keep && count != size; \
        keep = !keep, count++) \
      for(item = (array) + count; keep; keep = !keep)

And can be used like

int values[] = { 1, 2, 3 };
foreach(int *v, values) {
    printf("value: %d\n", *v);
}

Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer

or

sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

How to save a Seaborn plot into a file

You would get an error for using sns.figure.savefig("output.png") in seaborn 0.8.1.

Instead use:

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

CSS Float: Floating an image to the left of the text

Solution using display: flex (with responsive behavior): http://jsfiddle.net/dkulahin/w3472kct

HTML:

<div class="content">
    <img src="myimage.jpg" alt="" />
    <div class="details">
        <p>Lorem ipsum dolor sit amet...</p>
    </div>
</div>

CSS:

.content{
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
}
.content img {
    width: 150px;
}
.details {
    width: calc(100% - 150px);
}
@media only screen and (max-width: 480px) {
    .content {
        flex-direction: column;
    }
    .details {
        width: 100%;
    }
}

Make a number a percentage

The best solution, where en is the English locale:

fraction.toLocaleString("en", {style: "percent"})

Sending HTTP Post request with SOAP action using org.apache.http

Here is the example i have tried and it is working for me:

Create the XML file SoapRequestFile.xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

And here the code in java:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }

How to resize images proportionally / keeping the aspect ratio?

After some trial and error I came to this solution:

function center(img) {
    var div = img.parentNode;
    var divW = parseInt(div.style.width);
    var divH = parseInt(div.style.height);
    var srcW = img.width;
    var srcH = img.height;
    var ratio = Math.min(divW/srcW, divH/srcH);
    var newW = img.width * ratio;
    var newH = img.height * ratio;
    img.style.width  = newW + "px";
    img.style.height = newH + "px";
    img.style.marginTop = (divH-newH)/2 + "px";
    img.style.marginLeft = (divW-newW)/2 + "px";
}

How to replace a character with a newline in Emacs?

More explicitly:

To replace the semi colon character (;) with a newline, follow these exact steps.

  1. locate cursor at upper left of buffer containing text you want to change
  2. Type m-x replace-string and hit RETURN
  3. the mini-buffer will display something like this: Replace string (default ^ -> ):
  4. Type in the character you want to replace. In this case, ; and hit RETURN
  5. the mini-buffer will display something like this: string ; with:
  6. Now execute C-q C-j
  7. All instances of semi-colon will be replaced a newline (from the cursor location to the end of the buffer will now appear)

Bit more to it than the original explanation says.

How do I put the image on the right side of the text in a UIButton?

Swift 4 & 5

Change the direction of UIButton image (RTL and LTR)

extension UIButton {
    func changeDirection(){
       isArabic ? (self.contentHorizontalAlignment = .right) : (self.contentHorizontalAlignment = .left)
        // left-right margin 
        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    }
}

Error in MySQL when setting default value for DATE or DATETIME

Config syntax issue

On some versions of MYSQL (tested 5.7.*) under *nix systems you should use this syntax:

[mysqld]

sql-mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_ENGINE_SUBSTITUTION"

These won't work:

dash no quotes

sql-mode=NO_ENGINE_SUBSTITUTION

underscore no quotes

sql_mode=NO_ENGINE_SUBSTITUTION

underscore and quotes

sql_mode="NO_ENGINE_SUBSTITUTION"

A more complete review of config values and sql-mode:

How to setup permanent Sql Mode flags

Powershell Execute remote exe with command line arguments on remote computer

I have been trying to achieve this by using 1 row single entry but I ended that Invoke command did not worked successfully because it is killing the process immediately after starting despite it can work if you are entering the session and waiting enough before exiting.

The only working way I could find, for example, to run a command with arguments and space on the remote machine HFVMACHINE1 (running Windows 7) is the following:

([WMICLASS]"\\HFVMACHINE1\ROOT\CIMV2:win32_process").Create('c:\Program Files (x86)\Thinware\vBackup\vBackup.exe -v HFSVR12-WWW')

How to resolve cURL Error (7): couldn't connect to host?

In PHP, If your network under proxy. You should set the proxy URL and port

curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number

This is solves my problem

How to install an apk on the emulator in Android Studio?

Drag and drop apk if the emulator is launched from Android Studio. If the emulator is started from command line, drag and drop doesn't work, but @Tarek K. Ajaj instructions (above) work.

Note: Installed app won't automatically appear on the home screen, it is in the apps container - the dotted grid icon. It can be dragged from there to the home screen.

Difference between "this" and"super" keywords in Java

super is used to access methods of the base class while this is used to access methods of the current class.

Extending the notion, if you write super(), it refers to constructor of the base class, and if you write this(), it refers to the constructor of the very class where you are writing this code.

Concatenate string with field value in MySQL

MySQL uses CONCAT() to concatenate strings

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)

Where is the kibana error log? Is there a kibana error log?

Kibana 4 logs to stdout by default. Here is an excerpt of the config/kibana.yml defaults:

# Enables you specify a file where Kibana stores log output.
# logging.dest: stdout

So when invoking it with service, use the log capture method of that service. For example, on a Linux distribution using Systemd / systemctl (e.g. RHEL 7+):

journalctl -u kibana.service

One way may be to modify init scripts to use the --log-file option (if it still exists), but I think the proper solution is to properly configure your instance YAML file. For example, add this to your config/kibana.yml:

logging.dest: /var/log/kibana.log

Note that the Kibana process must be able to write to the file you specify, or the process will die without information (it can be quite confusing).

As for the --log-file option, I think this is reserved for CLI operations, rather than automation.

What does a question mark represent in SQL queries?

It's a parameter. You can specify it when executing query.

How to pause a vbscript execution?

You can use a WScript object and call the Sleep method on it:

Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds

Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000

WAMP 403 Forbidden message on Windows 7

I read & tried All Fixes But Not one worked. At last i Found that the Wamp Server Logo Is Green But Need to Be "PUT ONLINE". So simple & a Quick Fix After Checking Your PHPMyAdmin.Cofg & HttPD.cofg Just Click on PUT ONLINE

Eclipse copy/paste entire line keyboard shortcut

Another shortcut way to do this is press Ctrl+Shift+L and select which command you want to perform and hit enter enter image description here

its best practice for beginner.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

How to change Android version and code version number?

I didn't get the other answers to work in Android Studio 1.4. But this worked: click on your app name to the left below the main ribbon. It will show a list of files. Open AndroidManifest.xml and change the version code and version number there.

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

What are the different types of indexes, what are the benefits of each?

OdeToCode has a good article covering the basic differences

As it says in the article:

Proper indexes are crucial for good performance in large databases. Sometimes you can make up for a poorly written query with a good index, but it can be hard to make up for poor indexing with even the best queries.

Quite true, too... If you're just starting out with it, I'd focus on clustered and composite indexes, since they'll probably be what you use the most.

Spring Boot: Cannot access REST Controller on localhost (404)

It could be that something else is running on port 8080, and you're actually connecting to it by mistake.

Definitely check that out, especially if you have dockers that are bringing up other services you don't control, and are port forwarding those services.

postgresql port confusion 5433 or 5432?

The default port of Postgres is commonly configured in:

sudo vi /<path to your installation>/data/postgresql.conf

On Ubuntu this might be:

sudo vi /<path to your installation>/main/postgresql.conf

Search for port in this file.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

postgreSQL - psql \i : how to execute script in a given path

i did try this and its working in windows machine to run a sql file on a specific schema.

psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

How do I measure request and response times at once using cURL?

curl -v --trace-time This must be done in verbose mode

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

Type List vs type ArrayList in Java

I think the people who use (2) don't know the Liskov substitution principle or the Dependency inversion principle. Or they really have to use ArrayList.

Get total of Pandas column

Similar to getting the length of a dataframe, len(df), the following worked for pandas and blaze:

Total = sum(df['MyColumn'])

or alternatively

Total = sum(df.MyColumn)
print Total

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Restarting MySQL works fine for me.

What good are SQL Server schemas?

I think schemas are like a lot of new features (whether to SQL Server or any other software tool). You need to carefully evaluate whether the benefit of adding it to your development kit offsets the loss of simplicity in design and implementation.

It looks to me like schemas are roughly equivalent to optional namespaces. If you're in a situation where object names are colliding and the granularity of permissions is not fine enough, here's a tool. (I'd be inclined to say there might be design issues that should be dealt with at a more fundamental level first.)

The problem can be that, if it's there, some developers will start casually using it for short-term benefit; and once it's in there it can become kudzu.

Error occurred during initialization of boot layer FindException: Module not found

I faced same problem when I updated the Java version to 12.x. I was executing my project through Eclipse IDE. I am not sure whether this error is caused by compatibility issues.

However, I removed 12.x from my system and installed 8.x and my project started working fine.

javascript: using a condition in switch case

This works:

switch (true) {
    case liCount == 0:
        setLayoutState('start');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount<=5 && liCount>0:
        setLayoutState('upload1Row');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount<=10 && liCount>5:
        setLayoutState('upload2Rows');
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;
    case liCount>10:
        var api = $('#UploadList').data('jsp');
        api.reinitialise();
        break;                  
}

A previous version of this answer considered the parentheses to be the culprit. In truth, the parentheses are irrelevant here - the only thing necessary is switch(true){...} and for your case expressions to evaluate to booleans.

It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..} and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.

Eg: if liCount is 3, the first comparison is true === (liCount == 0), meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0). This expression evaluates to true, meaning this case is run, and terminates at the break. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.

It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ... might introduce a lot of visual noise or fragility.

Use with caution, because it is a non-standard pattern, despite being valid code.

Running Python in PowerShell?

The command [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User") is not a Python command. Instead, this is an operating system command to the set the PATH variable.

You are getting this error as you are inside the Python interpreter which was triggered by the command python you have entered in the terminal (Windows PowerShell).

Please note the >>> at the left side of the line. It states that you are on inside Python interpreter.

Please enter quit() to exit the Python interpreter and then type the command. It should work!

How to fix "Headers already sent" error in PHP

COMMON PROBLEMS:

(copied from: source)

====================

1) there should not be any output (i.e. echo.. or HTML codes) before the header(.......); command.

2) remove any white-space(or newline) before <?php and after ?> tags.

3) GOLDEN RULE! - check if that php file (and also, if you include other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!

4) After header(...); you must use exit;

5) always use 301 or 302 reference:

header("location: http://example.com",  true,  301 );  exit;

6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.

7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:

echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;

Detect click inside/outside of element with single event handler

Rather than using the jQuery .parents function (as suggested in the accepted answer), it's better to use .closest for this purpose. As explained in the jQuery api docs, .closest checks the element passed and all its parents, whereas .parents just checks the parents. Consequently, this works:

$(function() {
    $("body").click(function(e) {
        if ($(e.target).closest("#myDiv").length) {
            alert("Clicked inside #myDiv");
        } else { 
            alert("Clicked outside #myDiv");
        }
    });
})

How to make the python interpreter correctly handle non-ASCII characters in string operations?

Way too late for an answer, but the original string was in UTF-8 and '\xc2\xa0' is UTF-8 for NO-BREAK SPACE. Simply decode the original string as s.decode('utf-8') (\xa0 displays as a space when decoded incorrectly as Windows-1252 or latin-1:

Example (Python 3)

s = b'6\xc2\xa0918\xc2\xa0417\xc2\xa0712'
print(s.decode('latin-1')) # incorrectly decoded
u = s.decode('utf8') # correctly decoded
print(u)
print(u.replace('\N{NO-BREAK SPACE}','_'))
print(u.replace('\xa0','-')) # \xa0 is Unicode for NO-BREAK SPACE

Output

6 918 417 712
6 918 417 712
6_918_417_712
6-918-417-712

JavaScript: remove event listener

If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.

clickHandler = function(event){
  if (click++ == 49)
    canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);

How to upload file using Selenium WebDriver in Java

driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension");

What happened to Lodash _.pluck?

There isn't a need for _.map or _.pluck since ES6 has taken off.

Here's an alternative using ES6 JavaScript:

clips.map(clip => clip.id)

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment) in the manifest file (manifest.mf) defined. For example:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
 org.jdom;bundle-version="1.0.0",
 org.apache.commons.codec;bundle-version="1.3.0",
 bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...

In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.

Difference between jar and war in Java

From Java Tips: Difference between ear jar and war files:

These files are simply zipped files using the java jar tool. These files are created for different purposes. Here is the description of these files:

  • .jar files: The .jar files contain libraries, resources and accessories files like property files.

  • .war files: The war file contains the web application that can be deployed on any servlet/jsp container. The .war file contains jsp, html, javascript and other files necessary for the development of web applications.


Official Sun/Oracle descriptions:


Wikipedia articles:

View not attached to window manager crash

See how the Code is working here:

After calling the Async task, the async task runs in the background. that is desirable. Now, this Async task has a progress dialog which is attached to the Activity, if you ask how to see the code:

pDialog = new ProgressDialog(CLASS.this);

You are passing the Class.this as context to the argument. So the Progress dialog is still attached to the activity.

Now consider the scenario: If we try to finish the activity using the finish() method, while the async task is in progress, is the point where you are trying to access the Resource attached to the activity ie the progress bar when the activity is no more there.

Hence you get:

java.lang.IllegalArgumentException: View not attached to the window manager

Solution to this:

1) Make sure that the Dialog box is dismissed or canceled before the activity finishes.

2) Finish the activity, only after the dialog box is dismissed, that is the async task is over.

How to float a div over Google Maps?

Just set the position of the div and you may have to set the z-index.

ex.

div#map-div {
    position: absolute;
    left: 10px;
    top: 10px;
}
div#cover-div {
    position:absolute;
    left:10px;
    top: 10px;
    z-index:3;
}

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Change the position attribute to fixed instead of absolute.

Display a decimal in scientific notation

To convert a Decimal to scientific notation without needing to specify the precision in the format string, and without including trailing zeros, I'm currently using

def sci_str(dec):
    return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)

print( sci_str( Decimal('123.456000') ) )    # 1.23456E+2

To keep any trailing zeros, just remove the normalize().

CSS vertical-align: text-bottom;

To use vertical-align properly, you should do it on table tag. But there is a way to make other html tags to behave as a table by assigning them a css of display:table to your parent, and display:table-cell on your child. Then vertical-align:bottom will work on that child.

HTML:

??????<div class="parent">
    <div class="child">
        This text is vertically aligned to bottom.    
    </div>
</div>????????????????????????

CSS:

?.parent {
    width: 300px;
    height: 50px;
    display:? table;
    border: 1px solid red;
}
.child { 
    display: table-cell;
    vertical-align: bottom;
}?

Here is a live example: link demo

Remove last characters from a string in C#. An elegant way?

You can use TrimEnd. It's efficient as well and looks clean.

"Name,".TrimEnd(',');

How can I extract the folder path from file path in Python?

WITH PATHLIB MODULE (UPDATED ANSWER)

One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion> and is much easier read and program with </opinion>.

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

WITH OS MODULE

Use the os.path module:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

You can go ahead and assume that if you need to do some sort of filename manipulation it's already been implemented in os.path. If not, you'll still probably need to use this module as the building block.

jQuery Scroll to bottom of page/iframe

If you want a nice slow animation scroll, for any anchor with href="#bottom" this will scroll you to the bottom:

$("a[href='#bottom']").click(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
  return false;
});

Feel free to change the selector.

Python Error: "ValueError: need more than 1 value to unpack"

I assume you found this code on Exercise 14: Prompting And Passing.

Do the following:

script = '*some arguments*' 
user_name = '*some arguments*'

and that works perfectly

Check if URL has certain string with PHP

I think the easiest way is:

if (strpos($_SERVER['REQUEST_URI'], "car") !== false){
// car found
}

Value cannot be null. Parameter name: source

It could be as silly as in my case where savechanges was erroring bcoz the db did not have foreign keys and associations were added to EDM tables. I added foreign keys in the db and regenerated EDM for a fix.

The errors I was seeing are as follows: Case 1 -> when using DBContext for EDM Message=Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)

Case 2 -> when using ObjectContext for EDM Message=Unable to update the EntitySet 'Contact' because it has a DefiningQuery and no element exists in the element to support the current operation.

(Just wanted to throw it in there in case it helps someone).

Dynamically Add C# Properties at Runtime

Have you taken a look at ExpandoObject?

see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

From MSDN:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Allowing you to do cool things like:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
    {
        Console.WriteLine(msg);
    };

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);

Based on your actual code you may be more interested in:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

public sealed class MyDynObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

That way you just need:

var dyn = GetDynamicObject(new Dictionary<string, object>()
    {
        {"prop1", 12},
    });

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;

Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.

Access is denied when attaching a database

I attached the mdf file by right clicking the database and removing the log file AdventureWorks2012_Data_log.ldf in the wizard . The mdf file was placed in the following location

    C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA

The above method helped me to resolve the issue .

Converting from byte to int in java

if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff

Python Socket Multiple Clients

def get_clients():
    first_run = True
    startMainMenu = False

    while True:
        if first_run:
            global done
            done = False
            Thread(target=animate, args=("Waiting For Connection",)).start()

        Client, address = objSocket.accept()
        global menuIsOn
        if menuIsOn:
            menuIsOn = False  # will stop main menu
            startMainMenu = True

        done = True

        # Get Current Directory in Client Machine
        current_client_directory = Client.recv(1024).decode("utf-8", errors="ignore")

        # beep on connection
        beep()
        print(f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}")
        print('* Connected to: ' + address[0] + ':' + str(address[1]))
        try:
            get_client_info(Client, first_run)
        except Exception as e:
            print("Error data received is not a json!")
            print(e)
        now = datetime.now()
        current_time = now.strftime("%D %H:%M:%S")
        print("* Current Time =", current_time)

        print("* Current Folder in Client: " + current_client_directory + bcolors.WARNING)

        connections.append(Client)

        addresses.append(address)

        if first_run:
            Thread(target=threaded_main_menu, daemon=True).start()

            first_run = False
        else:
            print(f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end="")
        if startMainMenu == True:
            Thread(target=threaded_main_menu, daemon=True).start()
            startMainMenu = False

React won't load local images

Best way to load local images in react is as follows

For example, Keep all your images(or any assets like videos, fonts) in the public folder as shown below.

enter image description here

Simply write <img src='/assets/images/Call.svg' /> to access the Call.svg image from any of your react component

Note: Keeping your assets in public folder ensures that, you can access it from anywhere from the project, by just giving '/path_to_image' and no need for any path traversal '../../' like this

Freeze the top row for an html table only (Fixed Table Header Scrolling)

This is called Fixed Header Scrolling. There are a number of documented approaches:

http://www.imaputz.com/cssStuff/bigFourVersion.html

You won't effectively pull this off without JavaScript ... especially if you want cross browser support.

There are a number of gotchyas with any approach you take, especially concerning cross browser/version support.

Edit:

Even if it's not the header you want to fix, but the first row of data, the concept is still the same. I wasn't 100% which you were referring to.

Additional thought I was tasked by my company to research a solution for this that could function in IE7+, Firefox, and Chrome.

After many moons of searching, trying, and frustration it really boiled down to a fundamental problem. For the most part, in order to gain the fixed header, you need to implement fixed height/width columns because most solutions involve using two separate tables, one for the header which will float and stay in place over the second table that contains the data.

//float this one right over second table
<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
</table>

<table>
//Data
</table>

An alternative approach some try is utilize the tbody and thead tags but that is flawed too because IE will not allow you put a scrollbar on the tbody which means you can't limit its height (so stupid IMO).

<table>
  <thead style="do some stuff to fix its position">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  </thead>
  <tbody style="No scrolling allowed here!">
     Data here
  </tbody>
</table>

This approach has many issues such as ensures EXACT pixel widths because tables are so cute in that different browsers will allocate pixels differently based on calculations and you simply CANNOT (AFAIK) guarantee that the distribution will be perfect in all cases. It becomes glaringly obvious if you have borders within your table.

I took a different approach and said screw tables since you can't make this guarantee. I used divs to mimic tables. This also has issues of positioning the rows and columns (mainly because floating has issues, using in-line block won't work for IE7, so it really left me with using absolute positioning to put them in their proper places).

There is someone out there that made the Slick Grid which has a very similar approach to mine and you can use and a good (albeit complex) example for achieving this.

https://github.com/6pac/SlickGrid/wiki

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Expanding a parent <div> to the height of its children

Try this for the parent, it worked for me.

overflow:auto; 

UPDATE:

One more solution that worked:

Parent:

display: table;

Child:

display: table-row;

How to create byte array from HttpPostedFile

before stream.copyto, you must reset stream.position to 0; then it works fine.

What is 'Currying'?

Here you can find a simple explanation of currying implementation in C#. In the comments, I have tried to show how currying can be useful:

public static class FuncExtensions {
    public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
    {
        return x1 => x2 => func(x1, x2);
    }
}

//Usage
var add = new Func<int, int, int>((x, y) => x + y).Curry();
var func = add(1);

//Obtaining the next parameter here, calling later the func with next parameter.
//Or you can prepare some base calculations at the previous step and then
//use the result of those calculations when calling the func multiple times 
//with different input parameters.

int result = func(1);

Java Generics With a Class & an Interface - Together

Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:

<T extends ClassA & InterfaceB>

See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName for each one that you need.

This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max, which (wrapped onto two lines) is:

public static <T extends Object & Comparable<? super T>> T
                                           max(Collection<? extends T> coll)

why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.

It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:

class classB { }
interface interfaceC { }

public class MyClass<T extends classB & interfaceC> {
    Class<T> variable;
}

to get variable that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>, the class name must come first, and interfaces follow. And of course you can only list a single class.

Bootstrap carousel multiple frames at once

This is what worked for me. Very simple jQuery and CSS to make responsive carousel works independently of carousels on the same page. Highly customizable but basically a div with white-space nowrap containing a bunch of inline-block elements and put the last one at the beginning to move back or the first one to the end to move forward. Thank you insertAfter!

_x000D_
_x000D_
$('.carosel-control-right').click(function() {_x000D_
  $(this).blur();_x000D_
  $(this).parent().find('.carosel-item').first().insertAfter($(this).parent().find('.carosel-item').last());_x000D_
});_x000D_
$('.carosel-control-left').click(function() {_x000D_
  $(this).blur();_x000D_
  $(this).parent().find('.carosel-item').last().insertBefore($(this).parent().find('.carosel-item').first());_x000D_
});
_x000D_
@media (max-width: 300px) {_x000D_
  .carosel-item {_x000D_
    width: 100%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 300px) {_x000D_
  .carosel-item {_x000D_
    width: 50%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 500px) {_x000D_
  .carosel-item {_x000D_
    width: 33.333%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
  .carosel-item {_x000D_
    width: 25%;_x000D_
  }_x000D_
}_x000D_
.carosel {_x000D_
  position: relative;_x000D_
  background-color: #000;_x000D_
}_x000D_
.carosel-inner {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  font-size: 0;_x000D_
}_x000D_
.carosel-item {_x000D_
  display: inline-block;_x000D_
}_x000D_
.carosel-control {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  padding: 15px;_x000D_
  box-shadow: 0 0 10px 0px rgba(0, 0, 0, 0.5);_x000D_
  transform: translateY(-50%);_x000D_
  border-radius: 50%;_x000D_
  color: rgba(0, 0, 0, 0.5);_x000D_
  font-size: 30px;_x000D_
  display: inline-block;_x000D_
}_x000D_
.carosel-control-left {_x000D_
  left: 15px;_x000D_
}_x000D_
.carosel-control-right {_x000D_
  right: 15px;_x000D_
}_x000D_
.carosel-control:active,_x000D_
.carosel-control:hover {_x000D_
  text-decoration: none;_x000D_
  color: rgba(0, 0, 0, 0.8);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="carosel" id="carosel1">_x000D_
  <a class="carosel-control carosel-control-left glyphicon glyphicon-chevron-left" href="#"></a>_x000D_
  <div class="carosel-inner">_x000D_
    <img class="carosel-item" src="http://placehold.it/500/bbbbbb/fff&amp;text=1" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/CCCCCC&amp;text=2" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/eeeeee&amp;text=3" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f4f4f4&amp;text=4" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/fcfcfc/333&amp;text=5" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f477f4/fff&amp;text=6" />_x000D_
  </div>_x000D_
  <a class="carosel-control carosel-control-right glyphicon glyphicon-chevron-right" href="#"></a>_x000D_
</div>_x000D_
<div class="carosel" id="carosel2">_x000D_
  <a class="carosel-control carosel-control-left glyphicon glyphicon-chevron-left" href="#"></a>_x000D_
  <div class="carosel-inner">_x000D_
    <img class="carosel-item" src="http://placehold.it/500/bbbbbb/fff&amp;text=1" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/CCCCCC&amp;text=2" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/eeeeee&amp;text=3" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f4f4f4&amp;text=4" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/fcfcfc/333&amp;text=5" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f477f4/fff&amp;text=6" />_x000D_
  </div>_x000D_
  <a class="carosel-control carosel-control-right glyphicon glyphicon-chevron-right" href="#"></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert Java string to Time, NOT Date

You can use the following code for changing the String value into the time equivalent:

 String str = "08:03:10 pm";
 DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
 Date date = (Date)formatter.parse(str);

Hope this helps you.

What is the difference between call and apply?

To answer the part about when to use each function, use apply if you don't know the number of arguments you will be passing, or if they are already in an array or array-like object (like the arguments object to forward your own arguments. Use call otherwise, since there's no need to wrap the arguments in an array.

f.call(thisObject, a, b, c); // Fixed number of arguments

f.apply(thisObject, arguments); // Forward this function's arguments

var args = [];
while (...) {
    args.push(some_value());
}
f.apply(thisObject, args); // Unknown number of arguments

When I'm not passing any arguments (like your example), I prefer call since I'm calling the function. apply would imply you are applying the function to the (non-existent) arguments.

There shouldn't be any performance differences, except maybe if you use apply and wrap the arguments in an array (e.g. f.apply(thisObject, [a, b, c]) instead of f.call(thisObject, a, b, c)). I haven't tested it, so there could be differences, but it would be very browser specific. It's likely that call is faster if you don't already have the arguments in an array and apply is faster if you do.

Angular: date filter adds timezone, how to output UTC?

I just used getLocaleString() function for my application. It should adapt the timeformat common to the locale, so no +0200 etc. Ofcourse, there will be less possibility for controlling the width of your string then.

var str = (new Date(1400167800)).toLocaleString();

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I dug deeper into this and found the best solutions are here.

http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "

original code:

print("Process lines, file_name command_line %s\n"% command_line))

New code:

print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))  

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How to check if an excel cell is empty using Apache POI?

If you're using Apache POI 4.x, you can do that with:

 Cell c = row.getCell(3);
 if (c == null || c.getCellType() == CellType.Blank) {
    // This cell is empty
 }

For older Apache POI 3.x versions, which predate the move to the CellType enum, it's:

 Cell c = row.getCell(3);
 if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
    // This cell is empty
 }

Don't forget to check if the Row is null though - if the row has never been used with no cells ever used or styled, the row itself might be null!

how do you increase the height of an html textbox

  • With inline style:

    <input type="text" style="font-size: 18pt; height: 40px; width:280px; ">
    
  • or with apart CSS:

    HTML:

    <input type="text" id="txtbox">
    

    CSS:

    #txtbox {
        font-size: 18pt;
        height: 42px;
        width : 300px;
    }
    

How to check if string contains Latin characters only?

All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:

if (!str.match(/^[\d]+$/)) {
    //contains other characters as well
}