Programs & Examples On #Audio processing

Audio processing involves the study of mathematical and signal processing techniques to understand or alter the nature of audio signals. The different kind of audio signals under study include speech, music, environmental audio and computer audio. Audio is analyzed in the temporal or spectral domain by applying various filters.

How can I extract audio from video with ffmpeg?

Just a guess:

-ab 192

should be

-ab 192k

Seems like that could be a problem, but maybe ffmpeg is smart enough to correct it.

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Make sure it's not redefined again lower down in your settings.py. The default settings has:

ALLOWED_HOSTS = []

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

Be aware, using NSAllowsArbitraryLoads = true in the project's info.plist allows all connection to any server to be insecure. If you want to make sure only a specific domain is accessible through an insecure connection, try this:

enter image description here

Or, as source code:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>domain.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Clean & Build project after editing.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

I remember it this way:

  1. IEnumerable has one method GetEnumerator() which allows one to read through the values in a collection but not write to it. Most of the complexity of using the enumerator is taken care of for us by the for each statement in C#. IEnumerable has one property: Current, which returns the current element.

  2. ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.

  3. IList implements both IEnumerable and ICollection, and add the integer indexing access to items (which is not usually required, as ordering is done in database).

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

App.Config change value

AppSettings.Set does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0] you will see it change from "English" to "Russian" when that line of code runs.

The following code (used in a console application) will persist the change.

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}

From this post: http://vbcity.com/forums/t/152772.aspx

One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.

How to set the timezone in Django?

Here is the list of valid timezones:

http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

You can use

TIME_ZONE = 'Europe/Istanbul'

for UTC+02:00

How to find a value in an array of objects in JavaScript?

You can find the object in array with Alasql library:

var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
     { name : "larry", dinner : "hummus" } ];

var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);

Try this example in jsFiddle.

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

Simple check for SELECT query empty result

SELECT count(*) as CountThis ....

Then you can compare it as string like so:

IF CHECKROW_RS("CountThis")="0" THEN ...

CHECKROW_RS is an object

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

Call to undefined method mysqli_stmt::get_result

Here is my alternative. It is object-oriented and is more like mysql/mysqli things.

class MMySqliStmt{
    private $stmt;
    private $row;

    public function __construct($stmt){
        $this->stmt = $stmt;
        $md = $stmt->result_metadata();
        $params = array();
        while($field = $md->fetch_field()) {
            $params[] = &$this->row[$field->name];
        }
        call_user_func_array(array($stmt, 'bind_result'), $params) or die('Sql Error');
    }

    public function fetch_array(){
        if($this->stmt->fetch()){
            $result = array();
            foreach($this->row as $k => $v){
                $result[$k] = $v;
            }
            return $result;
        }else{
            return false;
        }
    }

    public function free(){
        $this->stmt->close();
    }
}

Usage:

$stmt = $conn->prepare($str);
//...bind_param... and so on
if(!$stmt->execute())die('Mysql Query(Execute) Error : '.$str);
$result = new MMySqliStmt($stmt);
while($row = $result->fetch_array()){
    array_push($arr, $row);
    //for example, use $row['id']
}
$result->free();
//for example, use the $arr

Functional programming vs Object Oriented programming

Object Oriented Programming offers:

  1. Encapsulation, to
    • control mutation of internal state
    • limit coupling to internal representation
  2. Subtyping, allowing:
    • substitution of compatible types (polymorphism)
    • a crude means of sharing implementation between classes (implementation inheritance)

Functional Programming, in Haskell or even in Scala, can allow substitution through more general mechanism of type classes. Mutable internal state is either discouraged or forbidden. Encapsulation of internal representation can also be achieved. See Haskell vs OOP for a good comparison.

Norman's assertion that "Adding a new kind of thing to a functional program may require editing many function definitions to add a new case." depends on how well the functional code has employed type classes. If Pattern Matching on a particular Abstract Data Type is spread throughout a codebase, you will indeed suffer from this problem, but it is perhaps a poor design to start with.

EDITED Removed reference to implicit conversions when discussing type classes. In Scala, type classes are encoded with implicit parameters, not conversions, although implicit conversions are another means to acheiving substitution of compatible types.

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

Making a div vertically scrollable using CSS

Use overflow-y: auto; on the div.

Also, you should be setting the width as well.

Setting query string using Fetch GET request

Template literals are also a valid option here, and provide a few benefits.

You can include raw strings, numbers, boolean values, etc:

    let request = new Request(`https://example.com/?name=${'Patrick'}&number=${1}`);

You can include variables:

    let request = new Request(`https://example.com/?name=${nameParam}`);

You can include logic and functions:

    let request = new Request(`https://example.com/?name=${nameParam !== undefined ? nameParam : getDefaultName() }`);

As far as structuring the data of a larger query string, I like using an array concatenated to a string. I find it easier to understand than some of the other methods:

let queryString = [
  `param1=${getParam(1)}`,
  `param2=${getParam(2)}`,
  `param3=${getParam(3)}`,
].join('&');

let request = new Request(`https://example.com/?${queryString}`, {
  method: 'GET'
});

How to put a link on a button with bootstrap?

The easiest solution is the first one of your examples:

<a href="#link" class="btn btn-info" role="button">Link Button</a>

The reason it's not working for you is most likely, as you say, a problem in the theme you're using. There is no reason to resort to bloated extra markup or inline Javascript for this.

Java OCR implementation

If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.

I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.

How can I get relative path of the folders in my android project?

In Android, application-level meta data is accessed through the Context reference, which an activity is a descendant of.

For example, you can get the source directory via the getApplicationInfo().sourceDir property. There are methods for other folders as well (assets directory, data dir, database dir, etc.).

Sys is undefined

In addition to ensuring you have the ScriptManager on your page you need to ensure that your web.config is appropriately configured.

When ASP.NET AJAX 1.0 was released (for .NET 2.0) there was a lot of custom web.config settings which added handlers, controls, etc.

You'll find the config info here: http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx

How to reload current page without losing any form data?

Register an event listener for keyup event:

document.getElementById("input").addEventListener("keyup", function(e){
  var someVarName = input.value;
  sessionStorage.setItem("someVarKey", someVarName);
  input.value = sessionStorage.getItem("someVarKey");
});

How to negate the whole regex?

Apply this if you use laravel.

Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match function internally.

'email' => 'not_regex:/^.+$/i'

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

How to uninstall a Windows Service when there is no executable for it left on the system?

found here

I just tried on windows XP, it worked

local computer: sc \\. delete [service-name]

  Deleting services in Windows Server 2003

  We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.

  To delete a service: 

  Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.

  Enter command:

  sc servername delete servicename

  For instance, sc \\dc delete myservice

  (Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)

  Below is the official help of all sc functions:

  DESCRIPTION:
    SC is a command line program used for communicating with the
    NT Service Controller and services. 
  USAGE:
          sc

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You need to add the following line:

using FootballLeagueSystem;

into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login.

At the moment the compiler can't find the Login class.

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

IMHO, the reason why 2 queries

SELECT * FROM count_test WHERE b = 666 ORDER BY c LIMIT 5;
SELECT count(*) FROM count_test WHERE b = 666;

are faster than using SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS * FROM count_test WHERE b = 555 ORDER BY c LIMIT 5;

has to be seen as a particular case.

It in facts depends on the selectivity of the WHERE clause compared to the selectivity of the implicit one equivalent to the ORDER + LIMIT.

As Arvids told in comment (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-1174394), the fact that the EXPLAIN use, or not, a temporay table, should be a good base for knowing if SCFR will be faster or not.

But, as I added (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-8166482), the result really, really depends on the case. For a particular paginator, you could get to the conclusion that “for the 3 first pages, use 2 queries; for the following pages, use a SCFR” !

jQuery: outer html()

Create a temporary element, then clone() and append():

$('<div>').append($('#xxx').clone()).html();

Export a list into a CSV or TXT file in R

So essentially you have a list of lists, with mylist being the name of the main list and the first element being $f10010_1 which is printed out (and which contains 4 more lists).

I think the easiest way to do this is to use lapply with the addition of dataframe (assuming that each list inside each element of the main list (like the lists in $f10010_1) has the same length):

lapply(mylist, function(x) write.table( data.frame(x), 'test.csv'  , append= T, sep=',' ))

The above will convert $f10010_1 into a dataframe then do the same with every other element and append one below the other in 'test.csv'

You can also type ?write.table on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc.

Ruby on Rails: Where to define global constants?

If your model is really "responsible" for the constants you should stick them there. You can create class methods to access them without creating a new object instance:

class Card < ActiveRecord::Base
  def self.colours
    ['white', 'blue']
  end
end

# accessible like this
Card.colours

Alternatively, you can create class variables and an accessor. This is however discouraged as class variables might act kind of surprising with inheritance and in multi-thread environments.

class Card < ActiveRecord::Base
  @@colours = ['white', 'blue'].freeze
  cattr_reader :colours
end

# accessible the same as above
Card.colours

The two options above allow you to change the returned array on each invocation of the accessor method if required. If you have true a truly unchangeable constant, you can also define it on the model class:

class Card < ActiveRecord::Base
  COLOURS = ['white', 'blue'].freeze
end

# accessible as
Card::COLOURS

You could also create global constants which are accessible from everywhere in an initializer like in the following example. This is probably the best place, if your colours are really global and used in more than one model context.

# put this into config/initializers/my_constants.rb
COLOURS = ['white', 'blue'].freeze

# accessible as a top-level constant this time
COLOURS

Note: when we define constants above, often we want to freeze the array. That prevents other code from later (inadvertently) modifying the array by e.g. adding a new element. Once an object is frozen, it can't be changed anymore.

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

How can I put a database under git (version control)?

Update Aug 26, 2019:

Netlify CMS is doing it with GitHub, an example implementation can be found here with all information on how they implemented it netlify-cms-backend-github

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

