Programs & Examples On #Sql convert

How to convert DateTime to VarChar

Write a function

CREATE FUNCTION dbo.TO_SAP_DATETIME(@input datetime)
RETURNS VARCHAR(14)
AS BEGIN
    DECLARE @ret VARCHAR(14)
    SET @ret = COALESCE(SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(26), @input, 25),'-',''),' ',''),':',''),1,14),'00000000000000');
    RETURN @ret
END

Custom Date/Time formatting in SQL Server

The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'

That statement is false. That's just how Enterprise Manager or SQL Server chooses to show the date. Internally it's a 8-byte binary value, which is why some of the functions posted by Andrew will work so well.

Kibbee makes a valid point as well, and in a perfect world I would agree with him. However, sometimes you want to bind query results directly to display control or widgets and there's really not a chance to do any formatting. And sometimes the presentation layer lives on a web server that's even busier than the database. With those in mind, it's not necessarily a bad thing to know how to do this in SQL.

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

VBA: Convert Text to Number

''Convert text to Number with ZERO Digits and Number convert ZERO Digits  

Sub ZERO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0"
 Set rSelection = Nothing
End Sub

''Convert text to Number with TWO Digits and Number convert TWO Digits  

Sub TWO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.00"
 Set rSelection = Nothing
End Sub

''Convert text to Number with SIX Digits and Number convert SIX Digits  


Sub SIX_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.000000"
 Set rSelection = Nothing
End Sub



How to Enable ActiveX in Chrome?

This could be pretty ugly, but doesn't Chrome use the NPAPI for plugins like Safari? In that case, you could write a wrapper plugin with the NPAPI that made the appropriate ActiveX creation and calls to run the plugin. If you do a lot of scripting against those plugins, you might have to be a bit of work to proxy those calls through to the wrapped ActiveX control.

show all tags in git log

Note: the commit 5e1361c from brian m. carlson (bk2204) (for git 1.9/2.0 Q1 2014) deals with a special case in term of log decoration with tags:

log: properly handle decorations with chained tags

git log did not correctly handle decorations when a tag object referenced another tag object that was no longer a ref, such as when the second tag was deleted.
The commit would not be decorated correctly because parse_object had not been called on the second tag and therefore its tagged field had not been filled in, resulting in none of the tags being associated with the relevant commit.

Call parse_object to fill in this field if it is absent so that the chain of tags can be dereferenced and the commit can be properly decorated.
Include tests as well to prevent future regressions.

Example:

git tag -a tag1 -m tag1 &&
git tag -a tag2 -m tag2 tag1 &&
git tag -d tag1 &&
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

In your example

return $cnf::getConfig($key)

Probably should be:

return $cnf->getConfig($key)

And make getConfig not static

Get all Attributes from a HTML element with Javascript/jQuery

In javascript:

var attributes;
var spans = document.getElementsByTagName("span");
for(var s in spans){
  if (spans[s].getAttribute('name') === 'test') {
     attributes = spans[s].attributes;
     break;
  }
}

To access the attributes names and values:

attributes[0].nodeName
attributes[0].nodeValue

ASP.NET MVC: Html.EditorFor and multi-line text boxes

in your view, instead of:

@Html.EditorFor(model => model.Comments[0].Comment)

just use:

@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)

How do I create a round cornered UILabel on the iPhone?

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];

How to make sure that string is valid JSON using JSON.NET

Regarding Tom Beech's answer; I came up with the following instead:

public bool ValidateJSON(string s)
{
    try
    {
        JToken.Parse(s);
        return true;
    }
    catch (JsonReaderException ex)
    {
        Trace.WriteLine(ex);
        return false;
    }
}

With a usage of the following:

if (ValidateJSON(strMsg))
{
    var newGroup = DeserializeGroup(strMsg);
}

How do I calculate someone's age in Java?

If you are using GWT you will be limited to using java.util.Date, here is a method that takes the date as integers, but still uses java.util.Date:

public int getAge(int year, int month, int day) {
    Date now = new Date();
    int nowMonth = now.getMonth()+1;
    int nowYear = now.getYear()+1900;
    int result = nowYear - year;

    if (month > nowMonth) {
        result--;
    }
    else if (month == nowMonth) {
        int nowDay = now.getDate();

        if (day > nowDay) {
            result--;
        }
    }
    return result;
}

How do I detect "shift+enter" and generate a new line in Textarea?

Most of these answers overcomplicate this. Why not try it this way?

$("textarea").keypress(function(event) {
        if (event.keyCode == 13 && !event.shiftKey) {
         submitForm(); //Submit your form here
         return false;
         }
});

No messing around with caret position or shoving line breaks into JS. Basically, the function will not run if the shift key is being pressed, therefore allowing the enter/return key to perform its normal function.

Stash just a single file

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

However, if you do want to specify a message, use push.

git stash push -m "describe changes to filename.ext" filename.ext

Both methods work in git versions 2.13+

Declaring a boolean in JavaScript using just var

Variables in Javascript don't have a type. Non-zero, non-null, non-empty and true are "true". Zero, null, undefined, empty string and false are "false".

There's a Boolean type though, as are literals true and false.

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

React Native version mismatch

For Android developers who couldn't get it fixed by just closing and rebuilding, Manually uninstall the app on the emulator/device.

How do I uninstall a package installed using npm link?

you can use unlink to remove the symlink.

For Example:

cd ~/projects/node-redis 
npm link                 
cd ~/projects/node-bloggy
npm link redis             # links to your local redis

To reinstall from your package.json:

npm unlink redis
npm install

https://www.tachyonstemplates.com/npm-cheat-sheet/#unlinking-a-npm-package-from-an-application

100% width in React Native Flexbox

You should use Dimensions

First, define Dimensions.

import { Dimensions } from "react-native";

var width = Dimensions.get('window').width; //full width
var height = Dimensions.get('window').height; //full height

then, change line1 style like below:

line1: {
    backgroundColor: '#FDD7E4',
    width: width,
},

MySQL - how to front pad zip code with "0"?

Ok, so you've switched the column from Number to VARCHAR(5). Now you need to update the zipcode field to be left-padded. The SQL to do that would be:

UPDATE MyTable
SET ZipCode = LPAD( ZipCode, 5, '0' );

This will pad all values in the ZipCode column to 5 characters, adding '0's on the left.

Of course, now that you've got all of your old data fixed, you need to make sure that your any new data is also zero-padded. There are several schools of thought on the correct way to do that:

  • Handle it in the application's business logic. Advantages: database-independent solution, doesn't involve learning more about the database. Disadvantages: needs to be handled everywhere that writes to the database, in all applications.

  • Handle it with a stored procedure. Advantages: Stored procedures enforce business rules for all clients. Disadvantages: Stored procedures are more complicated than simple INSERT/UPDATE statements, and not as portable across databases. A bare INSERT/UPDATE can still insert non-zero-padded data.

  • Handle it with a trigger. Advantages: Will work for Stored Procedures and bare INSERT/UPDATE statements. Disadvantages: Least portable solution. Slowest solution. Triggers can be hard to get right.

In this case, I would handle it at the application level (if at all), and not the database level. After all, not all countries use a 5-digit Zipcode (not even the US -- our zipcodes are actually Zip+4+2: nnnnn-nnnn-nn) and some allow letters as well as digits. Better NOT to try and force a data format and to accept the occasional data error, than to prevent someone from entering the correct value, even though it's format isn't quite what you expected.

Create patch or diff file from git repository and apply it to another different git repository

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

Javascript foreach loop on associative array object

There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array is very different from a JavaScript Array.

