Programs & Examples On #Cursor.current

Displaying tooltip on mouse hover of a text

This is not elegant, but you might be able to use the RichTextBox.GetCharIndexFromPosition method to return to you the index of the character that the mouse is currently over, and then use that index to figure out if it's over a link, hotspot, or any other special area. If it is, show your tooltip (and you'd probably want to pass the mouse coordinates into the tooltip's Show method, instead of just passing in the textbox, so that the tooltip can be positioned next to the link).

Example here: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80).aspx

What are the differences between C, C# and C++ in terms of real-world applications?

Both C and C++ give you a lower level of abstraction that, with increased complexity, provides a breadth of access to underlying machine functionality that are not necessarily exposed with other languages. Compared to C, C++ adds the convenience of a fully object oriented language(reduced development time) which can, potentially, add an additional performance cost. In terms of real world applications, I see these languages applied in the following domains:

C

  • Kernel level software.
  • Hardware device drivers
  • Applications where access to old, stable code is required.

C,C++

  • Application or Server development where memory management needs to be fine tuned (and can't be left to generic garbage collection solutions).
  • Development environments that require access to libraries that do not interface well with more modern managed languages.
  • Although managed C++ can be used to access the .NET framework, it is not a seamless transition.

C# provides a managed memory model that adds a higher level of abstraction again. This level of abstraction adds convenience and improves development times, but complicates access to lower level APIs and makes specialized performance requirements problematic.

It is certainly possible to implement extremely high performance software in a managed memory environment, but awareness of the implications is essential.

The syntax of C# is certainly less demanding (and error prone) than C/C++ and has, for the initiated programmer, a shallower learning curve.

C#

  • Rapid client application development.
  • High performance Server development (StackOverflow for example) that benefits from the .NET framework.
  • Applications that require the benefits of the .NET framework in the language it was designed for.

Johannes Rössel makes the valid point that the use C# Pointers, Unsafe and Unchecked keywords break through the layer of abstraction upon which C# is built. I would emphasize that type of programming is the exception to most C# development scenarios and not a fundamental part of the language (as is the case with C/C++).

Changing cell color using apache poi

For apache POI 3.9 you can use the code bellow:

HSSFCellStyle style = workbook.createCellStyle()
style.setFillForegroundColor(HSSFColor.YELLOW.index)
style.setFillPattern((short) FillPatternType.SOLID_FOREGROUND.ordinal())

The methods for 3.9 version accept short and you should pay attention to the inputs.

Store output of sed into a variable

Use command substitution like this:

line=$(sed -n '2p' myfile)
echo "$line"

Also note that there is no space around the = sign.

Server.Mappath in C# classlibrary

Maybe you could abstract this as a dependency and create an IVirtualPathResolver. This way your service classes wouldn't be bound to System.Web and you could create another implementation if you wanted to reuse your logic in a different UI technology.

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

What is a "web service" in plain English?

A simple definition: A web service is a function that can be accessed by other programs over the web (HTTP).

For example, when you create a website in PHP that outputs HTML, its target is the browser and by extension the human reading the page in the browser. A web service is not targeted at humans but rather at other programs.

So your PHP site that generates a random integer could be a web service if it outputs the integer in a format that may be consumed by another program. It might be in an XML format or another format, as long as other programs can understand the output.

The full definition is obviously more complex but you asked for plain English.

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

You can used Lambda as "Lambda Proxy Integration" ,ref this [https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python] , options avalible to this lambda are

For Nodejs Lambda 'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables', and 'event.requestContext'

For Python Lambda event['headers']['parametername'] and so on

How to make pylab.savefig() save image for 'maximized' window instead of default size

I think you need to specify a different resolution when saving the figure to a file:

fig = matplotlib.pyplot.figure()
# generate your plot
fig.savefig("myfig.png",dpi=600)

Specifying a large dpi value should have a similar effect as maximizing the GUI window.

At runtime, find all classes in a Java application that extend a base class

Unfortunately this isn't entirely possible as the ClassLoader won't tell you what classes are available. You can, however, get fairly close doing something like this:

for (String classpathEntry : System.getProperty("java.class.path").split(System.getProperty("path.separator"))) {
    if (classpathEntry.endsWith(".jar")) {
        File jar = new File(classpathEntry);

        JarInputStream is = new JarInputStream(new FileInputStream(jar));

        JarEntry entry;
        while( (entry = is.getNextJarEntry()) != null) {
            if(entry.getName().endsWith(".class")) {
                // Class.forName(entry.getName()) and check
                //   for implementation of the interface
            }
        }
    }
}

Edit: johnstok is correct (in the comments) that this only works for standalone Java applications, and won't work under an application server.

Make A List Item Clickable (HTML/CSS)

I think you could use the following HTML and CSS combo instead:

<li>
  <a href="#">Backback</a>
</li>

Then use CSS background for the basket visibility on hover:

.listblock ul li a {
    padding: 5px 30px 5px 10px;
    display: block;
}

.listblock ul li a:hover {
    background: transparent url('../img/basket.png') no-repeat 3px 170px;
}

Simples!

Is it possible to get the current spark context settings in PySpark?

I would suggest you try the method below in order to get the current spark context settings.

SparkConf.getAll()

as accessed by

SparkContext.sc._conf

Get the default configurations specifically for Spark 2.1+

spark.sparkContext.getConf().getAll() 

Stop the current Spark Session

spark.sparkContext.stop()

Create a Spark Session

spark = SparkSession.builder.config(conf=conf).getOrCreate()

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

python pandas convert index to datetime

It should work as expected. Try to run the following example.

import pandas as pd
import io

data = """value          
"2015-09-25 00:46"    71.925000
"2015-09-25 00:47"    71.625000
"2015-09-25 00:48"    71.333333
"2015-09-25 00:49"    64.571429
"2015-09-25 00:50"    72.285714"""

df = pd.read_table(io.StringIO(data), delim_whitespace=True)

# Converting the index as date
df.index = pd.to_datetime(df.index)

# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df

#                          value  A   B
# 2015-09-25 00:46:00  71.925000  0  46
# 2015-09-25 00:47:00  71.625000  0  47
# 2015-09-25 00:48:00  71.333333  0  48
# 2015-09-25 00:49:00  64.571429  0  49
# 2015-09-25 00:50:00  72.285714  0  50

Create a temporary table in a SELECT statement without a separate CREATE TABLE

CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)

From the manual found at http://dev.mysql.com/doc/refman/5.7/en/create-table.html

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.

How to store a list in a column of a database table

You can just forget SQL all together and go with a "NoSQL" approach. RavenDB, MongoDB and CouchDB jump to mind as possible solutions. With a NoSQL approach, you are not using the relational model..you aren't even constrained to schemas.

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

Update: After several attempts, it looks like this may have been fixed in latest Chrome builds (per Paul Irish's comment below). That would suggest we will see this fixed in stable Chrome June-July 2016. Let's see ...

This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.

The Chromecast team have indicated they won't fix this bug.

If you are a developer shipping with this library, you can't do anything about it according to Chromecast team. You can only inform users to ignore the errors. (I believe Chromecast team is not entirely correct as the library could, at the least, avoid requesting the extension scipt if the browser is not Chrome. And I suspect it could be possible to suppress the error even if it is Chrome, but haven't tried anything.)

If you are a user annoyed by these console messages, you can switch to Chrome if not using it already. Within Chrome, either:

Update [Nov 13, 2014]: The problem has now been acknowledged by Google. A member of the Chromecast team seems to suggest the issue will be bypassed by a change the team is currently working on.

Update 2 [Feb 17, 2015]: The team claim there's nothing they can do to remove the error logs as it's a standard Chrome network error and they are still working on a long-term fix. Public comments on the bug tracker were closed with that update.

Update 3 [Dec 4, 2015]: This has finally been fixed! In the end, Chrome team simply added some code to block out this specific error. Hopefully some combination of devtools and extensions API will be improved in the future to make it possible to fix this kind of problem without patching the browser. Chrome Canary already has the patch, so it should roll out to all users around mid-January. Additionally, the team has confirmed the issue no longer affects other browsers as the SDK was updated to only activate if it's in Chrome.

Update 4 (April 30): Nope, not yet anyway. Thankfully Google's developer relations team are more aware than certain other stakeholders how badly this has affected developer experience. More whitelist updates have recently been made to clobber these log messages. Current status at top of the post.

How to use Bash to create a folder if it doesn't already exist?

You need spaces inside the [ and ] brackets:

#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ] 
then
    mkdir -p /home/mlzboy/b2c2/shared/db
fi

Recursively find all files newer than a given time

Assuming a modern release, find -newermt is powerful:

find -newermt '10 minutes ago' ## other units work too, see `Date input formats`

or, if you want to specify a time_t (seconds since epoch):

find -newermt @1568670245

For reference, -newermt is not directly listed in the man page for find. Instead, it is shown as -newerXY, where XY are placeholders for mt. Other replacements are legal, but not applicable for this solution.

From man find -newerXY:

Time specifications are interpreted as for the argument to the -d option of GNU date.

So the following are equivalent to the initial example:

find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'

The date -d (and find -newermt) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats

Installing PDO driver on MySQL Linux server

At first install necessary PDO parts by running the command

`sudo apt-get install php*-mysql` 

where * is a version name of php like 5.6, 7.0, 7.1, 7.2

After installation you need to mention these two statements

extension=pdo.so
extension=pdo_mysql.so

in your .ini file (uncomment if it is already there) and restart server by command

sudo service apache2 restart

Export table data from one SQL Server to another