When should you use 'friend' in C++?

Probably I missed something from the answers above but another important concept in encapsulation is hiding of implementation. Reducing access to private data members (the implementation details of a class) allows much easier modification of the code later. If a friend directly accesses the private data, any changes to the implementation data fields (private data), break the code accessing that data. Using access methods mostly eliminates this. Fairly important I would think.

How to do an update + join in PostgreSQL?

Here we go:

update vehicles_vehicle v
set price=s.price_per_vehicle
from shipments_shipment s
where v.shipment_id=s.id;

Simple as I could make it. Thanks guys!

Can also do this:

-- Doesn't work apparently
update vehicles_vehicle 
set price=s.price_per_vehicle
from vehicles_vehicle v
join shipments_shipment s on v.shipment_id=s.id;

But then you've got the vehicle table in there twice, and you're only allowed to alias it once, and you can't use the alias in the "set" portion.

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

Java: Unresolved compilation problem

(rewritten 2015-07-28)

The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn command, this may happen.

The cure is to fix the errors and recompile, before running again.

The setting is marked with a red box in this screendump:

Eclipse Preferences under OS X

PHP Notice: Undefined offset: 1 with array when reading data

How to reproduce the above error in PHP:

php> $yarr = array(3 => 'c', 4 => 'd');

php> echo $yarr[4];
d

php> echo $yarr[1];
PHP Notice:  Undefined offset: 1 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What does that error message mean?

It means the php compiler looked for the key 1 and ran the hash against it and didn't find any value associated with it then said Undefined offset: 1

How do I make that error go away?

Ask the array if the key exists before returning its value like this:

php> echo array_key_exists(1, $yarr);

php> echo array_key_exists(4, $yarr);
1

If the array does not contain your key, don't ask for its value. Although this solution makes double-work for your program to "check if it's there" and then "go get it".

Alternative solution that's faster:

If getting a missing key is an exceptional circumstance caused by an error, it's faster to just get the value (as in echo $yarr[1];), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131

how to convert object into string in php

There is an object serialization module, with the serialize function you can serialize any object.

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I was facing the same error while running command

pip install --upgrade pip

in a virtual venvironment (created with python -m venv venv).

using the --user flag fixed the problem for me

pip install --upgrade pip --user

If the problem not resolved use --user flag in a command prompt with admin rights.

Get HTML code using JavaScript with a URL

Edit: doesnt work yet...

Add this to your JS:

var src = fetch('https://page.com')

It saves the source of page.com to variable 'src'

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

Update Tkinter Label from variable

Maybe I'm not understanding the question but here is my simple solution that works -

# I want to Display total heads bent this machine so I define a label -
TotalHeadsLabel3 = Label(leftFrame)
TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))
TotalHeadsLabel3.pack(side=TOP)

# I update the int variable adding the quantity bent -
TotalHeads = TotalHeads + headQtyBent # update ready to write to file & display
TotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty

I agree that labels are not automatically updated but can easily be updated with the

<label name>.config(text="<new text>" + str(<variable name>))

That just needs to be included in your code after the variable is updated.

Oracle Convert Seconds to Hours:Minutes:Seconds

Assuming your time is called st.etime below and stored in seconds, here is what I use. This handles times where the seconds are greater than 86399 seconds (which is 11:59:59 pm)

case when st.etime > 86399 then to_char(to_date(st.etime - 86400,'sssss'),'HH24:MI:SS') else to_char(to_date(st.etime,'sssss'),'HH24:MI:SS') end readable_time

Android/Eclipse: how can I add an image in the res/drawable folder?

Just copy the image and paste into Eclipse in the res/drawable directory. Note that the image name should be in lowercase, otherwise it will end up with an error.

Get final URL after curl is redirected

You can do this with wget usually. wget --content-disposition "url" additionally if you add -O /dev/null you will not be actually saving the file.

wget -O /dev/null --content-disposition example.com

How can I pass parameters to a partial view in mvc 4

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
{
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
    {
        dictionary.Add(property.Name, property.GetValue(values));
    }
    return dictionary;
}

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
{
    Property1 = "Value1",
    Property2 = "Value2"
}.ToViewDataDictionary())

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.

<p>@ViewBag.Property1</p>
<p>@ViewBag.Property2</p>

How to perform keystroke inside powershell?

function Do-SendKeys {
    param (
        $SENDKEYS,
        $WINDOWTITLE
    )
    $wshell = New-Object -ComObject wscript.shell;
    IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
    Sleep 1
    IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'

MySQL "incorrect string value" error when save unicode string in Django

I just figured out one method to avoid above errors.

Save to database

user.first_name = u'Rytis'.encode('unicode_escape')
user.last_name = u'Slatkevicius'.encode('unicode_escape')
user.save()
>>> SUCCEED

print user.last_name
>>> Slatkevi\u010dius
print user.last_name.decode('unicode_escape')
>>> Slatkevicius

Is this the only method to save strings like that into a MySQL table and decode it before rendering to templates for display?

Creating a BAT file for python script

You can use python code directly in batch file, https://gist.github.com/jadient/9849314.

@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")

See explanation, Python command line -x option.

How to generate auto increment field in select query

DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO

Is it possible to get a list of files under a directory of a website? How?

There are only two ways to find a web page: through a link or by listing the directory.

Usually, web servers disable directory listing, so if there is really no link to the page, then it cannot be found.

BUT: information about the page may get out in ways you don't expect. For example, if a user with Google Toolbar visits your page, then Google may know about the page, and it can appear in its index. That will be a link to your page.

What's the difference between a Future and a Promise?

For client code, Promise is for observing or attaching callback when a result is available, whereas Future is to wait for result and then continue. Theoretically anything which is possible to do with futures what can done with promises, but due to the style difference, the resultant API for promises in different languages make chaining easier.

onchange event on input type=range is not triggering in firefox while dragging

You could use the JavaScript "ondrag" event to fire continuously. It is better than "input" due to the following reasons:

  1. Browser support.

  2. Could differentiate between "ondrag" and "change" event. "input" fires for both drag and change.

In jQuery:

$('#sample').on('drag',function(e){

});

Reference: http://www.w3schools.com/TAgs/ev_ondrag.asp

Getting the parameters of a running JVM

_JAVA_OPTIONS is an env variable that can be expanded.

echo $_JAVA_OPTIONS

Case statement in MySQL

Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html

Invariably, I first use one when I want the other.

How to create a new component in Angular 4 using CLI

ng g component component name

before you type this commend check you will be in your project directive path

Does GPS require Internet?

There are two issues:

  1. Getting the current coordinates (longitude, latitude, perhaps altitude) based on some external signals received by your device, and
  2. Deriving a human-readable position (address) from the coordinates.

To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.

As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.

how to make twitter bootstrap submenu to open on the left side?

I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side. Again if it has has enough space on the right side, it will show right side. it is a loop...

$(document).ready(function () {

$('body, html').css('overflow', 'hidden');
var screenWidth = $(window).width();
$('body, html').css('overflow', 'visible');

if (screenWidth > 767) {

    $(".dropdown-submenu").hover(function () {

        var dropdownPosition = $(this).offset().left + $(this).width() + $(this).find('ul').width();
        var newPosition = $(this).offset().left - $(this).find('ul').width();
        var windowPosition = $(window).width();

        var oldPosition = $(this).offset().left + $(this).width();
        //document.title = dropdownPosition;
        if (dropdownPosition > windowPosition) {
            $(this).find('ul').offset({ "left": newPosition });
        } else {
            $(this).find('ul').offset({ "left": oldPosition });
        }
    });

}

});

Display UIViewController as Popup in iPhone

Swift 4:

To add an overlay, or the popup view You can also use the Container View with which you get a free View Controller ( you get the Container View from the usual object palette/library)

enter image description here

Steps:

  1. Have a View (ViewForContainer in the pic) that holds this Container View, to dim it when the contents of Container View are displayed. Connect the outlet inside the first View Controller

  2. Hide this View when 1st VC loads

  3. Unhide when Button is clicked enter image description here

  4. To dim this View when the Container View content is displayed, set the Views Background to Black and opacity to 30%

enter image description here

You will get this effect when you click on the Button enter image description here

Laravel password validation rule

This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:

    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }

Would output:

    [
        'The email must be a valid email address.',
        'The password must be at least 10 characters.',
        'The password format is invalid.',
    ]

(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)

How can I include all JavaScript files in a directory via JavaScript file?

I was looking for an answer to this question and had my own problems. I found a couple solutions in various places and put them together into my own preferred answer.