In PHP, an associative array can do most of what a numerically-indexed array can (the array_* functions work, you can count() it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.

In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will effect its length, and can be iterated over using Array methods (map, forEach, reduce, filter, find, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:

array['Main'] = 'Main Page';

is actually equivalent to:

array.Main = 'Main Page';

From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array), and name based on what it should contain (e.g. pages). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object methods (Object.keys in this case -- there's also entries and values being added to some browsers right now) which we can loop.

// assigning values to corresponding keys
const pages = {
  Main: 'Main page',
  Guide: 'Guide page',
  Articles: 'Articles page',
  Forum: 'Forum board',
};

Object.keys(pages).forEach((page) => console.log(page));

Hibernate Union alternatives

Here is a special case, but might inspire you to create your own work around. The goal here is to count the total number of records from two different tables where records meet a particular criteria. I believe this technique will work for any case where you need to aggregate data from across multiple tables/sources.

I have some special intermediate classes setup, so the code which calls the named query is short and sweet, but you can use whatever method you normally use in conjunction with named queries to execute your query.

QueryParms parms=new QueryParms();
parms.put("PROCDATE",PROCDATE);

Long pixelAll = ((SourceCount)Fetch.row("PIXEL_ALL",parms,logger)).getCOUNT();

As you can see here, the named query begins to look an aweful lot like a union statement:

@Entity
@NamedQueries({
        @NamedQuery(
            name  ="PIXEL_ALL",
            query = "" +
                    "  SELECT new SourceCount(" +
                    "     (select count(a) from PIXEL_LOG_CURR1 a " +
                    "       where to_char(a.TIMESTAMP, 'YYYYMMDD') = :PROCDATE " +
                    "     )," +
                    "     (select count(b) from PIXEL_LOG_CURR2 b" +
                    "       where to_char(b.TIMESTAMP, 'YYYYMMDD') = :PROCDATE " +
                    "     )" +
                    ") from Dual1" +
                    ""
    )
})

public class SourceCount {
    @Id
    private Long   COUNT;

    public SourceCount(Long COUNT1, Long COUNT2) {
        this.COUNT = COUNT1+COUNT2;
    }

    public Long getCOUNT() {
        return COUNT;
    }

    public void setCOUNT(Long COUNT) {
        this.COUNT = COUNT;
    }
}

Part of the magic here is to create a dummy table and insert one record into it. In my case, I named it dual1 because my database is Oracle, but I don't think it matters what you call the dummy table.

@Entity
@Table(name="DUAL1")
public class Dual1 {
    @Id
    Long ID;
}

Don't forget to insert your dummy record:

SQL> insert into dual1 values (1);

How to validate an e-mail address in swift?

Create simple extension:

extension NSRegularExpression {

    convenience init(pattern: String) {
        try! self.init(pattern: pattern, options: [])
    }
}

extension String {

    var isValidEmail: Bool {
        return isMatching(expression: NSRegularExpression(pattern: "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"))
    }

    //MARK: - Private

    private func isMatching(expression: NSRegularExpression) -> Bool {
        return expression.numberOfMatches(in: self, range: NSRange(location: 0, length: characters.count)) > 0
    }
}

Example:

"[email protected]".isValidEmail //true
"b@bb".isValidEmail //false

You can extend following extension to anything you need: isValidPhoneNumber, isValidPassword etc...

How to change colour of blue highlight on select box dropdown

Add this in your CSS code and change the red background-color with a color of your choice:

.dropdown-menu>.active>a {color:black; background-color:red;}
.dropdown-menu>.active>a:focus {color:black; background-color:red;}
.dropdown-menu>.active>a:hover {color:black; background-color:red;}

Case insensitive regular expression without re.compile?

To perform case-insensitive operations, supply re.IGNORECASE

>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']

and if we want to replace text matching the case...

>>> def matchcase(word):
        def replace(m):
            text = m.group()
            if text.isupper():
                return word.upper()
            elif text.islower():
                return word.lower()
            elif text[0].isupper():
                return word.capitalize()
            else:
                return word
        return replace

>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'

get parent's view from a layout

You can get ANY view by using the code below

view.rootView.findViewById(R.id.*name_of_the_view*)

EDIT: This works on Kotlin. In Java, you may need to do something like this=

this.getCurrentFocus().getRootView().findViewById(R.id.*name_of_the_view*);

I learned getCurrentFocus() function from: @JFreeman 's answer

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

How to submit a form when the return key is pressed?

Use the following script.

<SCRIPT TYPE="text/javascript">
<!--
    function submitenter(myfield,e)
    {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        if (keycode == 13)
        {
            myfield.form.submit();
            return false;
        }
        else
            return true;
    }
//-->
</SCRIPT>

For each field that should submit the form when the user hits enter, call the submitenter function as follows.

<FORM ACTION="../cgi-bin/formaction.pl">
    name:     <INPUT NAME=realname SIZE=15><BR>
    password: <INPUT NAME=password TYPE=PASSWORD SIZE=10
       onKeyPress="return submitenter(this,event)"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>

Click a button programmatically - JS

window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {
       hangoutButton.click(); // this will trigger the click event
    };
};

this will do the trick

Show SOME invisible/whitespace characters in Eclipse

Navigate to Window > Preferences > General > Editors > Text Editors

Click on the CheckBox "Show whitespace characters".

enter image description here

Thats all.!!!

What does it mean to "program to an interface"?

It can be advantageous to program to interfaces, even when we are not depending on abstractions.

Programming to interfaces forces us to use a contextually appropriate subset of an object. That helps because it:

  1. prevents us from doing contextually inappropriate things, and
  2. lets us safely change the implementation in the future.

For example, consider a Person class that implements the Friend and the Employee interface.

class Person implements AbstractEmployee, AbstractFriend {
}

In the context of the person's birthday, we program to the Friend interface, to prevent treating the person like an Employee.

function party() {
    const friend: Friend = new Person("Kathryn");
    friend.HaveFun();
}

In the context of the person's work, we program to the Employee interface, to prevent blurring workplace boundaries.

function workplace() {
    const employee: Employee = new Person("Kathryn");
    employee.DoWork();
}

Great. We have behaved appropriately in different contexts, and our software is working well.

Far into the future, if our business changes to work with dogs, we can change the software fairly easily. First, we create a Dog class that implements both Friend and Employee. Then, we safely change new Person() to new Dog(). Even if both functions have thousands of lines of code, that simple edit will work because we know the following are true:

  1. Function party uses only the Friend subset of Person.
  2. Function workplace uses only the Employee subset of Person.
  3. Class Dog implements both the Friend and Employee interfaces.

On the other hand, if either party or workplace were to have programmed against Person, there would be a risk of both having Person-specific code. Changing from Person to Dog would require us to comb through the code to extirpate any Person-specific code that Dog does not support.

The moral: programming to interfaces helps our code to behave appropriately and to be ready for change. It also prepares our code to depend on abstractions, which brings even more advantages.

gcc-arm-linux-gnueabi command not found

Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx

where xxx is gcc or ar or ld, etc

Type Checking: typeof, GetType, or is?

Type t = typeof(obj1);
if (t == typeof(int))
    // Some code here

This is an error. The typeof operator in C# can only take type names, not objects.

if (obj1.GetType() == typeof(int))
    // Some code here

This will work, but maybe not as you would expect. For value types, as you've shown here, it's acceptable, but for reference types, it would only return true if the type was the exact same type, not something else in the inheritance hierarchy. For instance:

class Animal{}
class Dog : Animal{}

static void Foo(){
    object o = new Dog();

    if(o.GetType() == typeof(Animal))
        Console.WriteLine("o is an animal");
    Console.WriteLine("o is something else");
}

This would print "o is something else", because the type of o is Dog, not Animal. You can make this work, however, if you use the IsAssignableFrom method of the Type class.

if(typeof(Animal).IsAssignableFrom(o.GetType())) // note use of tested type
    Console.WriteLine("o is an animal");

This technique still leaves a major problem, though. If your variable is null, the call to GetType() will throw a NullReferenceException. So to make it work correctly, you'd do:

if(o != null && typeof(Animal).IsAssignableFrom(o.GetType()))
    Console.WriteLine("o is an animal");

With this, you have equivalent behavior of the is keyword. Hence, if this is the behavior you want, you should use the is keyword, which is more readable and more efficient.

if(o is Animal)
    Console.WriteLine("o is an animal");

In most cases, though, the is keyword still isn't what you really want, because it's usually not enough just to know that an object is of a certain type. Usually, you want to actually use that object as an instance of that type, which requires casting it too. And so you may find yourself writing code like this:

if(o is Animal)
    ((Animal)o).Speak();

But that makes the CLR check the object's type up to two times. It will check it once to satisfy the is operator, and if o is indeed an Animal, we make it check again to validate the cast.

It's more efficient to do this instead:

Animal a = o as Animal;
if(a != null)
    a.Speak();

The as operator is a cast that won't throw an exception if it fails, instead returning null. This way, the CLR checks the object's type just once, and after that, we just need to do a null check, which is more efficient.

But beware: many people fall into a trap with as. Because it doesn't throw exceptions, some people think of it as a "safe" cast, and they use it exclusively, shunning regular casts. This leads to errors like this:

(o as Animal).Speak();

In this case, the developer is clearly assuming that o will always be an Animal, and as long as their assumption is correct, everything works fine. But if they're wrong, then what they end up with here is a NullReferenceException. With a regular cast, they would have gotten an InvalidCastException instead, which would have more correctly identified the problem.

Sometimes, this bug can be hard to find:

class Foo{
    readonly Animal animal;

    public Foo(object o){
        animal = o as Animal;
    }

    public void Interact(){
        animal.Speak();
    }
}

This is another case where the developer is clearly expecting o to be an Animal every time, but this isn't obvious in the constructor, where the as cast is used. It's not obvious until you get to the Interact method, where the animal field is expected to be positively assigned. In this case, not only do you end up with a misleading exception, but it isn't thrown until potentially much later than when the actual error occurred.

In summary:

  • If you only need to know whether or not an object is of some type, use is.

  • If you need to treat an object as an instance of a certain type, but you don't know for sure that the object will be of that type, use as and check for null.

  • If you need to treat an object as an instance of a certain type, and the object is supposed to be of that type, use a regular cast.

Doctrine and LIKE query

This is not possible with the magic find methods. Try using the query builder:

$result = $em->getRepository("Orders")->createQueryBuilder('o')
   ->where('o.OrderEmail = :email')
   ->andWhere('o.Product LIKE :product')
   ->setParameter('email', '[email protected]')
   ->setParameter('product', 'My Products%')
   ->getQuery()
   ->getResult();

Zoom to fit all markers in Mapbox or Leaflet

To fit to the visible markers only, I've this method.

fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}

