Programs & Examples On #Wp list categories

Detect iPhone/iPad purely by css

Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.

Meanwhile, media queries for device-width, device-height, and device-aspect-ratio have been deprecated, so they may not work in future browser versions. (Source: MDN)

TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.

Difficulty with ng-model, ng-repeat, and inputs

The problem seems to be in the way how ng-model works with input and overwrites the name object, making it lost for ng-repeat.

As a workaround, one can use the following code:

<div ng-repeat="name in names">
    Value: {{name}}
    <input ng-model="names[$index]">                         
</div>

Hope it helps

Local storage in Angular 2

Save into LocalStorage:

localStorage.setItem('key', value);

For objects with properties:

localStorage.setItem('key', JSON.stringify(object));

Get From Local Storage:

localStorage.getItem('key');

For objects:

JSON.parse(localStorage.getItem('key'));

localStorage Object will save data as string and retrieve as string. You need to Parse desired output if value is object stored as string. e.g. parseInt(localStorage.getItem('key'));

It is better to use framework provided localStroage instead of 3rd party library localStorageService or anything else because it reduces your project size.

How do I make a simple crawler in PHP?

It's an old question. A lot of good things happened since then. Here are my two cents on this topic:

  1. To accurately track the visited pages you have to normalize URI first. The normalization algorithm includes multiple steps:

    • Sort query parameters. For example, the following URIs are equivalent after normalization: GET http://www.example.com/query?id=111&cat=222 GET http://www.example.com/query?cat=222&id=111
    • Convert the empty path. Example: http://example.org ? http://example.org/

    • Capitalize percent encoding. All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive. Example: http://example.org/a%c2%B1b ? http://example.org/a%C2%B1b

    • Remove unnecessary dot-segments. Example: http://example.org/../a/b/../c/./d.html ? http://example.org/a/c/d.html

    • Possibly some other normalization rules

  2. Not only <a> tag has href attribute, <area> tag has it too https://html.com/tags/area/. If you don't want to miss anything, you have to scrape <area> tag too.

  3. Track crawling progress. If the website is small, it is not a problem. Contrarily it might be very frustrating if you crawl half of the site and it failed. Consider using a database or a filesystem to store the progress.

  4. Be kind to the site owners. If you are ever going to use your crawler outside of your website, you have to use delays. Without delays, the script is too fast and might significantly slow down some small sites. From sysadmins perspective, it looks like a DoS attack. A static delay between the requests will do the trick.

If you don't want to deal with that, try Crawlzone and let me know your feedback. Also, check out the article I wrote a while back https://www.codementor.io/zstate/this-is-how-i-crawl-n98s6myxm

Create Git branch with current changes

To add new changes to a new branch and push to remote:

git branch branch/name
git checkout branch/name
git push origin branch/name

Often times I forget to add the origin part to push and get confused why I don't see the new branch/commit in bitbucket

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

How to identify object types in java

Use value instanceof YourClass

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

There's also another way to do this-

select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;

PHP checkbox set to check based on database value

This simplest ways is to add the "checked attribute.

<label for="tag_1">Tag 1</label>
<input type="checkbox" name="tag_1" id="tag_1" value="yes" 
    <?php if($tag_1_saved_value === 'yes') echo 'checked="checked"';?> />

How to list all the files in a commit?

If you want to get list of changed files:

git diff-tree --no-commit-id --name-only -r <commit-ish>

If you want to get list of all files in a commit, you can use

git ls-tree --name-only -r <commit-ish>

UITableView Cell selected Color?

Table View Cell selection background color can be set via the Storyboard in Interface Builder:

table view cell selection color None

Is there a way to word-wrap long words in a div?

As david mentions, DIVs do wrap words by default.

If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:

thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace

It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.

delete all from table

This is deletes the table table_name.

Replace it with the name of the table, which shall be deleted.

DELETE FROM table_name;

How to convert date to timestamp?

Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:

var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000

How to build a Horizontal ListView with RecyclerView?

With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.

enter image description here

You can download a full working demo from this post

How to delete multiple files at once in Bash on Linux?

A wild card would work nicely for this, although to be safe it would be best to make the use of the wild card as minimal as possible, so something along the lines of this:

rm -rf abc.log.2012-*

Although from the looks of it, are those just single files? The recursive option should not be necessary if none of those items are directories, so best to not use that, just for safety.

How can I render repeating React elements?

You can put expressions inside braces. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(Also: Remember to add key attributes to components rendered inside loops.)

JSX + ES2015:

render() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(title =>
            <th key={title}>{title}</th>
          )}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map((row, i) =>
          <tr key={i}>
            {row.map((col, j) =>
              <td key={j}>{col}</td>
            )}
          </tr>
        )}
      </tbody>
    </table>
  );
} 

JavaScript:

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 

How can I check if a program exists from a Bash script?

Script

#!/bin/bash

# Commands found in the hash table are checked for existence before being
# executed and non-existence forces a normal PATH search.
shopt -s checkhash

function exists() {
 local mycomm=$1; shift || return 1

 hash $mycomm 2>/dev/null || \
 printf "\xe2\x9c\x98 [ABRT]: $mycomm: command does not exist\n"; return 1;
}
readonly -f exists

exists notacmd
exists bash
hash
bash -c 'printf "Fin.\n"'

Result

? [ABRT]: notacmd: command does not exist
hits    command
   0    /usr/bin/bash
Fin.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

How to get CRON to call in the correct PATHs

Make your variables work for you, this will allow access t