function exploreFolder(folderURL,options){
/* options:                 type            explaination

    **REQUIRED** callback:  FUNCTION        function to be called on each file. passed the complete filepath
    then:                   FUNCTION        function to be called after loading all files in folder. passed the number of files loaded
    recursive:              BOOLEAN         specifies wether or not to travel deep into folders
    ignore:                 REGEX           file names matching this regular expression will not be operated on
    accept:                 REGEX           if this is present it overrides the `ignore` and only accepts files matching the regex
*/
$.ajax({
    url: folderURL,
    success: function(data){
        var filesLoaded = 0,
        fileName = '';

        $(data).find("td > a").each(function(){
            fileName = $(this).attr("href");

            if(fileName === '/')
                return;  //to account for the (go up a level) link

            if(/\/\//.test(folderURL + fileName))
                return; //if the url has two consecutive slashes '//'

            if(options.accept){
                if(!options.accept.test(fileName))
                    //if accept is present and the href fails, dont callback
                    return;
            }else if(options.ignore)
                if(options.ignore.test(fileName))
                    //if ignore is present and the href passes, dont callback
                    return;

            if(fileName.length > 1 && fileName.substr(fileName.length-1) === "/")
                if(options.recursive)
                    //only recurse if we are told to
                    exploreFolder(folderURL + fileName, options);
                else
                    return;

            filesLoaded++;
            options.callback(folderURL + fileName);
            //pass the full URL into the callback function
        });
        if(options.then && filesLoaded > 0) options.then(filesLoaded);
    }
});
}

Then you can call it like this:

var loadingConfig = {
    callback: function(file) { console.log("Loaded file: " + file); },
    then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
    recursive: true,
    ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);

This example will call that callback on every file/folder in the specified folder except for ones that start with NOLOAD. If you want to actually load the file into the page then you can use this other helper function that I developed.

function getFileExtension(fname){
    if(fname)
        return fname.substr((~-fname.lastIndexOf(".") >>> 0) + 2);
    console.warn("No file name provided");
}
var loadFile = (function(filename){
    var img = new Image();

    return function(){
        var fileref,
            filename = arguments[0],
            filetype = getFileExtension(filename).toLowerCase();

        switch (filetype) {
            case '':
                return;
            case 'js':
                fileref=document.createElement('script');
                fileref.setAttribute("type","text/javascript");
                fileref.setAttribute("src", filename);
                break;
            case "css":
                fileref=document.createElement("link");
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", filename);
                break;
            case "jpg":
            case "jpeg":
            case 'png':
            case 'gif':
                img.src = filename;
                break;
            default:
                console.warn("This file type is not supported: "+filetype);
                return;
        }
        if (typeof fileref !== undefined){
            $("head").append(fileref);
            console.log('Loaded file: ' + filename);
        }
    }
})();

This function accepts a JS | CSS | (common image) file and loads it. It will also execute the JS files. The complete call that needs to be run in your script to load all images and* stylesheets and other scripts could look like this:

loadingConfig = {
    callback: loadfile,
    then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
    recursive: true,
    ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);

It works amazingly!

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

How can I find my php.ini on wordpress?

Open .htaccess file in a code editor like sublime text and then add..

php_value upload_max_filesize 1000M
php_value post_max_size 2000M
php_value memory_limit 3000M
php_value max_execution_time 1800
php_value max_input_time 180

hope it helps..............it did for me.

How to prevent Browser cache for php site

try this

<?php

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

Outline effect to text

There is an experimental webkit property called text-stroke in CSS3, I've been trying to get this to work for some time but have been unsuccessful so far.

What I have done instead is used the already supported text-shadow property (supported in Chrome, Firefox, Opera, and IE 9 I believe).

Use four shadows to simulate a stroked text:

_x000D_
_x000D_
.strokeme {_x000D_
  color: white;_x000D_
  text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;_x000D_
}
_x000D_
<div class="strokeme">_x000D_
  This text should have a stroke in some browsers_x000D_
</div>
_x000D_
_x000D_
_x000D_

I have made a demo for you here

And a hovered example is available here


As Jason C has mentioned in the comments, the text-shadow CSS property is now supported by all major browsers, with the exception of Opera Mini. Where this solution will work for backwards compatibility (not really an issue regarding browsers that auto-update) I believe the text-stroke CSS should be used.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Mathematical functions in Swift

You can use them right inline:

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Bound method error

Your helpful comments led me to the following solution:

class Word_Parser:
    """docstring for Word_Parser"""
    def __init__(self, sentences):
        self.sentences = sentences

    def parser(self):
        self.word_list = self.sentences.split()
        word_list = []
        word_list = self.word_list
        return word_list

    def sort_word_list(self):
        self.sorted_word_list = sorted(self.sentences.split())
        sorted_word_list = self.sorted_word_list
        return sorted_word_list

    def get_num_words(self):
        self.num_words = len(self.word_list)
        num_words = self.num_words
        return num_words

test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.get_num_words()
print test.word_list
print test.sorted_word_list
print test.num_words

and returns: ['mary', 'had', 'a', 'little', 'lamb'] ['a', 'had', 'lamb', 'little', 'mary'] 5

Thank you all.

Remote debugging Tomcat with Eclipse

Modifying the startup.bat with the CATALINA_OPTS AND JPDA_OPTS didn't work for me but adding them to catalina.bat did

  1. Modify catalina.bat

CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

  1. Modify startup.bat to include jpda

change call "%EXECUTABLE%" start %CMD_LINE_ARGS% to

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

Then configure remote java application in your debug configurations in Eclipse.

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

#include <stdio.h>
#include <string.h>

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

How to merge 2 List<T> and removing duplicate values from it in C#

Union has not good performance : this article describe about compare them with together

var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
        dict[person.Number] = person;
}
var merged = dict.Values.ToList();

Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms

How to write data to a JSON file using Javascript

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

If you want update your JSON file cross-browser you have to use server and client side together.

The client side script

On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // we convert your JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // we add new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // we send with new request the updated JSON file to the server:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if you want to handle the POST response write (in this case you do not need it):
        // xhr.onreadystatechange = function(){ /* handle POST response */ };
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // but on this place you have to have a server for write updated JSON to the file
    }
};
xhr.send(null);

Server side scripts

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

PHP server side script solution

The PHP script for reading and writing from JSON file:

<?php

// This PHP script must be in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
    file_put_contents($file, $_POST["jsonTxt"]);
    //may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
    echo file_get_contents($file);
    //may be some error handeling if you want
}
?>

Node.js server side script solution

I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The Node.js script for reading and writing from JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Converting unix time into date-time via excel

=A1/(24*60*60) + DATE(1970;1;1) should work with seconds.

=(A1/86400/1000)+25569 if your time is in milliseconds, so dividing by 1000 gives use the correct date

Don't forget to set the type to Date on your output cell. I tried it with this date: 1504865618099 which is equal to 8-09-17 10:13.

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

TypeScript, Looping through a dictionary

There is one caveat to the key/value loop that Ian mentioned. If it is possible that the Objects may have attributes attached to their Prototype, and when you use the in operator, these attributes will be included. So you will want to make sure that the key is an attribute of your instance, and not of the prototype. Older IEs are known for having indexof(v) show up as a key.

for (const key in myDictionary) {
    if (myDictionary.hasOwnProperty(key)) {
        let value = myDictionary[key];
    }
}

What is private bytes, virtual bytes, working set?

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

How to convert timestamp to datetime in MySQL?

Use the FROM_UNIXTIME() function in MySQL

Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

Excel to CSV with UTF8 encoding

You can use iconv command under Unix (also available on Windows as libiconv).

After saving as CSV under Excel in the command line put:

iconv -f cp1250 -t utf-8 file-encoded-cp1250.csv > file-encoded-utf8.csv

(remember to replace cp1250 with your encoding).

Works fast and great for big files like post codes database, which cannot be imported to GoogleDocs (400.000 cells limit).

What are the differences between ArrayList and Vector?

Basically both ArrayList and Vector both uses internal Object Array.

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.

Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.

Some other differences are: enter image description here

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\

For example, your installer puts your dlls into:

\program files\<your app dir>\

or

\program files\common files\<your app name>\

(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)

and then sets a registry tag :

HKLM\software\<your app name>
-- dllLocation

The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.

The above is the smart way to go.

You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)

system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)

Simple Random Samples from a Sql database

Faster Than ORDER BY RAND()

I tested this method to be much faster than ORDER BY RAND(), hence it runs in O(n) time, and does so impressively fast.

From http://technet.microsoft.com/en-us/library/ms189108%28v=sql.105%29.aspx:

Non-MSSQL version -- I did not test this

SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= RAND()

MSSQL version:

SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)

This will select ~1% of records. So if you need exact # of percents or records to be selected, estimate your percentage with some safety margin, then randomly pluck excess records from resulting set, using the more expensive ORDER BY RAND() method.

Even Faster

I was able to improve upon this method even further because I had a well-known indexed column value range.

For example, if you have an indexed column with uniformly distributed integers [0..max], you can use that to randomly select N small intervals. Do this dynamically in your program to get a different set for each query run. This subset selection will be O(N), which can many orders of magnitude smaller than your full data set.

In my test I reduced the time needed to get 20 (out 20 mil) sample records from 3 mins using ORDER BY RAND() down to 0.0 seconds!

How to get numbers after decimal point?

You can use this:

number = 5.55
int(str(number).split('.')[1])

How to print React component on click of a button?

Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.

Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:

https://stackoverflow.com/a/30137174/3123109

This is what the component ended up looking like. It prints everything in the body of the modal.

import React, { Component } from 'react';
import {
    Button,
    Modal,
    ModalBody,
    ModalHeader
} from 'reactstrap';

export default class TestPrint extends Component{
    constructor(props) {
        super(props);
        this.state = {
            modal: false,
            data: [
                'test', 'test', 'test', 'test', 'test', 'test', 
                'test', 'test', 'test', 'test', 'test', 'test', 
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test'            
            ]
        }
        this.toggle = this.toggle.bind(this);
        this.print = this.print.bind(this);
    }

    print() {
        var content = document.getElementById('printarea');
        var pri = document.getElementById('ifmcontentstoprint').contentWindow;
        pri.document.open();
        pri.document.write(content.innerHTML);
        pri.document.close();
        pri.focus();
        pri.print();
    }

    renderContent() {
        var i = 0;
        return this.state.data.map((d) => {
            return (<p key={d + i++}>{i} - {d}</p>)
        });
    }

    toggle() {
        this.setState({
            modal: !this.state.modal
        })
    }

    render() {
        return (
            <div>
                <Button 
                    style={
                        {
                            'position': 'fixed',
                            'top': '50%',
                            'left': '50%',
                            'transform': 'translate(-50%, -50%)'
                        }
                    } 
                    onClick={this.toggle}
                >
                    Test Modal and Print
                </Button>         
                <Modal 
                    size='lg' 
                    isOpen={this.state.modal} 
                    toggle={this.toggle} 
                    className='results-modal'
                >  
                    <ModalHeader toggle={this.toggle}>
                        Test Printing
                    </ModalHeader>
                    <iframe id="ifmcontentstoprint" style={{
                        height: '0px',
                        width: '0px',
                        position: 'absolute'
                    }}></iframe>      
                    <Button onClick={this.print}>Print</Button>
                    <ModalBody id='printarea'>              
                        {this.renderContent()}
                    </ModalBody>
                </Modal>
            </div>
        )
    }
}