How do you get the current text contents of a QComboBox?

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

For android source code with repo, I beleive you should use REPO. if you really want to use git, you should know if the project has .git directory with ls -a. Or you have to enter the sub project directory which should include the .git.

How do I force files to open in the browser instead of downloading (PDF)?

You can do this in the following way:

<a href="path to PDF file">Open PDF</a>

If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:

<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
    Order Allow,Deny
    Allow from all
</FilesMatch>

But now allow just certain necessary files.

I have used this code and it worked perfectly.

Round up value to nearest whole number in SQL UPDATE

You could use the ceiling function; this portion of SQL code :

select ceiling(45.01), ceiling(45.49), ceiling(45.99);

will get you "46" each time.

For your update, so, I'd say :

Update product SET price = ceiling(45.01)

BTW : On MySQL, ceil is an alias to ceiling ; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...

Quoting the documentation :

CEILING(X)

Returns the smallest integer value not less than X.

And the given example :

mysql> SELECT CEILING(1.23);
        -> 2
mysql> SELECT CEILING(-1.23);
        -> -1

List files recursively in Linux CLI with path relative to the current directory

DIR=your_path
find $DIR | sed 's:""$DIR""::'

'sed' will erase 'your_path' from all 'find' results. And you recieve relative to 'DIR' path.

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

How to convert current date into string in java?

String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

Why is an OPTIONS request sent and can I disable it?

Have gone through this issue, below is my conclusion to this issue and my solution.

According to the CORS strategy (highly recommend you read about it) You can't just force the browser to stop sending OPTIONS request if it thinks it needs to.

There are two ways you can work around it:

  1. Make sure your request is a "simple request"
  2. Set Access-Control-Max-Age for the OPTIONS request

Simple request

A simple cross-site request is one that meets all the following conditions:

The only allowed methods are:

  • GET
  • HEAD
  • POST

Apart from the headers set automatically by the user agent (e.g. Connection, User-Agent, etc.), the only headers which are allowed to be manually set are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type

The only allowed values for the Content-Type header are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

A simple request will not cause a pre-flight OPTIONS request.

Set a cache for the OPTIONS check

You can set a Access-Control-Max-Age for the OPTIONS request, so that it will not check the permission again until it is expired.

Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request.

Limitation Noted

  • For Chrome, the maximum seconds for Access-Control-Max-Age is 600 which is 10 minutes, according to chrome source code
  • Access-Control-Max-Age only works for one resource every time, for example, GET requests with same URL path but different queries will be treated as different resources. So the request to the second resource will still trigger a preflight request.

Add some word to all or some rows in Excel?

Insert a column, for instance a new A column. Then use this function;

="k"&B1

and copy it down.

Then you can hide the new column A if you need too.

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

what you have is fine - however to save some typing, you can simply use for your data


data: $('#formId').serialize()

see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.

Filtering a pyspark dataframe using isin by exclusion

Also could be like this

df.filter(col('bar').isin(['a','b']) == False).show()

font-weight is not working properly?

font-weight can also fail to work if the font you are using does not have those weights in existence – you will often hit this when embedding custom fonts. In those cases the browser will likely round the number to the closest weight that it does have available.

For example, if I embed the following font...

@font-face {
    font-family: 'Nexa';
    src: url(...);
    font-weight: 300;
    font-style: normal;
}

Then I will not be able to use anything other than a weight of 300. All other weights will revert to 300, unless I specify additional @font-face declarations with those additional weights.

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

How to fix Cannot find module 'typescript' in Angular 4?

Run 'npm install' it will install all necessary pkg .

How to Validate a DateTime in C#?

protected static bool CheckDate(DateTime date)
{
    if(new DateTime() == date)      
        return false;       
    else        
        return true;        
} 

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

This error you are receiving :

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.

If $matches contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash)

If $values & $matches do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches.

I believe you will also need to ensure the column hash has a unique index on it as well.

Try the code here:

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }


$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
    $values[] = '?';
}

// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);

//Error reporting if something went wrong...
var_dump($dbh->errorInfo());

?>

You will need to adapt it a little.

Table structure I used is here:

CREATE TABLE IF NOT EXISTS `hashes` (
  `hashid` int(11) NOT NULL AUTO_INCREMENT,
  `hash` varchar(250) NOT NULL,
  PRIMARY KEY (`hashid`),
  UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.

I hope this helps.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

WPF Timer Like C# Timer

With Dispatcher you will need to include

using System.Windows.Threading;

Also note that if you right-click DispatcherTimer and click Resolve it should add the appropriate references.

How to get the index with the key in Python dictionary?

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the 'index' of b depends entirely on what was inserted into and deleted from the mapping before:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

Simply append your key/value pair to the post string

Angular, content type is not being sent with $http

You need to include a body with the request. Angular removes the content-type header otherwise.

Add data: '' to the argument to $http.

Detect encoding and make everything UTF-8

The interesting thing about mb_detect_encoding and mb_convert_encoding is that the order of the encodings you suggest does matter:

// $input is actually UTF-8

mb_detect_encoding($input, "UTF-8", "ISO-8859-9, UTF-8");
// ISO-8859-9 (WRONG!)

mb_detect_encoding($input, "UTF-8", "UTF-8, ISO-8859-9");
// UTF-8 (OK)

So you might want to use a specific order when specifying expected encodings. Still, keep in mind that this is not foolproof.

How to convert CharSequence to String?

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

Timeout a command in bash without unnecessary delay

I have a cron job that calls a php script and, some times, it get stuck on php script. This solution was perfect to me.

I use:

scripttimeout -t 60 /script.php

How do I tell Gradle to use specific JDK version?

There is one more option to follow. In your gradle tasks available in Eclipse, you can set your desired jdk path. (I know this is a while since the question was posted. This answer can help someone.)

Right click on the deploy or any other task and select "Open Gradle Run Configuration..."

enter image description here

Then navigate to "Java Home" and paste your desired java path.

enter image description here

Please note that, bin will be added by the gradle task itself. So don't add the "bin" to the path.

How to set the margin or padding as percentage of height of parent container?

An answer to a slightly different question: You can use vh units to pad elements to the center of the viewport:

.centerme {
    margin-top: 50vh;
    background: red;
}

<div class="centerme">middle</div>

chrome undo the action of "prevent this page from creating additional dialogs"

Turning Hardware Acceleration OFF seems to be the setting that affects popups & dialogs.

Chrome was continually hiding Dialog Windows when I needed to respond Yes or No to things, also when I needed to Rename folders in my bookmarks panel. After weeks of doing this. I disabled all the Chrome helpers in Settings, Also In windows 10 I switched Window Snapping off. It has done something to put the popups and dialogs back in the Viewport.

When this bug is happening, I was able to shut a tab by first pressing Enter before clicking the tab close X button. The browser had an alert box, hidden which needed a response from the user.

Switching Hardware Accleration Off and back On, Killing the Chrome process and switching all the other Helpers Off and back has fixed it for me... It must be in chrome itself because Ive just gone into a Chrome window in the Mac and it has now stopped the problem, without any intervention. Im guessing flicking the chrome settings on/off/on has caused it to reposition the dialogs. I cant get the browser to repeat the fault now...

Converting an integer to binary in C

You need to initialise bin, e.g.

bin = malloc(1);
bin[0] = '\0';

or use calloc:

bin = calloc(1, 1);

You also have a bug here:

 bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));

