Programs & Examples On #Cgpoint

CGPoint is a structure from Apple's Core Graphics framework. It is used to represent a point in two dimensions.

IOS: verify if a point is inside a rect

It is so simple,you can use following method to do this kind of work:-

-(BOOL)isPoint:(CGPoint)point insideOfRect:(CGRect)rect
{
    if ( CGRectContainsPoint(rect,point))
        return  YES;// inside
    else
        return  NO;// outside
}

In your case,you can pass imagView.center as point and another imagView.frame as rect in about method.

You can also use this method in bellow UITouch Method :

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}

Django: TemplateSyntaxError: Could not parse the remainder

There should not be a space after name.

Incorrect:

{% url 'author' name = p.article_author.name.username %}

Correct:

{% url 'author' name=p.article_author.name.username %}

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

Javascript: How to check if a string is empty?

If you want to know if it's an empty string use === instead of ==.

if(variable === "") {
}

This is because === will only return true if the values on both sides are of the same type, in this case a string.

for example: (false == "") will return true, and (false === "") will return false.

How do I align spans or divs horizontally?

Look at the css Float property. http://w3schools.com/css/pr_class_float.asp

It works with block elements like div. Alternatively, what are you trying to display, tables aren't evil if you're really trying to show a table of some information.

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I faced this problem in a Framework7 & Cordova project. I tried all the solutions above. They did not solve my problem.

In my case, I was using 10+ css animations on the same page with infinite rotation (transform). I had to remove the animations. It is ok now with the lack of some visual features.

If the solutions above do not help you, you may start eliminating some animations.

Can MySQL convert a stored UTC time to local timezone?

I propose to use

SET time_zone = 'proper timezone';

being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.

How to fully clean bin and obj folders within Visual Studio?

I store my finished VS projects by saving only source code.

I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

This reduces the size of the project considerably. The project

must be rebuilt when pulled out of storage.

Android emulator-5554 offline

In my case, the emulator was working with Oreo and lower, but not with Pie, and everything I tried seemed to have no effect. What finally worked was updating the emulator to latest (version 28).

how to add new <li> to <ul> onclick with javascript

You have not appended your li as a child to your ul element

Try this

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  ul.appendChild(li);
}

If you need to set the id , you can do so by

li.setAttribute("id", "element4");

Which turns the function into

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  li.setAttribute("id", "element4"); // added line
  ul.appendChild(li);
  alert(li.id);
}

How do I overload the square-bracket operator in C#?

If you mean the array indexer,, You overload that just by writing an indexer property.. And you can overload, (write as many as you want) indexer properties as long as each one has a different parameter signature

public class EmployeeCollection: List<Employee>
{
    public Employee this[int employeeId]
    {   
        get 
        { 
            foreach(var emp in this)
            {
                if (emp.EmployeeId == employeeId)
                    return emp;
            }

            return null;
        }
    }

    public Employee this[string employeeName]
    {   
        get 
        { 
            foreach(var emp in this)
            {
                if (emp.Name == employeeName)
                    return emp;
            }

            return null;
        }
    }
}

Step-by-step debugging with IPython

What about ipdb.set_trace() ? In your code :

import ipdb; ipdb.set_trace()

update: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.

This allows for full inspection of your code, and you have access to commands such as c (continue), n (execute next line), s (step into the method at point) and so on.

See the ipdb repo and a list of commands. IPython is now called (edit: part of) Jupyter.


ps: note that an ipdb command takes precedence over python code. So in order to write list(foo) you'd need print(list(foo)), or !list(foo) .

Also, if you like the ipython prompt (its emacs and vim modes, history, completions,…) it's easy to get the same for your project since it's based on the python prompt toolkit.

git push rejected: error: failed to push some refs

What I did to solve the problem was:

git pull origin [branch]
git push origin [branch]

Also make sure that you are pointing to the right branch by running:

git remote set-url origin [url]

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.

It does however need a simple modification to work from within a batch file:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e

if else statement in AngularJS templates

You could use your video.yt$aspectRatio property directly by passing it through a filter, and binding the result to the height attribute in your template.

Your filter would look something like:

app.filter('videoHeight', function () {
  return function (input) {
    if (input === 'widescreen') {
      return '270px';
    } else {
      return '360px';
    }
  };
});

And the template would be:

<video height={{video.yt$aspectRatio | videoHeight}}></video>

Filter Pyspark dataframe column with None value

If you want to filter out records having None value in column then see below example:

df=spark.createDataFrame([[123,"abc"],[234,"fre"],[345,None]],["a","b"])

Now filter out null value records:

df=df.filter(df.b.isNotNull())

df.show()

If you want to remove those records from DF then see below:

df1=df.na.drop(subset=['b'])

df1.show()

Postgres user does not exist?

the discussion and answer here was massively helpful to me:

psql: FATAL: database "<user>" does not exist

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.

Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.

def convert(o):
    if isinstance(o, np.generic): return o.item()  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

How to get year/month/day from a date object?

EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.

function getFormattedDate(today) 
{
    var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    var day  = week[today.getDay()];
    var dd   = today.getDate();
    var mm   = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    var hour = today.getHours();
    var minu = today.getMinutes();

    if(dd<10)  { dd='0'+dd } 
    if(mm<10)  { mm='0'+mm } 
    if(minu<10){ minu='0'+minu } 

    return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}

var date = new Date();
var text = getFormattedDate(date);


*For Spanish format, just translate the WEEK variable.

var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');


Output: Monday - 16/11/2015 14:24

Download File Using Javascript/jQuery

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

_x000D_
_x000D_
fetch('https://jsonplaceholder.typicode.com/todos/1')_x000D_
  .then(resp => resp.blob())_x000D_
  .then(blob => {_x000D_
    const url = window.URL.createObjectURL(blob);_x000D_
    const a = document.createElement('a');_x000D_
    a.style.display = 'none';_x000D_
    a.href = url;_x000D_
    // the filename you want_x000D_
    a.download = 'todo-1.json';_x000D_
    document.body.appendChild(a);_x000D_
    a.click();_x000D_
    window.URL.revokeObjectURL(url);_x000D_
    alert('your file has downloaded!'); // or you know, something with better UX..._x000D_
  })_x000D_
  .catch(() => alert('oh no!'));
_x000D_
_x000D_
_x000D_

2012 original jQuery/iframe/cookie based approach

I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

  • Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too

  • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications

  • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation

  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this. Hope this helps someone!

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Asp.net 4.0 has not been registered

I had the same issue but solved it...... Microsoft has a fix for something close to this that actually worked to solve this issue. you can visit this page http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6.aspx

The issue occurs after you installed framework 4.5 and/or framework 4.6. The Visual Studio 2012 Update 5 doesn't fix the issue, I tried that first.

The msdn blog has this to say: "After the installation of the Microsoft .NET Framework 4.6, users may experience the following dialog box displayed in Microsoft Visual Studio when either creating new Web Site or Windows Azure project or when opening existing projects....."

According to the Blog the dialog is benign. just click OK, nothing is effected by the dialog... The comments in the blog suggests that VS 2015 has the same problem, maybe even worse.

How to make a button redirect to another page using jQuery or just Javascript

Without script:

<form action="where-you-want-to-go"><input type="submit"></form>

Better yet, since you are just going somewhere, present the user with the standard interface for "just going somewhere":

<a href="where-you-want-to-go">ta da</a>

Although, the context sounds like "Simulate a normal search where the user submits a form", in which case the first option is the way to go.

How to tell PowerShell to wait for each command to end before starting the next?

Taking it further you could even parse on the fly

e.g.

& "my.exe" | %{
    if ($_ -match 'OK')
    { Write-Host $_ -f Green }
    else if ($_ -match 'FAIL|ERROR')
    { Write-Host $_ -f Red }
    else 
    { Write-Host $_ }
}

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

Recursive search and replace in text files on Mac and Linux

If you are using a zsh terminal you're able to use wildcard magic:

sed -i "" "s/search/high-replace/g" *.txt

jquery input select all on focus

<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>

Displaying unicode symbols in HTML

I think this is a file problem, you simple saved your file in 1-byte encoding like latin-1. Google up your editor and how to set files to utf-8.

I wonder why there are editors that don't default to utf-8.

How to automatically select all text on focus in WPF TextBox?

After googling and testing, I've found a simple solution that worked for me.

You need to add an event handler to the Loaded event of your container window:

private void yourwindow_Loaded(object sender, RoutedEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox),
        TextBox.PreviewMouseLeftButtonDownEvent,
        new RoutedEventHandler(SelectivelyIgnoreMouseButton));
}

Next, you have to create the handler to the referenced RoutedEventHandler in previous code:

private void SelectivelyIgnoreMouseButton(object sender, RoutedEventArgs e)
{
    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
        if (!tb.IsKeyboardFocusWithin)
        {
            e.Handled = true;
            tb.Focus();
        }
    }
}

Now, you can add the SelectAll() command on GotFocus event handlers to any TextBox controls separately:

private void myTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).SelectAll();
}

Your text now is selected on focus!

Adapted from Dr. WPF solution, MSDN Forums

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe

Code:

df_data=pd.read_csv('../input/data.csv')
print(df_data.columns.values)

Output:

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

Manually install Gradle and use it in Android Studio

If you are on LINUX follow the steps below:

  • Go to the download https://gradle.org/ and download the latest zip file (currently 3.1 is the latest version)

  • Extract the downloaded zip file into /opt/android-studio/gradle/.

  • Open your project in Android Studio and hit Ctrl + Alt + S

  • Search for Gradle in the Search bar of the setting window

  • Select: (X) Use local gradle distribution and set Gradle home to /opt/andriod-studio/gradle/gradle.x.x (where x.x is the vesrion of the gradle zip file you just downloaded.). Then click on apply.

  • Try to sync Gradle again if the sync has already failed.If not close your project and reopen your project.

    Hope this solves your problem.