Note: However, I am having difficulty getting styles to be reflected in the iframe.

How to get all selected values of a multiple select box?

No jQuery:

// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}

Quick example:

<select multiple>
  <option>opt 1 text
  <option value="opt 2 value">opt 2 text
</select>
<button onclick="
  var el = document.getElementsByTagName('select')[0];
  alert(getSelectValues(el));
">Show selected values</button>

Convert a list to a string in C#

You have a List<string> - so if you want them concatenated, something like

string s = string.Join("", list);

would work (in .NET 4.0 at least). The first parameter is the delimiter. So you could also comma-delimit etc.

You might also want to look at using StringBuilder to do running concatenations, rather than forming a list.

Is there a Python equivalent to Ruby's string interpolation?

You can also have this

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

How to prevent a dialog from closing when a button is clicked

Here are some solutions for all types of dialogs including a solution for AlertDialog.Builder that will work on all API levels (works below API 8, which the other answer here does not). There are solutions for AlertDialogs using AlertDialog.Builder, DialogFragment, and DialogPreference.

Below are the code examples showing how to override the default common button handler and prevent the dialog from closing for these different forms of dialogs. All the examples show how to prevent the positive button from closing the dialog.

Note: A description of how the dialog closing works under the hood for the base android classes and why the following approaches are chosen follows after the examples, for those who want more details


AlertDialog.Builder - Change default button handler immediately after show()

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test", 
        new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //Do nothing here because we override this button later to change the close behaviour. 
                //However, we still need this because on older versions of Android unless we 
                //pass a handler the button doesn't get instantiated
            }
        });
final AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
      {            
          @Override
          public void onClick(View v)
          {
              Boolean wantToCloseDialog = false;
              //Do stuff, possibly set wantToCloseDialog to true then...
              if(wantToCloseDialog)
                  dialog.dismiss();
              //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
          }
      });
      

DialogFragment - override onResume()

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Test for preventing dialog close");
    builder.setPositiveButton("Test", 
        new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //Do nothing here because we override this button later to change the close behaviour. 
                //However, we still need this because on older versions of Android unless we 
                //pass a handler the button doesn't get instantiated
            }
        });
    return builder.create();
}

//onStart() is where dialog.show() is actually called on 
//the underlying dialog, so we have to do it there or 
//later in the lifecycle.
//Doing it in onResume() makes sure that even if there is a config change 
//environment that skips onStart then the dialog will still be functioning
//properly after a rotation.
@Override
public void onResume()
{
    super.onResume();    
    final AlertDialog d = (AlertDialog)getDialog();
    if(d != null)
    {
        Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        Boolean wantToCloseDialog = false;
                        //Do stuff, possibly set wantToCloseDialog to true then...
                        if(wantToCloseDialog)
                            d.dismiss();
                        //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                    }
                });
    }
}

DialogPreference - override showDialog()

@Override
protected void onPrepareDialogBuilder(Builder builder)
{
    super.onPrepareDialogBuilder(builder);
    builder.setPositiveButton("Test", this);   //Set the button here so it gets created
}

@Override
protected void showDialog(Bundle state)
{       
    super.showDialog(state);    //Call show on default first so we can override the handlers

    final AlertDialog d = (AlertDialog) getDialog();
    d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
            {            
                @Override
                public void onClick(View v)
                {
                    Boolean wantToCloseDialog = false;
                    //Do stuff, possibly set wantToCloseDialog to true then...
                    if(wantToCloseDialog)
                        d.dismiss();
                    //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                }
            });
}

Explanation of approaches:

Looking through Android source code the AlertDialog default implementation works by registering a common button handler to all the actual buttons in OnCreate(). When a button is clicked the common button handler forwards the click event to whatever handler you passed in setButton() then calls dismisses the dialog.

If you wish to prevent a dialog box from closing when one of these buttons is pressed you must replace the common button handler for the actual view of the button. Because it is assigned in OnCreate(), you must replace it after the default OnCreate() implementation is called. OnCreate is called in the process of the show() method. You could create a custom Dialog class and override OnCreate() to call the super.OnCreate() then override the button handlers, but if you make a custom dialog you don't get the Builder for free, in which case what is the point?

So, in using a dialog the way it is designed but with controlling when it is dismissed, one approach is to call dialog.Show() first, then obtain a reference to the button using dialog.getButton() to override the click handler. Another approach is to use setOnShowListener() and implement finding the button view and replacing the handler in the OnShowListener. The functional difference between the two is 'almost' nill, depending on what thread originally creates the dialog instance. Looking through the source code, the onShowListener gets called by a message posted to a handler running on the thread that created that dialog. So, since your OnShowListener is called by a message posted on the message queue it is technically possible that calling your listener is delayed some time after show completes.

Therefore, I believe the safest approach is the first: to call show.Dialog(), then immediately in the same execution path replace the button handlers. Since your code that calls show() will be operating on the main GUI thread, it means whatever code you follow show() with will be executed before any other code on that thread, whereas the timing of the OnShowListener method is at the mercy of the message queue.

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

text-overflow: ellipsis not working

I was having an issue with ellipsis under chrome. Turning on white-space: nowrap seemed to fix it.

max-width: 95px;
max-height: 20px;
overflow: hidden;
display: inline-block;
text-overflow: ellipsis;
border: solid 1px black;
font-size: 12pt;
text-align: right;
white-space: nowrap;

Breaking up long strings on multiple lines in Ruby without stripping newlines

You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

Comparing results with today's date?

For me the query that is working, if I want to compare with DrawDate for example is:

CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)

This is comparing results with today's date.

or the whole query:

SELECT TOP (1000) *
FROM test
where DrawName != 'NULL' and CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
order by id desc

Find all tables containing column with specified name - MS SQL Server

You can find it from INFORMATION_SCHEMA.COLUMNS by column_name filter

Select DISTINCT TABLE_NAME as TableName,COLUMN_NAME as ColumnName
     From INFORMATION_SCHEMA.COLUMNS Where column_name like '%myname%'

UIView background color in Swift

Try This, It worked like a charm! for me,

The simplest way to add backgroundColor programmatically by using ColorLiteral.

You need to add the property ColorLiteral, Xcode will prompt you with a whole list of colors in which you can choose any color. The advantage of doing this is we use lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard.

Follow steps ,

1) Add below line of code in viewDidLoad() ,

self.view.backgroundColor = ColorLiteral

and clicked on enter button .

2) Display square box next to =

enter image description here

3) When Clicked on Square Box Xcode will prompt you with a whole list of colors which you can choose any colors also you can set HEX values or RGB

enter image description here

4) You can successfully set the colors .

enter image description here

Hope this will help some one to set backgroundColor in different ways.

how to delete files from amazon s3 bucket?

I'm surprised there isn't this easy way : key.delete() :

from boto.s3.connection import S3Connection, Bucket, Key

conn = S3Connection(AWS_ACCESS_KEY, AWS_SECERET_KEY)
bucket = Bucket(conn, S3_BUCKET_NAME)
k = Key(bucket = bucket, name=path_to_file)
k.delete()

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Convert char* to string C++

std::string str(buffer, buffer + length);

Or, if the string already exists:

str.assign(buffer, buffer + length);

Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length characters, or until a null terminator, whichever comes first, then you can use this:

std::string str(buffer, std::find(buffer, buffer + length, '\0'));

How to add rows dynamically into table layout

The way you have added a row into the table layout you can add multiple TableRow instances into your tableLayout object

tl.addView(row1);
tl.addView(row2);

etc...

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Go to the following setting:

Window -> Preferences -> Java-Compiler-Errors/Warnings-Deprecated and restricted API-Forbidden reference (access rules)

Set it to Warning or Ignore.

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

How to assign execute permission to a .sh file in windows to be executed in linux

As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.

I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:

unzip zip_name.zip && chmod +x script_name.sh

If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh as follows:

#!/bin/bash
# file: grant_perms.sh

chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh

(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)

And now your unzip one-liner becomes:

unzip zip_name.zip && source grant_perms.sh

Note that since you are using source to run grant_perms.sh, it doesn't need execute permission

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

Properties private set;

This is normally the case then the ID is not a natural part of the entity, but a database artifact that needs be abstracted away.

It is a design decision - to only allow setting the ID during construction or through method invocation, so it is managed internally by the class.

You can write a setter yourself, assuming you have a backing field:

private int Id = 0;
public void SetId (int id)
{
  this.Id = id;
}

Or through a constructor:

private int Id = 0;
public Person (int id)
{
  this.Id = id;
}

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

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

Get a pixel from HTML Canvas?

// Get pixel data
var imageData = context.getImageData(x, y, width, height);

// Color at (x,y) position
var color = [];
color['red'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 0];
color['green'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 1];
color['blue'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 2];
color['alpha'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 3];

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I was having the same problem but only with a few machines. I found that using Invoke-Command to run the same command on the remote server worked.

So instead of:

Get-WmiObject win32_SystemEnclosure -ComputerName $hostname -Authentication Negotiate

Use this:

Invoke-Command -ComputerName $hostname -Authentication Negotiate -ScriptBlock {Get-WmiObject win32_SystemEnclosure}

Manifest Merger failed with multiple errors in Android Studio

The following hack works:

  1. Add the xmlns:tools="http://schemas.android.com/tools" line in the manifest tag
  2. Add tools:replace="android:icon,android:theme,android:allowBackup,label,name" in the application tag

How to remove special characters from a string?

That depends on what you define as special characters, but try replaceAll(...):

String result = yourString.replaceAll("[-+.^:,]","");

Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".

Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).