this needs to be:

 bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));

(i.e. use strlen, not sizeof).

And you should increase the size before calling strcat.

And you're not freeing bin, so you have a memory leak.

And you need to convert 0, 1 to '0', '1'.

And you can't strcat a char to a string.

So apart from that, it's close, but the code should probably be more like this (warning, untested !):

int int_to_bin(int k)
{
   char *bin;
   int tmp;

   bin = calloc(1, 1);
   while (k > 0)
   {
      bin = realloc(bin, strlen(bin) + 2);
      bin[strlen(bin) - 1] = (k % 2) + '0';
      bin[strlen(bin)] = '\0';
      k = k / 2;
   }
   tmp = atoi(bin);
   free(bin);
   return tmp;
}

Vbscript list all PDF files in folder and subfolders

(For those who stumble upon this from your search engine of choice)

This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.

Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)

Wscript.Echo "end."

WScript.Quit 0

Sub ShowSubFolders(fFolder)
    Set objFolder = objFSO.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
        If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
            Wscript.Echo objFile.Name
        End If
    Next

    For Each Subfolder in fFolder.SubFolders
        ShowSubFolders(Subfolder)
    Next
End Sub

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

In SQL*Plus putting SET DEFINE ? at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.

How to end a session in ExpressJS

use,

delete req.session.yoursessionname;

PHP Pass by reference in foreach

I found this example also tricky. Why that in the 2nd loop at the last iteration nothing happens ($v stays 'two'), is that $v points to $a[3] (and vice versa), so it cannot assign value to itself, so it keeps the previous assigned value :)

Php, wait 5 seconds before executing an action

In https://www.php.net/manual/es/function.usleep.php

<?php
// Wait 2 seconds
usleep(2000000);

// if you need 5 seconds
usleep(5000000);
?>

IntelliJ - show where errors are

For IntelliJ 2017:

Use "Problem" tool window to see all errors. This window appears in bottom/side tabs when you enable "automatic" build/make as mentioned by @pavan above (https://stackoverflow.com/a/45556424/828062).

enter image description here

To access this Problems panel, you must set your project to build automatically. Check the box for Preferences/Settings > Build, Execution, Deployment > Compiler > Build project automatically.

screenshot of <code>Preferences</code>/<code>Settings</code> > <code>Build, Execution, Deployment</code> > <code>Compiler</code> > <code>Build project automatically</code>

jQuery Keypress Arrow Keys

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) 
      alert( "arrowkey pressed" );          
});

jsfiddle demo

Python: pandas merge multiple dataframes

functools.reduce and pd.concat are good solutions but in term of execution time pd.concat is the best.

from functools import reduce
import pandas as pd

dfs = [df1, df2, df3, ...]
nan_value = 0

# solution 1 (fast)
result_1 = pd.concat(dfs, join='outer', axis=1).fillna(nan_value)

# solution 2
result_2 = reduce(lambda df_left,df_right: pd.merge(df_left, df_right, 
                                              left_index=True, right_index=True, 
                                              how='outer'), 
                  dfs).fillna(nan_value)

ansible: lineinfile for several lines?

Here is a noise-free version of the solution which is to use with_items:

- name: add lines
  lineinfile: 
    dest: fruits.txt
    line: '{{ item }}'
  with_items:
    - 'Orange'
    - 'Apple'
    - 'Banana' 

For each item, if the item exists in fruits.txt no action is taken.

If the item does not exist it will be appended to the end of the file.

Easy-peasy.

How to make rpm auto install dependencies

The link @gertvdijk provided shows a quick way to achieve the desired results without configuring a local repository:

$ yum --nogpgcheck localinstall packagename.arch.rpm

Just change packagename.arch.rpm to the RPM filename you want to install.

Edit Just a clarification, this will automatically install all dependencies that are already available via system YUM repositories.

If you have dependencies satisfied by other RPMs that are not in the system's repositories, then this method will not work unless each RPM is also specified along with packagename.arch.rpm on the command line.

Padding is invalid and cannot be removed?

A serval times of fighting, I finally solved the problem.
(Note: I use standard AES as symmetric algorithm. This answer may not suitable for everyone.)

  1. Change the algorithm class. Replace the RijndaelManaged class to AESManaged one.
  2. Do not explicit set the KeySize of algorithm class, left them default.
    (This is the very important step. I think there is a bug in KeySize property.)

Here is a list you want to check which argument you might have missed:

  • Key
    (byte array, length must be exactly one of 16, 24, 32 byte for different key size.)
  • IV
    (byte array, 16 bytes)
  • CipherMode
    (One of CBC, CFB, CTS, ECB, OFB)
  • PaddingMode
    (One of ANSIX923, ISO10126, None, PKCS7, Zeros)

printf formatting (%d versus %u)

If I understand your question correctly, you need %p to show the address that a pointer is using, for example:

int main() {
    int a = 5;
    int *p = &a;
    printf("%d, %u, %p", p, p, p);

    return 0;
}

will output something like:

-1083791044, 3211176252, 0xbf66a93c

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Inserting code in this LaTeX document with indentation

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

Reading/Writing a MS Word file in PHP

I don't know about reading native Word documents in PHP, but if you want to write a Word document in PHP, WordprocessingML (aka WordML) might be a good solution. All you have to do is create an XML document in the correct format. I believe Word 2003 and 2007 both support WordML.

Deleting a file in VBA

The following can be used to test for the existence of a file, and then to delete it.

Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
     Kill aFile
End If 

Cannot use object of type stdClass as array?

When you try to access it as $result['context'], you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context

Getting the document object of an iframe

For even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

replace \n and \r\n with <br /> in java

For me, this worked:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");

Tip: use regex tester for quick testing without compiling in your environment

How do I set the focus to the first input element in an HTML form independent from the id?

Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute:

<form>
  <input type="text" name="username" autofocus>
  <input type="password" name="password">
  <input type="submit" value="Login">
</form>

Dive in to HTML5 has more information.

Toggle display:none style with JavaScript

you can do this easily by using jquery using .css property... try this one: http://api.jquery.com/css/

How do I iterate through each element in an n-dimensional matrix in MATLAB?

As pointed out in a few other answers, you can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop. There are also a couple of functions you can use: arrayfun and cellfun.

Let's first assume you have a function that you want to apply to each element of A (called my_func). You first create a function handle to this function:

fcn = @my_func;

If A is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun to apply my_func to each element:

outArgs = arrayfun(fcn, A);

If A is a cell array of arbitrary dimension, you can use cellfun to apply my_func to each cell:

outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.

One caveat on outputs... if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:

outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);

Add data to JSONObject

The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:

JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()

JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);

"Parse Error : There is a problem parsing the package" while installing Android application

I have had this problem Parse Error : There is a problem parsing the package. I was testing on Android-8. I have same apk with same signature .Everything was same without the version number and version name. App was installing when I install it manually but this error occurred when I was downloading and installing updates programmatically. Then I have found my cause of problem.

There was an option to check canRequestPackageInstalls () When this method returns true then app get installed successfully. It was returning false always in my case.

So first I check this and then let the user to download and install updates.

In onCreate()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!packageManager.canRequestPackageInstalls()) {
                    startActivityForResult(
                        Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(
                            Uri.parse(String.format("package:%s", packageName))
                        ), requestCodeqInstallPackage
                    )
                } else {
                    canInstallPackage = true
                }

        }

In onActivityResult()

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            if (requestCode == requestCodeqInstallPackage && resultCode == Activity.RESULT_OK) {
                if (packageManager.canRequestPackageInstalls()) {
                    canInstallPackage = true
                }
            } else {
                canInstallPackage = false
                Toast.makeText(mContext, "Auto update feature will not work", Toast.LENGTH_LONG)
                    .show()
            }
    }

Then when need to install update then-

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   if(canInstallPackage){
      doInstallAppProcess()
   }else{
        // generate error message
   }
}

Hope it will help someone.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

Simply add this

$id = ''; 
if( isset( $_GET['id'])) {
    $id = $_GET['id']; 
} 

How to convert JSON to CSV format and store in a variable

I wanted to riff off @Christian Landgren's answer above. I was confused why my CSV file only had 3 columns/headers. This was because the first element in my json only had 3 keys. So you need to be careful with the const header = Object.keys(json[0]) line. It's assuming that the first element in the array is representative. I had messy JSON that with some objects having more or less.