How to delete last item in list?

If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:

interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim

What is the difference between atomic / volatile / synchronized?

Declaring a variable as volatile means that modifying its value immediately affects the actual memory storage for the variable. The compiler cannot optimize away any references made to the variable. This guarantees that when one thread modifies the variable, all other threads see the new value immediately. (This is not guaranteed for non-volatile variables.)

Declaring an atomic variable guarantees that operations made on the variable occur in an atomic fashion, i.e., that all of the substeps of the operation are completed within the thread they are executed and are not interrupted by other threads. For example, an increment-and-test operation requires the variable to be incremented and then compared to another value; an atomic operation guarantees that both of these steps will be completed as if they were a single indivisible/uninterruptible operation.

Synchronizing all accesses to a variable allows only a single thread at a time to access the variable, and forces all other threads to wait for that accessing thread to release its access to the variable.

Synchronized access is similar to atomic access, but the atomic operations are generally implemented at a lower level of programming. Also, it is entirely possible to synchronize only some accesses to a variable and allow other accesses to be unsynchronized (e.g., synchronize all writes to a variable but none of the reads from it).

Atomicity, synchronization, and volatility are independent attributes, but are typically used in combination to enforce proper thread cooperation for accessing variables.

Addendum (April 2016)

Synchronized access to a variable is usually implemented using a monitor or semaphore. These are low-level mutex (mutual exclusion) mechanisms that allow a thread to acquire control of a variable or block of code exclusively, forcing all other threads to wait if they also attempt to acquire the same mutex. Once the owning thread releases the mutex, another thread can acquire the mutex in turn.

Addendum (July 2016)

Synchronization occurs on an object. This means that calling a synchronized method of a class will lock the this object of the call. Static synchronized methods will lock the Class object itself.

Likewise, entering a synchronized block requires locking the this object of the method.

This means that a synchronized method (or block) can be executing in multiple threads at the same time if they are locking on different objects, but only one thread can execute a synchronized method (or block) at a time for any given single object.

How many files can I put in a directory?

What most of the answers above fail to show is that there is no "One Size Fits All" answer to the original question.

In today's environment we have a large conglomerate of different hardware and software -- some is 32 bit, some is 64 bit, some is cutting edge and some is tried and true - reliable and never changing. Added to that is a variety of older and newer hardware, older and newer OSes, different vendors (Windows, Unixes, Apple, etc.) and a myriad of utilities and servers that go along. As hardware has improved and software is converted to 64 bit compatibility, there has necessarily been considerable delay in getting all the pieces of this very large and complex world to play nicely with the rapid pace of changes.

IMHO there is no one way to fix a problem. The solution is to research the possibilities and then by trial and error find what works best for your particular needs. Each user must determine what works for their system rather than using a cookie cutter approach.

I for example have a media server with a few very large files. The result is only about 400 files filling a 3 TB drive. Only 1% of the inodes are used but 95% of the total space is used. Someone else, with a lot of smaller files may run out of inodes before they come near to filling the space. (On ext4 filesystems as a rule of thumb, 1 inode is used for each file/directory.) While theoretically the total number of files that may be contained within a directory is nearly infinite, practicality determines that the overall usage determine realistic units, not just filesystem capabilities.

I hope that all the different answers above have promoted thought and problem solving rather than presenting an insurmountable barrier to progress.

mongodb how to get max value from collections

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

I have been faced with this problem.

The cause is your table doesn't have a primary key field.

And I have a simple solution: Set a field to primary key to specific field that suits your business logic.

For example, I have database thesis_db and field thesis_id, I will press button Primary (key icon) to set thesis_id to become primary key field:

enter image description here

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Python: call a function from string name

Why cant we just use eval()?

def install():
    print "In install"

New method

def installWithOptions(var1, var2):
    print "In install with options " + var1 + " " + var2

And then you call the method as below

method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)

This gives the output as

In install
In install with options a b

How do I create HTML table using jQuery dynamically?

You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):

$(document.createElement('table'));

InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

Edit:

Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

How can I get a JavaScript stack trace when I throw an exception?

This polyfill code working in modern (2017) browsers (IE11, Opera, Chrome, FireFox, Yandex):

printStackTrace: function () {
    var err = new Error();
    var stack = err.stack || /*old opera*/ err.stacktrace || ( /*IE11*/ console.trace ? console.trace() : "no stack info");
    return stack;
}

Other answers:

function stackTrace() {
  var err = new Error();
  return err.stack;
}

not working in IE 11 !

Using arguments.callee.caller - not working in strict mode in any browser!

HTML 5 Video "autoplay" not automatically starting in CHROME

Extremeandy has mentioned as of Chrome 66 autoplay video has been disabled.

After looking into this I found that muted videos are still able to be autoplayed. In my case the video didn't have any audio, but adding muted to the video tag has fixed it:

Hopefully this will help others also.

Configuring Hibernate logging using Log4j XML config file?

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging

Here's the list of logger categories:

Category                    Function

org.hibernate.SQL           Log all SQL DML statements as they are executed
org.hibernate.type          Log all JDBC parameters
org.hibernate.tool.hbm2ddl  Log all SQL DDL statements as they are executed
org.hibernate.pretty        Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache         Log all second-level cache activity
org.hibernate.transaction   Log transaction related activity
org.hibernate.jdbc          Log all JDBC resource acquisition
org.hibernate.hql.ast.AST   Log HQL and SQL ASTs during query parsing
org.hibernate.secure        Log all JAAS authorization requests
org.hibernate               Log everything (a lot of information, but very useful for troubleshooting) 

Formatted for pasting into a log4j XML configuration file:

<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />

NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.

And a category is specified as such:

<logger name="org.hibernate">
    <level value="ALL" />
    <appender-ref ref="FILE"/>
</logger>

It must be placed before the root element.

How to add content to html body using JS?

You're probably using

document.getElementById('element').innerHTML = "New content"

Try this instead:

document.getElementById('element').innerHTML += "New content"

Or, preferably, use DOM Manipulation:

document.getElementById('element').appendChild(document.createElement("div"))

Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.

splitting a string into an array in C++ without using vector

#define MAXSPACE 25

string line =  "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;

do
{

    spacePos = line.find(search,currPos);

    if(spacePos >= 0)
    {

        currPos = spacePos;
        arr[k] = line.substr(prevPos, currPos - prevPos);
        currPos++;
        prevPos = currPos;
        k++;
    }


}while( spacePos >= 0);

arr[k] = line.substr(prevPos,line.length());

for(int i = 0; i < k; i++)
{
   cout << arr[i] << endl;
}

How to get list of all installed packages along with version in composer?

Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()

Multiple github accounts on the same computer?

Simpler and Easy fix to avoid confusions..

For Windows users to use multiple or different git accounts for different projects.

Following steps: Go Control Panel and Search for Credential Manager. Then Go to Credential Manager -> Windows Credentials

Now remove the git:https//github.com node under Generic Credentials Heading

This will remove the current credentials. Now you can add any project through git pull it will ask for username and password.

When you face any issue with other account do the same process.

Thanks

refer to image

COALESCE Function in TSQL

Here is the way I look at COALESCE...and hopefully it makes sense...

In a simplistic form….

Coalesce(FieldName, 'Empty')

So this translates to…If "FieldName" is NULL, populate the field value with the word "EMPTY".

Now for mutliple values...

Coalesce(FieldName1, FieldName2, Value2, Value3)

If the value in Fieldname1 is null, fill it with the value in Fieldname2, if FieldName2 is NULL, fill it with Value2, etc.

This piece of test code for the AdventureWorks2012 sample database works perfectly & gives a good visual explanation of how COALESCE works:

SELECT Name, Class, Color, ProductNumber,
COALESCE(Class, Color, ProductNumber) AS FirstNotNull
FROM Production.Product

Create table (structure) from existing table

Its probably also worth mentioning that you can do the following:

Right click the table you want to duplicate > Script Table As > Create To > New Query Editor Window

Then, where is says the name of the table you just right clicked in the script that has been generated, change the name to what ever you want your new table to be called and click Execute

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

How to change legend size with matplotlib.pyplot

you can reduce the legend size setting:

plt.legend(labelspacing=y, handletextpad=x,fontsize)  

labelspacing is the vertical space between each label.

handletextpad is the distance between the actual legend and your label.

And fontsize is self-explanatory

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

How to get current local date and time in Kotlin

I use this to fetch data from API every 20 seconds

 private fun isFetchNeeded(savedAt: Long): Boolean {
        return savedAt + 20000 < System.currentTimeMillis()
    }

Trying to use Spring Boot REST to Read JSON String from POST

To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode. The appropriate converter is automatically configured.

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
        System.out.println(payload);
    }

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Where can I find a list of Mac virtual key codes?

In addition to the keycodes supplied in other answers, there are also "usage IDs" used for key remapping in the newer APIs introduced in macOS Sierra:

Technical Note TN2450

Remapping Keys in macOS 10.12 Sierra

Under macOS Sierra 10.12, the mechanism for key remapping was changed. This Technical Note is for developers of key remapping software so that they can update their software to support macOS Sierra 10.12. We present 2 solutions for implementing key remapping functionality for macOS 10.12 in this Technical Note.

https://developer.apple.com/library/archive/technotes/tn2450/_index.html

Keyboard a and A - 0x04
Keyboard b and B - 0x05
Keyboard c and C - 0x06
Keyboard d and D - 0x07
Keyboard e and E - 0x08
...

window.history.pushState refreshing the browser

As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.

If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").

But this function is not intended to reload the browser.

All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.

Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).