Define your PATH in /etc/profile.d/*.sh

System-wide environment variables

Files with the .sh extension in the /etc/profile.d directory get executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads.

You can for instance create the file /etc/profile.d/myenvvars.sh and set variables like this:

export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
export PATH=$PATH:$JAVA_HOME/bin

Execute crontab with login option!

CRONTAB run script or command with Environment Variables

0 9 * * * cd /var/www/vhosts/foo/crons/; bash -l -c 'php -f ./download.php'
0 9 * * * cd /var/www/vhosts/foo/crons/; bash -l -c download.sh

Adding one day to a date

While I agree with Doug Hays' answer, I'll chime in here to say that the reason your code doesn't work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)

If you turn on max error reporting you'll see this as a "A non well formed numeric value" error which is E_NOTICE level.

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

How to animate the change of image in an UIImageView?

Why not try this.

NSArray *animationFrames = [NSArray arrayWithObjects:
  [UIImage imageWithName:@"image1.png"],
  [UIImage imageWithName:@"image2.png"], 
  nil];

UIImageView *animatedImageView = [[UIImageView alloc] init];
animatedImageView.animationImages = animationsFrame;
[animatedImageView setAnimationRepeatCount:1];
[animatedImageView startAnimating];

A swift version:

let animationsFrames = [UIImage(named: "image1.png"), UIImage(named: "image2.png")]
let animatedImageView = UIImageView()
animatedImageView.animationImages = animationsFrames
animatedImageView.animationRepeatCount = 1
animatedImageView.startAnimating()

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.

Select <a> which href ends with some string

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

They are the same thing. If you use the set transaction isolation level statement, it will apply to all the tables in the connection, so if you only want a nolock on one or two tables use that; otherwise use the other.

Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider snapshot or serializable hints instead.

OnClick vs OnClientClick for an asp:CheckBox?

Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:

C#:

    private void Page_Load(object sender, EventArgs e)
    {
        SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
    }

Note: Ensure you don't set AutoEventWireup="false" in page header.

VB:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
    End Sub

Add space between two particular <td>s

The simplest way:

td:nth-child(2) {
    padding-right: 20px;
}?

But that won't work if you need to work with background color or images in your table. In that case, here is a slightly more advanced solution (CSS3):

td:nth-child(2) {
    border-right: 10px solid transparent;
    -webkit-background-clip: padding;
    -moz-background-clip: padding;
    background-clip: padding-box;
}

It places a transparent border to the right of the cell and pulls the background color/image away from the border, creating the illusion of spacing between the cells.

Note: For this to work, the parent table must have border-collapse: separate. If you have to work with border-collapse: collapse then you have to apply the same border style to the next table cell, but on the left side, to accomplish the same results.

Fixed header, footer with scrollable content

Something like this

<html>
  <body style="height:100%; width:100%">
    <div id="header" style="position:absolute; top:0px; left:0px; height:200px; right:0px;overflow:hidden;"> 
    </div> 
    <div id="content" style="position:absolute; top:200px; bottom:200px; left:0px; right:0px; overflow:auto;"> 
    </div> 
    <div id="footer" style="position:absolute; bottom:0px; height:200px; left:0px; right:0px; overflow:hidden;"> 
    </div>
  </body>
</html> 

mysqldump data only

Try to dump to a delimited file.

mysqldump -u [username] -p -t -T/path/to/directory [database] --fields-enclosed-by=\" --fields-terminated-by=,

Difference between return 1, return 0, return -1 and exit?

return in function return execution back to caller and exit from function terminates the program.

in main function return 0 or exit(0) are same but if you write exit(0) in different function then you program will exit from that position.

returning different values like return 1 or return -1 means that program is returning error .

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

Modifying a query string without reloading the page

Then the history API is exactly what you are looking for. If you wish to support legacy browsers as well, then look for a library that falls back on manipulating the URL's hash tag if the browser doesn't provide the history API.

Python SQL query string formatting

I would suggest sticking to option 2 (I'm always using it for queries any more complex than SELECT * FROM table) and if you want to print it in a nice way you may always use a separate module.

How can I undo git reset --hard HEAD~1?

What you want to do is to specify the sha1 of the commit you want to restore to. You can get the sha1 by examining the reflog (git reflog) and then doing

git reset --hard <sha1 of desired commit>

But don't wait too long... after a few weeks git will eventually see that commit as unreferenced and delete all the blobs.

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

Because python checks in the directories in sequential order starting at the first directory in sys.path list, till it find the .py file it was looking for.

Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So, most probably, you had a .py file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).

Also, a thing to note about ImportErrors , lets say the import error says - ImportError: No module named main - it doesn't mean the main.py is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py or some other file.

Example -

My directory structure looks like -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py

Now From testmain.py , I call from shared import phtest , it works fine.

Now lets say I introduce a shared.py in test directory` , example -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py 
  - shared.py

Now when I try to do from shared import phtest from testmain.py , I will get the error -

ImportError: cannot import name 'phtest'

As you can see above, the file that is causing the issue is shared.py , not phtest.py .

Remove characters from a String in Java

This will safely remove only if token is at end of string.

StringUtils.removeEnd(string, ".xml");

Apache StringUtils functions are null-, empty-, and no match- safe

Can we open pdf file using UIWebView on iOS?

Swift version:

if let docPath = NSBundle.mainBundle().pathForResource("sample", ofType: "pdf") {
    let docURL = NSURL(fileURLWithPath: docPath)
    webView.loadRequest(NSURLRequest(URL: docURL))
}

Referencing system.management.automation.dll in Visual Studio

if it is 64bit them - C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell**3.0**

and version could be different

Google Chrome Printing Page Breaks

Beware of CSS : display:inline-block when printing.

None of the CCS property to go to next page would work for me in Chrome and Firefox if my table was inside a div with the style display:inline-block

For example, the following doesn't work :

<div style='display:inline-block'>
  <table style='page-break-before:always'>
    ...
  </table>
  <table style='page-break-before:always'>
    ...
  </table>
</div>

But the following work :

<div>
  <table style='page-break-before:always'>
    ...
  </table>
  <table style='page-break-before:always'>
    ...
  </table>
</div>

How can I easily view the contents of a datatable or dataview in the immediate window

Give Xml Visualizer a try. Haven't tried the latest version yet, but I can't work without the previous one in Visual Studio 2003.

on top of displaying DataSet hierarchically, there are also a lot of other handy features such as filtering and selecting the RowState which you want to view.

Catch an exception thrown by an async void method

Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.

The code below does the following:

  • Create 4 tasks
  • Each task will asynchronously increment a number and return the incremented number
  • When the async result has arrived it is traced.

 

static TypeHashes _type = new TypeHashes(typeof(Program));        
private void Run()
{
    TracerConfig.Reset("debugoutput");

    using (Tracer t = new Tracer(_type, "Run"))
    {
        for (int i = 0; i < 4; i++)
        {
            DoSomeThingAsync(i);
        }
    }
    Application.Run();  // Start window message pump to prevent termination
}


private async void DoSomeThingAsync(int i)
{
    using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
    {
        t.Info("Hi in DoSomething {0}",i);
        try
        {
            int result = await Calculate(i);
            t.Info("Got async result: {0}", result);
        }
        catch (ArgumentException ex)
        {
            t.Error("Got argument exception: {0}", ex);
        }
    }
}

Task<int> Calculate(int i)
{
    var t = new Task<int>(() =>
    {
        using (Tracer t2 = new Tracer(_type, "Calculate"))
        {
            if( i % 2 == 0 )
                throw new ArgumentException(String.Format("Even argument {0}", i));
            return i++;
        }
    });
    t.Start();
    return t;
}

When you observe the traces

22:25:12.649  02172/02820 {          AsyncTest.Program.Run 
22:25:12.656  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.657  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0    
22:25:12.658  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.659  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.659  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1    
22:25:12.660  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3    
22:25:12.664  02172/02756          } AsyncTest.Program.Calculate Duration 4ms   
22:25:12.666  02172/02820          } AsyncTest.Program.Run Duration 17ms  ---- Run has completed. The async methods are now scheduled on different threads. 
22:25:12.667  02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1    
22:25:12.667  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 8ms    
22:25:12.667  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.665  02172/05220 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.668  02172/02756 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.724  02172/05220          } AsyncTest.Program.Calculate Duration 66ms      
22:25:12.724  02172/02756          } AsyncTest.Program.Calculate Duration 57ms      
22:25:12.725  02172/05220 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106    
22:25:12.725  02172/02756 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0      
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 70ms   
22:25:12.726  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   
22:25:12.726  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.726  02172/05220          } AsyncTest.Program.Calculate Duration 0ms   
22:25:12.726  02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3    
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   

You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.

The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.

Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.


You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I had the same issue with Xcode... black screen on launching apps, no debugging and clicking would lock up Xcode.

I finally found the problem... following the lead that the simulator could not connect to Xcode I took a look at my etc/hosts file and found that months ago to solve a different issue I had edited the host file to map localhost to my fixed IP instead of the default... my value:

10.0.1.17 localhost

This should work since that is my IP, but changing it back to the default IP fixed Xcode...

127.0.0.1 localhost

Hope this helps.

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

How do I clone a Django model instance object and save it to the database?

I've run into a couple gotchas with the accepted answer. Here is my solution.

import copy

def clone(instance):
    cloned = copy.copy(instance) # don't alter original instance
    cloned.pk = None
    try:
        delattr(cloned, '_prefetched_objects_cache')
    except AttributeError:
        pass
    return cloned

Note: this uses solutions that aren't officially sanctioned in the Django docs, and they may cease to work in future versions. I tested this in 1.9.13.

The first improvement is that it allows you to continue using the original instance, by using copy.copy. Even if you don't intend to reuse the instance, it can be safer to do this step if the instance you're cloning was passed as an argument to a function. If not, the caller will unexpectedly have a different instance when the function returns.

copy.copy seems to produce a shallow copy of a Django model instance in the desired way. This is one of the things I did not find documented, but it works by pickling and unpickling, so it's probably well-supported.

Secondly, the approved answer will leave any prefetched results attached to the new instance. Those results shouldn't be associated with the new instance, unless you explicitly copy the to-many relationships. If you traverse the the prefetched relationships, you will get results that don't match the database. Breaking working code when you add a prefetch can be a nasty surprise.

Deleting _prefetched_objects_cache is a quick-and-dirty way to strip away all prefetches. Subsequent to-many accesses work as if there never was a prefetch. Using an undocumented property that begins with an underscore is probably asking for compatibility trouble, but it works for now.

Using grep and sed to find and replace a string

Not sure if this will be helpful but you can use this with a remote server like the example below

ssh example.server.com "find /DIR_NAME -type f -name "FILES_LOOKING_FOR" -exec sed -i 's/LOOKINGFOR/withThisString/g' {} ;"

replace the example.server.com with your server replace DIR_NAME with your directory/file locations replace FILES_LOOKING_FOR with files you are looking for replace LOOKINGFOR with what you are looking for replace withThisString with what your want to be replaced in the file

Async/Await Class Constructor

You may immediately invoke an anonymous async function that returns message and set it to the message variable. You might want to take a look at immediately invoked function expressions (IEFES), in case you are unfamiliar with this pattern. This will work like a charm.

var message = (async function() { return await grabUID(uid) })()

How can I insert new line/carriage returns into an element.textContent?

You could use regular expressions to replace the '\n' or '\n\r' characters with '<br />'.

you have this:

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

you can replace your characters like this:

h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');

check the javascript reference for the String and Regex objects:

http://www.w3schools.com/jsref/jsref_replace.asp

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Just Add:

android:screenOrientation="portrait"

in "AndroidManifest.xml" :

<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="@string/app_name">
</activity>

Two inline-block, width 50% elements wrap to second line

I continued to have this problem in ie7 when the browser was at certain widths. Turns out older browsers round the pixel value up if the percentage result isn't a whole number. To solve this you can try setting

overflow: hidden;

on the last element (or all of them).

What is copy-on-write?

It's also used in Ruby 'Enterprise Edition' as a neat way of saving memory.

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

I still had the issue above after installing postgresql using homebrew - I resolved it by putting /usr/local/bin in my path before /usr/bin

How do I fix PyDev "Undefined variable from import" errors?

For code in your project, the only way is adding a declaration saying that you expected that -- possibly protected by an if False so that it doesn't execute (the static code-analysis only sees what you see, not runtime info -- if you opened that module yourself, you'd have no indication that main was expected).

To overcome this there are some choices:

  1. If it is some external module, it's possible to add it to the forced builtins so that PyDev spawns a shell for it to obtain runtime information (see http://pydev.org/manual_101_interpreter.html for details) -- i.e.: mostly, PyDev will import the module in a shell and do a dir(module) and dir on the classes found in the module to present completions and make code analysis.

  2. You can use Ctrl+1 (Cmd+1 for Mac) in a line with an error and PyDev will present you an option to add a comment to ignore that error.

  3. It's possible to create a stub module and add it to the predefined completions (http://pydev.org/manual_101_interpreter.html also has details on that).

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. I don't have any examples that I've done personally available right now. I'll post later when I find some. Basically you'll use reflection to load the assembly and then to pull whatever types you need for it.

In the meantime, this link should get you started:

Using reflection to load unreferenced assemblies at runtime

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)

but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

jQuery: value.attr is not a function

You are dealing with the raw DOM element .. need to wrap it in a jquery object

console.info("cat_id: ",$(value).attr('cat_id'));

How to delete the last row of data of a pandas dataframe

Since index positioning in Python is 0-based, there won't actually be an element in index at the location corresponding to len(DF). You need that to be last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

However, it's much simpler to just write DF[:-1].

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "

How to throw a C++ exception

You could define a message to throw when a certain error occurs:

throw std::invalid_argument( "received negative value" );

or you could define it like this:

std::runtime_error greatScott("Great Scott!");          
double getEnergySync(int year) {                        
    if (year == 1955 || year == 1885) throw greatScott; 
    return 1.21e9;                                      
}                                                       

Typically, you would have a try ... catch block like this:

try {
// do something that causes an exception
}catch (std::exception& e){ std::cerr << "exception: " << e.what() << std::endl; }

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:

package test;

public class Demo {

    public Demo() {
        System.out.println("Hi!");
    }

    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("test.Demo");
        Demo demo = (Demo) clazz.newInstance();
    }
}

As explained in its javadoc, calling Class.forName(String) returns the Class object associated with the class or interface with the given string name i.e. it returns test.Demo.class which is affected to the clazz variable of type Class.

Then, calling clazz.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. In other words, this is here actually equivalent to a new Demo() and returns a new instance of Demo.

And running this Demo class thus prints the following output:

Hi!

The big difference with the traditional new is that newInstance allows to instantiate a class that you don't know until runtime, making your code more dynamic.

A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples: they use dynamic runtime loading to load and create components they don't know anything before the runtime.

Actually, if you want to go further, have a look at Ted Neward paper Understanding Class.forName() that I was paraphrasing in the paragraph just above.

EDIT (answering a question from the OP posted as comment): The case of JDBC drivers is a bit special. As explained in the DriverManager chapter of Getting Started with the JDBC API:

(...) A Driver class is loaded, and therefore automatically registered with the DriverManager, in one of two ways:

  1. by calling the method Class.forName. This explicitly loads the driver class. Since it does not depend on any external setup, this way of loading a driver is the recommended one for using the DriverManager framework. The following code loads the class acme.db.Driver:

    Class.forName("acme.db.Driver");
    

    If acme.db.Driver has been written so that loading it causes an instance to be created and also calls DriverManager.registerDriver with that instance as the parameter (as it should do), then it is in the DriverManager's list of drivers and available for creating a connection.

  2. (...)

In both of these cases, it is the responsibility of the newly-loaded Driver class to register itself by calling DriverManager.registerDriver. As mentioned, this should be done automatically when the class is loaded.

To register themselves during initialization, JDBC driver typically use a static initialization block like this:

package acme.db;

public class Driver {

    static {
        java.sql.DriverManager.registerDriver(new Driver());
    }

    ...
}

Calling Class.forName("acme.db.Driver") causes the initialization of the acme.db.Driver class and thus the execution of the static initialization block. And Class.forName("acme.db.Driver") will indeed "create" an instance but this is just a consequence of how (good) JDBC Driver are implemented.

As a side note, I'd mention that all this is not required anymore with JDBC 4.0(added as a default package since Java 7) and the new auto-loading feature of JDBC 4.0 drivers. See JDBC 4.0 enhancements in Java SE 6.

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How do I pass named parameters with Invoke-Command?

-ArgumentList is based on use with scriptblock commands, like:

Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True

When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).

So, you have two options:

If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):

param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."

Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:

icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true

In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:

icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:

$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script

If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:

Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    & $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)

Python JSON encoding

I think you are simply exchanging dumps and loads.

>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]

The first returns as a (JSON encoded) string its data argument:

>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:

>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True

How to draw a filled triangle in android canvas?

You need remove path.moveTo after first initial.

Path path = new Path();
path.moveTo(point1_returned.x, point1_returned.y);
path.lineTo(point2_returned.x, point2_returned.y);
path.lineTo(point3_returned.x, point3_returned.y);
path.lineTo(point1_returned.x, point1_returned.y);
path.close();

Sort divs in jQuery based on attribute 'data-sort'?

Answered the same question here:

To repost:

After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

$('.item');
[<div class="item" data-order="2">2</div>,
 <div class="item" data-order="1">1</div>,
 <div class="item" data-order="4">4</div>,
 <div class="item" data-order="3">3</div>
]

Lets sort this by data-order

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
 <div class="item" data-order="2">2</div>,
 <div class="item" data-order="3">3</div>,
 <div class="item" data-order="4">4</div>
]

See how getSorted() works.

Hope this helps!

Regex to validate JSON

I realize that this is from over 6 years ago. However, I think there is a solution that nobody here has mentioned that is way easier than regexing

function isAJSON(string) {
    try {
        JSON.parse(string)  
    } catch(e) {
        if(e instanceof SyntaxError) return false;
    };  
    return true;
}

jQuery - Appending a div to body, the body is the object?

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');

Add image to left of text via css

This works great

.create:before{
    content: "";
    display: block;
    background: url('somewhere.jpg') no-repeat;
    width: 25px;
    height: 25px;
    float: left;
}

Oracle: how to set user password unexpire?

The following statement causes a user's password to expire:

ALTER USER user PASSWORD EXPIRE;

If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.

ALTER USER scott IDENTIFIED BY password;

Will set/reset the users password.

See the alter user doc for more info

Sequence contains no elements?

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();

Limit String Length

From php 4.0.6 , there is a function for the exact same thing

function mb_strimwidth can be used for your requirement

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>

It does have more options though,here is the documentation for this mb_strimwidth

How can I export Excel files using JavaScript?

To answer your question with a working example:

<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = new Array();

        for (var index in array[i]) {
           line.push('"' + array[i][index] + '"');
        }

        str += line.join(';');
        str += '\r\n';
    }
    window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>

Best way to strip punctuation from a string

Not necessarily simpler, but a different way, if you are more familiar with the re family.

import re, string
s = "string. With. Punctuation?" # Sample string 
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

How to retrieve all keys (or values) from a std::map and put them into a vector?

With the structured binding (“destructuring”) declaration syntax of C++17,

you can do this, which is easier to understand.

// To get the keys
std::map<int, double> map;
std::vector<int> keys;
keys.reserve(map.size());
for(const auto& [key, value] : map) {
    keys.push_back(key);
}
// To get the values
std::map<int, double> map;
std::vector<double> values;
values.reserve(map.size());
for(const auto& [key, value] : map) {
    values.push_back(value);
}

How to use glOrtho() in OpenGL?

glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:

OpenGL documentation (my bold)

The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).

The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:

Parallel projections have lines of projection that are parallel both in reality and in the projection plane.

Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".

What is the purpose of the return statement?

This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.

In line number 4:

def ret(n):
    if n > 9:
         temp = "two digits"
         return temp     #Line 4        
    else:
         temp = "one digit"
         return temp     #Line 8
    print("return statement")
ret(10)

After the conditional statement gets executed the ret() function gets terminated due to return temp (line 4). Thus the print("return statement") does not get executed.

Output:

two digits   

This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.

Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.

To bring out the difference between print and return:

def ret(n):
    if n > 9:
        print("two digits")
        return "two digits"           
    else :
        print("one digit")
        return "one digit"        
ret(25)

Output:

two digits
'two digits'

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

Excel - Combine multiple columns into one column

You can combine the columns without using macros. Type the following function in the formula bar:

=IF(ROW()<=COUNTA(A:A),INDEX(A:A,ROW()),IF(ROW()<=COUNTA(A:B),INDEX(B:B,ROW()-COUNTA(A:A)),IF(ROW()>COUNTA(A:C),"",INDEX(C:C,ROW()-COUNTA(A:B)))))

The statement uses 3 IF functions, because it needs to combine 3 columns:

  • For column A, the function compares the row number of a cell with the total number of cells in A column that are not empty. If the result is true, the function returns the value of the cell from column A that is at row(). If the result is false, the function moves on to the next IF statement.
  • For column B, the function compares the row number of a cell with the total number of cells in A:B range that are not empty. If the result is true, the function returns the value of the first cell that is not empty in column B. If false, the function moves on to the next IF statement.
  • For column C, the function compares the row number of a cell with the total number of cells in A:C range that are not empty. If the result is true, the function returns a blank cell and doesn't do any more calculation. If false, the function returns the value of the first cell that is not empty in column C.

The project type is not supported by this installation

As a addition to this, 'the project type is not supported by this installation' can occur if you're trying to open a project on a computer which does not contain the framework version that is targeted.

In my case I was trying to open a class library which was created on a machine with VS2012 and had defaulted the targeted framework to 4.5. Since I knew this library wasn't using any 4.5 bits, I resolved the issue by editing the .csproj file from <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> to <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> (or whatever is appropriate for your project) and the library opened.

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

OpenSuse

"sudo zypper install libxml2-devel"

It will install any other dependencies or required packages/libraries

Convert a string to an enum in C#

You're looking for Enum.Parse.

SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");

Git add and commit in one command

I use the following alias for add all and commit:

git config --global alias.ac '!git add -A && git commit -a'

Then, by typing:

git ac

I get a vim window to get more editing tools for my commit message.

CSS Input with width: 100% goes outside parent's bound

Do you want the input fields to be centered? A trick to center elements: specify the width of the element and set the margin to auto, eg:

margin : 0px auto;
width:300px

A link to your updated fiddle:

http://jsfiddle.net/4x2KP/5/

curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

C# Form.Close vs Form.Dispose

Close() - managed resource can be temporarily closed and can be opened once again.

Dispose() - permanently removes managed or not managed resource

How to count certain elements in array?

2017: If someone is still interested in the question, my solution is the following:

_x000D_
_x000D_
const arrayToCount = [1, 2, 3, 5, 2, 8, 9, 2];_x000D_
const result = arrayToCount.filter(i => i === 2).length;_x000D_
console.log('number of the found elements: ' + result);
_x000D_
_x000D_
_x000D_

Call parent method from child class c#

One way to do this would be to pass the instance of ParentClass to the ChildClass on construction

public ChildClass
{
    private ParentClass parent;

    public ChildClass(ParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Make sure to pass the reference to this when constructing ChildClass inside parent:

if(loadData){

     ChildClass childClass = new ChildClass(this); // here

     childClass.LoadData(this.Datatable);

}

Caveat: This is probably not the best way to organise your classes, but it directly answers your question.

EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass. This is possible with the introduction of an interface, eg:

public interface IParentClass
{
    void UpdateProgressBar();
    int CurrentRow{get; set;}
}

Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:

public ChildClass
{
    private IParentClass parent;

    public ChildClass(IParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Now anything that implements IParentClass can construct an instance of ChildClass and pass this to its constructor.

Excel compare two columns and highlight duplicates

The easiest way to do it, at least for me, is:

Conditional format-> Add new rule->Set your own formula:

=ISNA(MATCH(A2;$B:$B;0))

Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.

Once you have set the formula and picked the format, apply this rule to all elements in the column.

Hope this helps

Datatable vs Dataset

There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.

Visual Studio can't build due to rc.exe

In my case, I installed the Windows SDK 10586 via Visual Studio 2015 -> Modify, then the following paths are installed.

C:\Program Files (x86)\Windows Kits\10\bin\arm64\rc.exe

C:\Program Files (x86)\Windows Kits\10\bin\x64\rc.exe

C:\Program Files (x86)\Windows Kits\10\bin\x86\rc.exe

Grouping functions (tapply, by, aggregate) and the *apply family

I recently discovered the rather useful sweep function and add it here for the sake of completeness:

sweep

The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):

Let's say you have a matrix and want to standardize it column-wise:

dataPoints <- matrix(4:15, nrow = 4)

# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)

# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)

# Center the points 
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")

# Return the result
dataPoints_Trans1
##      [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,]  0.5  0.5  0.5
## [4,]  1.5  1.5  1.5

# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")

# Return the result
dataPoints_Trans2
##            [,1]       [,2]       [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,]  0.3872983  0.3872983  0.3872983
## [4,]  1.1618950  1.1618950  1.1618950

NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)

How to create a byte array in C++?

Byte is not a standard data type in C/C++ but it can still be used the way i suppose you want it. Here is how: Recall that a byte is an eight bit memory size which can represent any of the integers between -128 and 127, inclusive. (There are 256 integers in that range; eight bits can represent 256 -- two raised to the power eight -- different values.). Also recall that a char in C/C++ is one byte (eight bits). So, all you need to do to have a byte data type in C/C++ is to put this code at the top of your source file: #define byte char So you can now declare byte abc[3];

JavaScript: How do I print a message to the error console?

The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).

Pie chart with jQuery

A few others that have not been mentioned:

For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.

I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.

Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.

Not what I was after, but another commercial product (much like Highcharts) is TeeChart.

Getting the Username from the HKEY_USERS values

In the HKEY_USERS\oneyouwanttoknow\ you can look at \Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders and it will reveal their profile paths. c:\users\whothisis\Desktop, etc.

Adding iOS UITableView HeaderView (not section header)

You can do it pretty easy in Interface Builder. Just create a view with a table and drop another view onto the table. This will become the table header view. Add your labels and image to that view. See the pic below for the view hierarchy. View Hierarchy in Interface Builder

Clearing localStorage in javascript?

This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.

const allKeys = Object.keys(localStorage);

const toBeDeleted = allKeys.filter(value => {
  return !this.doNotDeleteList.includes(value);
});

toBeDeleted.forEach(value => {
  localStorage.removeItem(value);
});

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

I've only seen the parsing error when the android version on the device was lower than the version the app was compiled for. For example if the app is compiled for android OS v2.2 and your device only has android OS v2.1 you'd get a parse error when you try to install the app.

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.

#!/bin/bash

declare -A flags
declare -A booleans
args=()

while [ "$1" ];
do
    arg=$1
    if [ "${1:0:1}" == "-" ]
    then
      shift
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
      then
        bool=$(echo ${arg:1} | sed s/://g)
        booleans[$bool]=true
        echo \"$bool\" is boolean
      else
        value=$1
        flags[${arg:1}]=$value
        shift
        echo \"$arg\" is flag with value \"$value\"
      fi
    else
      args+=("$arg")
      shift
      echo \"$arg\" is an arg
    fi
done


echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command:

bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean


booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}
)

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

Find a pair of elements from an array whose sum equals a given number

Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:

def find_sum(arr,sum)
 result ={}
 h = Hash[arr.map {|i| [i,i]}]
 arr.each { |l| result[l] = sum-l  if h[sum-l] && !result[sum-l]  }
 result
end

To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l] instruction

Angular 5 - Copy to clipboard

Copy using angular cdk,

Module.ts

import {ClipboardModule} from '@angular/cdk/clipboard';

Programmatically copy a string: MyComponent.ts,

class MyComponent {
  constructor(private clipboard: Clipboard) {}

  copyHeroName() {
    this.clipboard.copy('Alphonso');
  }
}

Click an element to copy via HTML:

<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="2">Copy text</button>

Reference: https://material.angular.io/cdk/clipboard/overview

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
        if(bitmap!=null){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }

What Does 'zoom' do in CSS?

Zoom is not included in the CSS specification, but it is supported in IE, Safari 4, Chrome (and you can get a somewhat similar effect in Firefox with -moz-transform: scale(x) since 3.5). See here.

So, all browsers

 zoom: 2;
 zoom: 200%;

will zoom your object in by 2, so it's like doubling the size. Which means if you have

a:hover {
   zoom: 2;
}

On hover, the <a> tag will zoom by 200%.

Like I say, in FireFox 3.5+ use -moz-transform: scale(x), it does much the same thing.

Edit: In response to the comment from thirtydot, I will say that scale() is not a complete replacement. It does not expand in line like zoom does, rather it will expand out of the box and over content, not forcing other content out of the way. See this in action here. Furthermore, it seems that zoom is not supported in Opera.

This post gives a useful insight into ways to work around incompatibilities with scale and workarounds for it using jQuery.

Why did I get the compile error "Use of unassigned local variable"?

The following categories of variables are classified as initially unassigned:

  • Instance variables of initially unassigned struct variables.
  • Output parameters, including the this variable of struct instance constructors.
  • Local variables , except those declared in a catch clause or a foreach statement.

The following categories of variables are classified as initially assigned:

  • Static variables.
  • Instance variables of class instances.
  • Instance variables of initially assigned struct variables.
  • Array elements.
  • Value parameters.
  • Reference parameters.
  • Variables declared in a catch clause or a foreach statement.

Find the most frequent number in a NumPy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1

Github Windows 'Failed to sync this branch'

I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status command Git Shell suggested to push changes as

Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

I did the same as Git Shell suggested (git push) and everything is ok now.

Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.

fatal: Not a git repository (or any of the parent directories):

For example if your Project is in D drive in some folder you have to do something like below as you do in cmd to change directory.

cd D:\someFolder     // if your project is not deep in `D`

And if its within nested folder in D

cd D:\somefolder\someNestedFolder\nestedInNested     // if your project is not deep in `D`

If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.

Cannot use a leading ../ to exit above the top directory

You have an image or a favicon link of the style ="../" somewhere, that if the "../" were valid, would go beyond the top of the site, like this:

Image:

http://example.com/Images/test.jpg

Page

http://example.com/Pages/test.aspx

Valid on that page: ../Images/test.jpg
Would throw an error: ../../Images/test.jpg

Parse JSON in JavaScript?

JSON.parse() converts any JSON String passed into the function, to a JSON object.

For better understanding, press F12 to open the Inspect Element of your browser, and go to the console to write the following commands:

var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a JSON object.

Now run the command:

console.log(JSON.parse(response));

You'll get output as Object {result: true, count: 1}.

In order to use that object, you can assign it to the variable, let's say obj:

var obj = JSON.parse(response);

Now by using obj and the dot(.) operator you can access properties of the JSON Object.

Try to run the command

console.log(obj.result);

SQL Inner-join with 3 tables?

You can do the following (I guessed on table fields,etc)

SELECT s.studentname
    , s.studentid
    , s.studentdesc
    , h.hallname
FROM students s
INNER JOIN hallprefs hp
    on s.studentid = hp.studentid
INNER JOIN halls h
    on hp.hallid = h.hallid

Based on your request for multiple halls you could do it this way. You just join on your Hall table multiple times for each room pref id:

SELECT     s.StudentID
    , s.FName
    , s.LName
    , s.Gender
    , s.BirthDate
    , s.Email
    , r.HallPref1
    , h1.hallName as Pref1HallName
    , r.HallPref2 
    , h2.hallName as Pref2HallName
    , r.HallPref3
    , h3.hallName as Pref3HallName
FROM  dbo.StudentSignUp AS s 
INNER JOIN RoomSignUp.dbo.Incoming_Applications_Current AS r 
    ON s.StudentID = r.StudentID 
INNER JOIN HallData.dbo.Halls AS h1 
    ON r.HallPref1 = h1.HallID
INNER JOIN HallData.dbo.Halls AS h2
    ON r.HallPref2 = h2.HallID
INNER JOIN HallData.dbo.Halls AS h3
    ON r.HallPref3 = h3.HallID

Hibernate Criteria Query to get specific columns

You can use multiselect function for this.

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            

This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

Difference between two dates in MySQL

select 
unix_timestamp('2007-12-30 00:00:00') - 
unix_timestamp('2007-11-30 00:00:00');

Expression must have class type

a is a pointer. You need to use->, not .

How to get the instance id from within an ec2 instance?

For .NET People :

string instanceId = new StreamReader(
      HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
      .GetResponse().GetResponseStream())
    .ReadToEnd();

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

Typescript: Type 'string | undefined' is not assignable to type 'string'

if you want to have nullable property change your interface to this:

interface Person {
  name?:string | null,
  age?:string | null,
  gender?:string | null,
  occupation?:string | null,
 }

if being undefined is not the case you can remove question marks (?) from in front of the property names.

iPhone SDK on Windows (alternative solutions)

I looked into this before buying a Mac Mini. The answer is, essentially, no. You pretty much have to buy a Leopard Mac to do iPhone SDK development for apps that run on non-jailbroken iPhones.

Not that it's 100% impossible, but it's 99.99% unreasonable. Like changing light bulbs with your feet.

Not only do you have to be in Xcode, but you have to get certificates into the Keychain manager to be able to have Xcode and the iPhone communicate. And you have to set all kinds of setting in Xcode just right.

The way to check a HDFS directory's size?

Extending to Matt D and others answers, the command can be till Apache Hadoop 3.0.0

hadoop fs -du [-s] [-h] [-v] [-x] URI [URI ...]

It displays sizes of files and directories contained in the given directory or the length of a file in case it's just a file.

Options:

  • The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, the calculation is done by going 1-level deep from the given path.
  • The -h option will format file sizes in a human-readable fashion (e.g 64.0m instead of 67108864)
  • The -v option will display the names of columns as a header line.
  • The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.

du returns three columns with the following format:

 +-------------------------------------------------------------------+ 
 | size  |  disk_space_consumed_with_all_replicas  |  full_path_name | 
 +-------------------------------------------------------------------+ 

##Example command:

hadoop fs -du /user/hadoop/dir1 \
    /user/hadoop/file1 \
    hdfs://nn.example.com/user/hadoop/dir1 

Exit Code: Returns 0 on success and -1 on error.

source: Apache doc

detect key press in python?

As OP mention about raw_input - that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.

This code will detect keys until new line is pressed.

import curses
import os

def main(win):
    win.nodelay(True)
    key=""
    win.clear()                
    win.addstr("Detected key:")
    while 1:          
        try:                 
           key = win.getkey()         
           win.clear()                
           win.addstr("Detected key:")
           win.addstr(str(key)) 
           if key == os.linesep:
              break           
        except Exception as e:
           # No input   
           pass         

curses.wrapper(main)

Calculating how many days are between two dates in DB2?

It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

So your Query will be

select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';

Difference between RUN and CMD in a Dockerfile

RUN - command triggers while we build the docker image.

CMD - command triggers while we launch the created docker image.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

In my case it happened after I converted the whole solution (using an extension called Target Framework Migrator) to 4.6.2 but ended up undoing the changes and going back to 3.5 (solution is versioned by TFS). To solve this, I converted just the problematic project (which was using IIS Express to run) to 4.6.2 and then back to 3.5.

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

All answers here are using gradle but if someone like me ends up here and needs answer for maven:

    <build>
        <sourceDirectory>src/main/kotlin</sourceDirectory>
        <testSourceDirectory>src/test/kotlin</testSourceDirectory>

        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>11</jvmTarget>
                </configuration>
            </plugin>
        </plugins>
    </build>

The change from jetbrains archetype for kotlin-jvm is the <configuration></configuration> specifying the jvmTarget. In my case 11

Split an NSString to access one particular piece

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Char to int conversion in C

Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:

Both the basic source and basic execution character sets shall have the following members:
[...]
the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
[...]
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.

There is no library function to do it for a single char, you would need to build a string first:

int digit_to_int(char d)
{
 char str[2];

 str[0] = d;
 str[1] = '\0';
 return (int) strtol(str, NULL, 10);
}

You could also use the atoi() function to do the conversion, once you have a string, but strtol() is better and safer.

As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Remove cascading from the child entity Transaction, it should be just:

@Entity class Transaction {
    @ManyToOne // no cascading here!
    private Account account;
}

(FetchType.EAGER can be removed as well as it's the default for @ManyToOne)

That's all!

Why? By saying "cascade ALL" on the child entity Transaction you require that every DB operation gets propagated to the parent entity Account. If you then do persist(transaction), persist(account) will be invoked as well.

But only transient (new) entities may be passed to persist (Transaction in this case). The detached (or other non-transient state) ones may not (Account in this case, as it's already in DB).

Therefore you get the exception "detached entity passed to persist". The Account entity is meant! Not the Transaction you call persist on.


You generally don't want to propagate from child to parent. Unfortunately there are many code examples in books (even in good ones) and through the net, which do exactly that. I don't know, why... Perhaps sometimes simply copied over and over without much thinking...

Guess what happens if you call remove(transaction) still having "cascade ALL" in that @ManyToOne? The account (btw, with all other transactions!) will be deleted from the DB as well. But that wasn't your intention, was it?

How to select the row with the maximum value in each group

by is a version of tapply for data frames:

res <- by(group, group$Subject, FUN=function(df) df[which.max(df$pt),])

It returns an object of class by so we convert it to data frame:

do.call(rbind, b)
  Subject pt Event
1       1  5     2
2       2 17     2
3       3  5     2

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

I made exactly what @grepit made.

But I had to made some changes in my Java code:

In Producer and Receiver project I altered:

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("your-host-ip");
factory.setUsername("username-you-created");
factory.setPassword("username-password");

        

Doing that, you are connecting an specific host as the user you have created. It works for me!

Ignore self-signed ssl cert using Jersey Client

Since I am new to stackoverflow and have lesser reputation to comment on others' answers, I am putting the solution suggested by Chris Salij with some modification which worked for me.

            SSLContext ctx = null;
            TrustManager[] trustAllCerts = new X509TrustManager[]{new X509TrustManager(){
                public X509Certificate[] getAcceptedIssuers(){return null;}
                public void checkClientTrusted(X509Certificate[] certs, String authType){}
                public void checkServerTrusted(X509Certificate[] certs, String authType){}
            }};
            try {
                ctx = SSLContext.getInstance("SSL");
                ctx.init(null, trustAllCerts, null);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                LOGGER.info("Error loading ssl context {}", e.getMessage());
            }

            SSLContext.setDefault(ctx);

CakePHP find method with JOIN

Otro example, custom Data Pagination for JOIN

CODE in Controller CakePHP 2.6 is OK:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        'conditions'=>array(
            'Clientes.requiere_senasa'=>1
        ),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

OR Example 2, NOT active conditions:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id',
                    'Clientes.requiere_senasa = 1'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        //'conditions'=>array(
        //    'Clientes.requiere_senasa'=>1
        //),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

Case-insensitive search in Rails model

Find_or_create is now deprecated, you should use an AR Relation instead plus first_or_create, like so:

TombolaEntry.where("lower(name) = ?", self.name.downcase).first_or_create(name: self.name)

This will return the first matched object, or create one for you if none exists.

Getting absolute URLs using ASP.NET Core

If you just want to convert a relative path with optional parameters I created an extension method for IHttpContextAccessor

public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
    var request = httpContextAccessor.HttpContext.Request;

    var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();

    if (parameters != null)
    {
        url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
    }

    return url;
}


private static Dictionary<string, string> ToDictionary(object obj)
{
    var json = JsonConvert.SerializeObject(obj);
    return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}

You can then call the method from your service/view using the injected IHttpContextAccessor

var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });

How to re import an updated package while in Python Interpreter?

In Python 3, the behaviour changes.

>>> import my_stuff

... do something with my_stuff, then later:

>>>> import imp
>>>> imp.reload(my_stuff)

and you get a brand new, reloaded my_stuff.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

About the version of Android SDK Build-tools, the answer is

By default, the Android SDK uses the most recent downloaded version of the Build Tools.

Source

In Eclipse, you can choose a specific version by using the sdk.buildtools property in the project.properties file.

There seems to be no official page explaining all the build tools. Here is what the Android team says about this.

The [build] tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.

Source

Anyway, here is a synthesis of the differences between tools, platform-tools and build-tools:

  • Android SDK Tools
    • Location: $ANDROID_HOME/tools
    • Main tools: ant scripts (to build your APKs) and ddms (for debugging)
  • Android SDK Platform-tools
    • Location: $ANDROID_HOME/platform-tools
    • Main tool: adb (to manage the state of an emulator or an Android device)
  • Android SDK Build-tools
    • Location: $ANDROID_HOME/build-tools/$VERSION/
    • Documentation
    • Main tools: aapt (to generate R.java and unaligned, unsigned APKs), dx (to convert Java bytecode to Dalvik bytecode), and zipalign (to optimize your APKs)

How to define a variable in a Dockerfile?

Late to the party, but if you don't want to expose environment variables, I guess it's easier to do something like this:

RUN echo 1 > /tmp/__var_1
RUN echo `cat /tmp/__var_1`
RUN rm -f /tmp/__var_1

I ended up doing it because we host private npm packages in aws codeartifact:

RUN aws codeartifact get-authorization-token --output text > /tmp/codeartifact.token
RUN npm config set //company-123456.d.codeartifact.us-east-2.amazonaws.com/npm/internal/:_authToken=`cat /tmp/codeartifact.token`
RUN rm -f /tmp/codeartifact.token

And here ARG cannot work and i don't want to use ENV because i don't want to expose this token to anything else

HTTP POST using JSON in Java

For Java 11 you can use new HTTP client:

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

How to compare objects by multiple fields

If you implement the Comparable interface, you'll want to choose one simple property to order by. This is known as natural ordering. Think of it as the default. It's always used when no specific comparator is supplied. Usually this is name, but your use case may call for something different. You are free to use any number of other Comparators you can supply to various collections APIs to override the natural ordering.

Also note that typically if a.compareTo(b) == 0, then a.equals(b) == true. It's ok if not but there are side effects to be aware of. See the excellent javadocs on the Comparable interface and you'll find lots of great information on this.

Change class on mouseover in directive

This is my solution for my scenario:

<div class="btn-group btn-group-justified">
    <a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
        {{ song.name }}
    </a>
    <a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
        {{ match.name }}
    </a>
</div>

default state: enter image description here

on hover: enter image description here

Close Bootstrap Modal

to close bootstrap modal you can pass 'hide' as option to modal method as follow

$('#modal').modal('hide');

Please take a look at working fiddle here

bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation

If none of the above method work, give a id to your close button and trigger click on close button.

Create Windows service from executable

I created the cross-platform Service Manager software a few years back so that I could start PHP and other scripting languages as system services on Windows, Mac, and Linux OSes:

https://github.com/cubiclesoft/service-manager

Service Manager is a set of precompiled binaries that install and manage a system service on the target OS using nearly identical command-line options (source code also available). Each platform does have subtle differences but the core features are mostly normalized.

If the child process dies, Service Manager automatically restarts it.

Processes that are started with Service Manager should periodically watch for two notification files to handle restart and reload requests but they don't necessarily have to do that. Service Manager will force restart the child process if it doesn't respond in a timely fashion to controlled restart/reload requests.

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

If you need a quick fix, simply add this before the line of your import:

// @ts-ignore

How to prevent custom views from losing state across screen orientation changes

To augment other answers - if you have multiple custom compound views with the same ID and they are all being restored with the state of the last view on a configuration change, all you need to do is tell the view to only dispatch save/restore events to itself by overriding a couple of methods.

class MyCompoundView : ViewGroup {

    ...

    override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
        dispatchFreezeSelfOnly(container)
    }

    override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
        dispatchThawSelfOnly(container)
    }
}

For an explanation of what is happening and why this works, see this blog post. Basically your compound view's children's view IDs are shared by each compound view and state restoration gets confused. By only dispatching state for the compound view itself, we prevent their children from getting mixed messages from other compound views.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

Android: How to create a Dialog without a title?

Set the title to empty string using builder.

    Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("");
...
    builder.show();

How to get the path of a running JAR file?

I write in Java 7, and test in Windows 7 with Oracle's runtime, and Ubuntu with the open source runtime. This works perfect for those systems:

The path for the parent directory of any running jar file (assuming the class calling this code is a direct child of the jar archive itself):

try {
    fooDir = new File(this.getClass().getClassLoader().getResource("").toURI());
} catch (URISyntaxException e) {
    //may be sloppy, but don't really need anything here
}
fooDirPath = fooDir.toString(); // converts abstract (absolute) path to a String

So, the path of foo.jar would be:

fooPath = fooDirPath + File.separator + "foo.jar";

Again, this wasn't tested on any Mac or older Windows

How to change the ROOT application?

In Tomcat 7 with these changes, i'm able to access myAPP at / and ROOT at /ROOT

<Context path="" docBase="myAPP"/>
<Context path="ROOT" docBase="ROOT"/>

Add above to the <Host> section in server.xml

Access to ES6 array element index inside for-of loop

For those using objects that are not an Array or even array-like, you can build your own iterable easily so you can still use for of for things like localStorage which really only have a length:

function indexerator(length) {
    var output = new Object();
    var index = 0;
    output[Symbol.iterator] = function() {
        return {next:function() {
            return (index < length) ? {value:index++} : {done:true};
        }};
    };
    return output;
}

Then just feed it a number:

for (let index of indexerator(localStorage.length))
    console.log(localStorage.key(index))

How to apply font anti-alias effects in CSS?

Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:

body { 
    -webkit-font-smoothing: antialiased;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
    background: url('./images/background.png');
    text-align: left;
    margin: auto;

}

Android scale animation on view

Use this method (No need to xml file)

If you want scale to quarter(half x,half y)

view.animate().scaleX(0.5f).scaleY(0.5f)

If you want scale and move to bottom right

view.animate().scaleX(0.5f).scaleY(0.5f)
        .translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())

If you want move to top use (-view.height/4) and for left (-view.width/4)

If you want do something after animation ends use withEndAction(Runnable runnable) function.

You can use some other property like alpha and rotation

Full code

view.animate()
      .scaleX(0.5f).scaleY(0.5f)//scale to quarter(half x,half y)
      .translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())// move to bottom / right
      .alpha(0.5f) // make it less visible
      .rotation(360f) // one round turns
      .setDuration(1000) // all take 1 seconds
      .withEndAction(new Runnable() {
           @Override
           public void run() {
              //animation ended
           }
      });

Get Bitmap attached to ImageView

For those who are looking for Kotlin solution to get Bitmap from ImageView.

var bitmap = (image.drawable as BitmapDrawable).bitmap

PDF Parsing Using Python - extracting formatted and plain texts

You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).

A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!

But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

How do I do a bulk insert in mySQL using node.js

If you want to insert object, use this:

    currentLogs = [
 { socket_id: 'Server', message: 'Socketio online', data: 'Port  3333', logged: '2014-05-14 14:41:11' },
 { socket_id: 'Server', message: 'Waiting for Pi to connect...', data: 'Port: 8082', logged: '2014-05-14 14:41:11' }
];

console.warn(currentLogs.map(logs=>[ logs.socket_id , logs.message , logs.data , logs.logged ]));

The output will be:

[
  [ 'Server', 'Socketio online', 'Port  3333', '2014-05-14 14:41:11' ],
  [
    'Server',
    'Waiting for Pi to connect...',
    'Port: 8082',
    '2014-05-14 14:41:11'
  ]
]

Also, please check the documentation to know more about the map function.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

RGB to hex and hex to RGB

The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.

function RGBtoHex (red, green, blue) {
  red = Math.max(0, Math.min(~~this.red, 255));
  green = Math.max(0, Math.min(~~this.green, 255));
  blue = Math.max(0, Math.min(~~this.blue, 255));

  return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};

The use of left shift '<<' and or '|' operators make this a fun solution too.

Post parameter is always null

Met with a similar problem in ASP.NET Core and another possible cause is ASP.NET binding (silent) failure due to various reasons such as sending null to be bound to a not null property:

{
    "prop1":1139357,
    "prop2":1139356,

    "items":[
        {"key":"15","someprop":34,"notnullprop":null},
        {"key":"16","someprop":34,"notnullprop":null},
        {"key":"22","someprop":34,"notnullprop":null}]
}

On such case there is no exception being thrown and the whole model will be null, even if this happens deep inside the object hierarchy.

Convert String with Dot or Comma as decimal separator to number in JavaScript

This answer accepts some edge cases that others don't:

  • Only thousand separator: 1.000.000 => 1000000
  • Exponentials: 1.000e3 => 1000e3 (1 million)

Run the code snippet to see all the test suite.

const REGEX_UNWANTED_CHARACTERS = /[^\d\-.,]/g
const REGEX_DASHES_EXEPT_BEGINNING = /(?!^)-/g
const REGEX_PERIODS_EXEPT_LAST = /\.(?=.*\.)/g

export function formatNumber(number) {
  // Handle exponentials
  if ((number.match(/e/g) ?? []).length === 1) {
    const numberParts = number.split('e')
    return `${formatNumber(numberParts[0])}e${formatNumber(numberParts[1])}`
  }

  const sanitizedNumber = number
    .replace(REGEX_UNWANTED_CHARACTERS, '')
    .replace(REGEX_DASHES_EXEPT_BEGINING, '')

  // Handle only thousands separator
  if (
    ((sanitizedNumber.match(/,/g) ?? []).length >= 2 && !sanitizedNumber.includes('.')) ||
    ((sanitizedNumber.match(/\./g) ?? []).length >= 2 && !sanitizedNumber.includes(','))
  ) {
    return sanitizedNumber.replace(/[.,]/g, '')
  }

  return sanitizedNumber.replace(/,/g, '.').replace(REGEX_PERIODS_EXEPT_LAST, '')
}

function formatNumberToNumber(number) {
  return Number(formatNumber(number))
}

_x000D_
_x000D_
const REGEX_UNWANTED_CHARACTERS = /[^\d\-.,]/g
const REGEX_DASHES_EXEPT_BEGINING = /(?!^)-/g
const REGEX_PERIODS_EXEPT_LAST = /\.(?=.*\.)/g

function formatNumber(number) {
  if ((number.match(/e/g) ?? []).length === 1) {
    const numberParts = number.split('e')
    return `${formatNumber(numberParts[0])}e${formatNumber(numberParts[1])}`
  }

  const sanitizedNumber = number
    .replace(REGEX_UNWANTED_CHARACTERS, '')
    .replace(REGEX_DASHES_EXEPT_BEGINING, '')

  if (
    ((sanitizedNumber.match(/,/g) ?? []).length >= 2 && !sanitizedNumber.includes('.')) ||
    ((sanitizedNumber.match(/\./g) ?? []).length >= 2 && !sanitizedNumber.includes(','))
  ) {
    return sanitizedNumber.replace(/[.,]/g, '')
  }

  return sanitizedNumber.replace(/,/g, '.').replace(REGEX_PERIODS_EXEPT_LAST, '')
}

const testCases = [
  '1',
  '1.',
  '1,',
  '1.5',
  '1,5',
  '1,000.5',
  '1.000,5',
  '1,000,000.5',
  '1.000.000,5',
  '1,000,000',
  '1.000.000',

  '-1',
  '-1.',
  '-1,',
  '-1.5',
  '-1,5',
  '-1,000.5',
  '-1.000,5',
  '-1,000,000.5',
  '-1.000.000,5',
  '-1,000,000',
  '-1.000.000',

  '1e3',
  '1e-3',
  '1e',
  '-1e',
  '1.000e3',
  '1,000e-3',
  '1.000,5e3',
  '1,000.5e-3',
  '1.000,5e1.000,5',
  '1,000.5e-1,000.5',

  '',
  'a',
  'a1',
  'a-1',
  '1a',
  '-1a',
  '1a1',
  '1a-1',
  '1-',
  '-',
  '1-1'
]

document.getElementById('tbody').innerHTML = testCases.reduce((total, input) => {
  return `${total}<tr><td>${input}</td><td>${formatNumber(input)}</td></tr>`
}, '')
_x000D_
<table>
  <thead><tr><th>Input</th><th>Output</th></tr></thead>
  <tbody id="tbody"></tbody>
</table>
_x000D_
_x000D_
_x000D_

Reset CSS display property to default value

No, it is generally not possible. Once some CSS (or HTML) code sets a value for a property on an element, there is no way to undo it and tell the browser to use its default value.

It is of course possible to set a property a value that you expect to be the default value. This may work rather widely if you check the Rendering section of HTML5 CR, mostly reflecting what browsers actually do.

Still, the answer is “No”, because browsers may have whatever default values they like. You should analyze what was the reason for wanting to reset to defaults; the original problem may still be solvable.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Swift 5, update @Ankush's Alamofire Code to

     var fullUrl = "http://httpbin.org/post" // for example

           Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append( imagePathUrl! , withName: "photo")
                multipartFormData.append( videoPathUrl!,  withName: "video")
                multipartFormData.append(Constants.AuthKey.data(using: .utf8, allowLossyConversion: false)!, withName: "authKey")
                multipartFormData.append("16".data(using: .utf8, allowLossyConversion: false)!, withName: "idUserChallenge")
                multipartFormData.append("111".data(using: .utf8, allowLossyConversion: false)!, withName: "authKey")
                multipartFormData.append("comment".data(using: .utf8, allowLossyConversion: false)!, withName: "comment")
                multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "latitude")
                multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "longitude")
                multipartFormData.append("India".data(using: .utf8, allowLossyConversion: false)!, withName: "location")

            }, to: fullUrl, method: .post) { (encodingResult) in
                switch encodingResult {
                case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
                    upload.responseJSON { (response) in   // do sth     }
                case .failure(let encodingError):
                    ()
                }
            }

Convert xlsx file to csv using batch

Alternative way of converting to csv. Use libreoffice:

libreoffice --headless --convert-to csv *

Please be aware that this will only convert the first worksheet of your Excel file.

How to provide a mysql database connection in single file in nodejs

From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:

    const mysql = require('mysql');

    var connection;

    module.exports = {

    dbConnection: function () {

        connection = mysql.createConnection({
            host: "127.0.0.1",
            user: "Your_user",
            password: "Your_password",
            database: 'Your_bd'
        });
        connection.connect();
        return connection;
    }

    };

Then, the file where you are going to use the connection could be like useDb.js:

const dbConnection = require('./db');

var connection;

function callDb() {

    try {

        connection = dbConnectionManager.dbConnection();

        connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (!error) {

                let response = "The solution is: " + results[0].solution;
                console.log(response);

            } else {
                console.log(error);
            }
        });
        connection.end();


    } catch (err) {
        console.log(err);
    }
}

html select only one checkbox in a group

My version: use data attributes and Vanilla JavaScript

<div class="test-checkbox">
    Group One: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play</label>
    <br />
    Group Two: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy</label>
</div>
<script>
    let cbxes = document.querySelectorAll('input[type="checkbox"][data-limit="only-one-in-a-group"]');
    [...cbxes].forEach((cbx) => {
        cbx.addEventListener('change', (e) => {
            if (e.target.checked)
                uncheckOthers(e.target);
        });
    });
    function uncheckOthers (clicked) {
        let name = clicked.getAttribute('name');
        // find others in same group, uncheck them
        [...cbxes].forEach((other) => {
            if (other != clicked && other.getAttribute('name') == name)
                other.checked = false;
        });
    }
</script>

Docker - a way to give access to a host USB or serial device?

With current versions of Docker, you can use the --device flag to achieve what you want, without needing to give access to all USB devices.

For example, if you wanted to make only /dev/ttyUSB0 accessible within your Docker container, you could do something like:

docker run -t -i --device=/dev/ttyUSB0 ubuntu bash

How do I echo and send console output to a file in a bat script?

If you don't need the output in real time (i.e. as the program is writing it) you could add

type windows-dir.txt

after that line.

Compile a DLL in C/C++, then call it from another program

For VB6:

You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:

can I take arguments by pointer/reference from the VB front-end?

Yes, use ByRef/ByVal modifiers.

Can the DLL call a theoretical function in the front-end?

Yes, use AddressOf statement. You need to pass function pointer to dll before.

Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)

Yes, use AddressOf statement.

update (more questions appeared :)):

to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?

You need to decaler API function in VB6 code, like next:

Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
   (ByVal hwndOwner As Long, _
    ByVal nFolder As Long, _
    ByRef pidl As Long) As Long

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

Why does 2 mod 4 = 2?

Modulo (mod, %) is the Remainder operator.

2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)

PHP check file extension

$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}

BigDecimal to string

For better support different locales use this way:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);

df.format(bigDecimal);

also you can customize it:

DecimalFormat df = new DecimalFormat("###,###,###");
df.format(bigDecimal);

Two values from one input in python?

Check this handy function:

def gets(*types):
    return tuple([types[i](val) for i, val in enumerate(raw_input().split(' '))])

# usage:
a, b, c = gets(int, float, str)

How to check whether a pandas DataFrame is empty?

1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.
2) when this situation can happen? 
This situation happens when a single function is used to plot more than one DataFrame 
which are passed as parameter.In such a situation the function try to plot the data even 
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.
3) why? 
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values 
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message 
if a DataFrame is empty(instead of plotting):
df1                     df2
col1 col2           col1 col2 
Nan   2              Nan  Nan 
2     Nan            Nan  Nan  

and the function:

def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')

How to exit from ForEach-Object in PowerShell

I found this question while looking for a way to have fine grained flow control to break from a specific block of code. The solution I settled on wasn't mentioned...

Using labels with the break keyword

From: about_break

A Break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as Foreach, For, or While, in a script.

Here's a simple example

:myLabel for($i = 1; $i -le 2; $i++) {
        Write-Host "Iteration: $i"
        break myLabel
}

Write-Host "After for loop"

# Results:
# Iteration: 1
# After for loop

And then a more complicated example that shows the results with nested labels and breaking each one.

:outerLabel for($outer = 1; $outer -le 2; $outer++) {

    :innerLabel for($inner = 1; $inner -le 2; $inner++) {
        Write-Host "Outer: $outer / Inner: $inner"
        #break innerLabel
        #break outerLabel
    }

    Write-Host "After Inner Loop"
}

Write-Host "After Outer Loop"

# Both breaks commented out
# Outer: 1 / Inner: 1
# Outer: 1 / Inner: 2
# After Inner Loop
# Outer: 2 / Inner: 1
# Outer: 2 / Inner: 2
# After Inner Loop
# After Outer Loop

# break innerLabel Results
# Outer: 1 / Inner: 1
# After Inner Loop
# Outer: 2 / Inner: 1
# After Inner Loop
# After Outer Loop

# break outerLabel Results
# Outer: 1 / Inner: 1
# After Outer Loop

You can also adapt it to work in other situations by wrapping blocks of code in loops that will only execute once.

:myLabel do {
    1..2 | % {

        Write-Host "Iteration: $_"
        break myLabel

    }
} while ($false)

Write-Host "After do while loop"

# Results:
# Iteration: 1
# After do while loop

Setting a backgroundImage With React Inline Styles

You Can try usimg

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")

mysqld: Can't change dir to data. Server doesn't start

If you are having this issue and can't find the MySQL service either, just launch "MySQL Installer" from the Start menu (or download it), then choose "Reconfigure" on MySQL Server. Follow the steps to set a root user password and then the service will be created and started automatically (and set to auto-start on boot).

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

Addition to Alex' answer:

JavaScript

$(function() {
    $('input[type="submit"]').prop('disabled', true);
    $('#check').on('input', function(e) {
        if(this.value.length === 6) {
            $('input[type="submit"]').prop('disabled', false);
        } else {
            $('input[type="submit"]').prop('disabled', true);
        }
    });
});

HTML

<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />

JsFiddle

But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.

The object 'DF__*' is dependent on column '*' - Changing int to double

This is the tsql way

 ALTER TABLE yourtable DROP CONSTRAINT constraint_name     -- DF_Movies_Rating__48CFD27E

For completeness, this just shows @Joe Taras's comment as an answer

How to delete columns that contain ONLY NAs?

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]

What is the purpose of meshgrid in Python / NumPy?

The purpose of meshgrid is to create a rectangular grid out of an array of x values and an array of y values.

So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a rectangular grid, we need every combination of the x and y points.

This is going to be 25 points, right? So if we wanted to create an x and y array for all of these points, we could do the following.

x[0,0] = 0    y[0,0] = 0
x[0,1] = 1    y[0,1] = 0
x[0,2] = 2    y[0,2] = 0
x[0,3] = 3    y[0,3] = 0
x[0,4] = 4    y[0,4] = 0
x[1,0] = 0    y[1,0] = 1
x[1,1] = 1    y[1,1] = 1
...
x[4,3] = 3    y[4,3] = 4
x[4,4] = 4    y[4,4] = 4

This would result in the following x and y matrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.

x =   0 1 2 3 4        y =   0 0 0 0 0
      0 1 2 3 4              1 1 1 1 1
      0 1 2 3 4              2 2 2 2 2
      0 1 2 3 4              3 3 3 3 3
      0 1 2 3 4              4 4 4 4 4

We can then plot these to verify that they are a grid:

plt.plot(x,y, marker='.', color='k', linestyle='none')

enter image description here

Obviously, this gets very tedious especially for large ranges of x and y. Instead, meshgrid can actually generate this for us: all we have to specify are the unique x and y values.

xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);

Now, when we call meshgrid, we get the previous output automatically.

xx, yy = np.meshgrid(xvalues, yvalues)

plt.plot(xx, yy, marker='.', color='k', linestyle='none')

enter image description here

Creation of these rectangular grids is useful for a number of tasks. In the example that you have provided in your post, it is simply a way to sample a function (sin(x**2 + y**2) / (x**2 + y**2)) over a range of values for x and y.

Because this function has been sampled on a rectangular grid, the function can now be visualized as an "image".

enter image description here

Additionally, the result can now be passed to functions which expect data on rectangular grid (i.e. contourf)

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

This isn't C, but it's certainly does work. All the other methods I see here work by casing everything into parts of a hexagon, and approximating "angles" from that. By instead starting with a different equation using cosines, and solving for h s and v, you get a lot nicer relationship between hsv and rgb, and tweening becomes smoother (at the cost of it being way slower).

Assume everything is floating point. If r g and b go from 0 to 1, h goes from 0 to 2pi, v goes from 0 to 4/3, and s goes from 0 to 2/3.

The following code is written in Lua. It's easily translatable into anything else.

local hsv do
    hsv         ={}
    local atan2 =math.atan2
    local cos   =math.cos
    local sin   =math.sin

    function hsv.fromrgb(r,b,g)
        local c=r+g+b
        if c<1e-4 then
            return 0,2/3,0
        else
            local p=2*(b*b+g*g+r*r-g*r-b*g-b*r)^0.5
            local h=atan2(b-g,(2*r-b-g)/3^0.5)
            local s=p/(c+p)
            local v=(c+p)/3
            return h,s,v
        end
    end

    function hsv.torgb(h,s,v)
        local r=v*(1+s*(cos(h)-1))
        local g=v*(1+s*(cos(h-2.09439)-1))
        local b=v*(1+s*(cos(h+2.09439)-1))
        return r,g,b
    end

    function hsv.tween(h0,s0,v0,h1,s1,v1,t)
        local dh=(h1-h0+3.14159)%6.28318-3.14159
        local h=h0+t*dh
        local s=s0+t*(s1-s0)
        local v=v0+t*(v1-v0)
        return h,s,v
    end
end

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

iTerm2 keyboard shortcut - split pane navigation

I was using Terminator before, so I found it convenient to re-map Alt + arrow-key to switch between the panes. This can be done in Preferences -> Keys -> Key Mappings - press the '+' button to add a mapping. Also, in my case such a mapping was already defined in Profiles, I simply removed it.

Asp.net MVC ModelState.Clear

Update:

  • This is not a bug.
  • Please stop returning View() from a POST action. Use PRG instead and redirect to a GET if the action is a success.
  • If you are returning a View() from a POST action, do it for form validation, and do it the way MVC is designed using the built in helpers. If you do it this way then you shouldn't need to use .Clear()
  • If you're using this action to return ajax for a SPA, use a web api controller and forget about ModelState since you shouldn't be using it anyway.

Old answer:

ModelState in MVC is used primarily to describe the state of a model object largely with relation to whether that object is valid or not. This tutorial should explain a lot.

Generally you should not need to clear the ModelState as it is maintained by the MVC engine for you. Clearing it manually might cause undesired results when trying to adhere to MVC validation best practises.

It seems that you are trying to set a default value for the title. This should be done when the model object is instantiated (domain layer somewhere or in the object itself - parameterless ctor), on the get action such that it goes down to the page the 1st time or completely on the client (via ajax or something) so that it appears as if the user entered it and it comes back with the posted forms collection. Some how your approach of adding this value on the receiving of a forms collection (in the POST action // Edit) is causing this bizarre behaviour that might result in a .Clear() appearing to work for you. Trust me - you don't want to be using the clear. Try one of the other ideas.

Convert time fields to strings in Excel

copy the column paste it into notepad copy it again paste special as Text

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

For me, this problem was due to the fact that I had not appropriately sym-linked the cv2.so file in the~/.virtualenvs/cv/lib/python3.5/site-packages folder (the name of your virualenv may not be "cv", your version of python may not be 3.5--adjust accordingly).

If you go to the ~/.virtualenvs/cv/lib/python3.5/site-packages folder and ls, the cv2.so file should appear in light blue (Ubuntu 16.04) showing that it is linked. You can check the link location by typing: readlink cv2.so

If cv2.so appears in red (as mine did), rm the file and type: (for my install of python 3.5)

ln -s /usr/local/lib/python3.5/dist-packages/cv2.cpython-35m-x86_64-linux-gnu.so cv2.so

OR (if you have python 3.6)

ln -s /usr/local/lib/python3.6/dist-packages/cv2.cpython-36m-x86_64-linux-gnu.so cv2.so

If you are working in python 2.6 or python 2.7, you instead type:

ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so

If the cv2.so or cv2.cpython-36m-x86_64-linux-gnu.so files do not exist in your /usr/local/lib/python***/dist-packages location, check to see if they're in a /usr/local/lib/python***/sites-packages folder. If so, adjust the path accordingly. If not, something has gone wrong with your opencv installation.