So I added an array.sort to this which will order the JSON by number of keys. So that way your CSV file will have the max number of columns.

This is also a function that you can use in your code. Just feed it JSON!

function convertJSONtocsv(json) {
    if (json.length === 0) {
        return;
    }

    json.sort(function(a,b){ 
       return Object.keys(b).length - Object.keys(a).length;
    });

    const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
    const header = Object.keys(json[0])
    let csv = json.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
    csv.unshift(header.join(','))
    csv = csv.join('\r\n')

    fs.writeFileSync('awesome.csv', csv)
}

JavaScript OR (||) variable assignment explanation

Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.

The following values are considered falsy in JavaScript.

  • false
  • null
  • "" (empty string)
  • 0
  • Nan
  • undefined

Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"

The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

1 && [] && {} && true && "World" && null && 2010 // null

The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

var a = false;
var b = a || "Hello";

You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);

Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

I know this post is a little dated but just wanted to share the commands that worked for me in Terminal when removing Node.js.

lsbom -f -l -s -pf /var/db/receipts/org.nodejs.pkg.bom | while read f; do  sudo rm /usr/local/${f}; done
 
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*

UPDATE: 23 SEP 2016


If you're afraid of running these commands...

Thanks to jguix for this quick tutorial.

First, create an intermediate file:

lsbom -f -l -s -pf /var/db/receipts/org.nodejs.node.pkg.bom >> ~/filelist.txt

Manually review your file (located in your Home folder)

 ~/filelist.txt

Then delete the files:

cat ~/filelist.txt | while read f; do sudo rm /usr/local/${f}; done

sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*

For 10.10.5 and above

Thanks Lenar Hoyt

Gist Comment Source: gistcomment-1572198

Original Gist: TonyMtz/d75101d9bdf764c890ef

lsbom -f -l -s -pf /var/db/receipts/org.nodejs.node.pkg.bom | while read f; do sudo rm /usr/local/${f}; done

sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

SQL Server 2017 does introduce a new aggregate function

STRING_AGG ( expression, separator).

Concatenates the values of string expressions and places separator values between them. The separator is not added at the end of string.

The concatenated elements can be ordered by appending WITHIN GROUP (ORDER BY some_expression)

For versions 2005-2016 I typically use the XML method in the accepted answer.

This can fail in some circumstances however. e.g. if the data to be concatenated contains CHAR(29) you see

FOR XML could not serialize the data ... because it contains a character (0x001D) which is not allowed in XML.

A more robust method that can deal with all characters would be to use a CLR aggregate. However applying an ordering to the concatenated elements is more difficult with this approach.

The method of assigning to a variable is not guaranteed and should be avoided in production code.

Split column at delimiter in data frame

strsplit(c('a|b','b|c'),'|',fixed=TRUE)

Set keyboard caret position in html textbox

I found an easy way to fix this issue, tested in IE and Chrome:

function setCaret(elemId, caret)
 {
   var elem = document.getElementById(elemId);
   elem.setSelectionRange(caret, caret);
 }

Pass text box id and caret position to this function.

Hashing a string with Sha256

public string EncryptPassword(string password, string saltorusername)
        {
            using (var sha256 = SHA256.Create())
            {
                var saltedPassword = string.Format("{0}{1}", salt, password);
                byte[] saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
                return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
            }
        }

Could not install packages due to an EnvironmentError: [Errno 13]

On Mac, there is no 3.7 directory or the directory 3.7 is owned by root. So, I removed that directory, create a new directory by current user, and move it there. Then installation finishes without error.

sudo rm -rf /Library/Python/3.7
mkdir 3.7
sudo mv 3.7 /Library/Python
ll /Library/Python/
pip3 install numpy

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

matplotlib savefig in jpeg format

Matplotlib can handle directly and transparently jpg if you have installed PIL. You don't need to call it, it will do it by itself. If Python cannot find PIL, it will raise an error.

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I'm developing an UWP application which connects to a MQTT broker in the LAN. I go a similar error.

MQTTnet.Exceptions.MqttCommunicationException: 'An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883'

ExtendedSocketException: An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883

Turned out that I forgot to give the app the correct capabilites ... enter image description here

How to Export Private / Secret ASC Key to Decrypt GPG Files

this ended up working for me:

   gpg -a --export-secret-keys > exportedKeyFilename.asc 

you can name keyfilename.asc by any name as long as you keep on the .asc extension.
this command copies all secret-keys on a user's computer to keyfilename.asc in the working directory of where the command was called.

To Export just 1 specific secret key instead of all of them:

   gpg -a --export-secret-keys keyIDNumber > exportedKeyFilename.asc

keyIDNumber is the number of the key id for the desired key you are trying to export.

Can I use VARCHAR as the PRIMARY KEY?

A blanket "no you shouldn't" is terrible advice. This is perfectly reasonable in many situations depending on your use case, workload, data entropy, hardware, etc.. What you shouldn't do is make assumptions.

It should be noted that you can specify a prefix which will limit MySQL's indexing, thereby giving you some help in narrowing down the results before scanning the rest. This may, however, become less useful over time as your prefix "fills up" and becomes less unique.

It's very simple to do, e.g.:

CREATE TABLE IF NOT EXISTS `foo` (
  `id` varchar(128),
  PRIMARY KEY (`id`(4))
)

Also note that the prefix (4) appears after the column quotes. Where the 4 means that it should use the first 4 characters of the 128 possible characters that can exist as the id.

Lastly, you should read how index prefixes work and their limitations before using them: https://dev.mysql.com/doc/refman/8.0/en/create-index.html

ImportError: No module named win32com.client

Try this command:

pip install pywin32

Note

If it gives the following error:

Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions:)
No matching distribution found for pywin32>=223 (from pypiwin32)

upgrade 'pip', using:

pip install --upgrade pip

How do I get out of 'screen' without typing 'exit'?

In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.

Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

For the upgrade scenario specifically an alternative approach might be to have a web service that delivers the current version number and check that instead of downloading the entire apk just to check its version. It would save some bandwidth, be a little more performant (much faster to download than an apk if the whole apk isn't needed most of the time) and much simpler to implement.

In the simplest form you could have a simple text file on your server... http://some-place.com/current-app-version.txt

Inside of that text file have something like

3.1.4

and then download that file and check against the currently installed version.

Building a more advanced solution to that would be to implement a proper web service and have an api call at launch which could return some json, i.e. http://api.some-place.com/versionCheck:

{
    "current_version": "3.1.4"
}

Python: convert string to byte array

encode function can help you here, encode returns an encoded version of the string

In [44]: str = "ABCD"

In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']

or you can use array module

In [49]: import array

In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])

How to get the parent dir location

You can apply dirname repeatedly to climb higher: dirname(dirname(file)). This can only go as far as the root package, however. If this is a problem, use os.path.abspath: dirname(dirname(abspath(file))).

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

Suppose we have a datetime object and date is represented as: "2017-05-04"

>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

How to add an image to the emulator gallery in android studio?

After trying to add an image via the Device Monitor or via drop, I could find it when exploring, but it was still not shown in the Gallery.

For me, it helped to eject the (virtual) sdcard from Settings > Storage & USB and reinserting it.

How do you unit test private methods?

Also note that the InternalsVisibleToAtrribute has a requirement that your assembly be strong named, which creates it's own set of problems if you're working in a solution that had not had that requirement before. I use the accessor to test private methods. See this question that for an example of this.

The view or its master was not found or no view engine supports the searched locations

This could be a permissions issue.

I had the same issue recently. As a test, I created a simple hello.html page. When I tried loading it, I got an error message regarding permissions. Once I fixed the permissions issue in the root web folder, both the html page and the MVC rendering issues were resolved.

What is Domain Driven Design?

You CAN ONLY understand Domain driven design by first comprehending what the following are:

What is a domain?

The field for which a system is built. Airport management, insurance sales, coffee shops, orbital flight, you name it.

It's not unusual for an application to span several different domains. For example, an online retail system might be working in the domains of shipping (picking appropriate ways to deliver, depending on items and destination), pricing (including promotions and user-specific pricing by, say, location), and recommendations (calculating related products by purchase history).

What is a model?

"A useful approximation to the problem at hand." -- Gerry Sussman

An Employee class is not a real employee. It models a real employee. We know that the model does not capture everything about real employees, and that's not the point of it. It's only meant to capture what we are interested in for the current context.