For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.

Hence the need for the function

history.pushState({},"Results for `Cats`",'url.html?s=cats');

It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.

When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.

If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.

As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.

See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.

$watch an object

Little performance tip if somebody has a datastore kind of service with key -> value pairs:

If you have a service called dataStore, you can update a timestamp whenever your big data object changes. This way instead of deep watching the whole object, you are only watching a timestamp for change.

app.factory('dataStore', function () {

    var store = { data: [], change: [] };

    // when storing the data, updating the timestamp
    store.setData = function(key, data){
        store.data[key] = data;
        store.setChange(key);
    }

    // get the change to watch
    store.getChange = function(key){
        return store.change[key];
    }

    // set the change
    store.setChange = function(key){
        store.change[key] = new Date().getTime();
    }

});

And in a directive you are only watching the timestamp to change

app.directive("myDir", function ($scope, dataStore) {
    $scope.dataStore = dataStore;
    $scope.$watch('dataStore.getChange("myKey")', function(newVal, oldVal){
        if(newVal !== oldVal && newVal){
            // Data changed
        }
    });
});

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

The problem could also come because of a lack of SQL driver in your Tomcat installation directory.

I had to had mysql-connector-java-5.1.23-bin.jar in apache-tomcat-9.0.12/lib/ folder.

https://dev.mysql.com/downloads/connector/j/

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

sql query with multiple where statements

What is meta_key? Strip out all of the meta_value conditionals, reduce, and you end up with this:

SELECT
*
FROM
meta_data
WHERE
(
        (meta_key = 'lat')
)
AND
(
        (meta_key = 'long')
)
GROUP BY
item_id

Since meta_key can never simultaneously equal two different values, no results will be returned.


Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:

SELECT
*
FROM
meta_data
WHERE
(
    (meta_key = 'lat')
    AND
    (
        (meta_value >= '60.23457047672217')
        OR
        (meta_value <= '60.23457047672217')
    )
)
OR
(
    (meta_key = 'long')
    AND
    (
        (meta_value >= '24.879140853881836')
        OR
        (meta_value <= '24.879140853881836')
    )
)
GROUP BY
item_id

Note the OR between the top-level conditionals. This is because you want records which are lat or long, since no single record will ever be lat and long.

I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY clause, but that might be outside the context of this question entirely.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line.

for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:

/usr/local/opencv/

Then run

sudo ldconfig -v

If you can't find the libraries, try running

sudo updatedb && locate libopencv_core.so.2.4

in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.

References:

About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html

About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux

How to draw a graph in LaTeX?

Aside from the (excellent) suggestion to use TikZ, you could use gastex. I used this before TikZ was available and it did its job too.

How do I show the number keyboard on an EditText in android?

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...
    android:inputType="number|phone"/> 

will show the large number pad as dialer.

Align div with fixed position on the right side

You can use two imbricated div. But you need a fixed width for your content, that's the only limitation.

<div style='float:right; width: 180px;'>
 <div style='position: fixed'>
   <!-- Your content -->
 </div>
</div>

Changing user agent on urllib2.urlopen

headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()

Or, a bit shorter:

req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

Try this, It worked for me

SELECT * FROM (
            SELECT
                [Code],
                [Name],
                [CategoryCode],
                [CreatedDate],
                [ModifiedDate],
                [CreatedBy],
                [ModifiedBy],
                [IsActive],
                ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
            FROM MasterTable
          ) a
        WHERE rownumber = 1 

Checking if object is empty, works with ng-show but not from controller?

Use an empty object literal isn't necessary here, you can use null or undefined:

$scope.items = null;

In this way, ng-show should keep working, and in your controller you can just do:

if ($scope.items) {
    // items have value
} else {
    // items is still null
}

And in your $http callbacks, you do the following:

$http.get(..., function(data) {
    $scope.items = {
        data: data,
        // other stuff
    };
});

When does Git refresh the list of remote branches?

Use git fetch to fetch all latest created branches.

Calling async method synchronously

Microsoft Identity has extension methods which call async methods synchronously. For example there is GenerateUserIdentityAsync() method and equal CreateIdentity()

If you look at UserManagerExtensions.CreateIdentity() it look like this:

 public static ClaimsIdentity CreateIdentity<TUser, TKey>(this UserManager<TUser, TKey> manager, TUser user,
        string authenticationType)
        where TKey : IEquatable<TKey>
        where TUser : class, IUser<TKey>
    {
        if (manager == null)
        {
            throw new ArgumentNullException("manager");
        }
        return AsyncHelper.RunSync(() => manager.CreateIdentityAsync(user, authenticationType));
    }

Now lets see what AsyncHelper.RunSync does

  public static TResult RunSync<TResult>(Func<Task<TResult>> func)
    {
        var cultureUi = CultureInfo.CurrentUICulture;
        var culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew(() =>
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap().GetAwaiter().GetResult();
    }

So, this is your wrapper for async method. And please don't read data from Result - it will potentially block your code in ASP.

There is another way - which is suspicious for me, but you can consider it too

  Result r = null;

            YourAsyncMethod()
                .ContinueWith(t =>
                {
                    r = t.Result;
                })
                .Wait();

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

List of Java class file format major version numbers?

I found a list of Java class file versions on the Wikipedia page that describes the class file format:

http://en.wikipedia.org/wiki/Java_class_file#General_layout

Under byte offset 6 & 7, the versions are listed with which Java VM they correspond to.

How to find index of all occurrences of element in array?

["a", "b", "a", "b"]
   .map((val, index) => ({ val, index }))
   .filter(({val, index}) => val === "a")
   .map(({val, index}) => index)

=> [0, 2]

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

OS X Framework Library not loaded: 'Image not found'

None of these issues solved this for me. The problem in the end was pretty easy. It looks like its a pretty major Xcode bug which I have logged the problem and fix under Apple bug: 29820370. If you are struggling (as it seems like there are several pages of problems similar to this ) then it would be great if you can raise a bug on bug reporter: https://bugreport.apple.com/ and reference the bug I raised to gain visibility. I want to make Xcode back into the pleasure that it was before - and this is something I am sure Xcode should have fixed itself.

Here is the fix: 1. Open Keychain - go to Apple Worldwide Developer Cert. 2. Double Click on it 3. Change the permission level from "always trust" to use System Defaults 4. Save and close it 5. Restart Xcode, Clean and build your project and it should be gone.

Screenshot below of the correct settings: Keychain access fixed Hope this helps!

Generate random numbers using C++11 random library

Here's something that I just wrote along those lines::

#include <random>
#include <chrono>
#include <thread>

using namespace std;

//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
  public:
    random_device                      rd;
    mt19937                            mt;
    uniform_real_distribution<double>  dist;

    backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}

    double rand() {
      return dist(mt);
    }
};

thread_local backoff_time_t backoff_time;


int main(int argc, char** argv) {
   double x1 = backoff_time.rand();
   double x2 = backoff_time.rand();
   double x3 = backoff_time.rand();
   double x4 = backoff_time.rand();
   return 0;
}

~

How to SSH to a VirtualBox guest externally through a host?

You can also initiate a port forward TO your HOST, OR ANY OTHER SERVER, from your Guest. This is especially useful if your Guest is 'locked' or can't otherwise complete the ModifyVM option (e.g. no permission to VBoxManage).

Three minor requirements are 1) you are/can log into the VirtualBox Guest (via 'console' GUI, another Guest, etc), 2) you have an account on the VirtualBox HOST (or other Server), and 3) SSH and TCP forwarding is not blocked.

Presuming you can meet the 3 requirements, these are the steps:

  1. On the Guest, run netstat -rn and find the Gateway address to the default route destination 0.0.0.0. Let's say it's "10.0.2.2". This 'Gateway' address is (one of) the VirtualBox Host virtual IP(s).
  2. On the Guest, run ssh -R 2222:localhost:22 10.0.2.2 where "10.0.2.2" is the VirtualBox server's IP address -OR- any other server IP you wish to port forward to.
  3. On the Host, run ssh 10.0.2.2 -p2222 where 10.0.2.2 is the default gateway/VBHost virtual IP found in step 1. If it is NOT the VirtualBox host you are port forwarding to, then the command is ssh localhost -p2222

How to check if any flags of a flag combination are set?

To check if for example AB is set I can do this:

if((letter & Letters.AB) == Letters.AB)

Is there a simpler way to check if any of the flags of a combined flag constant are set than the following?

This checks that both A and B are set, and ignores whether any other flags are set.

if((letter & Letters.A) == Letters.A || (letter & Letters.B) == Letters.B)

This checks that either A or B is set, and ignores whether any other flags are set or not.

This can be simplified to:

if(letter & Letters.AB)

Here's the C for binary operations; it should be straightforward to apply this to C#:

enum {
     A = 1,
     B = 2,
     C = 4,
     AB = A | B,
     All = AB | C,
};

int flags = A|C;

bool anything_and_a = flags & A;

bool only_a = (flags == A);

bool a_and_or_c_and_anything_else = flags & (A|C);

bool both_ac_and_anything_else = (flags & (A|C)) == (A|C);

bool only_a_and_c = (flags == (A|C));

Incidentally, the naming of the variable in the question's example is the singular 'letter', which might imply that it represents only a single letter; the example code makes it clear that its a set of possible letters and that multiple values are allowed, so consider renaming the variable 'letters'.

How to insert image in mysql database(table)?

If I use the following query,

INSERT INTO xx_BLOB(ID,IMAGE) 
VALUES(1,LOAD_FILE('E:/Images/xxx.png'));

Error: no such function: LOAD_FILE

Convert and format a Date in JSP