This answer was inspired by information here: https://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

PHP array() to javascript array()

You should need to convert your PHP array to javascript array using PHP syntax json_encode. json_encode convert PHP array to JSON string

Single Dimension PHP array to javascript array

<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>

Multi Dimension PHP array to javascript array

<?php
var $itemsarray= array( 
               array('name'='Apple', 'price'=>'12345'),
               array('name'='Bear', 'price'=>'13344'),
               array('name'='Potato', 'price'=>'00440')
             );
?>


<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>

For more detail, you can also check php array to javascript array

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

What's the difference between ".equals" and "=="?

== is an operator. equals is a method defined in the Object class

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

Do the parentheses after the type name make a difference with new?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

The gotcha lies in-between:

struct Thingy {
  ~Thingy(); // No-longer a trivial class
  virtual WaxOn();
  int i;
};

The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

Use of PUT vs PATCH methods in REST API real life scenarios

A very nice explanation is here-

https://blog.segunolalive.com/posts/restful-api-design-%E2%80%94-put-vs-patch/#:~:text=RFC%205789,not%20required%20to%20be%20idempotent.

A Normal Payload- // House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 20 } PUT For Updated- // PUT request payload to update windows of House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 21 } Note: In above payload we are trying to update windows from 20 to 21.

Now see the PATH payload- // Patch request payload to update windows on the House { windows: 21 }