Different domains may be interested in different ways to model the same thing. For example, the salary department and the human resources department may model employees in different ways.

What is a domain model?

A model for a domain.

What is Domain-Driven Design (DDD)?

It is a development approach that deeply values the domain model and connects it to the implementation. DDD was coined and initially developed by Eric Evans.

Culled from here

How to align td elements in center

I personally didn't find any of these answers helpful. What worked in my case was giving the element float:none and position:relative. After that the element centered itself in the <td>.

How should I log while using multiprocessing in Python?

Here's my simple hack/workaround... not the most comprehensive, but easily modifiable and simpler to read and understand I think than any other answers I found before writing this:

import logging
import multiprocessing

class FakeLogger(object):
    def __init__(self, q):
        self.q = q
    def info(self, item):
        self.q.put('INFO - {}'.format(item))
    def debug(self, item):
        self.q.put('DEBUG - {}'.format(item))
    def critical(self, item):
        self.q.put('CRITICAL - {}'.format(item))
    def warning(self, item):
        self.q.put('WARNING - {}'.format(item))

def some_other_func_that_gets_logger_and_logs(num):
    # notice the name get's discarded
    # of course you can easily add this to your FakeLogger class
    local_logger = logging.getLogger('local')
    local_logger.info('Hey I am logging this: {} and working on it to make this {}!'.format(num, num*2))
    local_logger.debug('hmm, something may need debugging here')
    return num*2

def func_to_parallelize(data_chunk):
    # unpack our args
    the_num, logger_q = data_chunk
    # since we're now in a new process, let's monkeypatch the logging module
    logging.getLogger = lambda name=None: FakeLogger(logger_q)
    # now do the actual work that happens to log stuff too
    new_num = some_other_func_that_gets_logger_and_logs(the_num)
    return (the_num, new_num)

if __name__ == '__main__':
    multiprocessing.freeze_support()
    m = multiprocessing.Manager()
    logger_q = m.Queue()
    # we have to pass our data to be parallel-processed
    # we also need to pass the Queue object so we can retrieve the logs
    parallelable_data = [(1, logger_q), (2, logger_q)]
    # set up a pool of processes so we can take advantage of multiple CPU cores
    pool_size = multiprocessing.cpu_count() * 2
    pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=4)
    worker_output = pool.map(func_to_parallelize, parallelable_data)
    pool.close() # no more tasks
    pool.join()  # wrap up current tasks
    # get the contents of our FakeLogger object
    while not logger_q.empty():
        print logger_q.get()
    print 'worker output contained: {}'.format(worker_output)

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How to browse localhost on Android device?

For the mac user:

I have worked on this problem for one afternoon until I realized the Xampp I used was not the real "Xampp" It was Xampp VM which runs itself based on a Linux virtual machine. That made it not running on localhost, instead, another IP. I installed the real Xampp and run my local server on localhost and then just access it with the IP of my mac.

Hope this will help someone.

Mixing a PHP variable with a string literal

$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";

print $bucket;

yields:

$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']

Get IPv4 addresses from Dns.GetHostEntry()

To find all valid address list this is the code I have used

public static IEnumerable<string> GetAddresses()
{
      var host = Dns.GetHostEntry(Dns.GetHostName());
      return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}

How do I read configuration settings from Symfony2 config.yml?

Like it was saying previously - you can access any parameters by using injection container and use its parameter property.

"Symfony - Working with Container Service Definitions" is a good article about it.

Limiting the number of characters in a string, and chopping off the rest

If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.

int maxLength = 5;
StringUtils.left(string, maxLength);

Output:

      null -> null
        "" -> ""
       "a" -> "a"
"abcd1234" -> "abcd1"

Left Documentation

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

Angular - Use pipes in services and components

You can use formatDate() to format the date in services or component ts. syntax:-

    formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string

import the formatDate() from common module like this,

    import { formatDate } from '@angular/common';

and just use it in the class like this ,

    formatDate(new Date(), 'MMMM dd yyyy', 'en');

You can also use the predefined format options provided by angular like this ,

    formatDate(new Date(), 'shortDate', 'en');

You can see all other predefined format options here ,

https://angular.io/api/common/DatePipe

How to trim a list in Python

l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]

How do you query for "is not null" in Mongo?

db.collection_name.find({"filed_name":{$exists:true}});

fetch documents that contain this filed_name even it is null.

Warning

db.collection_name.find({"filed_name":{$ne:null}});

fetch documents that its field_name has a value $ne to null but this value could be an empty string also.

My proposition:

db.collection_name.find({ "field_name":{$ne:null},$where:"this.field_name.length >0"})

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

jQuery if statement to check visibility

 $('#column-left form').hide();
 $('.show-search').click(function() {
    $('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
    $('#column-left form').hide(); 
    if(!($('#column-left form').is(":visible"))) {
        $("#offers").show();
    } else {
        $('#offers').hide();
    }
  });

Read/Write String from/to a File in Android

For those looking for a general strategy for reading and writing a string to file:

First, get a file object

You'll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

Or with Google Guava

String contents = Files.toString(file, StandardCharsets.UTF_8);

Read the file to a string

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

Or if you are using Google Guava

String contents = Files.toString(file,"UTF-8");

For completeness I'll mention

String contents = new Scanner(file).useDelimiter("\\A").next();

which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).

Notes

For each of these strategies, you'll be asked to catch an IOException.

The default character encoding on Android is UTF-8.

If you are using external storage, you'll need to add to your manifest either:

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

or

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

Write permission implies read permission, so you don't need both.

What's the difference between text/xml vs application/xml for webservice response

From the RFC (3023), under section 3, XML Media Types:

If an XML document -- that is, the unprocessed, source XML document -- is readable by casual users, text/xml is preferable to application/xml. MIME user agents (and web user agents) that do not have explicit support for text/xml will treat it as text/plain, for example, by displaying the XML MIME entity as plain text. Application/xml is preferable when the XML MIME entity is unreadable by casual users.

(emphasis mine)

Use URI builder in Android or create URL with variables

here is a good way to explain it:

there are two forms of the URI

1 - Builder(ready to be modified, not ready to be used)

2 - Built(not ready to be modified, ready to be used )

You can create a builder by

Uri.Builder builder = new Uri.Builder();

this gonna return a Builder ready to be modified like this:-

builder.scheme("https");
builder.authority("api.github.com");
builder.appendPath("search");
builder.appendPath("repositories");
builder.appendQueryParameter(PARAMETER_QUERY,parameterValue);

but to use it you have to build it first

retrun builder.build();

or however you gonna use it. and then you have built that is already built for you, ready to use but cannot be modified.

Uri built = Uri.parse("your URI goes here");

this is ready to use but if you want to modify it you need to buildUpon()

Uri built = Uri.parse("Your URI goes here")
           .buildUpon(); //now it's ready to be modified
           .buildUpon()
           .appendQueryParameter(QUERY_PARAMATER, parameterValue) 
           //any modification you want to make goes here
           .build(); // you have to build it back cause you are storing it 
                     // as Uri not Uri.builder

now every time you want to modify it you need to buildUpon() and in the end build().

so Uri.Builder is a Builder type that store a Builder in it. Uri is a Built type that store an already built URI in it.

new Uri.Builder(); rerurns a Builder. Uri.parse("your URI goes here") returns a Built.

and with build() you can change it from Builder to Built. buildUpon() you can change it from Built to Builder. Here is what you can do

Uri.Builder builder = Uri.parse("URL").buildUpon();
// here you created a builder, made an already built URI with Uri.parse
// and then change it to builder with buildUpon();
Uri built = builder.build();
//when you want to change your URI, change Builder 
//when you want to use your URI, use Built

and also the opposite:-

Uri built = new Uri.Builder().build();
// here you created a reference to a built URI
// made a builder with new Uri.Builder() and then change it to a built with 
// built();
Uri.Builder builder = built.buildUpon();

hope my answer helped :) <3

C - gettimeofday for computing time?

Your curtime variable holds the number of seconds since the epoch. If you get one before and one after, the later one minus the earlier one is the elapsed time in seconds. You can subtract time_t values just fine.

How to get client IP address using jQuery

A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.

$.getJSON('getip.php', function(data){
  alert('Your ip is: ' +  data.ip);
});

Then in php you might do:

<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));

Count words in a string method?

create variable count, state. initialize variables
if space is present keep count as it is else increase count. for eg:

if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;

"psql: could not connect to server: Connection refused" Error when connecting to remote database

I think you are using the machine-name instead of the ip of the host.