The example above showing the import with ...sun.com/jsp/jstl/format is incorrect (meaning it didn't work for me).

Instead try the below -this import statement is valid

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %><%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<html>
  <head>
    <title>Format Date</title>
  </head>

  <body>
    <c-rt:set var="now" value="<%=new java.util.Date()%>" />

    <table border="1" cellpadding="0" cellspacing="0"
    style="border-collapse: collapse" bordercolor="#111111"
    width="63%" id="AutoNumber2">
      <tr>
        <td width="100%" colspan="2" bgcolor="#0000FF">
          <p align="center">
            <b>
              <font color="#FFFFFF" size="4">Formatting: 
              <fmt:formatDate value="${now}" type="both"
              timeStyle="long" dateStyle="long" />
              </font>
            </b>
          </p>
        </td>
      </tr>

Server did not recognize the value of HTTP Header SOAPAction

While calling the .asmx / wcf web service please take care of below points:

  1. The namespace is case sensitive,the SOAP request MUST be sent with the same namespace with which the WebService is declared.

e.g. For the WebService declared as below

[WebService(Namespace = "http://MyDomain.com/TestService")] 
public class FooClass : System.Web.Services.WebService 
{
   [WebMethod]   
    public bool Foo( string name)    
     {

      ...... 
     }

 }

The SOAP request must maintain the same case for namespace while calling.Sometime we overlook the case sensitivity.

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
     <Foo xmlns="http://MyDomain.com/TestService">
     <name>string</name>      
     </Foo>
  </soap:Body> 
</soap:Envelope>
  1. The namespace need not be same as hosted url of the service.The namespace can be any string.

e.g. Above service may be hosted at http://84.23.9.65/MyTestService , but still while invoking the Web Service from client the namespace should be the same which the serice class is having i.e.http://MyDomain.com/TestService

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

If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:

  1. Go to C:/Users/user_name/.p4qt

user_name will be your username of your computer

  1. Inside 001Clients folder WorkspaceSettings.xml file will be there.

There will be two tag

  1. varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag

  2. A propertyList tag will be there with varName=deleted_workspace_name delete that tag.

from drop down menu workspace name will be deleted

Convert PDF to image with high resolution

I really haven't had good success with convert [update May 2020: actually: it pretty much never works for me], but I've had EXCELLENT success with pdftoppm. Here's a couple examples of producing high-quality images from a PDF:

  1. [Produces ~25 MB-sized files per pg] Output uncompressed .tif file format at 300 DPI into a folder called "images", with files being named pg-1.tif, pg-2.tif, pg-3.tif, etc:

     mkdir -p images && pdftoppm -tiff -r 300 mypdf.pdf images/pg
    
  2. [Produces ~1MB-sized files per pg] Output in .jpg format at 300 DPI:

     mkdir -p images && pdftoppm -jpeg -r 300 mypdf.pdf images/pg
    
  3. [Produces ~2MB-sized files per pg] Output in .jpg format at highest quality (least compression) and still at 300 DPI:

     mkdir -p images && pdftoppm -jpeg -jpegopt quality=100 -r 300 mypdf.pdf images/pg
    

For more explanations, options, and examples, see my full answer here:

https://askubuntu.com/questions/150100/extracting-embedded-images-from-a-pdf/1187844#1187844.

Related:

  1. [How to turn a PDF into a searchable PDF w/pdf2searchablepdf] https://askubuntu.com/questions/473843/how-to-turn-a-pdf-into-a-text-searchable-pdf/1187881#1187881
  2. Cross-linked:
    1. How to convert a PDF into JPG with command line in Linux?
    2. https://unix.stackexchange.com/questions/11835/pdf-to-jpg-without-quality-loss-gscan2pdf/585574#585574

SeekBar and media player in android

    int  pos  = 0;
    yourSeekBar.setMax(mPlayer.getDuration());

After You start Your MediaPlayer i.e mplayer.start()

Try this code

while(mPlayer!=null){
         try {
                Thread.sleep(1000);
                pos  = mPlayer.getCurrentPosition();
            }  catch (Exception e) {
                //show exception in LogCat
            }
            yourSeekBar.setProgress(pos);

   }

Before you added this code you have to create xml resource for SeekBar and use it in Your Activity class of ur onCreate() method.

how to automatically scroll down a html page?

Use document.scrollTop to change the position of the document. Set the scrollTop of the document equal to the bottom of the featured section of your site

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

Android: How to stretch an image to the screen width while maintaining aspect ratio?

Everyone is doing this programmily so I thought this answer would fit perfectly here. This code worked for my in the xml. Im NOT thinking about ratio yet, but still wanted to place this answer if it would help anyone.

android:adjustViewBounds="true"

Cheers..

How to clear a textbox using javascript

Give this in input tag of textbox:

onClick="(this.value='')" 

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Referencing another schema in Mongoose

Late reply, but adding that Mongoose also has the concept of Subdocuments

With this syntax, you should be able to reference your userSchema as a type in your postSchema like so:

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var postSchema = new Schema({
    name: String,
    postedBy: userSchema,
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Note the updated postedBy field with type userSchema.

This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.

How To Include CSS and jQuery in my WordPress plugin?

Very Simple:

Adding JS/CSS in the Front End:

function enqueue_related_pages_scripts_and_styles(){
        wp_enqueue_style('related-styles', plugins_url('/css/bootstrap.min.css', __FILE__));
        wp_enqueue_script('releated-script', plugins_url( '/js/custom.js' , __FILE__ ), array('jquery','jquery-ui-droppable','jquery-ui-draggable', 'jquery-ui-sortable'));
    }
add_action('wp_enqueue_scripts','enqueue_related_pages_scripts_and_styles');

Adding JS/CSS in WP Admin Area:

function enqueue_related_pages_scripts_and_styles(){
        wp_enqueue_style('related-pages-admin-styles',  get_stylesheet_directory_uri() . '/admin-related-pages-styles.css');
        wp_enqueue_script('releated-pages-admin-script', plugins_url( '/js/custom.js' , __FILE__ ), array('jquery','jquery-ui-droppable','jquery-ui-draggable', 'jquery-ui-sortable'));
    }
add_action('admin_enqueue_scripts','enqueue_related_pages_scripts_and_styles');

Using iText to convert HTML to PDF

I have ended up using ABCPdf from webSupergoo. It works really well and for about $350 it has saved me hours and hours based on your comments above. Thanks again Daniel and Bratch for your comments.

Seeing the underlying SQL in the Spring JdbcTemplate?

I use this line for Spring Boot applications:

logging.level.org.springframework.jdbc.core = TRACE

This approach pretty universal and I usually use it for any other classes inside my application.

Excel how to fill all selected blank cells with text

If you want to do this in VBA, then this is a shorter method:

Sub FillBlanksWithNull()

'This macro will fill all "blank" cells with the text "Null"

'When no range is selected, it starts at A1 until the last used row/column

'When a range is selected prior, only the blank cell in the range will be used.

On Error GoTo ErrHandler:

Selection.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "Null"

Exit Sub

ErrHandler:

MsgBox "No blank cells found", vbDefaultButton1, Error

Resume Next

End Sub

Regards,

Robert Ilbrink

How to use <md-icon> in Angular Material?

<md-button class="md-fab md-primary" md-theme="cyan" aria-label="Profile">
    <md-icon icon="/img/icons/ic_people_24px.svg" style="width: 24px; height: 24px;"></md-icon>
</md-button>

source: https://material.angularjs.org/#/demo/material.components.button

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

List to array conversion to use ravel() function

If all you want is calling ravel on your (nested, I s'pose?) list, you can do that directly, numpy will do the casting for you:

L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)

Also worth mentioning that you needn't go through numpy at all.

Full width layout with twitter bootstrap

The easiest way with BS3 is to reset the max-width and padding set by BS3 CSS simply like this. You get again a container-fluid :

.container{
  max-width:100%;
  padding:0;
}

How do I create an abstract base class in JavaScript?

JavaScript Classes and Inheritance (ES6)

According to ES6, you can use JavaScript classes and inheritance to accomplish what you need.

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

First of all, we define our abstract class. This class can't be instantiated, but can be extended. We can also define functions that must be implemented in all classes that extends this one.

/**
 * Abstract Class Animal.
 *
 * @class Animal
 */
class Animal {

  constructor() {
    if (this.constructor == Animal) {
      throw new Error("Abstract classes can't be instantiated.");
    }
  }

  say() {
    throw new Error("Method 'say()' must be implemented.");
  }

  eat() {
    console.log("eating");
  }
}

After that, we can create our concrete Classes. These classes will inherit all functions and behaviour from abstract class.

/**
 * Dog.
 *
 * @class Dog
 * @extends {Animal}
 */
class Dog extends Animal {
  say() {
    console.log("bark");
  }
}

/**
 * Cat.
 *
 * @class Cat
 * @extends {Animal}
 */
class Cat extends Animal {
  say() {
    console.log("meow");
  }
}

/**
 * Horse.
 *
 * @class Horse
 * @extends {Animal}
 */
class Horse extends Animal {}

And the results...

// RESULTS

new Dog().eat(); // eating
new Cat().eat(); // eating
new Horse().eat(); // eating

new Dog().say(); // bark
new Cat().say(); // meow
new Horse().say(); // Error: Method say() must be implemented.

new Animal(); // Error: Abstract classes can't be instantiated.

Get the number of rows in a HTML table

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
<!--
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');
//-->
</script>

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

How to read a file in other directory in python

In case you're not in the specified directory (i.e. direct), you should use (in linux):

x_file = open('path/to/direct/filename.txt')

Note the quotes and the relative path to the directory.

This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.

How to get a table creation script in MySQL Workbench?

Solution for MySQL Workbench 6.3E

  • On left panel, right click your table and selecct "Table Inspector"
  • On center panel, click DDL label

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

org.apache.jasper.JasperException: Unable to compile class for JSP:

The problem is caused because you need to import the pageNumber.Member class in your JSP. Make sure to also include another packages and classes like java.util.List.

<%@ page import="pageNumber.*, java.util.*" %>

Still, you have a major problem by using scriptlets in your JSP. Refer to How to avoid Java Code in JSP-Files? and start practicing EL and JSTL and focusing more on a MVC solution instead.

fatal: 'origin' does not appear to be a git repository

I had the same error on git pull origin branchname when setting the remote origin as path fs and not ssh in .git/config:

fatal: '/path/to/repo.git' does not appear to be a git repository 
fatal: The remote end hung up unexpectedly

It was like so (this only works for users on same server of git that have access to git):

url = file:///path/to/repo.git/

Fixed it like so (this works on all users that have access to git user (ssh authorizes_keys or password)):

url = [email protected]:path/to/repo.git

the reason I had it as a directory path was because the git files are on the same server.

get string value from HashMap depending on key name

 HashMap<Integer, String> hmap = new HashMap<Integer, String>();
 hmap.put(4, "DD");

The Value mapped to Key 4 is DD

How to test the type of a thrown exception in Jest

In Jest you have to pass a function into expect(function).toThrow(<blank or type of error>).

Example:

test("Test description", () => {
  const t = () => {
    throw new TypeError();
  };
  expect(t).toThrow(TypeError);
});

Or if you also want to check for error message:

test("Test description", () => {
  const t = () => {
    throw new TypeError("UNKNOWN ERROR");
  };
  expect(t).toThrow(TypeError);
  expect(t).toThrow("UNKNOWN ERROR");
});

If you need to test an existing function whether it throws with a set of arguments, you have to wrap it inside an anonymous function in expect().

Example:

test("Test description", () => {
  expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);
});

Easiest way to use SVG in Android?

Try the SVG2VectorDrawable Plugin. Go to Preferences->Plugins->Browse Plugins and install SVG2VectorDrawable. Great for converting sag files to vector drawable. Once you have installed you will find an icon for this in the toolbar section just to the right of the help (?) icon.

How to make php display \t \n as tab and new line instead of characters

Put it in double quotes:

echo "\t";

Single quotes do not expand escaped characters.

Use the documentation when in doubt.

How to use `replace` of directive definition?

As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.

First result:

<span myd1="">directive template1</span>

Second result:

<div myd2=""><span>directive template2</span></div>

Asynchronously load images with jQuery

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

Capitalize words in string

There's also locutus: https://locutus.io/php/strings/ucwords/ which defines it this way:

function ucwords(str) {
  //  discuss at: http://locutus.io/php/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva (http://waldo.malqui.info)
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld')
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD')
  //   returns 2: 'HELLO WORLD'
  //   example 3: ucwords('? ???? ??? ????????? ??????? ? ??? ??? ????? ??????')
  //   returns 3: '? ???? ??? ????????? ??????? ? ??? ??? ????? ??????'
  //   example 4: ucwords('t???st? a??p?? ßaf?? ??µ??? ??, d?as?e???e? ?p?? ?????? ?????')
  //   returns 4: '????st? ???p?? ?af?? ??µ??? G?, ??as?e???e? ?p?? ?????? ?????'

  return (str + '').replace(/^(.)|\s+(.)/g, function ($1) {
    return $1.toUpperCase();
  });
};

Automatically enter SSH password with script

Use public key authentication: https://help.ubuntu.com/community/SSH/OpenSSH/Keys

In the source host run this only once:

ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost

That's all, after that you'll be able to do ssh without password.

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

Leave your email.php code the same, but replace this JavaScript code:

 var name = $("#form_name").val();
        var email = $("#form_email").val();
        var text = $("#msg_text").val();
        var dataString = 'name='+ name + '&email=' + email + '&text=' + text;

        $.ajax({
            type: "POST",
            url: "email.php",
            data: dataString,
            success: function(){
            $('.success').fadeIn(1000);
            }
        });

with this:

    $.ajax({
        type: "POST",
        url: "email.php",
        data: $(form).serialize(),
        success: function(){
        $('.success').fadeIn(1000);
        }
    });

So that your form input names match up.

Merge a Branch into Trunk

Do an svn update in the trunk, note the revision number.

From the trunk:

svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName

You can check where the branch was cut from the trunk by doing an svn log

svn log --stop-on-copy

How do I compare two hashes?

... and now in module form to be applied to a variety of collection classes (Hash among them). It's not a deep inspection, but it's simple.

# Enable "diffing" and two-way transformations between collection objects
module Diffable
  # Calculates the changes required to transform self to the given collection.
  # @param b [Enumerable] The other collection object
  # @return [Array] The Diff: A two-element change set representing items to exclude and items to include
  def diff( b )
    a, b = to_a, b.to_a
    [a - b, b - a]
  end

  # Consume return value of Diffable#diff to produce a collection equal to the one used to produce the given diff.
  # @param to_drop [Enumerable] items to exclude from the target collection
  # @param to_add  [Enumerable] items to include in the target collection
  # @return [Array] New transformed collection equal to the one used to create the given change set
  def apply_diff( to_drop, to_add )
    to_a - to_drop + to_add
  end
end

if __FILE__ == $0
  # Demo: Hashes with overlapping keys and somewhat random values.
  Hash.send :include, Diffable
  rng = Random.new
  a = (:a..:q).to_a.reduce(Hash[]){|h,k| h.merge! Hash[k, rng.rand(2)] }
  b = (:i..:z).to_a.reduce(Hash[]){|h,k| h.merge! Hash[k, rng.rand(2)] }
  raise unless a == Hash[ b.apply_diff(*b.diff(a)) ] # change b to a
  raise unless b == Hash[ a.apply_diff(*a.diff(b)) ] # change a to b
  raise unless a == Hash[ a.apply_diff(*a.diff(a)) ] # change a to a
  raise unless b == Hash[ b.apply_diff(*b.diff(b)) ] # change b to b
end

GitHub authentication failing over https, returning wrong email address

Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:

  • Get you personal access token. This you have to check and generate if not available already. Link for this: https://github.com/settings/tokens
  • Go to your local and delete folder and re-clone branch from github.
  • Now try the command you were trying earlier i.e: git pull origin master
  • Enter username and In password paste the token generated and also don't forget to save that token somewhere, so you can re-use if required.

Doing this will solve your issue.

JavaScript to scroll long page to DIV

The difficulty with scrolling is that you may not only need to scroll the page to show a div, but you may need to scroll inside scrollable divs on any number of levels as well.

The scrollTop property is a available on any DOM element, including the document body. By setting it, you can control how far down something is scrolled. You can also use clientHeight and scrollHeight properties to see how much scrolling is needed (scrolling is possible when clientHeight (viewport) is less than scrollHeight (the height of the content).

You can also use the offsetTop property to figure out where in the container an element is located.

To build a truly general purpose "scroll into view" routine from scratch, you would need to start at the node you want to expose, make sure it's in the visible portion of it's parent, then repeat the same for the parent, etc, all the way until you reach the top.

One step of this would look something like this (untested code, not checking edge cases):

function scrollIntoView(node) {
  var parent = node.parent;
  var parentCHeight = parent.clientHeight;
  var parentSHeight = parent.scrollHeight;
  if (parentSHeight > parentCHeight) {
    var nodeHeight = node.clientHeight;
    var nodeOffset = node.offsetTop;
    var scrollOffset = nodeOffset + (nodeHeight / 2) - (parentCHeight / 2);
    parent.scrollTop = scrollOffset;
  }
  if (parent.parent) {
    scrollIntoView(parent);
  }
}

GridLayout (not GridView) how to stretch all children evenly

You can set width of every child dynamically:

GridLayout.LayoutParams params = (GridLayout.LayoutParams) child.getLayoutParams();
    params.width = (parent.getWidth()/parent.getColumnCount()) -params.rightMargin - params.leftMargin;
    child.setLayoutParams(params);

Check for false

If you want to check for false and alert if not, then no there isn't.

If you use if(val), then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using === and !== is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.

Limit results in jQuery UI Autocomplete

Adding to Andrew's answer, you can even introduce a maxResults property and use it this way:

$("#auto").autocomplete({ 
    maxResults: 10,
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(src, request.term);
        response(results.slice(0, this.options.maxResults));
    }
});

jsFiddle: http://jsfiddle.net/vqwBP/877/

This should help code readability and maintainability!

How to crop an image using C#?

I was looking for a easy and FAST function with no additional libary to do the job. I tried Nicks solution, but i needed 29,4 sec to "extract" 1195 images of an atlas file. So later i managed this way and needed 2,43 sec to do the same job. Maybe this will be helpful.

// content of the Texture class
public class Texture
{
    //name of the texture
    public string name { get; set; }
    //x position of the texture in the atlas image
    public int x { get; set; }
    //y position of the texture in the atlas image
    public int y { get; set; }
    //width of the texture in the atlas image
    public int width { get; set; }
    //height of the texture in the atlas image
    public int height { get; set; }
}

Bitmap atlasImage = new Bitmap(@"C:\somepicture.png");
PixelFormat pixelFormat = atlasImage.PixelFormat;

foreach (Texture t in textureList)
{
     try
     {
           CroppedImage = new Bitmap(t.width, t.height, pixelFormat);
           // copy pixels over to avoid antialiasing or any other side effects of drawing
           // the subimages to the output image using Graphics
           for (int x = 0; x < t.width; x++)
               for (int y = 0; y < t.height; y++)
                   CroppedImage.SetPixel(x, y, atlasImage.GetPixel(t.x + x, t.y + y));
           CroppedImage.Save(Path.Combine(workingFolder, t.name + ".png"), ImageFormat.Png);
     }
     catch (Exception ex)
     {
          // handle the exception
     }
}

Add content to a new open window

When You want to open new tab/window (depends on Your browser configuration defaults):

output = 'Hello, World!';
window.open().document.write(output);

When output is an Object and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)

output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));