Since PATCH is not idempotent, failed requests are not automatically re-attempted on the network. Also, if a PATCH request is made to a non-existent url e.g attempting to replace the front door of a non-existent building, it should simply fail without creating a new resource unlike PUT, which would create a new one using the payload. Come to think of it, it’ll be odd having a lone door at a house address.

Can't import Numpy in Python

The following command worked for me:

python.exe -m pip install numpy

better way to drop nan rows in pandas

bool_series=pd.notnull(dat["x"])
dat=dat[bool_series]

Validation of file extension before uploading file

check that if file is selected or not

       if (document.myform.elements["filefield"].value == "")
          {
             alert("You forgot to attach file!");
             document.myform.elements["filefield"].focus();
             return false;  
         }

check the file extension

  var res_field = document.myform.elements["filefield"].value;   
  var extension = res_field.substr(res_field.lastIndexOf('.') + 1).toLowerCase();
  var allowedExtensions = ['doc', 'docx', 'txt', 'pdf', 'rtf'];
  if (res_field.length > 0)
     {
          if (allowedExtensions.indexOf(extension) === -1) 
             {
               alert('Invalid file Format. Only ' + allowedExtensions.join(', ') + ' are allowed.');
               return false;
             }
    }

Django Model() vs Model.objects.create()

UPDATE 15.3.2017:

I have opened a Django-issue on this and it seems to be preliminary accepted here: https://code.djangoproject.com/ticket/27825

My experience is that when using the Constructor (ORM) class by references with Django 1.10.5 there might be some inconsistencies in the data (i.e. the attributes of the created object may get the type of the input data instead of the casted type of the ORM object property) example:

models

class Payment(models.Model):
     amount_cash = models.DecimalField()

some_test.py - object.create

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor.objects.create(**actual_data)
            print(type(_obj.amount_cash)) # Decimal
            assert created
           objs.append(_obj)
        return objs

some_test.py - Constructor()

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor(**actual_data)
            print(type(_obj.amount_cash)) # Float
            assert created
           objs.append(_obj)
        return objs