I got the same error when i tried with machine's name. Because, It is allowed only when both the client and host are under same network and they have the same Operating system installed.

Counting the number of elements with the values of x in a vector

The most direct way is sum(numbers == x).

numbers == x creates a logical vector which is TRUE at every location that x occurs, and when suming, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.

However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6).

How can I find the dimensions of a matrix in Python?

The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

I got a shortcut for Idle (Python GUI).

  • Click on Window icon at the bottom left or use Window Key (only Python 2), you will see Idle (Python GUI) icon
  • Right click on the icon then more
  • Open File Location
  • A new window will appears, and you will see the shortcut of Idle (Python GUI)
  • Right click, hold down and pull out to desktop to create a shortcut of Python GUI on desktop.

typescript - cloning object

Came across this problem myself and in the end wrote a small library cloneable-ts that provides an abstract class, which adds a clone method to any class extending it. The abstract class borrows the Deep Copy Function described in the accepted answer by Fenton only replacing copy = {}; with copy = Object.create(originalObj) to preserve the class of the original object. Here is an example of using the class.

import {Cloneable, CloneableArgs} from 'cloneable-ts';

// Interface that will be used as named arguments to initialize and clone an object
interface PersonArgs {
    readonly name: string;
    readonly age: number;
}

// Cloneable abstract class initializes the object with super method and adds the clone method
// CloneableArgs interface ensures that all properties defined in the argument interface are defined in class
class Person extends Cloneable<TestArgs>  implements CloneableArgs<PersonArgs> {
    readonly name: string;
    readonly age: number;

    constructor(args: TestArgs) {
        super(args);
    }
}

const a = new Person({name: 'Alice', age: 28});
const b = a.clone({name: 'Bob'})
a.name // Alice
b.name // Bob
b.age // 28

Or you could just use the Cloneable.clone helper method:

import {Cloneable} from 'cloneable-ts';

interface Person {
    readonly name: string;
    readonly age: number;
}

const a: Person = {name: 'Alice', age: 28};
const b = Cloneable.clone(a, {name: 'Bob'})
a.name // Alice
b.name // Bob
b.age // 28    

What is a Windows Handle?

Think of the window in Windows as being a struct that describes it. This struct is an internal part of Windows and you don't need to know the details of it. Instead, Windows provides a typedef for pointer to struct for that struct. That's the "handle" by which you can get hold on the window.,

How do I create a Java string from the contents of a file?

If you need a string processing (parallel processing) Java 8 has the great Stream API.

String result = Files.lines(Paths.get("file.txt"))
                    .parallel() // for parallel processing 
                    .map(String::trim) // to change line   
                    .filter(line -> line.length() > 2) // to filter some lines by a predicate                        
                    .collect(Collectors.joining()); // to join lines

More examples are available in JDK samples sample/lambda/BulkDataOperations that can be downloaded from Oracle Java SE 8 download page

Another one liner example

String out = String.join("\n", Files.readAllLines(Paths.get("file.txt")));

Adding a custom header to HTTP request using angular.js

What you see for OPTIONS request is fine. Authorisation headers are not exposed in it.

But in order for basic auth to work you need to add: withCredentials = true; to your var config.

From the AngularJS $http documentation:

withCredentials - {boolean} - whether to to set the withCredentials flag on the XHR object. See requests with credentials for more information.

Array.size() vs Array.length

Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.

The size accessor property returns the number of (unique) elements in a Set object.

const set1 = new Set();
const object1 = new Object();

set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);

console.log(set1.size);
// expected output: 3

And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];

console.log(clothing.length);
// expected output: 4

Java String.split() Regex

str.split (" ") 
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)

Convert Java object to XML string

Using ByteArrayOutputStream

public static String printObjectToXML(final Object object) throws TransformerFactoryConfigurationError,
        TransformerConfigurationException, SOAPException, TransformerException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder xmlEncoder = new XMLEncoder(baos);
    xmlEncoder.writeObject(object);
    xmlEncoder.close();

    String xml = baos.toString();
    System.out.println(xml);

    return xml.toString();
}

Undefined reference to main - collect2: ld returned 1 exit status

It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

To compile only to an object file, use the -c option:

gcc es3.c -c
gcc es3.o main.c -o es3

The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.

Python: OSError: [Errno 2] No such file or directory: ''

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Add the line below in application.properties file under resource folder and restart your application.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

How to change DatePicker dialog color for Android 5.0

<style name="AppThemeDatePicker" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/select2</item>
    <item name="android:colorAccent">@color/select2</item>
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>


<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/select2</item>
</style>

How to concatenate multiple lines of output to one line?

Here is the method using ex editor (part of Vim):

  • Join all lines and print to the standard output:

    $ ex +%j +%p -scq! file
    
  • Join all lines in-place (in the file):

    $ ex +%j -scwq file
    

    Note: This will concatenate all lines inside the file it-self!

Datatables warning(table id = 'example'): cannot reinitialise data table

You have to destroy the datatable and empty the table body before binding DataTable by doing this below,