Update

Google Chrome (60.0.3112.90) block this code:

Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9

When You want to append some data to existing page

output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;

output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;

HttpClient - A task was cancelled?

var clientHttp = new HttpClient();
clientHttp.Timeout = TimeSpan.FromMinutes(30);

The above is the best approach for waiting on a large request. You are confused about 30 minutes; it's random time and you can give any time that you want.

In other words, request will not wait for 30 minutes if they get results before 30 minutes. 30 min means request processing time is 30 min. When we occurred error "Task was cancelled", or large data request requirements.

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

How to convert FormData (HTML5 object) to JSON

Worked for me

                var myForm = document.getElementById("form");
                var formData = new FormData(myForm),
                obj = {};
                for (var entry of formData.entries()){
                    obj[entry[0]] = entry[1];
                }
                console.log(obj);

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How to change value of object which is inside an array using JavaScript or jQuery?

upsert(array, item) { 
        const i = array.findIndex(_item => _item.id === item.id);
        if (i > -1) {
            let result = array.filter(obj => obj.id !== item.id);
            return [...result, item]
        }
        else {
            return [...array, item]
        };
    }

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

org.json.simple.JSONArray resultantJson = new org.json.simple.JSONArray();

        org.json.JSONArray o1 = new org.json.JSONArray("[{\"one\":[],\"two\":\"abc\"}]");
        org.json.JSONArray o2 = new org.json.JSONArray("[{\"three\":[1,2],\"four\":\"def\"}]");


        resultantJson.addAll(o1.toList());
        resultantJson.addAll(o2.toList());