So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):

String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");


If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").

A third way could be something like this, if you can exactly define what should be left in your string:

String  result = yourString.replaceAll("[^\\w\\s]","");

This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.

Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.

Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:

String  result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");

The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.

Additional information on Unicode

Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:

split -l 100000 database.sql database-

It will give files like:

database-aaa
database-aab
database-aac
...

How to grep and replace

You could even do it like this:

Example

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

This will search for the string 'windows' in all files relative to the current directory and replace 'windows' with 'linux' for each occurrence of the string in each file.

How do I revert a Git repository to a previous commit?

There is a command (not a part of core Git, but it is in the git-extras package) specifically for reverting and staging old commits:

git back

Per the man page, it can also be used as such:

# Remove the latest three commits
git back 3

Creating a JSON dynamically with each input value using jquery

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

Finding the length of a Character Array in C

You can use this function:

int arraySize(char array[])
{
    int cont = 0;
    for (int i = 0; array[i] != 0; i++)
            cont++;
    return cont;
}

use std::fill to populate vector with increasing numbers

I've seen the answers with std::generate but you can also "improve" that by using static variables inside the lambda, instead of declaring a counter outside of the function or creating a generator class :

std::vector<int> vec;
std::generate(vec.begin(), vec.end(), [] {
    static int i = 0;
    return i++;
});

I find it a little more concise

HashSet vs LinkedHashSet

I suggest you to use LinkedHashSet most of the time, because it has better performance overall):

  1. Predictable iteration order LinkedHashSet (Oracle)
  2. LinkedHashSet is more expensive for insertions than HashSet;
  3. In general slightly better performance than HashMap, because the most of the time we use Set structures for iterating.

Performance tests:

------------- TreeSet -------------
 size       add  contains   iterate
   10       746       173        89
  100       501       264        68
 1000       714       410        69
10000      1975       552        69
------------- HashSet -------------
 size       add  contains   iterate
   10       308        91        94
  100       178        75        73
 1000       216       110        72
10000       711       215       100
---------- LinkedHashSet ----------
 size       add  contains   iterate
   10       350        65        83
  100       270        74        55
 1000       303       111        54
10000      1615       256        58

You can see source test page here: The Final Performance Testing Example

How to write unit testing for Angular / TypeScript for private methods with Jasmine

Sorry for the necro on this post, but I feel compelled to weigh in on a couple of things that do not seem to have been touched on.

First a foremost - when we find ourselves needing access to private members on a class during unit testing, it is generally a big, fat red flag that we've goofed in our strategic or tactical approach and have inadvertently violated the single responsibility principal by pushing behavior where it does not belong. Feeling the need to access methods that are really nothing more than an isolated subroutine of a construction procedure is one of the most common occurrences of this; however, it's kind of like your boss expecting you to show up for work ready-to-go and also having some perverse need to know what morning routine you went through to get you into that state...

The other most common instance of this happening is when you find yourself trying to test the proverbial "god class." It is a special kind of problem in and of itself, but suffers from the same basic issue with needing to know intimate details of a procedure - but that's getting off topic.

In this specific example, we've effectively assigned the responsibility of fully initializing the Bar object to the FooBar class's constructor. In object oriented programming, one of the core tenents is that the constructor is "sacred" and should be guarded against invalid data that would invalidate its' own internal state and leave it primed to fail somewhere else downstream (in what could be a very deep pipeline.)

We've failed to do that here by allowing the FooBar object to accept a Bar that is not ready at the time that the FooBar is constructed, and have compensated by sort-of "hacking" the FooBar object to take matters into its' own hands.

This is the result of a failure to adhere to another tenent of object oriented programming (in the case of Bar,) which is that an object's state should be fully initialized and ready to handle any incoming calls to its' public members immediately after creation. Now, this does not mean immediately after the constructor is called in all instances. When you have an object that has many complex construction scenarios, then it is better to expose setters to its optional members to an object that is implemented in accordance with a creation design-pattern (Factory, Builder, etc...) In any of the latter cases, you would be pushing the initialization of the target object off into another object graph whose sole purpose is directing traffic to get you to a point where you have a valid instance of that which you are requesting - and the product should not be considered "ready" until after this creation object has served it up.

In your example, the Bar's "status" property does not seem to be in a valid state in which a FooBar can accept it - so the FooBar does something to it to correct that issue.

The second issue I am seeing is that it appears that you are trying to test your code rather than practice test-driven development. This is definitely my own opinion at this point in time; but, this type of testing is really an anti-pattern. What you end up doing is falling into the trap of realizing that you have core design problems that prevent your code from being testable after the fact, rather than writing the tests you need and subsequently programming to the tests. Either way you come at the problem, you should still end up with the same number of tests and lines of code had you truly achieved a SOLID implementation. So - why try and reverse engineer your way into testable code when you can just address the matter at the onset of your development efforts?

Had you done that, then you would have realized much earlier on that you were going to have to write some rather icky code in order to test against your design and would have had the opportunity early on to realign your approach by shifting behavior to implementations that are easily testable.

Xpath for href element

Try below locator.

selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");

or

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

Check if object value exists within a Javascript array of objects and if not add a new object to array

i did try the above steps for some reason it seams not to be working for me but this was my final solution to my own problem just maybe helpful to any one reading this :

let pst = post.likes.some( (like) => {  //console.log(like.user, req.user.id);
                                     if(like.user.toString() === req.user.id.toString()){
                                         return true
                                     } } )

here post.likes is an array of users who liked a post.

How do I use a Boolean in Python?

Booleans in python are subclass of integer. Constructor of booleans is bool. bool class inherits from int class.

 issubclass(bool,int) // will return True
 isinstance(True,bool) , isinstance(False,bool) //they both True

True and False are singleton objects. they will retain same memory address throughout the lifetime of your app. When you type True, python memory manager will check its address and will pull the value '1'. for False its value is '0'.

Comparisons of any boolean expression to True or False can be performed using either is (identity) or == (equality) operator.

int(True) == 1
int(False) == 0

But note that True and '1' are not the same objects. You can check:

 id(True) == id(1) // will return False

you can also easily see that

  True > False // returns true cause 1>0

any integer operation can work with the booleans.

  True + True + True =3 

All objects in python have an associated truth value. Every object has True value except:

  • None

  • False

  • 0 in any numeric type (0,0.0,0+0j etc)

  • empty sequences (list, tuple, string)

  • empty mapping types (dictionary, set, etc)

  • custom classes that implement __bool__ or __len__ method that returns False or 0.

every class in python has truth values defined by a special instance method:

 __bool__(self)   OR
 __len__

When you call bool(x) python will actually execute

 x.__bool__() 

if instance x does not have this method, then it will execute

 x.__len__()

if this does not exist, by default value is True.

For Example for int class we can define bool as below:

  def __bool__(self):
      return self != 0

for bool(100), 100 !=0 will return True. So

bool(100) == True

you can easily check that bool(0) will be False. with this for instances of int class only 0 will return False.

another example= bool([1,2,3])

[1,2,3] has no __bool__() method defined but it has __len__() and since its length is greater than 0, it will return True. Now you can see why empty lists return False.

How can I find the last element in a List<>?

Though this was posted 11 years ago, I'm sure the right number of answers is one more than there are!

You can also doing something like;


if (integerList.Count > 0) 
   var item = integerList[^1];

See the tutorial post on the MS C# docs here from a few months back.

I would personally still stick with LastOrDefault() / Last() but thought I'd share this.

EDIT; Just realised another answer has mentioned this with another doc link.

Popup window in winform c#

If you mean to create a new form when a button is clicked, the below code may be of some use to you:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

From here, you could also use the 'Show Dialog' method

Generate random integers between 0 and 9

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.

CSS: How to change colour of active navigation page menu

The CSS :active state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.

To fix your problem you have to create a class and add it manually to the current page's menu:

a.active { color: #f00 }

<ul>
    <li><a href="index.php" class="active">HOME</a></li>
    <li><a href="two.php">PORTFOLIO</a></li>
    <li><a href="three.php">ABOUT</a></li>
    <li><a href="four.php">CONTACT</a></li>
    <li><a href="five.php">SHOP</a></li>
</ul>

Where is GACUTIL for .net Framework 4.0 in windows 7?

VS 2012/13 Win 7 64 bit gacutil.exe is located in

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

Java: using switch statement with enum under subclass

this should do:

//Main Class
public class SomeClass {

    //Sub-Class
    public static class AnotherClass {
        public enum MyEnum {
            VALUE_A, VALUE_B
        }    
        public MyEnum myEnum;
    }

    public void someMethod() { 
        AnotherClass.MyEnum enumExample = AnotherClass.MyEnum.VALUE_A; //...

        switch (enumExample) {
            case VALUE_A: { //<-- error on this line
            //..
            break;
            }
        }
    }
}

SQL grouping by month and year

If you want to stay having the field in datetime datatype, try using this:

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order] o
WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0)

It it also easy to change to group by hours, days, weeks, years...
I hope it is of use to someone,

Regards!

How to remove an HTML element using Javascript?

Just do this element.remove();

Try it here LOOK

http://jsfiddle.net/4WGRP/

How to overcome root domain CNAME restrictions?

I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.

Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):

; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mydomain.com.          IN  A

;; ANSWER SECTION:
mydomain.com.       394 IN  CNAME   myapp.parseapp.com.
myapp.parseapp.com. 300 IN  CNAME   parseapp.com.
parseapp.com.       60  IN  A   54.243.93.102

How to calculate rolling / moving average using NumPy / SciPy?

Starting in Numpy 1.20, the sliding_window_view provides a way to slide/roll through windows of elements. Windows that you can then individually average.

For instance, for a 4-element window:

from numpy.lib.stride_tricks import sliding_window_view