Just to show yet another option (for SQL Server 2008 and above):

  1. right-click on Database -> select 'Tasks' -> select 'Generate Scripts'
  2. Select specific database objects you want to copy. Let's say one or more tables. Click Next
  3. Click Advanced and scroll down to 'Types of Data to script' and choose 'Schema and Data'. Click OK
  4. Choose where to save generated script and proceed by clicking Next

Call one constructor from another

When you inherit a class from a base class, you can invoke the base class constructor by instantiating the derived class

class sample
{
    public int x;

    public sample(int value)
    {
        x = value;
    }
}

class der : sample
{
    public int a;
    public int b;

    public der(int value1,int value2) : base(50)
    {
        a = value1;
        b = value2;
    }
}

class run 
{
    public static void Main(string[] args)
    {
        der obj = new der(10,20);

        System.Console.WriteLine(obj.x);
        System.Console.WriteLine(obj.a);
        System.Console.WriteLine(obj.b);
    }
}

Output of the sample program is

50 10 20


You can also use this keyword to invoke a constructor from another constructor

class sample
{
    public int x;

    public sample(int value) 
    {
        x = value;
    }

    public sample(sample obj) : this(obj.x) 
    {
    }
}

class run
{
    public static void Main(string[] args) 
    {
        sample s = new sample(20);
        sample ss = new sample(s);

        System.Console.WriteLine(ss.x);
    }
}

The output of this sample program is

20

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To make use of regular expressions directly in Excel formulas the following UDF (user defined function) can be of help. It more or less directly exposes regular expression functionality as an excel function.

How it works

It takes 2-3 parameters.

  1. A text to use the regular expression on.
  2. A regular expression.
  3. A format string specifying how the result should look. It can contain $0, $1, $2, and so on. $0 is the entire match, $1 and up correspond to the respective match groups in the regular expression. Defaults to $0.

Some examples

Extracting an email address:

=regex("Peter Gordon: [email protected], 47", "\w+@\w+\.\w+")
=regex("Peter Gordon: [email protected], 47", "\w+@\w+\.\w+", "$0")

Results in: [email protected]

Extracting several substrings:

=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "E-Mail: $2, Name: $1")

Results in: E-Mail: [email protected], Name: Peter Gordon

To take apart a combined string in a single cell into its components in multiple cells:

=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "$" & 1)
=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "$" & 2)

Results in: Peter Gordon [email protected] ...

How to use

To use this UDF do the following (roughly based on this Microsoft page. They have some good additional info there!):

  1. In Excel in a Macro enabled file ('.xlsm') push ALT+F11 to open the Microsoft Visual Basic for Applications Editor.
  2. Add VBA reference to the Regular Expressions library (shamelessly copied from Portland Runners++ answer):
    1. Click on Tools -> References (please excuse the german screenshot) Tools -> References
    2. Find Microsoft VBScript Regular Expressions 5.5 in the list and tick the checkbox next to it.
    3. Click OK.
  3. Click on Insert Module. If you give your module a different name make sure the Module does not have the same name as the UDF below (e.g. naming the Module Regex and the function regex causes #NAME! errors).

    Second icon in the icon row -> Module

  4. In the big text window in the middle insert the following:

    Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
        Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
        Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
        Dim replaceNumber As Integer
    
        With inputRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
        With outputRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = "\$(\d+)"
        End With
        With outReplaceRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
        End With
    
        Set inputMatches = inputRegexObj.Execute(strInput)
        If inputMatches.Count = 0 Then
            regex = False
        Else
            Set replaceMatches = outputRegexObj.Execute(outputPattern)
            For Each replaceMatch In replaceMatches
                replaceNumber = replaceMatch.SubMatches(0)
                outReplaceRegexObj.Pattern = "\$" & replaceNumber
    
                If replaceNumber = 0 Then
                    outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)
                Else
                    If replaceNumber > inputMatches(0).SubMatches.Count Then
                        'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
                        regex = CVErr(xlErrValue)
                        Exit Function
                    Else
                        outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
                    End If
                End If
            Next
            regex = outputPattern
        End If
    End Function
    
  5. Save and close the Microsoft Visual Basic for Applications Editor window.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

In my case in Angular-5, service file was not imported from which i was accessing the method and subscribing the data.After importing service file it worked fine.

This Handler class should be static or leaks might occur: IncomingHandler

Here is a generic example of using a weak reference and static handler class to resolve the problem (as recommended in the Lint documentation):

public class MyClass{

  //static inner class doesn't hold an implicit reference to the outer class
  private static class MyHandler extends Handler {
    //Using a weak reference means you won't prevent garbage collection
    private final WeakReference<MyClass> myClassWeakReference; 

    public MyHandler(MyClass myClassInstance) {
      myClassWeakReference = new WeakReference<MyClass>(myClassInstance);
    }

    @Override
    public void handleMessage(Message msg) {
      MyClass myClass = myClassWeakReference.get();
      if (myClass != null) {
        ...do work here...
      }
    }
  }

  /**
   * An example getter to provide it to some external class
   * or just use 'new MyHandler(this)' if you are using it internally.
   * If you only use it internally you might even want it as final member:
   * private final MyHandler mHandler = new MyHandler(this);
   */
  public Handler getHandler() {
    return new MyHandler(this);
  }
}

Fade Effect on Link Hover?

Try this in your css:

.a {
    transition: color 0.3s ease-in-out;
}
.a {
    color:turquoise;
}
.a:hover {
    color: #454545;
}

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

As per my personal experience Adobe edge is the best tool for HTML5. It's still in preview mode but you will download it free from Adobe site.

Save string to the NSUserDefaults?

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

to get it back later

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

jQuery Scroll to Div

The script below is a generic solution that works for me. It is based on ideas pulled from this and other threads.

When a link with an href attribute beginning with "#" is clicked, it scrolls the page smoothly to the indicated div. Where only the "#" is present, it scrolls smoothly to the top of the page.