Difference between setUp() and setUpBeforeClass()

Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.

Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).

"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.

How to use a variable for a key in a JavaScript object literal?

ES5 quote that says it should not work

Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245

Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5

PropertyName :

  • IdentifierName
  • StringLiteral
  • NumericLiteral

[...]

The production PropertyName : IdentifierName is evaluated as follows:

  1. Return the String value containing the same sequence of characters as the IdentifierName.

The production PropertyName : StringLiteral is evaluated as follows:

  1. Return the SV [String value] of the StringLiteral.

The production PropertyName : NumericLiteral is evaluated as follows:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. Return ToString(nbr).

This means that:

  • { theTop : 10 } is the exact same as { 'theTop' : 10 }

    The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.

  • It is not possible to write object initializers (literals) with variable keys.

    The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).

How to prevent user from typing in text field without disabling the field?

I like to add one that also works with dynamic javascript DOM creation like D3 where it is impossible to add:

//.attr(function(){if(condition){"readonly"]else{""}) //INCORRECT CODE !

to prevent actions on a HTML input DOM element add readonly to class:

var d = document.getElementById("div1");
d.className += " readonly";

OR in D3:

 .classed("readonly", function(){
   if(condition){return true}else{return false}
 })

AND add to CSS or less:

.readonly {
  pointer-events: none;
}

the nice thing about this solution is that you can dynamically turn it on and of in a function so it can be integrated in for example D3 at creation time (not possible with the single "readonly" attribute).

to remove the element from class:

document.getElementById("MyID").className =
  document.getElementById("MyID").className.replace(/\breadonly\b/,'');

or use Jquery:

$( "div" ).removeClass( "readonly" )

or toggle the class:

$( "div" ).toggleClass( "readonly", addOrRemove );

Just to be complete, good luck =^)

Using different Web.config in development and production environment

The Enterprise Library configuration editor can help you do this. It allows you to create a base config file and then deltas for each environment. You can then merge the base config and the delta to create an environment-specific web.config. Take a look at the information here which takes you through it better than I can.

New warnings in iOS 9: "all bitcode will be dropped"

In my case for avoiding that problem:

  1. Be sure that you are dealing with Xcode 7, NOT lower versions. In lower version this flag does not exist.

  2. Setup: Project>Build Settings>All>Build Options>Enable Bitcode = NO

enter image description here

How to read all files in a folder from Java?

import java.io.File;


public class ReadFilesFromFolder {
  public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
  static String temp = "";

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
    listFilesForFolder(folder);
  }

  public static void listFilesForFolder(final File folder) {

    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {
        // System.out.println("Reading files under the folder "+folder.getAbsolutePath());
        listFilesForFolder(fileEntry);
      } else {
        if (fileEntry.isFile()) {
          temp = fileEntry.getName();
          if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
            System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
        }

      }
    }
  }
}

How do I get the XML root node with C#?

Try this

XElement root = XDocument.Load(fStream).Root;

How to select an item in a ListView programmatically?

        int i=99;//is what row you want to select and focus
        listViewRamos.FocusedItem = listViewRamos.Items[0];
        listViewRamos.Items[i].Selected = true;
        listViewRamos.Select();
        listViewRamos.EnsureVisible(i);//This is the trick

Background thread with QThread in PyQt

PySide2 Solution:

Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.

In order to match PyQt5's behavior, you have to create the started signal yourself.

Here is an easy solution:

# Use this class instead of QThread
class QThread2(QThread):
    # Use this signal instead of "started"
    started2 = Signal()

    def __init__(self):
        QThread.__init__(self)
        self.started.connect(self.onStarted)

    def onStarted(self):
        self.started2.emit()

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Git checkout: updating paths is incompatible with switching branches

For me what worked was:

git fetch

Which pulls all the refs down to your machine for all the branches on remote. Then I could do

git checkout <branchname>

and that worked perfectly. Similar to the top voted answer, but a little more simple.

Pythonic way to check if a list is sorted or not

If you want the fastest way for numpy arrays, use numba, which if you use conda should be already installed

The code will be fast because it will be compiled by numba

import numba
@numba.jit
def issorted(vec, ascending=True):
    if len(vec) < 2:
        return True
    if ascending:
        for i in range(1, len(vec)):
            if vec[i-1] > vec[i]:
                return False
        return True
    else:
        for i in range(1, len(vec)):
            if vec[i-1] < vec[i]:
                return False
        return True

and then:

>>> issorted(array([4,9,100]))
>>> True

Program does not contain a static 'Main' method suitable for an entry point

I have got the same error but then I found out that I typed small m instead of capital M in Main method

Get the Id of current table row with Jquery

You can use .closest() to get up to the current <tr> parent, like this:

$('input[type=button]' ).click(function() {
   var bid = this.id; // button ID 
   var trid = $(this).closest('tr').attr('id'); // table row ID 
 });

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

I had this issue occurring with mailto: and tel: links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.

Adding target="_blank", as suggested by this discussion of the issue fixed the problem for me.

Set content of iframe

I needed to reuse the same iframe and replace the content each time. I've tried a few ways and this worked for me:

// Set the iframe's src to about:blank so that it conforms to the same-origin policy 
iframeElement.src = "about:blank";

// Set the iframe's new HTML
iframeElement.contentWindow.document.open();
iframeElement.contentWindow.document.write(newHTML);
iframeElementcontentWindow.document.close();

Here it is as a function:

function replaceIframeContent(iframeElement, newHTML)
{
    iframeElement.src = "about:blank";
    iframeElement.contentWindow.document.open();
    iframeElement.contentWindow.document.write(newHTML);
    iframeElement.contentWindow.document.close();
}

How to set aliases in the Git Bash for Windows?

Follow below steps:

  1. Open the file .bashrc which is found in location C:\Users\USERNAME\.bashrc

    If file .bashrc not exist then create it using below steps:

    1. Open Command Prompt and goto C:\Users\USERNAME\.
    2. Type command notepad ~/.bashrc
      It generates the .bashrc file.
  2. Add below sample commands of WP CLI, Git, Grunt & PHPCS etc.


# ----------------------
# Git Command Aliases
# ----------------------
alias ga='git add'
alias gaa='git add .'
alias gaaa='git add --all'

# ----------------------
# WP CLI
# ----------------------
alias wpthl='wp theme list'
alias wppll='wp plugin list'

Now you can use the commands:

  • ga instead of git add .
  • wpthl instead of wp theme list

Eg. I have used wpthl for the WP CLI command wp theme list.

Yum@M MINGW64 /c/xampp/htdocs/dev.test
$ wpthl
+------------------------+----------+-----------+----------+
| name                   | status   | update    | version  |
+------------------------+----------+-----------+----------+
| twentyeleven           | inactive | none      | 2.8      |
| twentyfifteen          | inactive | none      | 2.0      |
| twentyfourteen         | inactive | none      | 2.2      |
| twentyseventeen        | inactive | available | 1.6      |
| twentysixteen          | inactive | none      | 1.5      |
| twentyten              | inactive | none      | 2.5      |
| twentythirteen         | inactive | none      | 2.4      |
| twentytwelve           | inactive | none      | 2.5      |

For more details read the article Keyboard shortcut/aliases for the WP CLI, Git, Grunt & PHPCS commands for windows

Command-line svn for Windows?

You can use Apache Subversion. It is owner of subversion . You can download from here . After install it, you have to restart pc to use svn from command line.

Parser Error when deploy ASP.NET application

In my case I missed the compile tag in the .csproj file

<Compile Include="Global.asax.cs">
  <DependentUpon>Global.asax</DependentUpon>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>

Press enter in textbox to and execute button command

there you go.

private void YurTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            YourButton_Click(this, new EventArgs());
        }
    }

Query based on multiple where clauses in Firebase

Firebase doesn't allow querying with multiple conditions. However, I did find a way around for this:

We need to download the initial filtered data from the database and store it in an array list.

                Query query = databaseReference.orderByChild("genre").equalTo("comedy");
                databaseReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        ArrayList<Movie> movies = new ArrayList<>();
                        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                            String lead = dataSnapshot1.child("lead").getValue(String.class);
                            String genre = dataSnapshot1.child("genre").getValue(String.class);

                            movie = new Movie(lead, genre);

                            movies.add(movie);

                        }

                        filterResults(movies, "Jack Nicholson");

                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

Once we obtain the initial filtered data from the database, we need to do further filter in our backend.

public void filterResults(final List<Movie> list,  final String genre) {
        List<Movie> movies = new ArrayList<>();
        movies = list.stream().filter(o -> o.getLead().equals(genre)).collect(Collectors.toList());
        System.out.println(movies);

        employees.forEach(movie -> System.out.println(movie.getFirstName()));
    }

Stuck at ".android/repositories.cfg could not be loaded."

I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works

How to add a line break within echo in PHP?

\n is a line break. /n is not.


use of \n with

1. echo directly to page

Now if you are trying to echo string to the page:

echo  "kings \n garden";

output will be:

kings garden

you won't get garden in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n. You need to use the nl2br() function for that.

What it does is:

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

echo  nl2br ("kings \n garden");

Output

kings
garden

Note Make sure you're echoing/printing \n in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is

so "\n" not '\n'

2. write to text file

Now if you echo to text file you can use just \n and it will echo to a new line, like:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
 

output will be:

kings
 garden

SQL Server replace, remove all after certain character

Use LEFT combined with CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

I get the following results:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)

Open Url in default web browser

In React 16.8+, using functional components, you would do

import React from 'react';
import { Button, Linking } from 'react-native';

const ExternalLinkBtn = (props) => {
  return <Button
            title={props.title}
            onPress={() => {
                Linking.openURL(props.url)
                .catch(err => {
                    console.error("Failed opening page because: ", err)
                    alert('Failed to open page')
                })}}
          />
}

export default function exampleUse() {
  return (
    <View>
      <ExternalLinkBtn title="Example Link" url="https://example.com" />
    </View>
  )
}

Only variables should be passed by reference

end(...[explode('.', $file_name)]) has worked since PHP 5.6. This is documented in the RFC although not in PHP docs themselves.

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

vector vs. list in STL

The only hard rule where list must be used is where you need to distribute pointers to elements of the container.

Unlike with vector, you know that the memory of elements won't be reallocated. If it could be then you might have pointers to unused memory, which is at best a big no-no and at worst a SEGFAULT.

(Technically a vector of *_ptr would also work but in that case you are emulating list so that's just semantics.)

Other soft rules have to do with the possible performance issues of inserting elements into the middle of a container, whereupon list would be preferable.

Disallow Twitter Bootstrap modal window from closing

You can also include these attributes in the modal definition itself:

<div class="modal hide fade" data-keyboard="false" data-backdrop="static">

How to fix request failed on channel 0

I encountered this error while using my git bash. I was able to solve this by re-installing git for windows. More details in this answer.

Understanding repr( ) function in Python

1) The result of repr('foo') is the string 'foo'. In your Python shell, the result of the expression is expressed as a representation too, so you're essentially seeing repr(repr('foo')).

2) eval calculates the result of an expression. The result is always a value (such as a number, a string, or an object). Multiple variables can refer to the same value, as in:

x = 'foo'
y = x

x and y now refer to the same value.

3) I have no idea what you meant here. Can you post an example, and what you'd like to see?

When do I need a fb:app_id or fb:admins?

Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>

How to include scripts located inside the node_modules folder?

If you are linking to many files, create a whitelist, and then use sendFile():

app.get('/npm/:pkg/:file', (req, res) => {
    const ok = ['jquery','bootstrap','interactjs'];
    if (!ok.includes(req.params.pkg)) res.status(503).send("Not Permitted.");
    res.sendFile(__dirname + `/node_modules/${req.params.pkg}/dist/${req.params.file}`);
    });

For example, You can then safely link to /npm/bootstrap/bootsrap.js, /npm/bootstrap/bootsrap.css, etc.

As an aside, I would love to know if there was a way to whitelist using express.static

How can I get device ID for Admob

Add this class to your project

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;

import com.google.android.gms.ads.AdRequest;
import java.io.UnsupportedEncodingException;

public class AdsHelper {
public static AdRequest createRequest(Context context) {
    AdRequest.Builder adRequest = new AdRequest.Builder();
    adRequest.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
    if (BuildConfig.DEBUG) {
        String deviceId = MD5(getDeviceId(context));
        if (!TextUtils.isEmpty(deviceId)) {
            adRequest.addTestDevice(deviceId.toUpperCase());
        }
    }

    return adRequest.build();
}



    private static String MD5(String md5) {
        if (TextUtils.isEmpty(md5)) return null;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte anArray : array) {
                sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException ignored) {
        } catch(UnsupportedEncodingException ignored){
        }
        return null;
    }

    private static String getDeviceId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";
        }

    }
}

Usage:

AdRequest adRequest = AdsHelper.createRequest(this);

Correct way to try/except using Python requests module?

Exception object also contains original response e.response, that could be useful if need to see error body in response from the server. For example:

try:
    r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

Original purpose of <input type="hidden">?

I'll provide a simple Server Side Real World Example here, say if the records are looped and each record has a form with a delete button and you need to delete a specific record, so here comes the hidden field in action, else you won't get the reference of the record to be deleted in this case, it will be id

For example

<?php
    if(isset($_POST['delete_action'])) {
        mysqli_query($connection, "DELETE FROM table_name 
                                   WHERE record_id = ".$_POST['row_to_be_deleted']);
                                   //Here is where hidden field value is used
    }

    while(condition) {
?>
    <span><?php echo 'Looped Record Name'; ?>
    <form method="post">
        <input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>" />
        <input type="submit" name="delete_action" />
    </form>
<?php
    }
?>

Set time to 00:00:00

One more JAVA 8 way:

LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);

But it's a lot more useful to edit the date that already exists.

How to determine the content size of a UIWebView?

In Xcode 8 and iOS 10 to determine the height of a web view. you can get height using

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    NSLog(@"Webview height is:: %f", height);
}

OR for Swift

 func webViewDidFinishLoad(aWebView:UIWebView){
        let height: Float = (aWebView.stringByEvaluatingJavaScriptFromString("document.body.scrollHeight")?.toFloat())!
        print("Webview height is::\(height)")
    }

How to convert Milliseconds to "X mins, x seconds" in Java?

Just to add more info if you want to format like: HH:mm:ss

0 <= HH <= infinite

0 <= mm < 60

0 <= ss < 60

use this:

int h = (int) ((startTimeInMillis / 1000) / 3600);
int m = (int) (((startTimeInMillis / 1000) / 60) % 60);
int s = (int) ((startTimeInMillis / 1000) % 60);

I just had this issue now and figured this out

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

What does the keyword Set actually do in VBA?

set is used to assign a reference to an object. The C equivalent would be

 int i;
int* ref_i;

i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i)

How do you switch pages in Xamarin.Forms?

Call:

((App)App.Current).ChangeScreen(new Map());

Create this method inside App.xaml.cs:

public void ChangeScreen(Page page)
{
     MainPage = page;
}

Dynamically display a CSV file as an HTML table on a web page

XmlGrid.net has tool to convert csv to html table. Here is the link: http://xmlgrid.net/csvToHtml.html

I used your sample data, and got the following html table:

<table>
<!--Created with XmlGrid Free Online XML Editor (http://xmlgrid.net)-->
<tr>
  <td>Name</td>
  <td> Age</td>
  <td> Sex</td>
</tr>
<tr>
  <td>Cantor, Georg</td>
  <td> 163</td>
  <td> M</td>
</tr>
</table>

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

Nested ifelse statement

If the data set contains many rows it might be more efficient to join with a lookup table using data.table instead of nested ifelse().

Provided the lookup table below

lookup
     idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

and a sample data set

library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
                 idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
      idnat     idbp
 1:  french   colony
 2:  french   colony
 3:  french overseas
 4: foreign  foreign
 5:  french mainland
 6: foreign  foreign
 7: foreign  foreign
 8:  french overseas
 9:  french overseas
10:  french mainland

then we can do an update while joining:

DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
      idnat     idbp   idnat2
 1:  french   colony overseas
 2:  french   colony overseas
 3:  french overseas overseas
 4: foreign  foreign  foreign
 5:  french mainland mainland
 6: foreign  foreign  foreign
 7: foreign  foreign  foreign
 8:  french overseas overseas
 9:  french overseas overseas
10:  french mainland mainland

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

Add floating point value to android resources/values

Although I've used the accepted answer in the past, it seems with the current Build Tools it is possible to do:

   <dimen name="listAvatarWidthPercent">0.19</dimen>

I'm using Build Tools major version 29.

Database corruption with MariaDB : Table doesn't exist in engine

I've just had this problem with MariaDB/InnoDB and was able to fix it by

  • create the required table in the correct database in another MySQL/MariaDB instance
  • stop both servers
  • copy .ibd, .frm files to original server
  • start both servers
  • drop problem table on both servers

What is the best way to compare 2 folder trees on windows?

You can use git for exactly this purpose. Basically, you create a git repository in folder A (the repo is in A/.git), then copy A/.git to B/.git, then change to B folder and compare simply by running git diff. And the --exclude functionality can be achieved with .gitignore.

So, sticking to your example (but using bash shell on Linux):

# Create a Git repo in current_vss
pushd current_vss
printf ".svn\n*.vspscc\n*.scc" >> .gitignore
git init && git add . && git commit -m 'initial'
popd

# Copy the repo to current_svn and compare
cp -r current_vss/.git* current_svn/
pushd current_svn
git diff

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

this is a sample case, which will make sense I believe!

node('master'){
    stage('stage1'){
    def commit = sh (returnStdout: true, script: '''echo hi
    echo bye | grep -o "e"
    date
    echo lol''').split()


    echo "${commit[-1]} "

    }
}

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

As already mentioned, compiling the app in x64 gives you far more available memory.

But in the case one must build an app in x86, there is a way to raise the memory limit from 1,2GB to 4GB (which is the actual limit for 32 bit processes):

In the VC/bin folder of the Visual Studio installation directory, there must be an editbin.exe file. So in my default installation I find it under

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\editbin.exe

In order to make the program work, maybe you must execute vcvars32.bat in the same directory first. Then a

editbin /LARGEADDRESSAWARE <your compiled exe file>

is enough to let your program use 4GB RAM. <your compiled exe file> is the exe, which VS generated while compiling your project.

If you want to automate this behavior every time you compile your project, use the following Post-Build event for the executed project:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

Sidenote: The same can be done with the devenv.exe to let Visual Studio also use 4GB RAM instead of 1.2GB (but first backup the old devenv.exe).

Does Python have a package/module management system?

Poetry is what you're looking for. It takes care of dependency management, virtual environments, running.

What is the best project structure for a Python application?

Try starting the project using the python_boilerplate template. It largely follows the best practices (e.g. those here), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).

  • Where do you put the source?

    • For decently large projects it makes sense to split the source into several eggs. Each egg would go as a separate setuptools-layout under PROJECT_ROOT/src/<egg_name>.
  • Where do you put application startup scripts?

    • The ideal option is to have application startup script registered as an entry_point in one of the eggs.
  • Where do you put the IDE project cruft?

    • Depends on the IDE. Many of them keep their stuff in PROJECT_ROOT/.<something> in the root of the project, and this is fine.
  • Where do you put the unit/acceptance tests?

    • Each egg has a separate set of tests, kept in its PROJECT_ROOT/src/<egg_name>/tests directory. I personally prefer to use py.test to run them.
  • Where do you put non-Python data such as config files?

    • It depends. There can be different types of non-Python data.
      • "Resources", i.e. data that must be packaged within an egg. This data goes into the corresponding egg directory, somewhere within package namespace. It can be used via the pkg_resources package from setuptools, or since Python 3.7 via the importlib.resources module from the standard library.
      • "Config-files", i.e. non-Python files that are to be regarded as external to the project source files, but have to be initialized with some values when application starts running. During development I prefer to keep such files in PROJECT_ROOT/config. For deployment there can be various options. On Windows one can use %APP_DATA%/<app-name>/config, on Linux, /etc/<app-name> or /opt/<app-name>/config.
      • Generated files, i.e. files that may be created or modified by the application during execution. I would prefer to keep them in PROJECT_ROOT/var during development, and under /var during Linux deployment.
  • Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
    • Into PROJECT_ROOT/src/<egg_name>/native

Documentation would typically go into PROJECT_ROOT/doc or PROJECT_ROOT/src/<egg_name>/doc (this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like PROJECT_ROOT/buildout.cfg and PROJECT_ROOT/setup.cfg.

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
_x000D_
_x000D_

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

How to properly set the 100% DIV height to match document/window height?

I figured it out myself with the help of someone's answer. But he deleted it for some reason.

Here's the solution:

  1. remove all CSS height hacks and 100% heights
  2. Use 2 nested wrappers, one in another, e.g. #wrapper and #truecontent
  3. Get the height of a browser viewport. IF it's larger than #wrapper, then set inline CSS for #wrapper to match the current browser viewport height (while keeping #truecontent intact)
  4. Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact

    $(function(){
        var windowH = $(window).height();
        var wrapperH = $('#wrapper').height();
        if(windowH > wrapperH) {                            
            $('#wrapper').css({'height':($(window).height())+'px'});
        }                                                                               
        $(window).resize(function(){
            var windowH = $(window).height();
            var wrapperH = $('#wrapper').height();
            var differenceH = windowH - wrapperH;
            var newH = wrapperH + differenceH;
            var truecontentH = $('#truecontent').height();
            if(windowH > truecontentH) {
                $('#wrapper').css('height', (newH)+'px');
            }
    
        })          
    });
    

iOS 6 apps - how to deal with iPhone 5 screen size?

@Pascal's comment on the OP's question is right. By simply adding the image, it removes the black borders and the app will use the full height.

You will need to make adjustments to any CGRects by determining that the device is using the bigger display. I.e. If you need something aligned to the bottom of the screen.

I am sure there is a built in method, but I haven't seen anything and a lot is still under NDA so the method we use in our apps is quite simply a global function. Add the following to your .pch file and then its a simple if( is4InchRetina() ) { ... } call to make adjustments to your CGRects etc.

static BOOL is4InchRetina()
{
    if (![UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 548 || [UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 568)
        return YES;

    return NO;
}

Setting width of spreadsheet cell using PHPExcel

setAutoSize method must come before setWidth:

$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');

How do I get the Back Button to work with an AngularJS ui-router state machine?

history.back() and switch to previous state often give effect not that you want. For example, if you have form with tabs and each tab has own state, this just switched previous tab selected, not return from form. In case nested states, you usually need so think about witch of parent states you want to rollback.

This directive solves problem

angular.module('app', ['ui-router-back'])

<span ui-back='defaultState'> Go back </span>

It returns to state, that was active before button has displayed. Optional defaultState is state name that used when no previous state in memory. Also it restores scroll position

Code

class UiBackData {
    fromStateName: string;
    fromParams: any;
    fromStateScroll: number;
}

interface IRootScope1 extends ng.IScope {
    uiBackData: UiBackData;
}

class UiBackDirective implements ng.IDirective {
    uiBackDataSave: UiBackData;

    constructor(private $state: angular.ui.IStateService,
        private $rootScope: IRootScope1,
        private $timeout: ng.ITimeoutService) {
    }

    link: ng.IDirectiveLinkFn = (scope, element, attrs) => {
        this.uiBackDataSave = angular.copy(this.$rootScope.uiBackData);

        function parseStateRef(ref, current) {
            var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
            if (preparsed) ref = current + '(' + preparsed[1] + ')';
            parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
            if (!parsed || parsed.length !== 4)
                throw new Error("Invalid state ref '" + ref + "'");
            let paramExpr = parsed[3] || null;
            let copy = angular.copy(scope.$eval(paramExpr));
            return { state: parsed[1], paramExpr: copy };
        }

        element.on('click', (e) => {
            e.preventDefault();

            if (this.uiBackDataSave.fromStateName)
                this.$state.go(this.uiBackDataSave.fromStateName, this.uiBackDataSave.fromParams)
                    .then(state => {
                        // Override ui-router autoscroll 
                        this.$timeout(() => {
                            $(window).scrollTop(this.uiBackDataSave.fromStateScroll);
                        }, 500, false);
                    });
            else {
                var r = parseStateRef((<any>attrs).uiBack, this.$state.current);
                this.$state.go(r.state, r.paramExpr);
            }
        });
    };

    public static factory(): ng.IDirectiveFactory {
        const directive = ($state, $rootScope, $timeout) =>
            new UiBackDirective($state, $rootScope, $timeout);
        directive.$inject = ['$state', '$rootScope', '$timeout'];
        return directive;
    }
}

angular.module('ui-router-back')
    .directive('uiBack', UiBackDirective.factory())
    .run(['$rootScope',
        ($rootScope: IRootScope1) => {

            $rootScope.$on('$stateChangeSuccess',
                (event, toState, toParams, fromState, fromParams) => {
                    if ($rootScope.uiBackData == null)
                        $rootScope.uiBackData = new UiBackData();
                    $rootScope.uiBackData.fromStateName = fromState.name;
                    $rootScope.uiBackData.fromStateScroll = $(window).scrollTop();
                    $rootScope.uiBackData.fromParams = fromParams;
                });
        }]);

Use a URL to link to a Google map with a marker on it

This URL format worked like a charm:

http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}

Example for Mount Everest:

http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141

Preview

Full reference here:

https://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

-- EDIT --

Apparently the zoom parameter stopped working, here's the updated format.

Format

https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&center={LAT},{LONG}&zoom={ZOOM}

Example

https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&center=27.9879012,86.9253141&zoom=14

Xcode 6: Keyboard does not show up in simulator

Simple way is just Press command + k

Get client IP address via third party web service

    $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This will work https too

How can I convert a string to boolean in JavaScript?

The fastest safe way to convert a string to a boolean in one line of code

One of features that help to fasten the code execution in Javascript is Short-Circuit Evaluation:

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && (anything) is short-circuit evaluated to false.
  • true || (anything) is short-circuit evaluated to true.

So that if you want to test a string value for being true of false in JSON.parse way of test and keep the performance strong, you may use the || operator to exclude the slow code from execution in case the test value is of boolean type.

test === true || ['true','yes','1'].indexOf(test.toString().toLowerCase()) > -1

As the Array.prototype.indexOf() method is a part of ECMA-262 standard in the 5th edition, you may need a polyfill for the old browsers support.

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let O be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of O with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

When do you use varargs in Java?

I use varargs frequently for constructors that can take some sort of filter object. For example, a large part of our system based on Hadoop is based on a Mapper that handles serialization and deserialization of items to JSON, and applies a number of processors that each take an item of content and either modify and return it, or return null to reject.

What are DDL and DML?

DDL: Change the schema

DML: Change the data

Seems specific to MySQL limitations (rails's source code)

How to run bootRun with spring profile via gradle task

Using this shell command it will work:

SPRING_PROFILES_ACTIVE=test gradle clean bootRun

Sadly this is the simplest way I have found. It sets environment property for that call and then runs the app.