function Create() {
if ($.fn.DataTable.isDataTable('#dataTable')) {
    $('#dataTable').DataTable().destroy();
}
$('#dataTable tbody').empty();
//Here call the Datatable Bind function;} 

Android Debug Bridge (adb) device - no permissions

...the OP’s own answer is wrong in so far, that there are no “special system permissions”. – The “no permission” problem boils down to ... no permissions.

Unfortunately it is not easy to debug, because adb makes it a secret which device it tries to access! On Linux, it tries to open the “USB serial converter” device of the phone, which is e.g. /dev/bus/usb/001/115 (your bus number and device address will vary). This is sometimes linked and used from /dev/android_adb.

lsusb will help to find bus number and device address. Beware that the device address will change for sure if you re-plug, as might the bus number if the port gets confused about which speed to use (e.g. one physical port ends up on one logical bus or another).

An lsusb-line looks similar to this: Bus 001 Device 115: ID 4321:fedc bla bla bla

lsusb -v might help you to find the device if the “bla bla bla” is not hint enough (sometimes it does neither contain the manufacturer, nor the model of the phone).

Once you know the device, check with your own eyes that ls -a /dev/bus/usb/001/115 is really accessible for the user in question! Then check that it works with chmod and fix your udev setup.

PS1: /dev/android_adb can only point to one device, so make sure it does what you want.

PS2: Unrelated to this question, but less well known: adb has a fixed list of vendor ids it goes through. This list can be extended from ~/.android/adb_usb.ini, which should contain 0x4321 (if we follow my example lsusb line from above). – Not needed here, as you don’t even get a “no permissions” if the vendor id is not known.

How to get status code from webclient?

Erik's answer doesn't work on Windows Phone as is. The following does:

class WebClientEx : WebClient
{
    private WebResponse m_Resp = null;

    protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
    {
        try
        {
            this.m_Resp = base.GetWebResponse(request);
        }
        catch (WebException ex)
        {
            if (this.m_Resp == null)
                this.m_Resp = ex.Response;
        }
        return this.m_Resp;
    }

    public HttpStatusCode StatusCode
    {
        get
        {
            if (m_Resp != null && m_Resp is HttpWebResponse)
                return (m_Resp as HttpWebResponse).StatusCode;
            else
                return HttpStatusCode.OK;
        }
    }
}

At least it does when using OpenReadAsync; for other xxxAsync methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.

The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

Calculate correlation with cor(), only for numerical columns

Another option would be to just use the excellent corrr package https://github.com/drsimonj/corrr and do

require(corrr)
require(dplyr)

myData %>% 
   select(x,y,z) %>%  # or do negative or range selections here
   correlate() %>%
   rearrange() %>%  # rearrange by correlations
   shave() # Shave off the upper triangle for a cleaner result

Steps 3 and 4 are entirely optional and are just included to demonstrate the usefulness of the package.

Radio buttons not checked in jQuery

(!$('#radio').is(':checked'))

This worked for me

Toggle show/hide on click with jQuery

You can use .toggle() function instead of .click()....

Check if passed argument is file or directory in Bash

function check_file_path(){
    [ -f "$1" ] && return
    [ -d "$1" ] && return
    return 1
}
check_file_path $path_or_file

Get table names using SELECT statement in MySQL

Besides using the INFORMATION_SCHEMA table, to use SHOW TABLES to insert into a table you would use the following

<?php
 $sql = "SHOW TABLES FROM $dbname";
 $result = mysql_query($sql);
 $arrayCount = 0
 while ($row = mysql_fetch_row($result)) {
  $tableNames[$arrayCount] = $row[0];
  $arrayCount++; //only do this to make sure it starts at index 0
 }
 foreach ($tableNames as &$name {
  $query = "INSERT INTO metadata (table_name) VALUES ('".$name."')";
  mysql_query($query);
 }
?>

Skip first couple of lines while reading lines in Python file

Use itertools.islice, starting at index 17. It will automatically skip the 17 first lines.

import itertools
with open('file.txt') as f:
    for line in itertools.islice(f, 17, None):  # start=17, stop=None
        # process lines

Android: how to handle button click

Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.

Regex Named Groups in Java

For people coming to this late: Java 7 adds named groups. Matcher.group(String groupName) documentation.

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

ExpressJS - throw er Unhandled error event

In-order to fix this, terminate or close the server you are running. If you are using Eclipse IDE, then follow this,

Run > Debug

enter image description here

Right-click the running process and click on Terminate.

Split string in C every white space

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.

From the website:

char * strtok ( char * str, const char * delimiters );

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.

Parameters

  • str
    • C string to truncate.
    • Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
  • delimiters
    • C string containing the delimiter characters.
    • These may vary from one call to another.

Return Value

A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.

Example

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

anaconda - graphviz - can't import after installation

I have followed the following steps and it worked fine for me.

1 . Download and install graphviz-2.38.msi from https://graphviz.gitlab.io/_pages/Download/Download_windows.html

2 . Set the path variable

(a) Control Panel > System and Security > System > Advanced System Settings >  Environment Variables > Path > Edit

(b) add 'C:\Program Files (x86)\Graphviz2.38\bin'

Youtube - downloading a playlist - youtube-dl

Your link is not a playlist.

A proper playlist URL looks like this:

https://www.youtube.com/playlist?list=PLHSdFJ8BDqEyvUUzm6R0HxawSWniP2c9K

Your URL is just the first video OF a certain playlist. It contains https://www.youtube.com/watch? instead of https://www.youtube.com/playlist?.

Pick the playlist by clicking on the title of the playlist on the right side in the list of videos and use this URL.

How do I create a simple Qt console application in C++?

I managed to create a simple console "hello world" with QT Creator

used creator 2.4.1 and QT 4.8.0 on windows 7

two ways to do this

Plain C++

do the following

  1. File- new file project
  2. under projects select : other Project
  3. select "Plain C++ Project"
  4. enter project name 5.Targets select Desktop 'tick it'
  5. project managment just click next
  6. you can use c++ commands as normal c++

or

QT Console

  1. File- new file project
  2. under projects select : other Project
  3. select QT Console Application
  4. Targets select Desktop 'tick it'
  5. project managment just click next
  6. add the following lines (all the C++ includes you need)
  7. add "#include 'iostream' "
  8. add "using namespace std; "
  9. after QCoreApplication a(int argc, cghar *argv[]) 10 add variables, and your program code..

example: for QT console "hello world"

file - new file project 'project name '

other projects - QT Console Application

Targets select 'Desktop'

project management - next

code:

    #include <QtCore/QCoreApplication>
    #include <iostream>
    using namespace std;
    int main(int argc, char *argv[])
    {
     QCoreApplication a(argc, argv);
     cout<<" hello world";
     return a.exec();
     }

ctrl -R to run

compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)

hope this helps someone

As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...

Wait till a Function with animations is finished until running another Function

You can use jQuery's $.Deferred

var FunctionOne = function () {
  // create a deferred object
  var r = $.Deferred();

  // do whatever you want (e.g. ajax/animations other asyc tasks)

  setTimeout(function () {
    // and call `resolve` on the deferred object, once you're done
    r.resolve();
  }, 2500);

  // return the deferred object
  return r;
};

// define FunctionTwo as needed
var FunctionTwo = function () {
  console.log('FunctionTwo');
};

// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);

you could also pack multiple deferreds together:

var FunctionOne = function () {
  var
    a = $.Deferred(),
    b = $.Deferred();

  // some fake asyc task
  setTimeout(function () {
    console.log('a done');
    a.resolve();
  }, Math.random() * 4000);

  // some other fake asyc task
  setTimeout(function () {
    console.log('b done');
    b.resolve();
  }, Math.random() * 4000);

  return $.Deferred(function (def) {
    $.when(a, b).done(function () {
      def.resolve();
    });
  });
};

http://jsfiddle.net/p22dK/

How to revert to origin's master branch's version of file

If you didn't commit it to the master branch yet, its easy:

  • get off the master branch (like git checkout -b oops/fluke/dang)
  • commit your changes there (like git add -u; git commit;)
  • go back the master branch (like git checkout master)

Your changes will be saved in branch oops/fluke/dang; master will be as it was.

Simple JavaScript login form validation

Add a property to the form method="post".

Like this:

<form name="loginform" method="post">

Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

How do I run Java .class files?

This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

How to fix error with xml2-config not found when installing PHP from sources?

OpenSuse

"sudo zypper install libxml2-devel"

It will install any other dependencies or required packages/libraries

How to access Anaconda command prompt in Windows 10 (64-bit)

After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.

The link I provided below go through the three major issues with not recognized error. Which are:

  1. Environment PATH for Conda is not set
  2. Environment PATH is incorrectly added
  3. Anaconda version is older than the version of the Anaconda Navigator

LINK: https://appuals.com/fix-conda-is-not-recognized-as-an-internal-or-external-command-operable-program-or-batch-file/

My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.

Sending HTML Code Through JSON

You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.

C# Copy a file to another location with a different name

You can use the Copy method in the System.IO.File class.

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

Get program path in VB.NET?

For that you can use the Application object.

Startup path, just the folder, use Application.StartupPath()

Dim appPath As String = Application.StartupPath()

Full .exe path, including the program.exe name on the end:, use Application.ExecutablePath()

Dim exePath As String = Application.ExecutablePath()

HTML5 live streaming

You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:

<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video 
id="Video" 
class="video-js vjs-default-skin vjs-big-play-centered" 
controls 
preload="none" 
width="auto" 
height="auto" 
poster="poster.jpg" 
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The docs are pretty clear on this: HashSet.add doesn't replace:

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

But HashMap.put will replace:

If the map previously contained a mapping for the key, the old value is replaced.

How do I get the Date & Time (VBS)

There are also separate Time() and Date() functions.

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

How can I generate an ObjectId with mongoose?

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.

You can read more about the Types object at Mongoose#Types documentation.

How do I make a Git commit in the past?

In my case over time I had saved a bunch of versions of myfile as myfile_bak, myfile_old, myfile_2010, backups/myfile etc. I wanted to put myfile's history in git using their modification dates. So rename the oldest to myfile, git add myfile, then git commit --date=(modification date from ls -l) myfile, rename next oldest to myfile, another git commit with --date, repeat...

To automate this somewhat, you can use shell-foo to get the modification time of the file. I started with ls -l and cut, but stat(1) is more direct

git commit --date="`stat -c %y myfile`" myfile

Neither BindingResult nor plain target object for bean name available as request attribute

If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.

How to deal with the URISyntaxException

You need to encode the URI to replace illegal characters with legal encoded characters. If you first make a URL (so you don't have to do the parsing yourself) and then make a URI using the five-argument constructor, then the constructor will do the encoding for you.

import java.net.*;

public class Test {
  public static void main(String[] args) {
    String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
    try {
      URL url = new URL(myURL);
      String nullFragment = null;
      URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
      System.out.println("URI " + uri.toString() + " is OK");
    } catch (MalformedURLException e) {
      System.out.println("URL " + myURL + " is a malformed URL");
    } catch (URISyntaxException e) {
      System.out.println("URI " + myURL + " is a malformed URL");
    }
  }
}

How to delete a selected DataGridViewRow and update a connected database table?

private void btnDelete_Click(object sender, EventArgs e)
{
    if (e.ColumIndex == 10)// 10th column the button
    {
        dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
    }                
}

This solution can be delete a row (not selected, clicked row!) via "e" param.

What is causing this error - "Fatal error: Unable to find local grunt"

I made the mistake to install some packages using sudo and other without privileges , this fixed my problem.

sudo chown -R $(whoami) $HOME/.npm

hope it helps someone.

How do I draw a circle in iOS Swift?

I find Core Graphics to be pretty simple for Swift 3:

if let cgcontext = UIGraphicsGetCurrentContext() {
    cgcontext.strokeEllipse(in: CGRect(x: center.x-diameter/2, y: center.y-diameter/2, width: diameter, height: diameter))
}