$('a[href^=#]').click(function(){
    event.preventDefault();
    var target = $(this).attr('href');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

For example, When the code above is present, clicking a link with the tag <a href="#"> scrolls to the top of the page at speed 600. Clicking a link with the tag <a href="#mydiv"> scrolls to 100px above <div id="mydiv"> at speed 600. Feel free to change these numbers.

I hope it helps!

Apache VirtualHost and localhost

Just change <VirtualHost *:80> to <VirtualHost 127.0.0.1:80>.

Then the default DocumentRoot will serve for all domains or IP addresses that point to your server and specified VirtualHost will work.

How does the bitwise complement operator (~ tilde) work?

This operation is a complement, not a negation.

Consider that ~0 = -1, and work from there.

The algorithm for negation is, "complement, increment".

Did you know? There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance "2" (with JMH):

class A{}
class B extends A{}

public class InstanceOfTest {

public static final Object a = new A();
public static final Object b = new B();

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testInstanceOf()
{
    return b instanceof A;
}

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testIsInstance()
{
    return A.class.isInstance(b);
}

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testIsAssignableFrom()
{
    return A.class.isAssignableFrom(b.getClass());
}

public static void main(String[] args) throws RunnerException {
    Options opt = new OptionsBuilder()
            .include(InstanceOfTest.class.getSimpleName())
            .warmupIterations(5)
            .measurementIterations(5)
            .forks(1)
            .build();

    new Runner(opt).run();
}
}

It gives:

Benchmark                            Mode  Cnt  Score   Error  Units
InstanceOfTest.testInstanceOf        avgt    5  1,972 ? 0,002  ns/op
InstanceOfTest.testIsAssignableFrom  avgt    5  1,991 ? 0,004  ns/op
InstanceOfTest.testIsInstance        avgt    5  1,972 ? 0,003  ns/op

So that we can conclude: instanceof as fast as isInstance() and isAssignableFrom() not far away (+0.9% executon time). So no real difference whatever you choose

Min/Max of dates in an array?

var max_date = dates.sort(function(d1, d2){
    return d2-d1;
})[0];

Difference between static, auto, global and local variable in the context of c and c++

Difference is static variables are those variables: which allows a value to be retained from one call of the function to another. But in case of local variables the scope is till the block/ function lifetime.

For Example:

#include <stdio.h>

void func() {
    static int x = 0; // x is initialized only once across three calls of func()
    printf("%d\n", x); // outputs the value of x
    x = x + 1;
}

int main(int argc, char * const argv[]) {
    func(); // prints 0
    func(); // prints 1
    func(); // prints 2
    return 0;
}

Java 8 optional: ifPresent return object orElseThrow exception

Use the map-function instead. It transforms the value inside the optional.

Like this:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object.map(() -> {
        String result = "result";
        //some logic with result and return it
        return result;
    }).orElseThrow(MyCustomException::new);
}

Spring boot: Unable to start embedded Tomcat servlet container

Simple way to handle this is to include this in your application.properties or .yml file: server.port=0 for application.properties and server.port: 0 for application.yml files. Of course need to be aware these may change depending on the springboot version you are using. These will allow your machine to dynamically allocate any free port available for use. To statically assign a port change the above to server.port = someportnumber. If running unix based OS you may want to check for zombie activities on the port in question and if possible kill it using fuser -k {theport}/tcp. Your .yml or .properties should look like this. server: port: 8089 servlet: context-path: /somecontextpath

How to get names of enum entries?

If you have enum

enum Diet {
  KETO = "Ketogenic",
  ATKINS = "Atkins",
  PALEO = "Paleo",
  DGAF = "Whatever"
}

Then you can get key and values like:

Object.keys(Diet).forEach((d: Diet) => {
  console.log(d); // KETO
  console.log(Diet[d]) // Ketogenic
});

Setting the selected value on a Django forms.ChoiceField

I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.

How to read and write into file using JavaScript?

No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

jQuery show for 5 seconds then hide

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");

fatal: The current branch master has no upstream branch

If you are on any branch, you can use this:

git push origin head -u

This will automatically create new branch of the same name on the remote.

What is the Angular equivalent to an AngularJS $watch?

Here is another approach using getter and setter functions for the model.

@Component({
  selector: 'input-language',
  template: `
  …
  <input 
    type="text" 
    placeholder="Language" 
    [(ngModel)]="query" 
  />
  `,
})
export class InputLanguageComponent {

  set query(value) {
    this._query = value;
    console.log('query set to :', value)
  }

  get query() {
    return this._query;
  }
}

How to create a database from shell command?

mysqladmin -u$USER -p$PASSWORD create $DB_NAME

Replace above variables and you are good to go with this oneliner. $USER is the username, $PASSWORD is the password and $DB_NAME is the name of the database.

REST API - why use PUT DELETE POST GET?

This is a security and maintainability question.

safe methods

Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.

idempotent methods

Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.

Source

How to insert a picture into Excel at a specified cell position with VBA

Try this:

With xlApp.ActiveSheet.Pictures.Insert(PicPath)
    With .ShapeRange
        .LockAspectRatio = msoTrue
        .Width = 75
        .Height = 100
    End With
    .Left = xlApp.ActiveSheet.Cells(i, 20).Left
    .Top = xlApp.ActiveSheet.Cells(i, 20).Top
    .Placement = 1
    .PrintObject = True
End With

It's better not to .select anything in Excel, it is usually never necessary and slows down your code.

How do you clone an Array of Objects in Javascript?

We can invent a simple recursive Array method to clone multidimensional arrays. While the objects within the nested arrays keep their reference to the corresponding objects in the source array, arrays won't.

_x000D_
_x000D_
Array.prototype.clone = function(){_x000D_
  return this.map(e => Array.isArray(e) ? e.clone() : e);_x000D_
};_x000D_
_x000D_
var arr = [ 1, 2, 3, 4, [ 1, 2, [ 1, 2, 3 ], 4 , 5], 6 ],_x000D_
    brr = arr.clone();_x000D_
brr[4][2][1] = "two";_x000D_
console.log(JSON.stringify(arr));_x000D_
console.log(JSON.stringify(brr));
_x000D_
_x000D_
_x000D_

Plotting time in Python with Matplotlib

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

Play audio with Python

Simply You can do it with the help of cvlc- I did it in this way:

import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")

/home/maulo/selfProject/task.mp3. This is the location of my mp3 file. with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.

self.tableView.reloadData() not working in Swift

I was also facing the same issue, what I did wrong was that I'd forgot to add

tableView.delegate = self    
tableView.dataSource = self

in the viewDidLoad() {} method. This could be one reason of self.tableView.reloadData() not working.

How to encode the filename parameter of Content-Disposition header in HTTP?

in asp.net mvc2 i use something like this:

return File(
    tempFile
    , "application/octet-stream"
    , HttpUtility.UrlPathEncode(fileName)
    );

I guess if you don't use mvc(2) you could just encode the filename using

HttpUtility.UrlPathEncode(fileName)

What's the difference between REST & RESTful

A service based on REST is called a "RESTful service".

Source I rely on posting that: Dr.Dobbs Archive

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to loop through a collection that supports IEnumerable?

Maybe you forgot the await before returning your collection

Populate one dropdown based on selection in another

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

jQuery multiselect drop down menu

Are you looking to do something like this http://jsfiddle.net/robert/xhHkG/

$('#transactionType').attr({
    'multiple': true,
    'size' : 10
});

Put that in a $(function() {...}) or some other onload

Edit

Reread your question, you're not really looking for a multiple select... but a dropdown box that allows you to select multiple. Yeah, probably best to use a plugin for that or write it from the ground up, it's not a "quick answer" type deal though.

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Why should I use var instead of a type?

In this case it is just coding style.

Use of var is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.

VMware Workstation and Device/Credential Guard are not compatible

To make it super easy:

  1. Just download this script directly from Microsoft.

  2. Run your Powershell as an admin and then execute following commands:

    • To Verify if DG/CG is enabled DG_Readiness.ps1 -Ready
    • To Disable DG/CG. DG_Readiness.ps1 -Disable

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

How to copy static files to build directory with Webpack?

You can write bash in your package.json:

# package.json
{
  "name": ...,
  "version": ...,
  "scripts": {
    "build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
    ...
  }
}

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

How to create a multiline UITextfield?

Use textView instead then conform with its delegate, call the textViewDidChange method inside of that method call tableView.beginUpdates() and tableView.endUpdates() and don't forget to set rowHeight and estimatedRowHeight to UITableView.automaticDimension.

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

Which particular version of Ubuntu is this and is this Ubuntu Server Edition?

Recent Ubuntu Server Editions (such as 10.04) ship with AppArmor and MySQL's profile might be in enforcing mode by default. You can check this by executing sudo aa-status like so:

# sudo aa-status
5 profiles are loaded.
5 profiles are in enforce mode.
   /usr/lib/connman/scripts/dhclient-script
   /sbin/dhclient3
   /usr/sbin/tcpdump
   /usr/lib/NetworkManager/nm-dhcp-client.action
   /usr/sbin/mysqld
0 profiles are in complain mode.
1 processes have profiles defined.
1 processes are in enforce mode :
   /usr/sbin/mysqld (1089)
0 processes are in complain mode.

If mysqld is included in enforce mode, then it is the one probably denying the write. Entries would also be written in /var/log/messages when AppArmor blocks the writes/accesses. What you can do is edit /etc/apparmor.d/usr.sbin.mysqld and add /data/ and /data/* near the bottom like so:

...  
/usr/sbin/mysqld  {  
    ...  
    /var/log/mysql/ r,  
    /var/log/mysql/* rw,  
    /var/run/mysqld/mysqld.pid w,  
    /var/run/mysqld/mysqld.sock w,  
    **/data/ r,  
    /data/* rw,**  
}

And then make AppArmor reload the profiles.

# sudo /etc/init.d/apparmor reload

WARNING: the change above will allow MySQL to read and write to the /data directory. We hope you've already considered the security implications of this.

How to auto-format code in Eclipse?

CTRL + SHIFT + F will auto format your code(whether it is highlighted or non highlighted).

library not found for -lPods

if you are running into problems with this on cocoapods v25 / Xcode 5

The Pods Xcode project now sets the ONLY_ACTIVE_ARCH build setting to YES in the Debug configuration. You will have to set the same on your project/target, otherwise the build will fail.

https://github.com/CocoaPods/CocoaPods/wiki/FAQ#running-into-build-failures-after-migrating-to-xcode-5-and-cocoapods-0250

UPDATE Make sure you have latest gems / cocoapods

  • gem update system
  • gem update cocoapods

You will want to rebuild project using Pod Install to rebuild project.

what are the .map files used for in Bootstrap 3.x?

If you just want to get rid of the error, you can also delete this line in bootstrap.css:

/*# sourceMappingURL=bootstrap.css.map */

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

There are several timezones in operation here:

  1. Java's Date classes (util and sql), which have implicit timezones of UTC
  2. The timezone your JVM is running in, and
  3. the default timezone of your database server.

All of these can be different. Hibernate/JPA has a severe design deficiency in that a user cannot easily ensure that timezone information is preserved in the database server (which allows reconstruction of correct times and dates in the JVM).

Without the ability to (easily) store timezone using JPA/Hibernate then information is lost and once information is lost it becomes expensive to construct it (if at all possible).

I would argue that it is better to always store timezone information (should be the default) and users should then have the optional ability to optimize the timezone away (although it only really affects display, there is still an implicit timezone in any date).

Sorry, this post doesn't provide a work-around (that's been answered elsewhere) but it is a rationalization of why always storing timezone information around is important. Unfortunately it seems many Computer Scientists and programming practitioners argue against the need for timezones simply because they don't appreciate the "loss of information" perspective and how that makes things like internationalization very difficult - which is very important these days with web sites accessible by clients and people in your organization as they move around the world.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Commenting filters solved the issue.

How to remove a key from HashMap while iterating over it?

Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

How to align iframe always in the center

First remove position:absolute of div#iframe-wrapper iframe, Remove position:fixed and all other css from div#iframe-wrapper

Then apply this css,

div#iframe-wrapper {
  width: 200px;
  height: 400px;
  margin: 0 auto;
}

FIDDLE DEMO

How to install and run Typescript locally in npm?

To install TypeScript local in project as a development dependency you can use --save-dev key

npm install --save-dev typescript

It's also writes the typescript into your package.json

You also need to have a tsconfig.json file. For example

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    ".npm"
  ]
}

For more information about the tsconfig you can see here http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

Best practice when adding whitespace in JSX

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:

<p>
    Hello {
        <span>World</span>
    }!
</p>

or

<p>
    Hello {}
    <span>World</span>
    {} again!
</p>

Each of these produces clean html without additional &nbsp; or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello &amp; goodbye '} does not.

sorting integers in order lowest to highest java

import java.util.Arrays;

public class sortNumber {

public static void main(String[] args) {
    // Our array contains 13 elements 
    int[] array = {9,  238,  248,  138,  118,  45,  180,  212,  103,  230,  104,  41,  49}; 

    Arrays.sort(array); 

    System.out.printf(" The result : %s", Arrays.toString(array)); 
  }
}