# values = np.array([5, 3, 8, 10, 2, 1, 5, 1, 0, 2])
np.average(sliding_window_view(values, window_shape = 4), axis=1)
# array([6.5, 5.75, 5.25, 4.5, 2.25, 1.75, 2])

Note the intermediary result of sliding_window_view:

# values = np.array([5, 3, 8, 10, 2, 1, 5, 1, 0, 2])
sliding_window_view(values, window_shape = 4)
# array([[ 5,  3,  8, 10],
#        [ 3,  8, 10,  2],
#        [ 8, 10,  2,  1],
#        [10,  2,  1,  5],
#        [ 2,  1,  5,  1],
#        [ 1,  5,  1,  0],
#        [ 5,  1,  0,  2]])

How to change or add theme to Android Studio?

In 2.3.2 i can change the theme by following

View -> Quick Switch Theme -> 6.Look and Feel

iText - add content to existing PDF file

Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream("E:/TextFieldForm.pdf"));
    document.open();

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;      

    // Code 2, add name TextField       
    table.addCell("Name"); 
    TextField nameField = new TextField(writer, 
        new Rectangle(0,0,200,10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);               
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 
        200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript(
        "var nameField = this.getField('nameField');" +
        "nameField.setAction('Keystroke'," +
        "'forceUpperCase()');" +
        "" +
        "function forceUpperCase(){" +
        "if(!event.willCommit)event.change = " +
        "event.change.toUpperCase();" +
        "}");


    // Code 3, add empty row
    table.addCell("");
    table.addCell("");


    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0,
         0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 
        30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript(
        "var ageField = this.getField('ageField');" +
        "ageField.setAction('Validate','checkAge()');" +
        "function checkAge(){" +
        "if(event.value < 12){" +
        "app.alert('Warning! Applicant\\'s age can not" +
        " be younger than 12.');" +
        "event.value = 12;" +
        "}}");      



    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, 
        new Rectangle(0, 0,200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 
        200, writer));
    table.addCell(cell);


    // check comment characters length javascript
    writer.addJavaScript(
        "var commentField = " +
        "this.getField('commentField');" +
        "commentField" +
        ".setAction('Keystroke','checkLength()');" +
        "function checkLength(){" +
        "if(!event.willCommit && " +
        "event.value.length > 100){" +
        "app.alert('Warning! Comment can not " +
        "be more than 100 characters.');" +
        "event.change = '';" +
        "}}");          

    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 6, add submit button    
    PushbuttonField submitBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15),"submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.
        setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.
        VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction
    .createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));

    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);



    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(
        PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn
    .setOptions(
        PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);        

    document.add(table);
    document.close();
}


class FieldCell implements PdfPCellEvent{

    PdfFormField formField;
    PdfWriter writer;
    int width;

    public FieldCell(PdfFormField formField, int width, 
        PdfWriter writer){
        this.formField = formField;
        this.width = width;
        this.writer = writer;
    }

    public void cellLayout(PdfPCell cell, Rectangle rect, 
        PdfContentByte[] canvas){
        try{
            // delete cell border
            PdfContentByte cb = canvas[PdfPTable
                .LINECANVAS];
            cb.reset();

            formField.setWidget(
                new Rectangle(rect.left(), 
                    rect.bottom(), 
                    rect.left()+width, 
                    rect.top()), 
                    PdfAnnotation
                    .HIGHLIGHT_NONE);

            writer.addAnnotation(formField);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

Effect of NOLOCK hint in SELECT statements

In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.

See http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

If you are using version 2.2 and above of Android Studio then in Android Studio use Build ? Analyze APK then select AndroidManifest.xml file.

Find all packages installed with easy_install/pip?

Newer versions of pip have the ability to do what the OP wants via pip list -l or pip freeze -l (--list).
On Debian (at least) the man page doesn't make this clear, and I only discovered it - under the assumption that the feature must exist - with pip list --help.

There are recent comments that suggest this feature is not obvious in either the documentation or the existing answers (although hinted at by some), so I thought I should post. I would have preferred to do so as a comment, but I don't have the reputation points.

How to 'grep' a continuous stream?

In most cases, you can tail -f /var/log/some.log |grep foo and it will work just fine.

If you need to use multiple greps on a running log file and you find that you get no output, you may need to stick the --line-buffered switch into your middle grep(s), like so:

tail -f /var/log/some.log | grep --line-buffered foo | grep bar

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

Use command + m(cmd + M) on MAC. Also make sure that you are accessing your application while you try to access the Debug Menui.e. your app must be running otherwise Cmd + M will just return the usual ordinary phone menu.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Oracle SQL Query for listing all Schemas in a DB

SELECT username FROM all_users ORDER BY username;

Making heatmap from pandas DataFrame

For people looking at this today, I would recommend the Seaborn heatmap() as documented here.

The example above would be done as follows:

import numpy as np 
from pandas import DataFrame
import seaborn as sns
%matplotlib inline

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

sns.heatmap(df, annot=True)

Where %matplotlib is an IPython magic function for those unfamiliar.

Importing JSON into an Eclipse project

The link of accepted answer is old and can cause warnings with generics use,

You should download latest jar from JSON-java github site

Add jar to Java build Path

In existing project in Order and Export tab move the new jar, as json-20180813.jar, as the first (or above other dependencies with JSONObject)

Where are $_SESSION variables stored?

How does it work? How does it know it's me?

Most sessions set a user-key(called the sessionid) on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key and runs to the server to get your variables.

If you mistakenly clear the cache, then your user-key will also be cleared. You won't be able to get your variables from the server any more since you don't know your id.

How to print the number of characters in each line of a text file

Try this:

while read line    
do    
    echo -e |wc -m      
done <abc.txt    

How can I pass a parameter to a setTimeout() callback?

// These are three very simple and concise answers:

function fun() {
    console.log(this.prop1, this.prop2, this.prop3);
}

let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };

let bound = fun.bind(obj);

setTimeout(bound, 3000);

 // or

function funOut(par1, par2, par3) {

  return function() { 

    console.log(par1, par2, par3);

  }
};

setTimeout(funOut('one', 'two', 'three'), 5000);

 // or

let funny = function(a, b, c) { console.log(a, b, c); };

setTimeout(funny, 2000, 'hello', 'worldly', 'people');

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

How to set the height of table header in UITableView?

Swift 4 - you can manage height with HEIGHT_VIEW,Just add this cods, Its working

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let HEIGHT_VIEW = 60
    tableView.tableFooterView?.frame.size = CGSize(width: tblView.frame.width, height: CGFloat(HEIGHT_VIEW))

    tableView.tableHeaderView?.frame.size = CGSize(width:tblView.frame.width, height: CGFloat(HEIGHT_VIEW))
}

How to implement a ConfigurationSection with a ConfigurationElementCollection

An easier alternative for those who would prefer not to write all that configuration boilerplate manually...

1) Install Nerdle.AutoConfig from NuGet

2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)

public interface IServiceConfiguration
{
    int Port { get; }
    ReportType ReportType { get; }
}

3) You'll need a type to hold the collection, e.g.

public interface IServiceCollectionConfiguration
{
    IEnumerable<IServiceConfiguration> Services { get; } 
}

4) Add the config section like so (note camelCase naming)

<configSections>
  <section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>

<serviceCollection>
  <services>
    <service port="6996" reportType="File" />
    <service port="7001" reportType="Other" />
  </services>
</serviceCollection>

5) Map with AutoConfig

var services = AutoConfig.Map<IServiceCollectionConfiguration>();

MVC4 StyleBundle not resolving images

CssRewriteUrlTransform fixed my problem.
If your code still not loading images after using CssRewriteUrlTransform, then change your css filename's from:

.Include("~/Content/jquery/jquery-ui-1.10.3.custom.css", new CssRewriteUrlTransform())

To:

.Include("~/Content/jquery/jquery-ui.css", new CssRewriteUrlTransform())

Someway .(dots) are not recognizing in url.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The best way I have found to get a feel for things like this is to try them out:

import java.io.File;
public class PathTesting {
    public static void main(String [] args) {
        File f = new File("test/.././file.txt");
        System.out.println(f.getPath());
        System.out.println(f.getAbsolutePath());
        try {
            System.out.println(f.getCanonicalPath());
        }
        catch(Exception e) {}
    }
}

Your output will be something like:

test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt

So, getPath() gives you the path based on the File object, which may or may not be relative; getAbsolutePath() gives you an absolute path to the file; and getCanonicalPath() gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.

When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths. Just one example.

Decrementing for loops

Check out the range documentation, you have to define a negative step:

>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

How to set entire application in portrait mode only?

For any Android version

From XML

You can specify android:screenOrientation="portrait" for each activity in your manifest.xml file. You cannot specify this option on the application tag.

From Java

Other option is to do it programmatically, for example in an Activity base class:

@Override
public void onCreate(Bundle savedInstanceState) {
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

For Android 4+ (API 14+)

Last option is to do it with activity lifecycle listeners which is only available since Android 4.0 (API 14+). Everything happens in a custom Application class:

@Override
public void onCreate() {
    super.onCreate();  
    registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() {
        @Override
        public void onActivityCreated(Activity a, Bundle savedInstanceState) {
            a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    });
}

ActivityLifecycleAdapter is just a helper class you'll need to create which will be an empty implementation of ActivityLifecycleCallbacks (so you don't have to override each and every methods of that interface when you simply need one of them).

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

How to copy text from a div to clipboard

Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.

Here is the link

How do I copy to the clipboard in JavaScript?

Pass parameter to controller from @Html.ActionLink MVC 4

The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g

@{         
     var blogPostId = 1;          
 }

If the error disappers, then u need to make sure that your model Id has a value before passing it to the view

Why am I getting a "401 Unauthorized" error in Maven?

If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847

The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.

How do I enable php to work with postgresql?

You need to install the pgsql module for php. In debian/ubuntu is something like this:

sudo apt-get install php5-pgsql

Or if the package is installed, you need to enable de module in php.ini

extension=php_pgsql.dll (windows)
extension=php_pgsql.so (linux)

Greatings.

Select first row in each GROUP BY group?

In PostgreSQL this is typically simpler and faster (more performance optimization below):

SELECT DISTINCT ON (customer)
       id, customer, total
FROM   purchases
ORDER  BY customer, total DESC, id;

Or shorter (if not as clear) with ordinal numbers of output columns:

SELECT DISTINCT ON (2)
       id, customer, total
FROM   purchases
ORDER  BY 2, 3 DESC, 1;

If total can be NULL (won't hurt either way, but you'll want to match existing indexes):

...
ORDER  BY customer, total DESC NULLS LAST, id;

Major points

DISTINCT ON is a PostgreSQL extension of the standard (where only DISTINCT on the whole SELECT list is defined).

List any number of expressions in the DISTINCT ON clause, the combined row value defines duplicates. The manual:

Obviously, two rows are considered distinct if they differ in at least one column value. Null values are considered equal in this comparison.

Bold emphasis mine.

DISTINCT ON can be combined with ORDER BY. Leading expressions in ORDER BY must be in the set of expressions in DISTINCT ON, but you can rearrange order among those freely. Example.
You can add additional expressions to ORDER BY to pick a particular row from each group of peers. Or, as the manual puts it:

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.

I added id as last item to break ties:
"Pick the row with the smallest id from each group sharing the highest total."

To order results in a way that disagrees with the sort order determining the first per group, you can nest above query in an outer query with another ORDER BY. Example.

If total can be NULL, you most probably want the row with the greatest non-null value. Add NULLS LAST like demonstrated. See:

The SELECT list is not constrained by expressions in DISTINCT ON or ORDER BY in any way. (Not needed in the simple case above):

  • You don't have to include any of the expressions in DISTINCT ON or ORDER BY.

  • You can include any other expression in the SELECT list. This is instrumental for replacing much more complex queries with subqueries and aggregate / window functions.

I tested with Postgres versions 8.3 – 13. But the feature has been there at least since version 7.1, so basically always.

Index

The perfect index for the above query would be a multi-column index spanning all three columns in matching sequence and with matching sort order:

CREATE INDEX purchases_3c_idx ON purchases (customer, total DESC, id);

May be too specialized. But use it if read performance for the particular query is crucial. If you have DESC NULLS LAST in the query, use the same in the index so that sort order matches and the index is applicable.

Effectiveness / Performance optimization

Weigh cost and benefit before creating tailored indexes for each query. The potential of above index largely depends on data distribution.

The index is used because it delivers pre-sorted data. In Postgres 9.2 or later the query can also benefit from an index only scan if the index is smaller than the underlying table. The index has to be scanned in its entirety, though.

For few rows per customer (high cardinality in column customer), this is very efficient. Even more so if you need sorted output anyway. The benefit shrinks with a growing number of rows per customer.
Ideally, you have enough work_mem to process the involved sort step in RAM and not spill to disk. But generally setting work_mem too high can have adverse effects. Consider SET LOCAL for exceptionally big queries. Find how much you need with EXPLAIN ANALYZE. Mention of "Disk:" in the sort step indicates the need for more:

For many rows per customer (low cardinality in column customer), a loose index scan (a.k.a. "skip scan") would be (much) more efficient, but that's not implemented up to Postgres 13. (An implementation for index-only scans is in development for Postgres 14. See here and here.)
For now, there are faster query techniques to substitute for this. In particular if you have a separate table holding unique customers, which is the typical use case. But also if you don't:

Benchmark

I had a simple benchmark here which is outdated by now. I replaced it with a detailed benchmark in this separate answer.

Add a scrollbar to a <textarea>

What you need is overflow-y: scroll;

Demo

_x000D_
_x000D_
    textarea {_x000D_
        overflow-y: scroll;_x000D_
        height: 100px;_x000D_
        resize: none; /* Remove this if you want the user to resize the textarea */_x000D_
    }
_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_

How to convert a string with comma-delimited items to a list in Python?

In case you want to split by spaces, you can just use .split():

a = 'mary had a little lamb'
z = a.split()
print z

Output:

['mary', 'had', 'a', 'little', 'lamb'] 

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

Divide and Conquer works by dividing the problem into sub-problems, conquer each sub-problem recursively and combine these solutions.

Dynamic Programming

Dynamic Programming is a technique for solving problems with overlapping subproblems. Each sub-problem is solved only once and the result of each sub-problem is stored in a table ( generally implemented as an array or a hash table) for future references. These sub-solutions may be used to obtain the original solution and the technique of storing the sub-problem solutions is known as memoization.

You may think of DP = recursion + re-use

A classic example to understand the difference would be to see both these approaches towards obtaining the nth fibonacci number. Check this material from MIT.


Divide and Conquer approach Divide and Conquer approach

Dynamic Programming Approach enter image description here

JWT refresh token flow

Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:

  1. just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens

  2. that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)

  3. an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants

append new row to old csv file python

If you use pandas, you can append your dataframes to an existing CSV file this way:

df.to_csv('log.csv', mode='a', index=False, header=False)

With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.

jQuery convert line breaks to br (nl2br equivalent)

I wrote a little jQuery extension for this:

$.fn.nl2brText = function (sText) {
    var bReturnValue = 'undefined' == typeof sText;
    if(bReturnValue) {
        sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
    }
    var aElms = [];
    sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
        if(aElms.length) {
            aElms.push(document.createElement('br'));
        }
        aElms.push(document.createTextNode(sSubstring));
    });
    var $aElms = $(aElms);
    if(bReturnValue) {
        return $aElms;
    }
    return this.empty().append($aElms);
};

SystemError: Parent module '' not loaded, cannot perform relative import

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

Swapping pointers in C (char, int)

In C, a string, as you know, is a character pointer (char *). If you want to swap two strings, you're swapping two char pointers, i.e. just two addresses. In order to do any swap in a function, you need to give it the addresses of the two things you're swapping. So in the case of swapping two pointers, you need a pointer to a pointer. Much like to swap an int, you just need a pointer to an int.

The reason your last code snippet doesn't work is because you're expecting it to swap two char pointers -- it's actually written to swap two characters!

Edit: In your example above, you're trying to swap two int pointers incorrectly, as R. Martinho Fernandes points out. That will swap the two ints, if you had:

int a, b;
intSwap(&a, &b);

Is it possible to do a sparse checkout without checking out the whole repository first?

I found the answer I was looking for from the one-liner posted earlier by pavek (thanks!) so I wanted to provide a complete answer in a single reply that works on Linux (GIT 1.7.1):

1--> mkdir myrepo
2--> cd myrepo
3--> git init
4--> git config core.sparseCheckout true
5--> echo 'path/to/subdir/' > .git/info/sparse-checkout
6--> git remote add -f origin ssh://...
7--> git pull origin master

I changed the order of the commands a bit but that does not seem to have any impact. The key is the presence of the trailing slash "/" at the end of the path in step 5.

Python: Finding differences between elements of a list

I suspect this is what the numpy diff command does anyway, but just for completeness you can simply difference the sub-vectors:

from numpy import array as a
a(x[1:])-a(x[:-1])

In addition, I wanted to add these solutions to generalizations of the question:

Solution with periodic boundaries

Sometimes with numerical integration you will want to difference a list with periodic boundary conditions (so the first element calculates the difference to the last. In this case the numpy.roll function is helpful:

v-np.roll(v,1)

Solutions with zero prepended

Another numpy solution (just for completeness) is to use

numpy.ediff1d(v)

This works as numpy.diff, but only on a vector (it flattens the input array). It offers the ability to prepend or append numbers to the resulting vector. This is useful when handling accumulated fields that is often the case fluxes in meteorological variables (e.g. rain, latent heat etc), as you want a resulting list of the same length as the input variable, with the first entry untouched.

Then you would write

np.ediff1d(v,to_begin=v[0])

Of course, you can also do this with the np.diff command, in this case though you need to prepend zero to the series with the prepend keyword:

np.diff(v,prepend=0.0) 

All the above solutions return a vector that is the same length as the input.

How do you test that a Python function throws an exception?

The code in my previous answer can be simplified to:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction)

And if afunction takes arguments, just pass them into assertRaises like this:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction, arg1, arg2)

Angular 4.3 - HttpClient set params

As for me, chaining set methods is the cleanest way

const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How do I expand the output display to see more columns of a pandas DataFrame?

Try this:

pd.set_option('display.expand_frame_repr', False)

From the documentation:

display.expand_frame_repr : boolean

Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if it’s width exceeds display.width. [default: True] [currently: True]

See: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html

How create table only using <div> tag and Css

A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS

.common_table{
    display:table;
    border-collapse:collapse;
    border:1px solid grey;
    }
.common_table DIV{
    display:table-row;
    border:1px solid grey;
    }
.common_table DIV DIV{
    display:table-cell;
    }

HTML

<DIV class="common_table">
   <DIV><DIV>this is a cell</DIV></DIV>
   <DIV><DIV>this is a cell</DIV></DIV>
</DIV>

Works on Chrome and Firefox

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

You can use auto in data placement like data-placement="auto left". It will automatic adjust according to your screen size and default placement will be left.

Want custom title / image / description in facebook share link from a flash app

I have a Joomla Module that displays stuff... and I want to be able to share that stuff on facebook and not the Page's Title Meta Description... so my workaround is to have a secret .php file on the server that gets executed when it detects the FB's

$_SERVER['HTTP_USER_AGENT']

if($_SERVER['HTTP_USER_AGENT'] != 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)') {
    echo 'Direct Access';
} else {
    echo 'FB Accessed';
}

and pass variables with the URL that formats that particular page with the title and meta desciption of the item I want to share from my joomla module...