What is a good naming convention for vars, methods, etc in C++?

While many people will suggest more or less strict Hungarian notation variants (scary!), for naming suggestions I'd suggest you take a look at Google C++ Coding Guidelines. This may well be not the most popular naming conventions, but at least it's fairly complete. Apart from sound naming conventions, there's some useful guidelines there, however much of it should be taken with a grain of salt (exception ban for example, and the tendency to keep away from modern C++ coding style).

Although personally I like the extreme low-tech convention style of STL and Boost ;).

Format string to a 3 digit number

If you're just formatting a number, you can just provide the proper custom numeric format to make it a 3 digit string directly:

myString = 3.ToString("000");

Or, alternatively, use the standard D format string:

myString = 3.ToString("D3");

How to Round to the nearest whole number in C#

See the official documentation for more. For example:

Basically you give the Math.Round method three parameters.

  1. The value you want to round.
  2. The number of decimals you want to keep after the value.
  3. An optional parameter you can invoke to use AwayFromZero rounding. (ignored unless rounding is ambiguous, e.g. 1.5)

Sample code:

var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2
var roundedD = Math.Round(2.5, 0); // Output: 2
var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3
var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3

Live Demo

You need MidpointRounding.AwayFromZero if you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round(). If using MidpointRounding.ToEven (the default) the value is rounded to the nearest even number (1.5 is rounded to 2, but 2.5 is also rounded to 2).

How does "FOR" work in cmd batch file?

It works for me, try it.

for /f "delims=;" %g in ('echo %PATH%') do echo %g%

MySQL check if a table exists without throwing an exception

Using mysqli i've created following function. Asuming you have an mysqli instance called $con.

function table_exist($table){
    global $con;
    $table = $con->real_escape_string($table);
    $sql = "show tables like '".$table."'";
    $res = $con->query($sql);
    return ($res->num_rows > 0);
}

Hope it helps.

Warning: as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

How can I save multiple documents concurrently in Mongoose/Node.js?

This is an old question, but it came up first for me in google results when searching "mongoose insert array of documents".

There are two options model.create() [mongoose] and model.collection.insert() [mongodb] which you can use. View a more thorough discussion here of the pros/cons of each option:

Mongoose (mongodb) batch insert?

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

Merge (Concat) Multiple JSONObjects in Java

In addition to @erel's answer, I had to make this edit (I'm using org.json.simple) to the outer else for dealing with JSONArray's:

            // existing value for "key" - recursively deep merge:
            if (value instanceof JSONObject) {
                JSONObject valueJson = (JSONObject)value;
                deepMerge(valueJson, (JSONObject) target.get(key));
            } 

            // insert each JSONArray's JSONObject in place
            if (value instanceof JSONArray) {
                ((JSONArray) value).forEach(
                    jsonobj ->
                    ((JSONArray) target.get(key)).add(jsonobj));
            }
            else {
                target.put(key, value);
            }

How to read a line from a text file in c/c++?

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

Assuming std namespace:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

Tomcat is web server or application server?

Tomcat is an application container that is also a web server. An application container can run web-applications (have "application" scope). It is not considered Some people do not consider it a full application server as it is lacking in some aspects such as user management and the like, but getting better all the time..

What is the difference between HTML tags and elements?

Tags and Elements are not the same.

Elements


They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.

Eg:

<p>This is the <span>Home</span> page</p>

Tags


Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.

The browser sees the letters '

' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '

' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.

- Opening tag.

- Closing tagenter image description here

How do I open a URL from C++?

Here's an example in windows code using winsock.

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

Insert node at a certain position in a linked list C++

I had some problems with the insertion process just like you, so here is the code how I have solved the problem:

void add_by_position(int data, int pos)
  {
        link *node = new link;
        link *linker = head;

        node->data = data;
        for (int i = 0; i < pos; i++){
            linker = linker->next;
        }
        node->next = linker;
        linker = head;
        for (int i = 0; i < pos - 1; i++){
            linker = linker->next;
        }
        linker->next = node;
        boundaries++;
    }

Android translate animation - permanently move View to new position using AnimationListener

I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.

Try this out, see if it works for you:

TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);

anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) 
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
        params.topMargin += amountToMoveDown;
        params.leftMargin += amountToMoveRight;
        view.setLayoutParams(params);
    }
});

view.startAnimation(anim);

Make sure to make amountToMoveRight / amountToMoveDown final

Hope this helps :)

How to get JavaScript variable value in PHP

Here is the Working example: Get javascript variable value on the same page.

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>

twitter bootstrap text-center when in xs mode

html

<div class="text-lg-right text-center">
  center in xs and right in lg devices
</div>

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

find filenames NOT ending in specific extensions on Unix?

Linux/OS X:

Starting from the current directory, recursively find all files ending in .dll or .exe

find . -type f | grep -P "\.dll$|\.exe$"

Starting from the current directory, recursively find all files that DON'T end in .dll or .exe

find . -type f | grep -vP "\.dll$|\.exe$"

Notes:

(1) The P option in grep indicates that we are using the Perl style to write our regular expressions to be used in conjunction with the grep command. For the purpose of excecuting the grep command in conjunction with regular expressions, I find that the Perl style is the most powerful style around.

(2) The v option in grep instructs the shell to exclude any file that satisfies the regular expression

(3) The $ character at the end of say ".dll$" is a delimiter control character that tells the shell that the filename string ends with ".dll"

Allow anything through CORS Policy

I have had a similar problem before where it turned out to be the web brower (chrome in my case) that was the issue.

If you are using chrome, try launching it so:

For Windows:

1) Create a shortcut to Chrome on your desktop. Right-click on the shortcut and choose Properties, then switch to “Shortcut” tab.

2) In the “Target” field, append the following: –args –disable-web-security

For Mac, Open a terminal window and run this from command-line: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security

Above info from:

http://documentumcookbook.wordpress.com/2012/03/13/disable-cross-domain-javascript-security-in-chrome-for-development/

fork: retry: Resource temporarily unavailable

This is commonly caused by running out of file descriptors.

There is the systems total file descriptor limit, what do you get from the command:

sysctl fs.file-nr

This returns counts of file descriptors:

<in_use> <unused_but_allocated> <maximum>

To find out what a users file descriptor limit is run the commands:

sudo su - <username>
ulimit -Hn

To find out how many file descriptors are in use by a user run the command:

sudo lsof -u <username> 2>/dev/null | wc -l

So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.

fs.file-max = 204708

What does the C++ standard state the size of int, long type to be?

Nope, there is no standard for type sizes. Standard only requires that:

sizeof(short int) <= sizeof(int) <= sizeof(long int)

The best thing you can do if you want variables of a fixed sizes is to use macros like this:

#ifdef SYSTEM_X
  #define WORD int
#else
  #define WORD long int
#endif

Then you can use WORD to define your variables. It's not that I like this but it's the most portable way.

break/exit script

Not pretty, but here is a way to implement an exit() command in R which works for me.

exit <- function() {
  .Internal(.invokeRestart(list(NULL, NULL), NULL))
}

print("this is the last message")
exit()
print("you should not see this")

Only lightly tested, but when I run this, I see this is the last message and then the script aborts without any error message.

How to get $HOME directory of different user in bash script?

In BASH, you can find a user's $HOME directory by prefixing the user's login ID with a tilde character. For example:

$ echo ~bob

This will echo out user bob's $HOME directory.

However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo as user bob:

$ sudo -i -ubob -sfoo

This will start up a new shell, and the -i will simulate a login with the user's default environment and shell (which means the foo command will execute from the bob's$HOME` directory.)

Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers). However, this file usually has several examples you can use.

In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.

How can I check if a View exists in a Database?

For people checking the existence to drop View use this

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

syntax

DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]

Query :

DROP VIEW IF EXISTS view_name

More info here

Read .csv file in C

With fscanf read the file until you encounter ';' or \n, then you can just skip it with fscang(f, "%*c").

int main()
{
    char str[128];
    int result;
    FILE* f = fopen("test.txt", "r");
    ...
    
    do {
        result = fscanf(f, "%127[^;\n]", str);
        
        if(result == 0)
        {
            result = fscanf(f, "%*c");
        }
        else
        {
            //whatever you want to do with your value
            printf("%s\n", str);
        }
        
    } while(result != EOF);

    return 0;
}

JQUERY: Uncaught Error: Syntax error, unrecognized expression

This can also happen in safari if you try a selector with a missing ], for example

$('select[name="something"')

but interestingly, this same jquery selector with a missing bracket will work in chrome.

Submit Button Image

<INPUT TYPE="image" SRC="images/submit.gif" HEIGHT="30" WIDTH="173" BORDER="0" ALT="Submit Form">
Where the standard submit button has TYPE="submit", we now have TYPE="image". The image type is by default a form submitting button. More simple

How to solve SyntaxError on autogenerated manage.py?

Solved my problem too when I activated my virtual environment using:

source bin/activate

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

Insert an element at a specific index in a list and return the updated list

The cleanest approach is to copy the list and then insert the object into the copy. On Python 3 this can be done via list.copy:

new = old.copy()
new.insert(index, value)

On Python 2 copying the list can be achieved via new = old[:] (this also works on Python 3).

In terms of performance there is no difference to other proposed methods:

$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 µsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 µsec per loop

How to get file path from OpenFileDialog and FolderBrowserDialog?

To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.

var file = choofdlog.FileName; // for one file

or for multiple files

var files = choofdlog.FileNames; // for multiple files.

To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path

Adding rows dynamically with jQuery

As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):

<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>

I have done this having some global variable by default set to 0:

var globalNewIndex = 0;

and in the add function after you've cloned and resetted the values in the new row:

                var newIndex = globalNewIndex+1;
                var changeIds = function(i, val) {
                    return val.replace(globalNewIndex,newIndex);
                }
                $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
                globalNewIndex++;

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say google.com
        d.browse(new URI("http://google.com"));

        }
    }
}

100% width Twitter Bootstrap 3 template

You're right using div.container-fluid and you also need a div.row child. Then, the content must be placed inside without any grid columns. If you have a look at the docs you can find this text:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.

Not using grid columns it's ok as stated here:

  • Content should be placed within columns, and only columns may be immediate children of rows.

And looking at this example, you can read this text:

Full width, single column: No grid classes are necessary for full-width elements.

Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.

Open links in new window using AngularJS

It works for me. Inject $window service in to your controller.

$window.open("somepath/", "_blank")

How to compare only date components from DateTime in EF?

You can user below link to compare 2 dates without time :

private bool DateGreaterOrEqual(DateTime dt1, DateTime dt2)
        {
            return DateTime.Compare(dt1.Date, dt2.Date) >= 0;
        }

private bool DateLessOrEqual(DateTime dt1, DateTime dt2)
        {
            return DateTime.Compare(dt1.Date, dt2.Date) <= 0;
        }

the Compare function return 3 different values: -1 0 1 which means dt1>dt2, dt1=dt2, dt1

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

I know I'm resurrecting quite an old question, but I recently ran into this issue, but needed something that scales to large numbers well. There wasn't any existing performance data, and since this question has had quite a bit of attention, I thought I'd post what I found.

The solutions that actually worked were the Alex Barrett's double sub-query/NOT IN method (similar to Bill Karwin's), and Quassnoi's LEFT JOIN method.

Unfortunately both of the above methods create very large intermediate temporary tables and performance degrades quickly as the number of records not being deleted gets large.

What I settled on utilizes Alex Barrett's double sub-query (thanks!) but uses <= instead of NOT IN:

DELETE FROM `test_sandbox`
  WHERE id <= (
    SELECT id
    FROM (
      SELECT id
      FROM `test_sandbox`
      ORDER BY id DESC
      LIMIT 1 OFFSET 42 -- keep this many records
    ) foo
  )

It uses OFFSET to get the id of the Nth record and deletes that record and all previous records.

Since ordering is already an assumption of this problem (ORDER BY id DESC), <= is a perfect fit.

It is much faster, since the temporary table generated by the subquery contains just one record instead of N records.

Test case

I tested the three working methods and the new method above in two test cases.

Both test cases use 10000 existing rows, while the first test keeps 9000 (deletes the oldest 1000) and the second test keeps 50 (deletes the oldest 9950).

+-----------+------------------------+----------------------+
|           | 10000 TOTAL, KEEP 9000 | 10000 TOTAL, KEEP 50 |
+-----------+------------------------+----------------------+
| NOT IN    |         3.2542 seconds |       0.1629 seconds |
| NOT IN v2 |         4.5863 seconds |       0.1650 seconds |
| <=,OFFSET |         0.0204 seconds |       0.1076 seconds |
+-----------+------------------------+----------------------+

What's interesting is that the <= method sees better performance across the board, but actually gets better the more you keep, instead of worse.

Resolve host name to an ip address

You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

Create a new cmd.exe window from within another cmd.exe prompt

Simply type start in the command prompt:

start

This will open up new cmd windows.

CSS override rules and specificity

The important needs to be inside the ;

td.rule2 div {     background-color: #ffff00 !important; } 

in fact i believe this should override it

td.rule2 { background-color: #ffff00 !important; } 

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I bumped into this too and found a solution.

First on how I got into this problem. I have a project which builds in x86. Then I used the Configuration Manager to add x64, and I hit this problem.

By looking at BuildLog.htm carefully, I saw both of these listed as linker options:

/MACHINE:X64  
/machine:X86 

I could not find anywhere in the Property Pages dialog where I could change this, so I opened up the .vcproj file and looked for the appropriate line and changed it to:

AdditionalOptions=" /STACK:10000000 /machine:x64 /debug"

and problem solved.

Converting Java objects to JSON with Jackson

You can use Google Gson like this

UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);

Gson gson = new Gson();
String jsonStr = gson.toJson(user);

Getting View's coordinates relative to the root layout

I wrote myself two utility methods that seem to work in most conditions, handling scroll, translation and scaling, but not rotation. I did this after trying to use offsetDescendantRectToMyCoords() in the framework, which had inconsistent accuracy. It worked in some cases but gave wrong results in others.

"point" is a float array with two elements (the x & y coordinates), "ancestor" is a viewgroup somewhere above the "descendant" in the tree hierarchy.

First a method that goes from descendant coordinates to ancestor:

public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
    point[1] = top + py + (point[1] - py) * sy + ty - scrollY;

    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToAncestor(point, ancestor, (View) parent);
    }
}

Next the inverse, from ancestor to descendant:

public static void transformToDescendant(float[] point, final View ancestor, final View descendant) {
    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToDescendant(point, ancestor, (View) parent);
    }

    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = px + (point[0] + scrollX - left - tx - px) / sx;
    point[1] = py + (point[1] + scrollY - top - ty - py) / sy;
}

Cannot open new Jupyter Notebook [Permission Denied]

In windows, I copied, what I think is a snapshot:

.~SomeAmazingNotebook.ipynb

renamed it:

SomeAmazingNotebook.ipynb

and could open it.

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

How do I split a multi-line string into multiple lines?

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

Python def function: How do you specify the end of the function?

It uses indentation

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 

Find the files that have been changed in last 24 hours

You can do that with

find . -mtime 0

From man find:

[The] time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

What's the meaning of exception code "EXC_I386_GPFLT"?

I got this error while doing this:

 NSMutableDictionary *aDictionary=[[NSMutableDictionary alloc] initWithObjectsAndKeys:<#(nonnull id), ...#>, nil]; //with 17 objects and keys

It went away when I reverted to:

NSMutableDictionary *aDictionary=[[NSMutableDictionary alloc] init];
[aDictionary setObject:object1 forKey:@"Key1"]; //17 times

What's the difference between a POST and a PUT HTTP REQUEST?

The request methods GET, PUT and DELETE are CRUD (create, read, update and delete) operations—that is data management operations—on the state of a target resource (the one identified by the request URI):

  • GET should read the state of the target resource;
  • PUT should create or update the state of the target resource;
  • DELETE should delete the state of the target resource.

The request method POST is a different beast. It should not create the state of the target resource like PUT because it is a process operation with a higher-level goal than CRUD (cf. RFC 7231, § 4.3.3). The process may create a resource but different from the target resource, otherwise the lower-level goal request method PUT should be used, so even in this case that does not make it a CRUD operation.

The difference between CRUD operations (GET, PUT and DELETE in HTTP) and non-CRUD operations (POST in HTTP) is the difference between abstract data types and objects that Alan Kay was stressing in most of his talks and his ACM paper The Early History of Smalltalk:

What I got from Simula was that you could now replace bindings and assignments with goals. The last thing you wanted any programmer to do is mess with internal state even if presented figuratively. Instead, the objects should be presented as sites of higher level behaviors more appropriate for use as dynamic components.

[…] It is unfortunate that much of what is called "object-oriented programming" today is simply old style programming with fancier constructs. Many programs are loaded with "assignment-style" operations now done by more expensive attached procedures.

[…] Assignment statements—even abstract ones—express very low-level goals, and more of them will be needed to get anything done. […] Another way to think of all this is: though the late-binding of automatic storage allocations doesn’t do anything a programmer can’t do, its presence leads both to simpler and more powerful code. OOP is a late binding strategy for many things and all of them together hold off fragility and size explosion much longer than the older methodologies.

sql query to get earliest date

SELECT TOP 1 ID, Name, Score, [Date]
FROM myTable
WHERE ID = 2
Order BY [Date]

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

Why I've got no crontab entry on OS X when using vim?

Use another text editor

env EDITOR=nano crontab -e 

or

env EDITOR=code crontab -e 

Delete branches in Bitbucket

I could delete most of my branches but one looked like this and I could not delete it:

enter image description here

Turned out someone had set Branch permissions under Settings and from there unchecked Allow deleting this branch. Hope this can help someone.

enter image description here

Update: Where settings are located from question in comment. Enter the repository that you wan't to edit to get the menu. You might need admin privileges to change this.

enter image description here

OnClick vs OnClientClick for an asp:CheckBox?

You can do the tag like this:

<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />

The .checked property in the called JavaScript will be correct...the current state of the checkbox:

  function checkchanged(obj) {
      alert(obj.checked)
  }

Open popup and refresh parent page on close popup

You can access parent window using 'window.opener', so, write something like the following in the child window:

<script>
    window.onunload = refreshParent;
    function refreshParent() {
        window.opener.location.reload();
    }
</script>

Resize font-size according to div size

Here's a SCSS version of @Patrick's mixin.

$mqIterations: 19;
@mixin fontResize($iterations)
{
  $i: 1;
  @while $i <= $iterations
  {
    @media all and (min-width: 100px * $i) {
      body { font-size:0.2em * $i; }
    }
    $i: $i + 1;
  }
}
@include fontResize($mqIterations);

Can you target <br /> with css?

old question but this is a pretty neat and clean fix, might come in use for people who are still wondering if it's possible :):

_x000D_
_x000D_
br{_x000D_
    content: '.';_x000D_
    display: inline-block;_x000D_
    width: 100%;_x000D_
    border-bottom: 1px dashed black;_x000D_
}
_x000D_
_x000D_
_x000D_

with this fix you can also remove BRs on websites ( just set the width to 0px )

Why does one use dependency injection?

First, I want to explain an assumption that I make for this answer. It is not always true, but quite often:

Interfaces are adjectives; classes are nouns.

(Actually, there are interfaces that are nouns as well, but I want to generalize here.)

So, e.g. an interface may be something such as IDisposable, IEnumerable or IPrintable. A class is an actual implementation of one or more of these interfaces: List or Map may both be implementations of IEnumerable.

To get the point: Often your classes depend on each other. E.g. you could have a Database class which accesses your database (hah, surprise! ;-)), but you also want this class to do logging about accessing the database. Suppose you have another class Logger, then Database has a dependency to Logger.

So far, so good.

You can model this dependency inside your Database class with the following line:

var logger = new Logger();

and everything is fine. It is fine up to the day when you realize that you need a bunch of loggers: Sometimes you want to log to the console, sometimes to the file system, sometimes using TCP/IP and a remote logging server, and so on ...

And of course you do NOT want to change all your code (meanwhile you have gazillions of it) and replace all lines

var logger = new Logger();

by:

var logger = new TcpLogger();

First, this is no fun. Second, this is error-prone. Third, this is stupid, repetitive work for a trained monkey. So what do you do?

Obviously it's a quite good idea to introduce an interface ICanLog (or similar) that is implemented by all the various loggers. So step 1 in your code is that you do:

ICanLog logger = new Logger();

Now the type inference doesn't change type any more, you always have one single interface to develop against. The next step is that you do not want to have new Logger() over and over again. So you put the reliability to create new instances to a single, central factory class, and you get code such as:

ICanLog logger = LoggerFactory.Create();

The factory itself decides what kind of logger to create. Your code doesn't care any longer, and if you want to change the type of logger being used, you change it once: Inside the factory.

Now, of course, you can generalize this factory, and make it work for any type:

ICanLog logger = TypeFactory.Create<ICanLog>();

Somewhere this TypeFactory needs configuration data which actual class to instantiate when a specific interface type is requested, so you need a mapping. Of course you can do this mapping inside your code, but then a type change means recompiling. But you could also put this mapping inside an XML file, e.g.. This allows you to change the actually used class even after compile time (!), that means dynamically, without recompiling!

To give you a useful example for this: Think of a software that does not log normally, but when your customer calls and asks for help because he has a problem, all you send to him is an updated XML config file, and now he has logging enabled, and your support can use the log files to help your customer.

And now, when you replace names a little bit, you end up with a simple implementation of a Service Locator, which is one of two patterns for Inversion of Control (since you invert control over who decides what exact class to instantiate).

All in all this reduces dependencies in your code, but now all your code has a dependency to the central, single service locator.

Dependency injection is now the next step in this line: Just get rid of this single dependency to the service locator: Instead of various classes asking the service locator for an implementation for a specific interface, you - once again - revert control over who instantiates what.

With dependency injection, your Database class now has a constructor that requires a parameter of type ICanLog:

public Database(ICanLog logger) { ... }

Now your database always has a logger to use, but it does not know any more where this logger comes from.

And this is where a DI framework comes into play: You configure your mappings once again, and then ask your DI framework to instantiate your application for you. As the Application class requires an ICanPersistData implementation, an instance of Database is injected - but for that it must first create an instance of the kind of logger which is configured for ICanLog. And so on ...

So, to cut a long story short: Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks).

In practice, there are things you can not do without a service locator (e.g., if you do not know in advance how many instances you do need of a specific interface: A DI framework always injects only one instance per parameter, but you can call a service locator inside a loop, of course), hence most often each DI framework also provides a service locator.

But basically, that's it.

P.S.: What I described here is a technique called constructor injection, there is also property injection where not constructor parameters, but properties are being used for defining and resolving dependencies. Think of property injection as an optional dependency, and of constructor injection as mandatory dependencies. But discussion on this is beyond the scope of this question.

In Java, what is the best way to determine the size of an object?

There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier.

If that's too slow or just more trouble than it's worth, there's always good old-fashioned row counting rule-of-thumbs.

How can I clone a JavaScript object except for one key?

Using Object Destructuring

_x000D_
_x000D_
const omit = (prop, { [prop]: _, ...rest }) => rest;_x000D_
const obj = { a: 1, b: 2, c: 3 };_x000D_
const objWithoutA = omit('a', obj);_x000D_
console.log(objWithoutA); // {b: 2, c: 3}
_x000D_
_x000D_
_x000D_

Customizing the template within a Directive

angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs) {
            var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
            element.replaceWith(htmlText);
        }
    };
})

Fade In Fade Out Android Animation in Java

AnimationSets don't appear to work as expected at all. In the end I gave up and used the Handler class's postDelayed() to sequence animations.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

RAII is usually better, but you can have easily the finally semantics in C++. Using a tiny amount of code.

Besides, the C++ Core Guidelines give finally.

Here is a link to the GSL Microsoft implementation and a link to the Martin Moene implementation

Bjarne Stroustrup multiple times said that everything that is in the GSL it meant to go in the standard eventually. So it should be a future-proof way to use finally.

You can easily implement yourself if you want though, continue reading.

In C++11 RAII and lambdas allows to make a general finally:

namespace detail { //adapt to your "private" namespace
template <typename F>
struct FinalAction {
    FinalAction(F f) : clean_{f} {}
   ~FinalAction() { if(enabled_) clean_(); }
    void disable() { enabled_ = false; };
  private:
    F clean_;
    bool enabled_{true}; }; }

template <typename F>
detail::FinalAction<F> finally(F f) {
    return detail::FinalAction<F>(f); }

example of use:

#include <iostream>
int main() {
    int* a = new int;
    auto delete_a = finally([a] { delete a; std::cout << "leaving the block, deleting a!\n"; });
    std::cout << "doing something ...\n"; }

the output will be:

doing something...
leaving the block, deleting a!

Personally I used this few times to ensure to close POSIX file descriptor in a C++ program.

Having a real class that manage resources and so avoids any kind of leaks is usually better, but this finally is useful in the cases where making a class sounds like an overkill.

Besides, I like it better than other languages finally because if used naturally you write the closing code nearby the opening code (in my example the new and delete) and destruction follows construction in LIFO order as usual in C++. The only downside is that you get an auto variable you don't really use and the lambda syntax make it a little noisy (in my example in the fourth line only the word finally and the {}-block on the right are meaningful, the rest is essentially noise).

Another example:

 [...]
 auto precision = std::cout.precision();
 auto set_precision_back = finally( [precision, &std::cout]() { std::cout << std::setprecision(precision); } );
 std::cout << std::setprecision(3);

The disable member is useful if the finally has to be called only in case of failure. For example, you have to copy an object in three different containers, you can setup the finally to undo each copy and disable after all copies are successful. Doing so, if the destruction cannot throw, you ensure the strong guarantee.

disable example:

//strong guarantee
void copy_to_all(BIGobj const& a) {
    first_.push_back(a);
    auto undo_first_push = finally([first_&] { first_.pop_back(); });

    second_.push_back(a);
    auto undo_second_push = finally([second_&] { second_.pop_back(); });

    third_.push_back(a);
    //no necessary, put just to make easier to add containers in the future
    auto undo_third_push = finally([third_&] { third_.pop_back(); });

    undo_first_push.disable();
    undo_second_push.disable();
    undo_third_push.disable(); }

If you cannot use C++11 you can still have finally, but the code becomes a bit more long winded. Just define a struct with only a constructor and destructor, the constructor take references to anything needed and the destructor does the actions you need. This is basically what the lambda does, done manually.

#include <iostream>
int main() {
    int* a = new int;

    struct Delete_a_t {
        Delete_a_t(int* p) : p_(p) {}
       ~Delete_a_t() { delete p_; std::cout << "leaving the block, deleting a!\n"; }
        int* p_;
    } delete_a(a);

    std::cout << "doing something ...\n"; }

Hopefully you can use C++11, this code is more to show how the "C++ does not support finally" has been nonsense since the very first weeks of C++, it was possible to write this kind of code even before C++ got its name.

How can I delete a newline if it is the last character in a file?

head -n -1 abc > newfile
tail -n 1 abc | tr -d '\n' >> newfile

Edit 2:

Here is an awk version (corrected) that doesn't accumulate a potentially huge array:

awk '{if (line) print line; line=$0} END {printf $0}' abc

Plotting 4 curves in a single plot, with 3 y-axes

This is a great chance to introduce you to the File Exchange. Though the organization of late has suffered from some very unfortunately interface design choices, it is still a great resource for pre-packaged solutions to common problems. Though many here have given you the gory details of how to achieve this (@prm!), I had a similar need a few years ago and found that addaxis worked very well. (It was a File Exchange pick of the week at one point!) It has inspired later, probably better mods. Here is some example output:

addaxis example http://www.mathworks.com/matlabcentral/fx_files/9016/1/addaxis_screenshot.jpg

I just searched for "plotyy" at File Exchange.

Though understanding what's going on in important, sometimes you just need to get things done, not do them yourself. Matlab Central is great for that.

symfony2 : failed to write cache directory

For a GOOD and definite solution see the Setting up Permissions section in Installing and Configuring Symfony section :

Setting up Permissions

One common issue when installing Symfony is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On a UNIX system, if your web server user is different from your command line user, you can try one of the following solutions.

  1. Use the same user for the CLI and the web server

In development environments, it is a common practice to use the same UNIX user for the CLI and the web server because it avoids any of these permissions issues when setting up new projects. This can be done by editing your web server configuration (e.g. commonly httpd.conf or apache2.conf for Apache) and setting its user to be the same as your CLI user (e.g. for Apache, update the User and Group values).

  1. Using ACL on a system that supports chmod +a

Many systems allow you to use the chmod +a command. Try this first, and if you get an error - try the next method. This uses a command to try to determine your web server user and set it as HTTPDUSER:

$ rm -rf app/cache/*
$ rm -rf app/logs/*

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
  1. Using ACL on a system that does not support chmod +a

Some systems don't support chmod +a, but do support another utility called setfacl. You may need to enable ACL support on your partition and install setfacl before using it (as is the case with Ubuntu). This uses a command to try to determine your web server user and set it as HTTPDUSER:

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs

For Symfony 3 it would be:

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs

If this doesn't work, try adding -n option.

  1. Without using ACL

If none of the previous methods work for you, change the umask so that the cache and log directories will be group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console, web/app.php and web/app_dev.php files:

umask(0002); // This will let the permissions be 0775

// or

umask(0000); // This will let the permissions be 0777

Note that using the ACL is recommended when you have access to them on your server because changing the umask is not thread-safe.

http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup

source : Failed to write cache file "/var/www/myapp/app/cache/dev/classes.php" when clearing the cache

How can I change IIS Express port for a site

Deploy your application in the IIS with the default port. Try to debug it using visual studio. It's a good practice. If you use visual studio, it will keep changing the port number most of the time. So better deploy the application in the IIS first and Open the same in visual studio and Debug it.

Calling a PHP function from an HTML form in the same file

You have a big misunderstanding of how the web works.

Basically, things happen this way:

  • User (well, the browser) requests test.php from your server
  • On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
  • The browser displays the form, the user can interact with it.
  • The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.

You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.

If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).

How to backup Sql Database Programmatically in C#

I have new method without SMO problems

1. Create .bat File with backup sqlcmd command

for backup

SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”

for restore

SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”

2. Run the the bat file with WPF/C# code

        FileInfo file = new FileInfo("DB\\batfile.bat");
        Process process = new Process();
        process.StartInfo.FileName = file.FullName;
        process.StartInfo.Arguments = @"-X";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
        process.StartInfo.UseShellExecute = false; //Changed Line
        process.StartInfo.RedirectStandardOutput = true;  //Changed Line
        process.Start();
        string output = process.StandardOutput.ReadToEnd(); //Changed Line
        process.WaitForExit(); //Moved Line

Why doesn't file_get_contents work?

Wrap your $adr in urlencode(). I was having this problem and this solved it for me.

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

How can I match a string with a regex in Bash?

To match regexes you need to use the =~ operator.

Try this:

[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched

Alternatively, you can use wildcards (instead of regexes) with the == operator:

[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched

If portability is not a concern, I recommend using [[ instead of [ or test as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.

Converting Stream to String and back...what are we missing?

Try this.

string output1 = Encoding.ASCII.GetString(byteArray, 0, byteArray.Length)

How to justify navbar-nav in Bootstrap 3

To justify the bootstrap 3 navbar-nav justify menu to 100% width you can use this code:

@media (min-width: 768px){
    .navbar-nav {
        margin: 0 auto;
        display: table;
        table-layout: auto;
        float: none;
        width: 100%;
    }
    .navbar-nav>li {
        display: table-cell;
        float: none;
        text-align: center;
    }
} 

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.

It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"

Starting a webserver can be as trivial as cding into the directory the files are in and running:

python -m SimpleHTTPServer

Maximum number of threads in a .NET app?

You can test it by using this snipped code:

private static void Main(string[] args)
{
   int threadCount = 0;
   try
   {
      for (int i = 0; i < int.MaxValue; i ++)
      {
         new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
         threadCount ++;
      }
   }
   catch
   {
      Console.WriteLine(threadCount);
      Console.ReadKey(true);
   }
}

Beware of 32-bit and 64-bit mode of application.

Java: convert seconds to minutes, hours and days

You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
        : "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
        secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
        : "hours"));
sb.append(String.format("%d %s and ", minutesCount,
        (minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
        (secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
        new DecimalFormat("#,###").format(secondsIn), sb, sb2);

Which, when I enter 500000 outputs the requested (manual line break added for post) -

You entered 500,000 seconds, which is 5 days, 18 hours, 
53 minutes and 20 seconds. (5 days, 18:53:20 hours)

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

org.hibernate.MappingException: Could not determine type for: java.util.Set

I got the same problem with @ManyToOne column. It was solved... in stupid way. I had all other annotations for public getter methods, because they were overridden from parent class. But last field was annotated for private variable like in all other classes in my project. So I got the same MappingException without the reason.

Solution: I placed all annotations at public getter methods. I suppose, Hibernate can't handle cases, when annotations for private fields and public getters are mixed in one class.

how to create a Java Date object of midnight today and midnight tomorrow?

java.time

If you are using Java 8 and later, you can try the java.time package (Tutorial):

LocalDate tomorrow = LocalDate.now().plusDays(1);
Date endDate = Date.from(tomorrow.atStartOfDay(ZoneId.systemDefault()).toInstant());

Combine multiple results in a subquery into a single comma-separated value

I have reviewed all the answers. I think in database insertion should be like:

ID     Name      SomeColumn
1.     ABC       ,X,Y Z (these are three different rows)
2.     MNO       ,R,S

The comma should be at previous end and do searching by like %,X,%

How do I left align these Bootstrap form items?

If you are saying that your problem is how to left align the form labels, see if this helps:
http://jsfiddle.net/panchroma/8gYPQ/

Try changing the text-align left / right in the CSS

.form-horizontal .control-label{
    /* text-align:right; */
    text-align:left;
    background-color:#ffa;
}

Good luck!

How to subtract 30 days from the current datetime in mysql?

Let's not use NOW() as you're losing any query caching or optimization because the query is different every time. See the list of functions you should not use in the MySQL documentation.

In the code below, let's assume this table is growing with time. New stuff is added and you want to show just the stuff in the last 30 days. This is the most common case.

Note that the date has been added as a string. It is better to add the date in this way, from your calling code, than to use the NOW() function as it kills your caching.

SELECT * FROM table WHERE exec_datetime >= DATE_SUB('2012-06-12', INTERVAL 30 DAY);

You can use BETWEEN if you really just want stuff from this very second to 30 days before this very second, but that's not a common use case in my experience, so I hope the simplified query can serve you well.

select count(*) from table of mysql in php

For mysqli users, the code will look like this:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);

or:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);

Strip double quotes from a string in .NET

s = s.Replace("\"",string.Empty);

What does MissingManifestResourceException mean and how to fix it?

Because I am pre-compiling my web application (using VS2012 publish feature). I was getting the error above. I tried all the suggestions, but weirdly changing 'Build Action' to 'Content' did the trick!

Forking / Multi-Threaded Processes | Bash

In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.

Here is what works well for me:

#!/bin/sh

set -m # Enable Job Control

for i in `seq 30`; do # start 30 jobs in parallel
  sleep 3 &
done

# Wait for all parallel jobs to finish
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done

The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.

What is the command to truncate a SQL Server log file?

In management studio:

  • Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
    • Right-click the database, choose Properties, then Options.
    • Make sure "Recovery model" is set to "Simple", not "Full"
    • Click OK
  • Right-click the database again, choose Tasks -> Shrink -> Files
  • Change file type to "Log"
  • Click OK.

Alternatively, the SQL to do it:

 ALTER DATABASE mydatabase SET RECOVERY SIMPLE
 DBCC SHRINKFILE (mydatabase_Log, 1)

Ref: http://msdn.microsoft.com/en-us/library/ms189493.aspx

Difference between EXISTS and IN in SQL?

  1. EXISTS is much faster than IN when the subquery results is very large.
    IN is faster than EXISTS when the subquery results is very small.

    CREATE TABLE t1 (id INT, title VARCHAR(20), someIntCol INT)
    GO
    CREATE TABLE t2 (id INT, t1Id INT, someData VARCHAR(20))
    GO
    
    INSERT INTO t1
    SELECT 1, 'title 1', 5 UNION ALL
    SELECT 2, 'title 2', 5 UNION ALL
    SELECT 3, 'title 3', 5 UNION ALL
    SELECT 4, 'title 4', 5 UNION ALL
    SELECT null, 'title 5', 5 UNION ALL
    SELECT null, 'title 6', 5
    
    INSERT INTO t2
    SELECT 1, 1, 'data 1' UNION ALL
    SELECT 2, 1, 'data 2' UNION ALL
    SELECT 3, 2, 'data 3' UNION ALL
    SELECT 4, 3, 'data 4' UNION ALL
    SELECT 5, 3, 'data 5' UNION ALL
    SELECT 6, 3, 'data 6' UNION ALL
    SELECT 7, 4, 'data 7' UNION ALL
    SELECT 8, null, 'data 8' UNION ALL
    SELECT 9, 6, 'data 9' UNION ALL
    SELECT 10, 6, 'data 10' UNION ALL
    SELECT 11, 8, 'data 11'
    
  2. Query 1

    SELECT
    FROM    t1 
    WHERE   not  EXISTS (SELECT * FROM t2 WHERE t1.id = t2.t1id)
    

    Query 2

    SELECT t1.* 
    FROM   t1 
    WHERE  t1.id not in (SELECT  t2.t1id FROM t2 )
    

    If in t1 your id has null value then Query 1 will find them, but Query 2 cant find null parameters.

    I mean IN can't compare anything with null, so it has no result for null, but EXISTS can compare everything with null.

Open file dialog box in JavaScript

This is what worked best for me (Tested on IE8, FF, Chrome, Safari).

_x000D_
_x000D_
#file-input {_x000D_
  cursor: pointer;_x000D_
  outline: none;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
  filter: alpha(opacity=0); /* IE < 9 */_x000D_
  opacity: 0;_x000D_
}_x000D_
.input-label {_x000D_
  cursor: pointer;_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<label for="file-input" class="input-label">_x000D_
  Click Me <!-- Replace with whatever text or icon you wish to use -->_x000D_
  <input type="file" id="file-input">_x000D_
</label>
_x000D_
_x000D_
_x000D_

Explanation: I positioned the file input directly above the element to be clicked, so any clicks would either land on it or its label (which pulls up the upload dialog just as if you clicked the label itself). I had some issues with the button part of the default input sticking out of the side of the label, so overflow: hidden on the input and display: inline-block on the label were necessary.

Does JavaScript guarantee object property order?

Just found this out the hard way.

Using React with Redux, the state container of which's keys I want to traverse in order to generate children is refreshed everytime the store is changed (as per Redux's immutability concepts).

Thus, in order to take Object.keys(valueFromStore) I used Object.keys(valueFromStore).sort(), so that I at least now have an alphabetical order for the keys.

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

Difference between $.ajax() and $.get() and $.load()

Important note : jQuery.load() method can do not only GET but also POST requests, if data parameter is supplied (see: http://api.jquery.com/load/)

data Type: PlainObject or String A plain object or string that is sent to the server with the request.

Request Method The POST method is used if data is provided as an object; otherwise, GET is assumed.

Example: pass arrays of data to the server (POST request)
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

How do I properly clean up Excel interop objects?

You can actually release your Excel Application object cleanly, but you do have to take care.

The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via Marshal.FinalReleaseComObject() is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses "two dots", or iterates cells via a for each loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project.

The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call GC.Collect() and then GC.WaitForPendingFinalizers() to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference.

You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object.

For example, assuming that you had a Range object variable named xlRng, a Worksheet variable named xlSheet, a Workbook variable named xlBook and an Excel Application variable named xlApp, then your cleanup code could look something like the following:

// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRng);
Marshal.FinalReleaseComObject(xlSheet);

xlBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlBook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);

In most code examples you'll see for cleaning up COM objects from .NET, the GC.Collect() and GC.WaitForPendingFinalizers() calls are made TWICE as in:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the next garbage collection. However, if you are not using VSTO, you should be able to call GC.Collect() and GC.WaitForPendingFinalizers() just once.

I know that explicitly calling GC.Collect() is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling GC.Collect().

This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-)

I have a tutorial on this here:

Automating Office Programs with VB.Net / COM Interop

It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.

Send email from localhost running XAMMP in PHP using GMAIL mail server

Here's the link that gives me the answer:

[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

[Modify] the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(ignore the "Unix only" bit, since we actually are using sendmail)

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)

Close a div by clicking outside

An other way which makes then your jsfiddle less buggy (needed double click on open).

This doesn't use any delegated event to body level

Set tabindex="-1" to DIV .popup ( and for style CSS outline:0 )

DEMO

$(".link").click(function(e){
    e.preventDefault();
    $(".popup").fadeIn(300,function(){$(this).focus();});
});

$('.close').click(function() {
   $(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
    $(this).fadeOut(300);
});

Powershell: How can I stop errors from being displayed in a script?

In some cases you can pipe after the command a Out-Null

command | Out-Null

In Python, when to use a Dictionary, List or Set?

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you just need to know whether or not you've already got a particular value, but without ordering (and you don't need to store duplicates)? Use a set.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

Formatting your code a bit, you have only closed the inner hover function. You have not closed the outer parts, marked below:

$(// missing closing)
 function() { // missing closing }
     $("#mewlyDiagnosed").hover(
        function() {
            $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
        }, 
        function() {
            $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
        });

Navigation Controller Push View Controller

UINavigationController is not automatically presented in UIViewController.

This is what you should see in Interface Builder. Files owner has view outlet to Navigation controller and from navigation controller is outlet to actual view;

Interface Builder

Convert list of dictionaries to a pandas DataFrame

You can also use pd.DataFrame.from_dict(d) as :

In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010}, 
   ...: {'points': 25, 'time': '6:00', 'month': "february"}, 
   ...: {'points':90, 'time': '9:00', 'month': 'january'}, 
   ...: {'points_h1':20, 'month': 'june'}]

In [12]: pd.DataFrame.from_dict(d)
Out[12]: 
      month  points  points_h1  time    year
0       NaN    50.0        NaN  5:00  2010.0
1  february    25.0        NaN  6:00     NaN
2   january    90.0        NaN  9:00     NaN
3      june     NaN       20.0   NaN     NaN

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

To expand on others' answers, here is a compact solution that doesn't expose/add any new variables. It doesn't cover all bases, but it should suit most people who just want a single page app to remain functional (despite no data persistence after reload).

(function(){
    try {
        localStorage.setItem('_storage_test', 'test');
        localStorage.removeItem('_storage_test');
    } catch (exc){
        var tmp_storage = {};
        var p = '__unique__';  // Prefix all keys to avoid matching built-ins
        Storage.prototype.setItem = function(k, v){
            tmp_storage[p + k] = v;
        };
        Storage.prototype.getItem = function(k){
            return tmp_storage[p + k] === undefined ? null : tmp_storage[p + k];
        };
        Storage.prototype.removeItem = function(k){
            delete tmp_storage[p + k];
        };
        Storage.prototype.clear = function(){
            tmp_storage = {};
        };
    }
})();

display Java.util.Date in a specific format

If you want to simply output a date, just use the following:

System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());

As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:

String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());

You can also customize your output by following the Java API on Date/Time conversions.

Java Wait for thread to finish

The join() method allows one thread to wait for the completion of another.However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

How do I search for an object by its ObjectId in the mongo console?

If you're using Node.js:

> var ObjectId = require('mongodb').ObjectId; 
> var id = req.params.gonderi_id;       
> var o_id = new ObjectId(id);
> db.test.find({_id:o_id})

Edit: corrected to new ObjectId(id), not new ObjectID(id)

Convert a Unix timestamp to time in JavaScript

If you want to convert Unix time duration to real hours, minutes, and seconds, you could use the following code:

var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.

If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.

How do you programmatically set an attribute?

Also works fine within a class:

def update_property(self, property, value):
   setattr(self, property, value)

How to find all positions of the maximum value in a list?

Here is the max value and the indexes it appears at:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
...     d[x].append(i)
... 
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]

Later: for the satisfaction of @SilentGhost

>>> from itertools import takewhile
>>> import heapq
>>> 
>>> def popper(heap):
...     while heap:
...         yield heapq.heappop(heap)
... 
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>> 
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]

Get last 30 day records from today date in SQL Server

You can use DateDiff for this. The where clause in your query would look like:

where DATEDIFF(day,pdate,GETDATE()) < 31

MySQL - Rows to Columns

I'm sorry to say this and maybe I'm not solving your problem exactly but PostgreSQL is 10 years older than MySQL and is extremely advanced compared to MySQL and there's many ways to achieve this easily. Install PostgreSQL and execute this query

CREATE EXTENSION tablefunc;

then voila! And here's extensive documentation: PostgreSQL: Documentation: 9.1: tablefunc or this query

CREATE EXTENSION hstore;

then again voila! PostgreSQL: Documentation: 9.0: hstore

PHP - concatenate or directly insert variables in string

I prefer this all the time and found it much easier.

echo "Welcome {$name}!"

java.net.UnknownHostException: Invalid hostname for server: local

java.net.UnknownHostException: Host is unresolved:

Thrown to indicate that the IP address of a host could not be determined.

This exception is also raised when you are connected to a valid wifi but router does not receive the internet. Its very easy to reproduce this:

  1. Connect to a valid wifi
  2. Now remove the cable from the router while router is pluged-in

You will observe this error!!

You can't really solve this, You can only notify the user gracefully. (something like - "Unable to make a connection")

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

There is a fundamental flaw in the way we think about web, especially when using MVC. The flaw is that JavaScript is somehow the view's responsibility. A view is a view, JavaScript (behavioral or otherwise) is JavaScript. In Silverlight and WPF's MVVM pattern we we're faced with "view first" or "model first". In MVC we should always try to reason from the model's standpoint and JavaScript is a part of this model in many ways.

I would suggest using the AMD pattern (I myself like RequireJS). Seperate your JavaScript in modules, define your functionality and hook into your html from JavaScript instead of relying on a view to load the JavaScript. This will clean up your code, seperate your concerns and make life easier all in one fell swoop.

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

I was solved this problem too: Just reinstall node to LTS version by nvm:

nvm install --lts

nvm use --lts

Then rm -rf node_modules And npm i

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

What is the correct syntax of ng-include?

On ng-build, file not found(404) error occur. So we can use below code

<ng-include src="'views/transaction/test.html'"></ng-include>

insted of,

<div ng-include="'views/transaction/test.html'"></div>

How to use function srand() with time.h?

#include"stdio.h"
#include"conio.h"
#include"time.h"

void main()
{
  time_t t;
  int i;
  srand(time(&t));

  for(i=1;i<=10;i++)
    printf("%c\t",rand()%10);
  getch();
}