a name="fb_share" share_url="MYURL/sharer.php?title=TITLE&desc=DESC"

hope this helps...

Reset the database (purge all), then seed a database

You can delete everything and recreate database + seeds with both:

  1. rake db:reset: loads from schema.rb
  2. rake db:drop db:create db:migrate db:seed: loads from migrations

Make sure you have no connections to db (rails server, sql client..) or the db won't drop.

schema.rb is a snapshot of the current state of your database generated by:

rake db:schema:dump

PHP Session Destroy on Log Out Button

First give the link of logout.php page in that logout button.In that page make the code which is given below:

Here is the code:

<?php
 session_start();
 session_destroy();
?>

When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.

error: passing xxx as 'this' argument of xxx discards qualifiers

Actually the C++ standard (i.e. C++ 0x draft) says (tnx to @Xeo & @Ben Voigt for pointing that out to me):

23.2.4 Associative containers
5 For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6 iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.

So VC++ 2008 Dinkumware implementation is faulty.


Old answer:

You got that error because in certain implementations of the std lib the set::iterator is the same as set::const_iterator.

For example libstdc++ (shipped with g++) has it (see here for the entire source code):

typedef typename _Rep_type::const_iterator            iterator;
typedef typename _Rep_type::const_iterator            const_iterator;

And in SGI's docs it states:

iterator       Container  Iterator used to iterate through a set.
const_iterator Container  Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)

On the other hand VC++ 2008 Express compiles your code without complaining that you're calling non const methods on set::iterators.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

The Unicode Method

I think it is much easier to just use a unicode character to get the job done. You can look through arrows by googling either Unicode Triangles or Unicode Arrows. Starting with iOS6 Apple changed the character to be an emoji character with a border. To disable the border I add the 0xFE0E Unicode Variation Selector.

NSString *backArrowString = @"\U000025C0\U0000FE0E"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR

UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.leftButtonItem = backBarButtonItem;

The code block is just for the demo. It would work in any button that accepts an NSString.

For a full list of characters search Google for Unicode character and what you want. Here is the entry for Black Left-Pointing Triangle.

Result

The result

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Implementing my own functional interfaces resolved this for me (so instead of using java.util.function.* just create your own single-method interface with the parameters and return-type you want).

removing bold styling from part of a header

It is super simple, By using "font" inside paragraph. An example is shown below:

<h1>Heading 1</h1>
<p><font size="6"> Heading 1</font></p>

Heading 1

Heading 1

Classes residing in App_Code is not accessible

In my case, I couldn't get a project to build with classes defined in the App_Code folder.

Can't replicate the scenario precisely to comment, but had to close and re-open visual studio for intellisense to co-operate agree...

I noticed that when a class in the App_Code folder is set to 'Compile' instead of 'Content' (right-click it) that the errors were coming from a second version of the class... Look to the left-most of the 3 of the 3 fields between the code pane and the tab. The 'other' one was called something along the lines of 10_App_Code or similar.

To rectify the issue, I renamed the folder from App_Code to Code, explicitly set namespaces on the classes and set all of the classes to 'Compile'

How to prove that a problem is NP complete?

First, you show that it lies in NP at all.

Then you find another problem that you already know is NP complete and show how you polynomially reduce NP Hard problem to your problem.

Android Studio 3.0 Execution failed for task: unable to merge dex

I also got the similar error.

Problem :

enter image description here

Solution :

Main root cause for this issue ismultiDex is not enabled. So in the Project/android/app/build.gradle, enable the multiDex

For further information refer the documentation: https://developer.android.com/studio/build/multidex#mdex-gradle

enter image description here

jQuery: Currency Format Number

Please find in the below code what I developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used ‘en’ while have tested for ‘es’, ‘fr’ and other countries where in the format varies. It not only stops user from keying characters but formats the value on tab out. Have created components for Number as well as for Decimal format. Apart from this have created parseNumber(value, locale) and parseDecimal(value, locale) functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used JQuery validator plugin in the below shared code.

HTML:

<tr>
                            <td>
                                <label class="control-label">
                                    Number Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="numberField" 
                                           name="numberField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="17"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           data-rule-numberExceedsMaxLimit="en"
                                           data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           onkeydown="return isNumber(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="numberFormatter(this,                                                           
                                                       'en', 
                                                       'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label class="control-label">
                                    Decimal Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="decimalField" 
                                           name="decimalField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="20"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           data-rule-decimalExceedsMaxLimit="en"
                                           data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           onkeydown="return isDecimal(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="decimalFormatter(this,
                                               'en', 
                                               'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>

JavaScript:

            /* 
     * @author: dinesh.lomte
     */
    /* Holds the maximum limit of digits to be entered in number field. */
    var numericMaxLimit = 13;
    /* Holds the maximum limit of digits to be entered in decimal field. */
    var decimalMaxLimit = 16;

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Boolean}
     */
    parseDecimal = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0.00;
        }
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            value = value.replace(/\./g, '');
        } else {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[0], 'g'), '');
        }
        if (getNumberFormat(locale)[1] === ',') {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[1], 'g'), '.');
        }
        return value;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    decimalFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();
        value = value.replace(/\s/g, '');
        value = parseDecimal(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    numberFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();    
        var format = getNumberFormat(locale);
        if (hasDecimal(value, format[1])) {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        value = value.replace(/\s/g, '');
        value = parseNumber(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} id
     * @param {type} flag
     * @param {type} message
     * @returns {undefined}
     */
    showErrorMessage = function(id, flag, message) {

        if (flag) {
            // only add if not added
            if ($('#'+id).parent().next('.app-error-message').length === 0) {
                var errorTag = '<div class=\'app-error-message\'>' + message + '</div>';
                $('#'+id).parent().after(errorTag);
            }
        } else {
            // remove it
            $('#'+id).parent().next(".app-error-message").remove(); 
        }
    };

    /**
     * 
     * @param {type} id             
     * @returns
     */
    setFocus = function(id) {

        id = id.trim();
        if (isNull(id)) {
            return;
        }
        setTimeout(function() {
            document.getElementById(id).focus();
        }, 10);
    };

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Array}
     */
    parseNumber = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0;
        }    
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            return value.replace(/\./g, '');
        }
        return value.replace(
                new RegExp(getNumberFormat(locale)[0], 'g'), '');
    };

    /**
     * 
     * @param {type} locale
     * @returns {Array}
     */
    getNumberFormat = function(locale) {

        var format = [];
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        var value = numberFormatObj.format('132617.07');
        format[0] = value.charAt(3);
        format[1] = value.charAt(7);
        return format;
    };

    /**
     * 
     * @param {type} value
     * @param {type} fractionFormat
     * @returns {Boolean}
     */
    hasDecimal = function(value, fractionFormat) {

        value = value.trim();
        if (isNull(value) || isNull(fractionFormat)) {
            return false;
        }
        if (value.indexOf(fractionFormat) >= 1) {
            return true;
        }
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isNumber = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {        
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && getNumberFormat(locale)[0] === getFormat(keyCode)) {        
            return true;
        }    
        return false;
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isDecimal = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && (getNumberFormat(locale)[0] === getFormat(keyCode)
                    || getNumberFormat(locale)[1] === getFormat(keyCode))) {
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {Boolean}
     */
    isNumberKey = function(keyCode) {

        if ((keyCode >= 48 && keyCode <= 57)
                || (keyCode >= 96 && keyCode <= 105)) {        
            return true;
        }
        var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];
        if (keys.indexOf(keyCode) !== -1) {        
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {JSON@call;parse.numberFormatter.value|String}
     */
    getFormat = function(keyCode) {

        var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';
        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.numberFormatter) {
            if (jsonObject.numberFormatter.hasOwnProperty(key)
                    && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {
                return jsonObject.numberFormatter[key].value;
            }
        }
        return '';
    };

    /**
     * 
     * @type String
     */
    var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';

    /**
     * 
     * @param {type} value
     * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}
     */
    getShiftCharSpecificNumber = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return jsonObject.shiftCharacterNumberMap[key].number;
            }
        }
        return '';
    };

    /**
     * 
     * @param {type} value
     * @returns {Boolean}
     */
    isShiftSpecificChar = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return true;
            }
        }
        return false;
    };

    /**
     * 
     * @param {type} element
     * @returns {undefined}
     */
    updateField = function(element) {

        var value = element.value;

        for (var index = 0; index < value.length; index++) {
            if (!isShiftSpecificChar(value.charAt(index))) {
                continue;
            }
            element.value = value.replace(
                    value.charAt(index),
                    getShiftCharSpecificNumber(value.charAt(index)));
        }
    };

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {

        value = parseInt(parseNumber(value, params));
        if (value.toString().length > numericMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {

        value = parseFloat(parseDecimal(value, params)).toFixed(2);    
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isNumberExceedMaxLimit = function(id, locale) {

        var value = parseInt(parseNumber(
                document.getElementById(id).value, locale));
        if (value.toString().length > numericMaxLimit) {
            setFocus(id);
            return true;
        }    
        return false;
    };

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isDecimalExceedsMaxLimit = function(id, locale) {

        var value = parseFloat(parseDecimal(
                document.getElementById(id).value, locale)).toFixed(2);
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            setFocus(id);
            return true;
        }
        return false;
    };

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if directory exists in %PATH%?

Another way to check if something is in the path is to execute some innocent executable that is not going to fail if it's there, and check the result. As an example, next code snippet checks if maven is in the path:

mvn --help > NUL 2> NUL 
if errorlevel 1 goto mvnNotInPath

So I try to run mvn --help, ignore the output (don't actually want to see the help if maven is there)( > NUL), and also don't display the error message if maven was not found (2> NUL).

How to quickly and conveniently create a one element arraylist

With Java 8 Streams:

Stream.of(object).collect(Collectors.toList())

or if you need a set:

Stream.of(object).collect(Collectors.toSet())