Programs & Examples On #Sentiment analysis

Sentiment analysis refers to categorizing some given data as to what sentiment(s) it expresses. Usually, it refers to extracting sentiment from text, e.g. tweets or blog posts.

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

What is the difference between a static method and a non-static method?

Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.

Refresh a page using JavaScript or HTML

If it has something to do control updates on cached pages here I have a nice method how to do this.

  • add some javascript to the page that always get the versionnumber of the page as a string (ajax) at loading. for example: www.yoursite.com/page/about?getVer=1&__[date]
  • Compare it to the stored versionnumber (stored in cookie or localStorage) if user has visited the page once, otherwise store it directly.
  • If version is not the same as local version, refresh the page using window.location.reload(true)
  • You will see any changes made on the page.

This method requires at least one request even when no request is needed because it already exists in the local browser cache. But the overhead is less comparing to using no cache at all (to be sure the page will show the right updated content). This requires just a few bytes for each page request instead of all content for each page.

IMPORTANT: The version info request must be implemented on your server otherwise it will return the whole page.

Example of version string returned by www.yoursite.com/page/about?getVer=1&__[date]: skg2pl-v8kqb

To give you an example in code, here is a part of my library (I don't think you can use it but maybe it gives you some idea how to do it):

o.gCheckDocVersion = function() // Because of the hard caching method, check document for changes with ajax 
{
  var sUrl = o.getQuerylessUrl(window.location.href),
      sDocVer = o.gGetData( sUrl, false );

  o.ajaxRequest({ url:sUrl+'?getVer=1&'+o.uniqueId(), cache:0, dataType:'text' }, 
                function(sVer)
                {
                   if( typeof sVer == 'string' && sVer.length )
                   {
                     var bReload = (( typeof sDocVer == 'string' ) && sDocVer != sVer );
                     if( bReload || !sDocVer )
                      { 
                        o.gSetData( sUrl, sVer ); 
                        sDocVer = o.gGetData( sUrl, false );
                        if( bReload && ( typeof sDocVer != 'string' || sDocVer != sVer ))
                         { bReload = false; }
                      }
                     if( bReload )
                      {  // Hard refresh page contents
                        window.location.reload(true); }
                   }
                }, false, false );
};

If you are using version independent resources like javascript or css files, add versionnumbers (implemented with a url rewrite and not with a query because they mostly won't be cached). For example: www.yoursite.com/ver-01/about.js

For me, this method is working great, maybe it can help you too.

Spring Boot - Cannot determine embedded database driver class for database type NONE

I tried all the mentioned things above but could not resolve the issue. I am using SQLite and my SQLite file was in the resources directory.

a) Set Up done for IDE

I need to manually add below lines in the .classpath file of my project.

<classpathentry kind="src" path="resources"/>
<classpathentry kind="output" path="target/classes"/>

After that, I refreshed and Cleaned the project from MenuBar at the top. like Project->Clean->My Project Name.

After that, I run the project and problem resolved.

application.properties for my project is

spring.datasource.url=jdbc:sqlite:resources/apiusers.sqlite
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.jpa.properties.hibernate.dialect=com.enigmabridge.hibernate.dialect.SQLiteDialect
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update

b) Set Up done if Jar deployment throw same error

You need to add following lines to your pom.xml

  <build>
        <resources>
        <resource>
            <directory>resources</directory>
            <targetPath>${project.build.outputDirectory}</targetPath>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>
</build>

May be it may help someone.

R: Break for loop

your break statement should break out of the for (in in 1:n).

Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n so I don't know if it would be helpful to you. Make a n some test value where you know before hand if it is supposed to break out or not before reaching n.

for (in in 1:n)
{
    if (in == n)         #add this statement
    {
        "sorry but the loop did not break"
    }

    id_novo <- new_table_df$ID[in]
    if(id_velho==id_novo)
    {
        break
    }
    else if(in == n)
    {
        sold_df <- rbind(sold_df,old_table_df[out,])
    }
}

Two's Complement in Python

A couple of implementations (just an illustration, not intended for use):

def to_int(bin):
    x = int(bin, 2)
    if bin[0] == '1': # "sign bit", big-endian
       x -= 2**len(bin)
    return x

def to_int(bin): # from definition
    n = 0
    for i, b in enumerate(reversed(bin)):
        if b == '1':
           if i != (len(bin)-1):
              n += 2**i
           else: # MSB
              n -= 2**i 
    return n

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Pass command parameter to method in ViewModel in WPF?

Try this:

 public class MyVmBase : INotifyPropertyChanged
{
  private ICommand _clickCommand;
   public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
        }
    }
    
       public void MyAction(object message)
    {
        if(message == null)
        {
            Notify($"Method {message} not defined");
            return;
        }
        switch (message.ToString())
        {
            case "btnAdd":
                {
                    btnAdd_Click();
                    break;
                }

            case "BtnEdit_Click":
                {
                    BtnEdit_Click();
                    break;
                }

            default:
                throw new Exception($"Method {message} not defined");
                break;
        }
    }
}

  public class CommandHandler : ICommand
{
    private Action<object> _action;
    private Func<object, bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action<object> action, Func<object, bool> canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
        _canExecute = canExecute ?? (x => true);
    }
    public CommandHandler(Action<object> action) : this(action, null)
    {
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
    public void Refresh()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

And in xaml:

     <Button
    Command="{Binding ClickCommand}"
    CommandParameter="BtnEdit_Click"/>

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

INNER JOIN in UPDATE sql for DB2

for you ask

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%'

if join give multiple result you can force update like this

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
fetch first rows only
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%' 

template methode

update table1 f1
set (f1.field1, f1.field2, f1.field3, f1.field4)=
(
select f2.field1, f2.field2, f2.field3, 'CONSTVALUE'
from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2) 
)
where exists 
(
select * from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2)
) 

Elegant solution for line-breaks (PHP)

I have defined this:

if (PHP_SAPI === 'cli')
{
   define( "LNBR", PHP_EOL);
}
else
{
   define( "LNBR", "<BR/>");
}

After this use LNBR wherever I want to use \n.

Web link to specific whatsapp contact

You can now use a very simple API https://wa.me/ to perform this task where you can provide a valid whatsapp contact number like 15555555555 ( add country code, remove all '+', '-', brackets, spaces or leading zeros). You can also provide a urlencoded text as a predefined msg which user can send directly or change before sending.

Chat with me link : <a href="https://wa.me/15555555555">Contact me by whatsapp</a>

Chat with me link with predefined text : <a href="https://wa.me/15555555555?text=I%27d%20like%20to%20chat%20with%20you">Contact me on whatsapp</a>

Beauty of this wa.me url is you don't need to check user agent as it works on both mobile and desktop (opens web.whatsapp.com)


Source : https://faq.whatsapp.com/en/general/26000030

More details in my answer on a similar question https://stackoverflow.com/a/51854282/2485420

Getting the array length of a 2D array in Java

.length = number of rows / column length

[0].length = number of columns / row length

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

How can I clear the SQL Server query cache?

Here is some good explaination. check out it.

http://www.mssqltips.com/tip.asp?tip=1360

CHECKPOINT; 
GO 
DBCC DROPCLEANBUFFERS; 
GO

From the linked article:

If all of the performance testing is conducted in SQL Server the best approach may be to issue a CHECKPOINT and then issue the DBCC DROPCLEANBUFFERS command. Although the CHECKPOINT process is an automatic internal system process in SQL Server and occurs on a regular basis, it is important to issue this command to write all of the dirty pages for the current database to disk and clean the buffers. Then the DBCC DROPCLEANBUFFERS command can be executed to remove all buffers from the buffer pool.

Adding a directory to the PATH environment variable in Windows

You don't need any set or setx command. Simply open the terminal and type:

PATH

This shows the current value of PATH variable. Now you want to add directory to it? Simply type:

PATH %PATH%;C:\xampp\php

If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:

PATH ;

Update

Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.

To check if an environmental variable exist or see its value, use the ECHO command:

echo %YOUR_ENV_VARIABLE%

RecyclerView - Get view at particular position

Keep in mind that you have to wait until adapter will added to list, then you can try to getting view by position

final int i = 0;
recyclerView.setAdapter(adapter);
recyclerView.post(new Runnable() {
    @Override
    public void run() {
        View view = recyclerView.getLayoutManager().findViewByPosition(i);
    }
});

adb server version doesn't match this client

I just exited HTC Sync, tried again, and it worked. Notice: Phone went black(locked), I just turned it on, and there was my application running. :)

ProgressDialog is deprecated.What is the alternate one to use?

Maybe this guide could help you.

Usually I prefer to make custom AlertDialogs with indicators. It solves such problems like customization of the App view.

Replace Line Breaks in a String C#

If you want to replace only the newlines:

var input = @"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
var match = @"[\\ ]+";
var replaceWith = " ";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input.Replace(@"\n", replaceWith).Replace(@"\r", replaceWith), match, replaceWith);
Console.WriteLine("output: " + x);

If you want to replace newlines, tabs and white spaces:

var input = @"sdfhlusdkuidfs\r\ndfgdgfd";
var match = @"[\\s]+";
var replaceWith = "";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input, match, replaceWith);
Console.WriteLine("output: " + x);

How to replace all occurrences of a character in string?

For simple situations this works pretty well without using any other library then std::string (which is already in use).

Replace all occurences of character a with character b in some_string:

for (size_t i = 0; i < some_string.size(); ++i) {
    if (some_string[i] == 'a') {
        some_string.replace(i, 1, "b");
    }
}

If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://stackoverflow.com/a/29752943/3622300

How to get datetime in JavaScript?

You can convert Date to almost any format using the Snippet I have added below.

Code:

dateFormat(new Date(),"dd/mm/yy h:MM TT")
//"20/06/14 6:49 PM"

Other examples

// Can also be used as a standalone function
dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

dateFormat(new Date(),"dddd d mmmm yyyy")
//Monday 2 June 2014"

Snippet:

Add following code taken from this link into your code.

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

Shortcut to create properties in Visual Studio?

When you write in Visual Studio,

public ServiceTypesEnum Type { get; set; }
public string TypeString { get { return this.Type.ToString();}}

ReSharper will keep suggesting to convert it to:

public string TypeString => Type.ToString();

How do I determine the size of my array in C?

#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))

Docker remove <none> TAG images

Remove images which have none as the repository name using the following:

docker rmi $(docker images | grep "^<none" | awk '{print $3}')

Remove images which have none tag or repository name:

docker rmi $(docker images | grep "none" | awk '{print $3}')

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman's answer for more clarity on what happens while executing the code.

The internal thread pool in nodeJs just has 4 threads by default. and its not like the whole request is attached to a new thread from the thread pool the whole execution of request happens just like any normal request (without any blocking task) , just that whenever a request has any long running or a heavy operation like db call ,a file operation or a http request the task is queued to the internal thread pool which is provided by libuv. And as nodeJs provides 4 threads in internal thread pool by default every 5th or next concurrent request waits until a thread is free and once these operations are over the callback is pushed to the callback queue. and is picked up by event loop and sends back the response.

Now here comes another information that its not once single callback queue, there are many queues.

  1. NextTick queue
  2. Micro task queue
  3. Timers Queue
  4. IO callback queue (Requests, File ops, db ops)
  5. IO Poll queue
  6. Check Phase queue or SetImmediate
  7. close handlers queue

Whenever a request comes the code gets executing in this order of callbacks queued.

It is not like when there is a blocking request it is attached to a new thread. There are only 4 threads by default. So there is another queueing happening there.

Whenever in a code a blocking process like file read occurs , then calls a function which utilises thread from thread pool and then once the operation is done , the callback is passed to the respective queue and then executed in the order.

Everything gets queued based on the the type of callback and processed in the order mentioned above.

For vs. while in C programming?

WHILE is more flexible. FOR is more concise in those instances in which it applies.

FOR is great for loops which have a counter of some kind, like

for (int n=0; n<max; ++n)

You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.

FOR can also work nicely with things other than a counter, of course. Like

for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())

Etc.

But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:

initializeList();
while (listHasMoreElements())
{
  n=getCurrentElement();
  int status=processElement(n);
  if (status>0)
  {
    skipElements(status);
    advanceElementPointer();
  }
  else
  {
    n=-status;
    findElement(n);
  }
}

That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.

In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

Centering elements in jQuery Mobile

An overkill approach: in inline css in the div did the trick:

style="margin:0 auto;
margin-left:auto;
margin-right:auto;
align:center;
text-align:center;"

Centers like a charm!

What is the most effective way to get the index of an iterator of an std::vector?

I would prefer it - vec.begin() precisely for the opposite reason given by Naveen: so it wouldn't compile if you change the vector into a list. If you do this during every iteration, you could easily end up turning an O(n) algorithm into an O(n^2) algorithm.

Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter.

Note: it is a common name for a container iterator,std::container_type::iterator it;.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

I added $(inherited) but my project was still not compiling. For me problem was flag "Build for active Architecture only", I had to set it to YES.

Detecting an undefined object property

I would like to show you something I'm using in order to protect the undefined variable:

Object.defineProperty(window, 'undefined', {});

This forbids anyone to change the window.undefined value therefore destroying the code based on that variable. If using "use strict", anything trying to change its value will end in error, otherwise it would be silently ignored.

Regular expression replace in C#

Try this::

sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
    m => string.Format(
        "{0},{1},{2}",
        m.Groups[1].Value,
        m.Groups[2].Value.Replace(",", string.Empty),
        m.Groups[3].Value));

This is about as clean an answer as you'll get, at least with regexes.

  • (\D+): First capture group. One or more non-digit characters.
  • \s+\$: One or more spacing characters, then a literal dollar sign ($).
  • ([\d,]+): Second capture group. One or more digits and/or commas.
  • \.\d+: Decimal point, then at least one digit.
  • \s+: One or more spacing characters.
  • (.): Third capture group. Any non-line-breaking character.

The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:

"$1,$2,$3"

mysql alphabetical order

i want to show records only starting with b

select name from user where name LIKE 'b%';

i am trying to sort MySQL data alphabeticaly

select name from user ORDER BY name;

i am trying to sort MySQL data in reverse alphabetic order

select name from user ORDER BY name desc;

What's the difference between JPA and Hibernate?

JPA is a specification to standardize ORM-APIs. Hibernate is a vendor of a JPA implementation. So if you use JPA with hibernate, you can use the standard JPA API, hibernate will be under the hood, offering some more non standard functions. See http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/ and http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

How to get back Lost phpMyAdmin Password, XAMPP

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password WhateverPassword

where 'WhateverPassword' is your new password.

PHP: Read Specific Line From File

You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).

This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.

<?php 
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
 {
  $theData = fgets($fh);
  $i++
 }
fclose($fh);
echo $theData;
?>

Converting a column within pandas dataframe from int to string

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

Convert a series

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

Don't forget to assign the result back:

df['A'] = df['A'].apply(str)

Convert the whole frame

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

How to get rid of underline for Link component of React Router?

I think the best way to use react-router-dom Link in a MenuItem (and other MaterialUI component such as buttons) is to pass the Link in the "component" prop

<Menu>
   <MenuItem component={Link} to={'/first'}>Team 1</MenuItem>
   <MenuItem component={Link} to={'/second'}>Team 2</MenuItem>
</Menu>

you need to pass the route path in the 'to' prop of the "MenuItem" (which will be passed down to the Link component). In this way you don't need to add any style as it will use the MenuItem style

Multiple Cursors in Sublime Text 2 Windows

I find using vintage mode works really well with sublime multiselect.

My most used keys would be "w" for jumping a word, "^" and "$" to move to first/last character of the line. Combinations like "2dw" (delete the next two words after the cursor) make using multiselect really powerful.

This sounds obvious but has really sped up my workflow, especially when editing HTML.

How to detect the OS from a Bash script?

Try using "uname". For example, in Linux: "uname -a".

According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.

BTW: $OSTYPE is also set to linux-gnu here :)

Get property value from string using reflection

jheddings and AlexD both wrote excellent answers on how to resolve property strings. I'd like to throw mine in the mix, since I wrote a dedicated library exactly for that purpose.

Pather.CSharp's main class is Resolver. Per default it can resolve properties, array and dictionary entries.

So, for example, if you have an object like this

var o = new { Property1 = new { Property2 = "value" } };

and want to get Property2, you can do it like this:

IResolver resolver = new Resolver();
var path = "Property1.Property2";
object result = r.Resolve(o, path); 
//=> "value"

This is the most basic example of the paths it can resolve. If you want to see what else it can, or how you can extend it, just head to its Github page.

JavaScript replace \n with <br />

Handles either type of line break

str.replace(new RegExp('\r?\n','g'), '<br />');

If '<selector>' is an Angular component, then verify that it is part of this module

Check which module the parent component is being declared in...

If your parent component is defined in the shared module, so must your child module.

The parent component could be declared in a shared module and not the module that is logical based on the file directory structure / naming, even the Angular CLI added it into the wrong module in my case.

Adding a column after another column within SQL

Assuming MySQL (EDIT: posted before the SQL variant was supplied):

ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn

The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.

How can I auto hide alert box after it showing it?

You can also try Notification API. Here's an example:

function message(msg){
    if (window.webkitNotifications) {
        if (window.webkitNotifications.checkPermission() == 0) {
        notification = window.webkitNotifications.createNotification(
          'picture.png', 'Title', msg);
                    notification.onshow = function() { // when message shows up
                        setTimeout(function() {
                            notification.close();
                        }, 1000); // close message after one second...
                    };
        notification.show();
      } else {
        window.webkitNotifications.requestPermission(); // ask for permissions
      }
    }
    else {
        alert(msg);// fallback for people who does not have notification API; show alert box instead
    }
    }

To use this, simply write:

message("hello");

Instead of:

alert("hello");

Note: Keep in mind that it's only currently supported in Chrome, Safari, Firefox and some mobile web browsers (jan. 2014)

Find supported browsers here.

selenium - chromedriver executable needs to be in PATH

try this :

driver = webdriver.Chrome(ChromeDriverManager().install())

How to count number of files in each directory?

find . -type f | cut -d/ -f2 | sort | uniq -c
  • find. -type f to find all items of the type file
  • cut -d/ -f2 to cut out their specific folder
  • sort to sort the list of foldernames
  • uniq -c to return the number of times each foldername has been counted

Selecting a row of pandas series/dataframe by integer index

echoing @HYRY, see the new docs in 0.11

http://pandas.pydata.org/pandas-docs/stable/indexing.html

Here we have new operators, .iloc to explicity support only integer indexing, and .loc to explicity support only label indexing

e.g. imagine this scenario

In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))

In [2]: df
Out[2]: 
          A         B
0  1.068932 -0.794307
2 -0.470056  1.192211
4 -0.284561  0.756029
6  1.037563 -0.267820
8 -0.538478 -0.800654

In [5]: df.iloc[[2]]
Out[5]: 
          A         B
4 -0.284561  0.756029

In [6]: df.loc[[2]]
Out[6]: 
          A         B
2 -0.470056  1.192211

[] slices the rows (by label location) only

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

CSS Layout - Dynamic width DIV

This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

<div style="width:100%;">
    <div style="width: 50px; float: left;">Left Side</div>
    <div style="width: 50px; float: right;">Right Side</div>
    <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>

Postgresql tables exists, but getting "relation does not exist" when querying

You have to include the schema if isnt a public one

SELECT *
FROM <schema>."my_table"

Or you can change your default schema

SHOW search_path;
SET search_path TO my_schema;

Check your table schema here

SELECT *
FROM information_schema.columns

enter image description here

For example if a table is on the default schema public both this will works ok

SELECT * FROM parroquias_region
SELECT * FROM public.parroquias_region

But sectors need specify the schema

SELECT * FROM map_update.sectores_point

Load image with jQuery and append it to the DOM

I imagine that you define your image something like this:

<img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />

You can simply load/update image for this tag and chage/set atts (width,height):

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Alternative to mysql_real_escape_string without connecting to DB

From further research, I've found:

http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html

Security Fix:

An SQL-injection security hole has been found in multi-byte encoding processing. The bug was in the server, incorrectly parsing the string escaped with the mysql_real_escape_string() C API function.

This vulnerability was discovered and reported by Josh Berkus and Tom Lane as part of the inter-project security collaboration of the OSDB consortium. For more information about SQL injection, please see the following text.

Discussion. An SQL injection security hole has been found in multi-byte encoding processing. An SQL injection security hole can include a situation whereby when a user supplied data to be inserted into a database, the user might inject SQL statements into the data that the server will execute. With regards to this vulnerability, when character set-unaware escaping is used (for example, addslashes() in PHP), it is possible to bypass the escaping in some multi-byte character sets (for example, SJIS, BIG5 and GBK). As a result, a function such as addslashes() is not able to prevent SQL-injection attacks. It is impossible to fix this on the server side. The best solution is for applications to use character set-aware escaping offered by a function such mysql_real_escape_string().

However, a bug was detected in how the MySQL server parses the output of mysql_real_escape_string(). As a result, even when the character set-aware function mysql_real_escape_string() was used, SQL injection was possible. This bug has been fixed.

Workarounds. If you are unable to upgrade MySQL to a version that includes the fix for the bug in mysql_real_escape_string() parsing, but run MySQL 5.0.1 or higher, you can use the NO_BACKSLASH_ESCAPES SQL mode as a workaround. (This mode was introduced in MySQL 5.0.1.) NO_BACKSLASH_ESCAPES enables an SQL standard compatibility mode, where backslash is not considered a special character. The result will be that queries will fail.

To set this mode for the current connection, enter the following SQL statement:

SET sql_mode='NO_BACKSLASH_ESCAPES';

You can also set the mode globally for all clients:

SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';

This SQL mode also can be enabled automatically when the server starts by using the command-line option --sql-mode=NO_BACKSLASH_ESCAPES or by setting sql-mode=NO_BACKSLASH_ESCAPES in the server option file (for example, my.cnf or my.ini, depending on your system). (Bug#8378, CVE-2006-2753)

See also Bug#8303.

SQL: How to properly check if a record exists

The other answers are quite good, but it would also be useful to add LIMIT 1 (or the equivalent, to prevent the checking of unnecessary rows.

How do I encode and decode a base64 string?

I'm sharing my implementation with some neat features:

  • uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
  • Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)).

Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding).

Code:

namespace MyApplication.Helpers.Encoding
{
    public static class EncodingForBase64
    {
        public static string EncodeBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return System.Convert.ToBase64String(textAsBytes);
        }

        public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
        {
            if (encodedText == null)
            {
                return null;
            }

            byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
            return encoding.GetString(textAsBytes);
        }
    }
}

Usage example:

using MyApplication.Helpers.Encoding; // !!!

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
            Test2();
        }

        static void Test1()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
            System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == "test1...");
        }

        static void Test2()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
            System.Diagnostics.Debug.Assert(textEncoded == null);

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == null);
        }
    }
}

single line comment in HTML

No, <!-- ... --> is the only comment syntax in HTML.

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

Sublime Text 2 - View whitespace characters

If you want to be able to toggle the display of whitespaces on and off, you can install the HighlightWhitespaces plugin

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Parse string to DateTime in C#

DateTime.Parse() should work fine for that string format. Reference:

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx#Y1240

Is it throwing a FormatException for you?

pip not working in Python Installation in Windows 10

I had the same problem on Visual Studio Code. For various reasons several python versions are installed on my computer. I was thus able to easily solve the problem by switching python interpreter.

If like me you have several versions of python on you machine, in Visual Studio Code, you can easily change the interpreter by clicking on the bottom left corner where it says Python...

enter image description here

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel

and

sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel

and

sudo python3 -m pip install pandas

Good Luck!

How to make promises work in IE11

You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.

used like: window.Promise https://www.npmjs.com/package/promise-polyfill

If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill

How do I pass JavaScript variables to PHP?

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

Import existing Gradle Git project into Eclipse

You can do the following steps:

  1. Install the Buildship Gradle Integration using the Eclipse Marketplace. Simply type Buildship and click on search item. Now click on Install.

  2. Click on File -> Import ? Existing Gradle Project.

  3. Navigate to project root directory.

  4. Click on a finish to load your project.

Might be it will take some time for the first time to import Gradle project. So please be patient on it.

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

How do I add a custom script to my package.json file that runs a javascript file?

Suppose I have this line of scripts in my "package.json"

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "export_advertisements": "node export.js advertisements",
    "export_homedata": "node export.js homedata",
    "export_customdata": "node export.js customdata",
    "export_rooms": "node export.js rooms"
  },

Now to run the script "export_advertisements", I will simply go to the terminal and type

npm run export_advertisements

You are most welcome

How to check whether the user uploaded a file in PHP?

@karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.

/**
 * Tests all upload fields to determine whether any files were submitted.
 * 
 * @return boolean
 */
function files_uploaded() {

    // bail if there were no upload forms
   if(empty($_FILES))
        return false;

    // check for uploaded files
    $files = $_FILES['files']['tmp_name'];
    foreach( $files as $field_title => $temp_name ){
        if( !empty($temp_name) && is_uploaded_file( $temp_name )){
            // found one!
            return true;
        }
    }   
    // return false if no files were found
   return false;
}

React.js inline style best practices

For some components, it is easier to use inline styles. Also, I find it easier and more concise (as I'm using Javascript and not CSS) to animate component styles.

For stand-alone components, I use the 'Spread Operator' or the '...'. For me, it's clear, beautiful, and works in a tight space. Here is a little loading animation I made to show it's benefits:

<div style={{...this.styles.container, ...this.state.opacity}}>
    <div style={{...this.state.colors[0], ...this.styles.block}}/>
    <div style={{...this.state.colors[1], ...this.styles.block}}/>
    <div style={{...this.state.colors[2], ...this.styles.block}}/>
    <div style={{...this.state.colors[7], ...this.styles.block}}/>
    <div style={{...this.styles.block}}/>
    <div style={{...this.state.colors[3], ...this.styles.block}}/>
    <div style={{...this.state.colors[6], ...this.styles.block}}/>
    <div style={{...this.state.colors[5], ...this.styles.block}}/>
    <div style={{...this.state.colors[4], ...this.styles.block}}/>
  </div>

    this.styles = {
  container: {
    'display': 'flex',
    'flexDirection': 'row',
    'justifyContent': 'center',
    'alignItems': 'center',
    'flexWrap': 'wrap',
    'width': 21,
    'height': 21,
    'borderRadius': '50%'
  },
  block: {
    'width': 7,
    'height': 7,
    'borderRadius': '50%',
  }
}
this.state = {
  colors: [
    { backgroundColor: 'red'},
    { backgroundColor: 'blue'},
    { backgroundColor: 'yellow'},
    { backgroundColor: 'green'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
  ],
  opacity: {
    'opacity': 0
  }
}

EDIT NOVEMBER 2019

Working in the industry (A Fortune 500 company), I am NOT allowed to make any inline styling. In our team, we've decided that inline style are unreadable and not maintainable. And, after having seen first hand how inline styles make supporting an application completely intolerable, I'd have to agree. I completely discourage inline styles.

Error to run Android Studio

Widows 7 64 bit.

  1. JAVA_HOME point to my JRE (NOT JDK) directory
  2. Coping of tools.jar from JDK\lib directory to ANDROIDSTUDIO\lib directory solve the problem

Printing *s as triangles in Java?

Ilmari Karonen has good advice, and I'd just like to generalize it a bit. In general, before you ask "how can I get a computer to do this?" ask "how would I do this?"

So, if someone gave you an empty Word document and asked you to create the triangles, how would you go about doing it? Whatever solution you come up with, it's usually not hard to translate it to Java (or any other programming language). It might not be the best solution, but (hopefully!) it'll work, and it may point you to a better solution.

So for instance, maybe you would say that you'd type out the base, then go up a line, then type the next highest line, etc. That suggests that you can do the same in Java -- create a list of Strings, base-to-top, and then reverse them. That might suggest that you can just create them in reverse order, and then not have to reverse them. And then that might suggest that you don't need the list anymore, since you'll just be creating and printing them out in the same order -- at which point you've come up with essentially Ilmari Karonen's advice.

Or, maybe you'd come up with another way of doing it -- maybe you'd come up with Ilmari Karonen's idea more directly. Regardless, it should help you solve this and many other problems.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

You can directly go to http://127.0.0.1:8080/apex/f?p=4950 and you will get Home Page Of your Oracle Database.

Right click on the shortcut > choose properties > go to security tab > Choose Authenticated Users > and give permission to do everything

and now try to change the URL you will be able to do it.

Hope this help

Why am I getting ImportError: No module named pip ' right after installing pip?

If you wrote

pip install --upgrade pip

and you got

Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.2.1
    Uninstalling pip-20.2.1:
ERROR: Could not install packages due to an EnvironmentError...

then you have uninstalled pip instead install pip. This could be the reason of your problem.

The Gorodeckij Dimitrij's answer works for me.

python -m ensurepip

HTML entity for check mark

HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <, >, " and & characters as these are reserved in SGML.

Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).

Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: &#x2714; ✔.

&#x2714;

Is using hex notation and is the same as

$#10004;

(as 2714 in base 16 is the same as 10004 in base 10)

How to copy a map?

You have to manually copy each key/value pair to a new map. This is a loop that people have to reprogram any time they want a deep copy of a map.

You can automatically generate the function for this by installing mapper from the maps package using

go get -u github.com/drgrib/maps/cmd/mapper

and running

mapper -types string:aStruct

which will generate the file map_float_astruct.go containing not only a (deep) Copy for your map but also other "missing" map functions ContainsKey, ContainsValue, GetKeys, and GetValues:

func ContainsKeyStringAStruct(m map[string]aStruct, k string) bool {
    _, ok := m[k]
    return ok
}

func ContainsValueStringAStruct(m map[string]aStruct, v aStruct) bool {
    for _, mValue := range m {
        if mValue == v {
            return true
        }
    }

    return false
}

func GetKeysStringAStruct(m map[string]aStruct) []string {
    keys := []string{}

    for k, _ := range m {
        keys = append(keys, k)
    }

    return keys
}

func GetValuesStringAStruct(m map[string]aStruct) []aStruct {
    values := []aStruct{}

    for _, v := range m {
        values = append(values, v)
    }

    return values
}

func CopyStringAStruct(m map[string]aStruct) map[string]aStruct {
    copyMap := map[string]aStruct{}

    for k, v := range m {
        copyMap[k] = v
    }

    return copyMap
}

Full disclosure: I am the creator of this tool. I created it and its containing package because I found myself constantly rewriting these algorithms for the Go map for different type combinations.

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

Why doesn't Java support unsigned ints?

Because unsigned type is pure evil.

The fact that in C unsigned - int produces unsigned is even more evil.

Here is a snapshot of the problem that burned me more than once:

// We have odd positive number of rays, 
// consecutive ones at angle delta from each other.
assert( rays.size() > 0 && rays.size() % 2 == 1 );

// Get a set of ray at delta angle between them.
for( size_t n = 0; n < rays.size(); ++n )
{
    // Compute the angle between nth ray and the middle one.
    // The index of the middle one is (rays.size() - 1) / 2,
    // the rays are evenly spaced at angle delta, therefore
    // the magnitude of the angle between nth ray and the 
    // middle one is: 
    double angle = delta * fabs( n - (rays.size() - 1) / 2 ); 

    // Do something else ...
}

Have you noticed the bug yet? I confess I only saw it after stepping in with the debugger.

Because n is of unsigned type size_t the entire expression n - (rays.size() - 1) / 2 evaluates as unsigned. That expression is intended to be a signed position of the nth ray from the middle one: the 1st ray from the middle one on the left side would have position -1, the 1st one on the right would have position +1, etc. After taking abs value and multiplying by the delta angle I would get the angle between nth ray and the middle one.

Unfortunately for me the above expression contained the evil unsigned and instead of evaluating to, say, -1, it evaluated to 2^32-1. The subsequent conversion to double sealed the bug.

After a bug or two caused by misuse of unsigned arithmetic one has to start wondering whether the extra bit one gets is worth the extra trouble. I am trying, as much as feasible, to avoid any use of unsigned types in arithmetic, although still use it for non-arithmetic operations such as binary masks.

self referential struct definition?

There is sort of a way around this:

struct Cell {
  bool isParent;
  struct Cell* child;
};

struct Cell;
typedef struct Cell Cell;

If you declare it like this, it properly tells the compiler that struct Cell and plain-ol'-cell are the same. So you can use Cell just like normal. Still have to use struct Cell inside of the initial declaration itself though.

Casting an int to a string in Python

You can use str() to cast it, or formatters:

"ME%d.txt" % (num,)

Call a child class method from a parent class object

A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:

class Person {
    String name;
    void getName(){...}
    void calculate();
}

and then

class Student extends Person{
    String class;
    void getClass(){...}

    @Override
    void calculate() {
        // do something with a Student
    }
}

and

class Teacher extends Person{
    String experience;
    void getExperience(){...}

    @Override
    void calculate() {
        // do something with a Student
    }

}

By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.

In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

What are the true benefits of ExpandoObject?

It's example from great MSDN article about using ExpandoObject for creating dynamic ad-hoc types for incoming structured data (i.e XML, Json).

We can also assign delegate to ExpandoObject's dynamic property:

dynamic person = new ExpandoObject();
person.FirstName = "Dino";
person.LastName = "Esposito";

person.GetFullName = (Func<String>)(() => { 
  return String.Format("{0}, {1}", 
    person.LastName, person.FirstName); 
});

var name = person.GetFullName();
Console.WriteLine(name);

Thus it allows us to inject some logic into dynamic object at runtime. Therefore, together with lambda expressions, closures, dynamic keyword and DynamicObject class, we can introduce some elements of functional programming into our C# code, which we knows from dynamic languages as like JavaScript or PHP.

Keyboard shortcut to comment lines in Sublime Text 2

Ctrl+d and Ctrl+Shift+d....

[

{ "keys": ["ctrl+d"], "command": "toggle_comment", "args": { "block": false } },

{ "keys": ["ctrl+shift+d"], "command": "toggle_comment", "args": { "block": true } },

]

How do I send a POST request as a JSON?

Here is an example of how to use urllib.request object from Python standard library.

import urllib.request
import json
from pprint import pprint

url = "https://app.close.com/hackwithus/3d63efa04a08a9e0/"

values = {
    "first_name": "Vlad",
    "last_name": "Bezden",
    "urls": [
        "https://twitter.com/VladBezden",
        "https://github.com/vlad-bezden",
    ],
}


headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}

data = json.dumps(values).encode("utf-8")
pprint(data)

try:
    req = urllib.request.Request(url, data, headers)
    with urllib.request.urlopen(req) as f:
        res = f.read()
    pprint(res.decode())
except Exception as e:
    pprint(e)

What is the default encoding of the JVM?

There are three "default" encodings:

  • file.encoding:
    System.getProperty("file.encoding")

  • java.nio.Charset:
    Charset.defaultCharset()

  • And the encoding of the InputStreamReader:
    InputStreamReader.getEncoding()

You can read more about it on this page.

How to convert upper case letters to lower case

You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.

w.strip(',.').lower()

How to make rpm auto install dependencies

Process of generating RPM from source file: 1) download source file with.gz extention. 2) install rpm-build and rpmdevtools from yum install. (rpmbuild folder will be generated...SPECS,SOURCES,RPMS.. folders will should be generated inside the rpmbuild folder). 3) copy the source code.gz to SOURCES folder.(rpmbuild/SOURCES) 4)Untar the tar ball by using the following command. go to SOURCES folder :rpmbuild/SOURCES where tar file is present. command: e.g tar -xvzf httpd-2.22.tar.gz httpd-2.22 folder will be generated in the same path. Check if apr and apr-util and there in httpd-2.22/srclib folder. If apr and apr-util doesnt exist download latest version from apache site ,untar it and put it inside httpd-2.22/srclib folder. Also make sure you have pcre install in your system .

5)go to extracted folder and then type below command: ./configure --prefix=/usr/local/apache2 --with-included-apr --enable-proxy --enable-proxy-balancer --with-mpm=worker --enable-mods-static=all 6)run below command once the configure is successful: make 7)after successfull execution od make command run: checkinstall in tha same folder. (if you dont have checkinstall software please download latest version from site) Also checkinstall software has bug which can be solved by following way::::: locate checkinstallrc and then replace TRANSLATE = 1 to TRANSLATE=0 using vim command. Also check for exclude package: EXCLUDE="/selinux" 8)checkinstall will ask for option (type R if you want tp build rpm for source file) 9)Done .rpm file will be built in RPMS folder inside rpmbuild/RPMS file... ALL the BEST ....

Regards, Prerana

Capture event onclose browser

Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.

The only working solution is How to capture the browser window close event?

Display a float with two decimal places in Python

String formatting:

print "%.2f" % 5

Node: log in a file instead of the console

For simple cases, we could redirect the Standard Out (STDOUT) and Standard Error (STDERR) streams directly to a file(say, test.log) using '>' and '2>&1'

Example:

// test.js
(function() {
    // Below outputs are sent to Standard Out (STDOUT) stream
    console.log("Hello Log");
    console.info("Hello Info");
    // Below outputs are sent to Standard Error (STDERR) stream
    console.error("Hello Error");
    console.warn("Hello Warning");
})();

node test.js > test.log 2>&1

As per the POSIX standard, 'input', 'output' and 'error' streams are identified by the positive integer file descriptors (0, 1, 2). i.e., stdin is 0, stdout is 1, and stderr is 2.

Step 1: '2>&1' will redirect from 2 (stderr) to 1 (stdout)

Step 2: '>' will redirect from 1 (stdout) to file (test.log)

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

How do you use NSAttributedString?

When building attributed strings, I prefer to use the mutable subclass, just to keep things cleaner.

That being said, here's how you create a tri-color attributed string:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

typed in a browser. caveat implementor

Obviously you're not going to hard-code in the ranges like this. Perhaps instead you could do something like:

NSDictionary * wordToColorMapping = ....;  //an NSDictionary of NSString => UIColor pairs
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@""];
for (NSString * word in wordToColorMapping) {
  UIColor * color = [wordToColorMapping objectForKey:word];
  NSDictionary * attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
  NSAttributedString * subString = [[NSAttributedString alloc] initWithString:word attributes:attributes];
  [string appendAttributedString:subString];
  [subString release];
}

//display string

How to get HttpContext.Current in ASP.NET Core?

Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory
    )
    {

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)
    {

Next, create a replacement class for System.Web:

namespace System.Web
{

    namespace Hosting
    {
        public static class HostingEnvironment 
        {
            public static bool m_IsHosted;

            static HostingEnvironment()
            {
                m_IsHosted = false;
            }

            public static bool IsHosted
            {
                get
                {
                    return m_IsHosted;
                }
            }
        }
    }


    public static class HttpContext
    {
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;
            }
        }


    } // End Class HttpContext 


}

Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;


    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false

    });

Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.


Perhaps a more maintainable method would be adding this helper class

namespace System.Web
{

    public static class HttpContext
    {
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;


        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }


    }


}

And then calling HttpContext.Configure in Startup->Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();


    System.Web.HttpContext.Configure(app.ApplicationServices.
        GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
    );

How to get first character of string?

You can use as well:

var x = "somestring";

console.log(x.split("")[0]); // output "s"

This should work with older browsers.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Delete a dictionary item if the key exists

There is also:

try:
    del mydict[key]
except KeyError:
    pass

This only does 1 lookup instead of 2. However, except clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.

SQL Server convert select a column and convert it to a string

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| RESULTS |
-----------
| 1,3,5,9 |

Is there an operator to calculate percentage in Python?

use of %

def percent(expression):
    if "%" in expression:
        expression = expression.replace("%","/100")
    return eval(expression)

>>> percent("1500*20%")
300.0

Somthing simple

>>> p = lambda x: x/100
>>> p(20)
0.2
>>> 100*p(20)
20.0
>>>

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

Add x and y labels to a pandas plot

For cases where you use pandas.DataFrame.hist:

plt = df.Column_A.hist(bins=10)

Note that you get an ARRAY of plots, rather than a plot. Thus to set the x label you will need to do something like this

plt[0][0].set_xlabel("column A")

Is there a simple way to remove multiple spaces in a string?

I have tried the following method and it even works with the extreme case like:

str1='          I   live    on    earth           '

' '.join(str1.split())

But if you prefer a regular expression it can be done as:

re.sub('\s+', ' ', str1)

Although some preprocessing has to be done in order to remove the trailing and ending space.

How do you comment out code in PowerShell?

I'm a little bit late to this party but seems that nobody actually wrote all use cases. So...

Only supported version of PowerShell these days (fall of 2020 and beyond) are:

  • Windows PowerShell 5.1.x
  • PowerShell 7.0.x.

You don't want to or you shouldn't work with different versions of PowerShell.

Both versions (or any another version which you could come around WPS 3.0-5.0, PS Core 6.x.x on some outdated stations) share the same comment functionality.

One line comments

# Get all Windows Service processes <-- one line comment, it starts with '#'
Get-Process -Name *host*

Get-Process -Name *host* ## You could put as many ### as you want, it does not matter

Get-Process -Name *host* # | Stop-Service # Everything from the first # until end of the line is treated as comment

Stop-Service -DisplayName Windows*Update # -WhatIf # You can use it to comment out cmdlet switches

Multi line comments

<#
Everyting between '< #' and '# >' is 
treated as a comment. A typical use case is for help, see below.

# You could also have a single line comment inside the multi line comment block.
# Or two... :)

#>

<#
.SYNOPSIS
    A brief description of the function or script.
    This keyword can be used only once in each topic.

.DESCRIPTION
    A detailed description of the function or script.
    This keyword can be used only once in each topic.

.NOTES
    Some additional notes. This keyword can be used only once in each topic.
    This keyword can be used only once in each topic.

.LINK
    A link used when Get-Help with a switch -OnLine is used.
    This keyword can be used only once in each topic.

.EXAMPLE
    Example 1
    You can use this keyword as many as you want.

.EXAMPLE
    Example 2
    You can use this keyword as many as you want.
#>

Nested multi line comments

<#
Nope, these are not allowed in PowerShell.

<# This will break your first multiline comment block... #>
...and this will throw a syntax error.
#>

In code nested multi line comments

<# 
The multi line comment opening/close
can be also used to comment some nested code
or as an explanation for multi chained operations..
#>
Get-Service | <# Step explanation #>
Where-Object { $_.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped } | 
<# Format-Table -Property DisplayName, Status -AutoSize |#>
Out-File -FilePath Services.txt -Encoding Unicode

Edge case scenario

# Some well written script
exit
Writing something after exit is possible but not recommended.
It isn't a comment.
Especially in Visual Studio Code, these words baffle PSScriptAnalyzer.
You could actively break your session in VS Code.

How to Code Double Quotes via HTML Codes

There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.

There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello &quot;world&quot;"), and even then, there are almost always better options (like title='Hello "word"' or title="Hello “word”".

If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like &quot; to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

You get that error because ASP.NET MVC cannot find an id parameter value to provide for the id parameter of your action method.

You need to either pass that as part of the url, ("/Home/Edit/123"), as a query string parameter ("/Home/Edit?id=123") or as a POSTed parameter (make sure to have something like <input type="hidden" name="id" value="123" /> in your HTML form).

Alternatively, you could make the id parameter be a nullable int (Edit(int? id, User collection) {...}), but if the id were null, you wouldn't know what to edit.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

You need to add asp content and add content place holder id correspond to the placeholder in master page.

You can read this link for more detail

SpringMVC RequestMapping for GET parameters

If you are willing to change your uri, you could also use PathVariable.

@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
    //Perform logic with foo and bar
}

NB: The first foo is part of the path, the second one is the PathVariable

Div width 100% minus fixed amount of pixels

While Guffa's answer works in many situations, in some cases you may not want the left and/or right pieces of padding to be the parent of the center div. In these cases, you can use a block formatting context on the center and float the padding divs left and right. Here's the code

The HTML:

<div class="container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

The CSS:

.container {
    width: 100px;
    height: 20px;
}

.left, .right {
    width: 20px;
    height: 100%;
    float: left;
    background: black;   
}

.right {
    float: right;
}

.center {
    overflow: auto;
    height: 100%;
    background: blue;
}

I feel that this element hierarchy is more natural when compared to nested nested divs, and better represents what's on the page. Because of this, borders, padding, and margin can be applied normally to all elements (ie: this 'naturality' goes beyond style and has ramifications).

Note that this only works on divs and other elements that share its 'fill 100% of the width by default' property. Inputs, tables, and possibly others will require you to wrap them in a container div and add a little more css to restore this quality. If you're unlucky enough to be in that situation, contact me and I'll dig up the css.

jsfiddle here: jsfiddle.net/RgdeQ

Enjoy!

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

In your css add folllowing

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    display: none !important;
 }

And then in you code you can add ng-cloak directive. For example,

<div ng-cloak>
   Welcome {{data.name}}
</div>

Thats it!

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

Generic type conversion FROM string

lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz"

Usage first:

TConverter.ChangeType<T>(StringValue);  

The class is below.

public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }

    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }

    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

I fixed this by adding
/p:VCTargetsPath="C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\V120"

into
Build > Build a Visual Studio project or solution using MSBuild > Command Line Arguments

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

When working on local add a server

I had a similar issue when working on local. You url is going to be the path to the local file e.g. file:///Users/PeterP/Desktop/folder/index.html.

Please note that I am on a MAC.

I got round this by installing http-server globally. https://www.npmjs.com/package/http-server

Steps:

  1. Global install: npm install http-server -g
  2. Run server: http-server ~/Desktop/folder/

PS: I assume you have node installed, otherwise you wont get very far running npm commands.

How to Kill A Session or Session ID (ASP.NET/C#)

You kill a session like this:

Session.Abandon()

If, however, you just want to empty the session, use:

Session.Clear()

How does DHT in torrents work?

DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal

What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.

If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Format ints into string of hex

Example with some beautifying, similar to the sep option available in python 3.8

def prettyhex(nums, sep=''):
    return sep.join(f'{a:02x}' for a in nums)

numbers = [0, 1, 2, 3, 127, 200, 255]
print(prettyhex(numbers,'-'))

output

00-01-02-03-7f-c8-ff

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

This is actually a better solution I've found. Uses jQuery however it works perfectly. Also it refreshes automatically similar to the way SO and Facebook does so you don't have to refresh the page to see the updates.

This plugin will read your datetime attr in the <time> tag and fill it in for you.

e.g. "4 minutes ago" or "about 1 day ago

http://timeago.yarp.com/

Correct way to convert size in bytes to KB, MB, GB in JavaScript

function formatBytes(bytes) {
    var marker = 1024; // Change to 1000 if required
    var decimal = 3; // Change as required
    var kiloBytes = marker; // One Kilobyte is 1024 bytes
    var megaBytes = marker * marker; // One MB is 1024 KB
    var gigaBytes = marker * marker * marker; // One GB is 1024 MB
    var teraBytes = marker * marker * marker * marker; // One TB is 1024 GB

    // return bytes if less than a KB
    if(bytes < kiloBytes) return bytes + " Bytes";
    // return KB if less than a MB
    else if(bytes < megaBytes) return(bytes / kiloBytes).toFixed(decimal) + " KB";
    // return MB if less than a GB
    else if(bytes < gigaBytes) return(bytes / megaBytes).toFixed(decimal) + " MB";
    // return GB if less than a TB
    else return(bytes / gigaBytes).toFixed(decimal) + " GB";
}

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

To add a little bit more information that confused me; I had always thought the same result could be achieved like so;

theDate.ToString("yyyy-MM-dd HH:mm:ss")

However, If your Current Culture doesn't use a colon(:) as the hour separator, and instead uses a full-stop(.) it could return as follow:

2009-06-15 13.45.30

Just wanted to add why the answer provided needs to be as it is;

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

:-)

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
main()
{
    int i,j,k;
    for(i=2;i<=100;i++)
    {
        k=0;
        for(j=2;j<=i;j++)
        {
            if(i%j==0)
            k++;
        }
        if(k==1)
        printf("%d\t",i);
    }
}

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For Rubyists:

gem install githubrepo
githubrepo create *reponame*

enter username and pw as prompted

git remote add origin *ctrl v*
git push origin master

Source: Elikem Adadevoh

Error in installation a R package

There could be a few things happening here. Start by first figuring out your library location:

Sys.getenv("R_LIBS_USER")

or

.libPaths()

We already know yours from the info you gave: C:\Program Files\R\R-3.0.1\library

I believe you have a file in there called: 00LOCK. From ?install.packages:

Note that it is possible for the package installation to fail so badly that the lock directory is not removed: this inhibits any further installs to the library directory (or for --pkglock, of the package) until the lock directory is removed manually.

You need to delete that file. If you had the pacman package installed you could have simply used p_unlock() and the 00LOCK file is removed. You can't install pacman now until the 00LOCK file is removed.

To install pacman use:

install.packages("pacman")

There may be a second issue. This is where you somehow corrupted MASS. This can occur, in my experience, if you try to update a package while it is in use in another R session. I'm sure there's other ways to cause this as well. To solve this problem try:

  1. Close out of all R sessions (use task manager to ensure you're truly R session free) Ctrl + Alt + Delete
  2. Go to your library location Sys.getenv("R_LIBS_USER"). In your case this is: C:\Program Files\R\R-3.0.1\library
  3. Manually delete the MASS package
  4. Fire up a vanilla session of R
  5. Install MASS via install.packages("MASS")

If any of this works please let me know what worked.

Get distance between two points in canvas

The distance between two coordinates x and y! x1 and y1 is the first point/position, x2 and y2 is the second point/position!

_x000D_
_x000D_
function diff (num1, num2) {_x000D_
  if (num1 > num2) {_x000D_
    return (num1 - num2);_x000D_
  } else {_x000D_
    return (num2 - num1);_x000D_
  }_x000D_
};_x000D_
_x000D_
function dist (x1, y1, x2, y2) {_x000D_
  var deltaX = diff(x1, x2);_x000D_
  var deltaY = diff(y1, y2);_x000D_
  var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));_x000D_
  return (dist);_x000D_
};
_x000D_
_x000D_
_x000D_

Can I set enum start value in Java?

If you use very big enum types then, following can be useful;

public enum deneme {

    UPDATE, UPDATE_FAILED;

    private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>();
    private static final int START_VALUE = 100;
    private int value;

    static {
        for(int i=0;i<values().length;i++)
        {
            values()[i].value = START_VALUE + i;
            ss.put(values()[i].value, values()[i]);
        }
    }

    public static deneme fromInt(int i) {
        return ss.get(i);
    }

    public int value() {
    return value;
    }
}

Python how to write to a binary file?

Use pickle, like this: import pickle

Your code would look like this:

import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
    pickle.dump(mybytes, mypicklefile)

To read the data back, use the pickle.load method

How do I skip a header from CSV files in Spark?

data = sc.textFile('path_to_data')
header = data.first() #extract header
data = data.filter(row => row != header)   #filter out header

Assign output to variable in Bash

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

What are MVP and MVC and what is the difference?

This is an oversimplification of the many variants of these design patterns, but this is how I like to think about the differences between the two.

MVC

MVC

MVP

enter image description here

Replacing NULL and empty string within Select statement

Sounds like you want a view instead of altering actual table data.

Coalesce(NullIf(rtrim(Address.Country),''),'United States')

This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.

MongoDB: How to find the exact version of installed MongoDB

From the Java API:

Document result = mongoDatabase.runCommand(new Document("buildInfo", 1));
String version = (String) result.get("version");
List<Integer> versionArray = (List<Integer>) result.get("versionArray");

How to calculate 1st and 3rd quartiles?

try that way:

dfo = sorted(df.time_diff)

n=len(dfo)

Q1=int((n+3)/4)  
Q3=int((3*n+1)/4)  


print("Q1 position: ", Q1, "Q1 position: " ,Q3)

print("Q1 value: ", dfo[Q1], "Q1 value: ", dfo[Q3])

How do I search for files in Visual Studio Code?

If you want to see your files in Explorer tree...

when you click anywhere in the explorer tree and start typing something on the keyboard, the search keyword appears in the top right corner of the screen : ("module.ts")

enter image description here

And when you hover over the keyword with the mouse cursor, you can click on "Enable Filter on Type" to filter tree with your search !

What happens to a declared, uninitialized variable in C? Does it have a value?

Because computers have finite storage capacity, automatic variables will typically be held in storage elements (whether registers or RAM) that have previously been used for some other arbitrary purpose. If a such a variable is used before a value has been assigned to it, that storage may hold whatever it held previously, and so the contents of the variable will be unpredictable.

As an additional wrinkle, many compilers may keep variables in registers which are larger than the associated types. Although a compiler would be required to ensure that any value which is written to a variable and read back will be truncated and/or sign-extended to its proper size, many compilers will perform such truncation when variables are written and expect that it will have been performed before the variable is read. On such compilers, something like:

uint16_t hey(uint32_t x, uint32_t mode)
{ uint16_t q; 
  if (mode==1) q=2; 
  if (mode==3) q=4; 
  return q; }

 uint32_t wow(uint32_t mode) {
   return hey(1234567, mode);
 }

might very well result in wow() storing the values 1234567 into registers 0 and 1, respectively, and calling foo(). Since x isn't needed within "foo", and since functions are supposed to put their return value into register 0, the compiler may allocate register 0 to q. If mode is 1 or 3, register 0 will be loaded with 2 or 4, respectively, but if it is some other value, the function may return whatever was in register 0 (i.e. the value 1234567) even though that value is not within the range of uint16_t.

To avoid requiring compilers to do extra work to ensure that uninitialized variables never seem to hold values outside their domain, and avoid needing to specify indeterminate behaviors in excessive detail, the Standard says that use of uninitialized automatic variables is Undefined Behavior. In some cases, the consequences of this may be even more surprising than a value being outside the range of its type. For example, given:

void moo(int mode)
{
  if (mode < 5)
    launch_nukes();
  hey(0, mode);      
}

a compiler could infer that because invoking moo() with a mode which is greater than 3 will inevitably lead to the program invoking Undefined Behavior, the compiler may omit any code which would only be relevant if mode is 4 or greater, such as the code which would normally prevent the launch of nukes in such cases. Note that neither the Standard, nor modern compiler philosophy, would care about the fact that the return value from "hey" is ignored--the act of trying to return it gives a compiler unlimited license to generate arbitrary code.

Rename column SQL Server 2008

Alternatively to SQL, you can do this in Microsoft SQL Server Management Studio. Here are a few quick ways using the GUI:

First Way

Slow double-click on the column. The column name will become an editable text box.


Second Way

Right click on column and choose Rename from the context menu.

For example:

To Rename column name


Third Way

This way is preferable for when you need to rename multiple columns in one go.

  1. Right-click on the table that contains the column that needs renaming.
  2. Click Design.
  3. In the table design panel, click and edit the textbox of the column name you want to alter.

For example: MSSMS Table Design Example

NOTE: I know OP specifically asked for SQL solution, thought this might help others :)

How to print Two-Dimensional Array like table

I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.

From the initial question, as has been adequately explained by @djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:

System.out.println();

However, printing that immediately after the first print statement gives erroneous results. What gives?

1 
2 
...
n 

This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!

Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.

for(i=0;i<7;i++){
    for(j=0;j<5;j++) {
        System.out.print(twoDm[i][j]+" ");  
    }
    System.out.println();
}

And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.

Working with select using AngularJS's ng-options

If you need a custom title for each option, ng-options is not applicable. Instead use ng-repeat with options:

<select ng-model="myVariable">
  <option ng-repeat="item in items"
          value="{{item.ID}}"
          title="Custom title: {{item.Title}} [{{item.ID}}]">
       {{item.Title}}
  </option>
</select>

Annotations from javax.validation.constraints not working

If you are using lombok then, you can use @NonNull annotation insted. or Just add the javax.validation dependency in pom.xml file.

Javascript variable access in HTML

<html>
<head>
<script>
    function putText() {
        var simpleText = "hello_world";
        var finalSplitText = simpleText.split("_");
        var splitText = finalSplitText[0];
        document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
    }
</script>
</head>
<body onLoad = putText()>
    <a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>

How to force remounting on React components?

What's probably happening is that React thinks that only one MyInput (unemployment-duration) is added between the renders. As such, the job-title never gets replaced with the unemployment-reason, which is also why the predefined values are swapped.

When React does the diff, it will determine which components are new and which are old based on their key property. If no such key is provided in the code, it will generate its own.

The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div and I believe that would trigger a re-render of all children (which is why it works). Had you added the span to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).

Here's what the official React documentation says:

The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.

When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).

You should be able to fix this by providing a unique key element yourself to either the parent div or to all MyInput elements.

For example:

render(){
    if (this.state.employed) {
        return (
            <div key="employed">
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div key="notEmployed">
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

OR

render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput key="title" ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
                <MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

Now, when React does the diff, it will see that the divs are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title and unemployment-reason since they now have different keys.

You can of course use any keys you want, as long as they are unique.


Update August 2017

For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.


Update November 2017

This update should've been posted a while ago, but using string literals in ref is now deprecated. For example ref="job-title" should now instead be ref={(el) => this.jobTitleRef = el} (for example). See my answer to Deprecation warning using this.refs for more info.

How can I call a method in Objective-C?

[self score]; instead of @selector(score)

Where to get "UTF-8" string literal in Java?

This constant is available (among others as: UTF-16, US-ASCII, etc.) in the class org.apache.commons.codec.CharEncoding as well.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

Sass .scss: Nesting and multiple classes?

Use &

SCSS

.container {
    background:red;
    color:white;

    &.hello {
        padding-left:50px;
    }
}

https://sass-lang.com/documentation/style-rules/parent-selector

Scheduling recurring task in Android

Timer

As mentioned on the javadocs you are better off using a ScheduledThreadPoolExecutor.

ScheduledThreadPoolExecutor

Use this class when your use case requires multiple worker threads and the sleep interval is small. How small ? Well, I'd say about 15 minutes. The AlarmManager starts schedule intervals at this time and it seems to suggest that for smaller sleep intervals this class can be used. I do not have data to back the last statement. It is a hunch.

Service

Your service can be closed any time by the VM. Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.

BroadcastReciever with AlarmManager

For longer sleep intervals (>15 minutes), this is the way to go. AlarmManager already has constants ( AlarmManager.INTERVAL_DAY ) suggesting that it can trigger tasks several days after it has initially been scheduled. It can also wake up the CPU to run your code.

You should use one of those solutions based on your timing and worker thread needs.

Bulk package updates using Conda

the Conda Package Manager is almost ready for beta testing, but it will not be fully integrated until the release of Spyder 2.4 (https://github.com/spyder-ide/spyder/wiki/Roadmap). As soon as we have it ready for testing we will post something on the mailing list (https://groups.google.com/forum/#!forum/spyderlib). Be sure to subscribe

Cheers!

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How is length implemented in Java Arrays?

It is a public final field for the array type. You can refer to the document below:

http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7

Cannot invoke an expression whose type lacks a call signature

As mentioned in the github issue originally linked by @peter in the comments:

const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);

Is there a 'foreach' function in Python 3?

Look at this article. The iterator object nditer from numpy package, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

Example:

import random
import numpy as np

ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]])

for ptr in np.nditer(ptrs, op_flags=['readwrite']):
    # apply random shift on 1 for each element of the matrix
    ptr += random.choice([-1, 1])

print(ptrs)

d:\>python nditer.py
[[ -1   1]
 [399  -1]
 [  1 399]
 [399 401]]

How to center images on a web page for all screen sizes

Try something like this...

<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>

Dart/Flutter : Converting timestamp

All of that above can work but for a quick and easy fix you can use the time_formatter package.

Using this package you can convert the epoch to human-readable time.

String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you 
   String formatted = formatTime(timeStamp).toString();
   return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"

Here you can check the format of the output that is going to be displayed: Formats

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Open Sublime Text from Terminal in macOS

Assuming:

  • You have already installed Homebrew.
  • /usr/local/bin is in your $PATH.
  • You are on Yosemite or El Capitain.

MacOS Sierra 10.12.5 works as well confirmed by David Rawson and MacOS Sierra 10.12.6 confirmed by Alexander K.

Run the following script in Terminal to create the specific symlink.

ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Then:

subl .

Hit Return and it should instantly open Sublime Text.

Regex select all text between tags

This seems to be the simplest regular expression of all that I found

(?:<TAG>)([\s\S]*)(?:<\/TAG>)
  1. Exclude opening tag (?:<TAG>) from the matches
  2. Include any whitespace or non-whitespace characters ([\s\S]*) in the matches
  3. Exclude closing tag (?:<\/TAG>) from the matches

How to call a method in another class in Java?

Try this :

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}

What is the Java ?: operator called and what does it do?

I happen to really like this operator, but the reader should be taken into consideration.

You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.

First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.

Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:

callMethodWhatever(Long + Expression + with + syntax) if conditional

If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.

The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.

When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.

Enable the display of line numbers in Visual Studio

Line numbers are not on by default. To turn on line numbers just go to Tools -> Options -> Text Editor -> All Languages -> General -> Display and check Line numbers:

http://blogs.msdn.com/blogfiles/zainnab/WindowsLiveWriter/TurnonLineNumbers_A5E7/image_thumb.png

Fixed header table with horizontal scrollbar and vertical scrollbar on

This has been driving me crazy for literally weeks. I found a solution that will work for me that includes:

  1. Non-fixed column widths - they shrink and grow on window resizing.
  2. Table has a horizontal scroll-bar when needed, but not when it isn't.
  3. Number of columns is irrelevant - it will size to however many columns you need it to.
  4. Not all columns need to be the same width.
  5. Header goes all the way to the end of the right scrollbar.
  6. No javascript!

...but there are a couple of caveats:

  1. The vertical scrollbar is not visible until you scroll all the way to the right. Given that most people have scroll wheels, this was an acceptable sacrifice.

  2. The width of the scrollbar must be known. On my website I set the scrollbar widths (I'm not overly concerned with older, incompatible browsers), so I can then calculate div and table widths that adjust based on the scrollbar.

Instead of posting my code here, I'll post a link to the jsFiddle.

Fixed header table + scroll left/right.

WHERE Clause to find all records in a specific month

SELECT * FROM yourtable WHERE yourtimestampfield LIKE 'AAAA-MM%';

Where AAAA is the year you want and MM is the month you want

How do AX, AH, AL map onto EAX?

The below snippet examines EAX using GDB.

    (gdb) info register eax
    eax            0xaa55   43605
    (gdb) info register ax
    ax             0xaa55   -21931
    (gdb) info register ah
    ah             0xaa -86
    (gdb) info register al
    al             0x55 85
  1. EAX - Full 32 bit value
  2. AX - lower 16 bit value
  3. AH - Bits from 8 to 15
  4. AL - lower 8 bits of EAX/AX

Using C# regular expressions to remove HTML tags

Use this method to remove tags:

public string From_To(string text, string from, string to)
{
    if (text == null)
        return null;
    string pattern = @"" + from + ".*?" + to;
    Regex rx = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    MatchCollection matches = rx.Matches(text);
    return matches.Count <= 0 ? text : matches.Cast<Match>().Where(match => !string.IsNullOrEmpty(match.Value)).Aggregate(text, (current, match) => current.Replace(match.Value, ""));
}

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

How can I get browser to prompt to save password?

There's an ultimate solution to force all browsers (tested: chrome 25, safari 5.1, IE10, Firefox 16) to ask for save the password using jQuery and ajax request:

JS:

$(document).ready(function() {
    $('form').bind('submit', $('form'), function(event) {
        var form = this;

        event.preventDefault();
        event.stopPropagation();

        if (form.submitted) {
            return;
        }

        form.submitted = true;

        $.ajax({
            url: '/login/api/jsonrpc/',
            data: {
                username: $('input[name=username]').val(),
                password: $('input[name=password]').val()
            },
            success: function(response) {
                form.submitted = false;
                form.submit(); //invoke the save password in browser
            }
        });
    });
});

HTML:

<form id="loginform" action="login.php" autocomplete="on">
    <label for="username">Username</label>
    <input name="username" type="text" value="" autocomplete="on" />
    <label for="password">Password</label>
    <input name="password" type="password" value="" autocomplete="on" />
   <input type="submit" name="doLogin" value="Login" />
</form>

The trick is in stopping the form to submit its own way (event.stopPropagation()), instead send your own code ($.ajax()) and in the ajax's success callback submit the form again so the browser catches it and display the request for password save. You may also add some error handler, etc.

Hope it helped to someone.

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

Rails doesnt like the using of ^ and $ for some security reasons , probably its better to use \A and \z to set the beginning and the end of the string

How to create a table from select query result in SQL Server 2008

Use following syntax to create new table from old table in SQL server 2008

Select * into new_table  from  old_table 

Can't type in React input text field

i'm also facing that problem now solved.Give the onChange to the searchTool. then that problem will solve for you.

List passed by ref - help me explain this behaviour

There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.

When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

Preferred Java way to ping an HTTP URL for availability

here the writer suggests this:

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) { e.printStackTrace(); }
    return false;
}

Possible Questions

  • Is this really fast enough?Yes, very fast!
  • Couldn’t I just ping my own page, which I want to request anyways? Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable What if the DNS is down? Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let ‘s just say, your app not responding would probably not be the talk of the day.

read the link. its seems very good

EDIT: in my exp of using it, it's not as fast as this method:

public boolean isOnline() {
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.


Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)


Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

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

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
%>
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">
    <tr>      
      <td>${entry.key}</td>
      <td>${entry.value}</td>
      <td>${entry.key.class}</td>
    </tr>
    </c:forEach>
</table>

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    <p>
    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
    <p>

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

How to align checkboxes and their labels consistently cross-browsers

I usually leave a checkbox unlabeled and then make its "label" a separate element. It's a pain, but there's so much cross-browser difference between how checkboxes and their labels are displayed (as you've noticed) that this is the only way I can come close to controlling how everything looks.

I also end up doing this in winforms development, for the same reason. I think the fundamental problem with the checkbox control is that it is really two different controls: the box and the label. By using a checkbox, you're leaving it up to the implementers of the control to decide how those two elements are displayed next to each other (and they always get it wrong, where wrong = not what you want).

I really hope someone has a better answer to your question.

Custom UITableViewCell from nib in Swift

Detailed Solution with Screenshots

  1. Create an empty user interface file and name it MyCustomCell.xib.

enter image description here

  1. Add a UITableViewCell as the root of your xib file and any other visual components you want.

enter image description here

  1. Create a cocoa touch class file with class name MyCustomCell as a subclass of UITableViewCell.

enter image description here enter image description here

  1. Set the custom class and reuse identifier for your custom table view cell.

enter image description here enter image description here

  1. Open the assistant editor and ctrl+drag to create outlets for your visual components.

enter image description here

  1. Configure a UIViewController to use your custom cell.
class MyViewController: UIViewController {

    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad {
        super.viewDidLoad()

        let nib = UINib(nibName: "MyCustomCell", bundle: nil)
        myTable.register(nib, forCellReuseIdentifier: "MyCustomCell")
        myTable.dataSource = self
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell") as? MyCustomCell {
            cell.myLabel.text = "Hello world."
            return cell
        }
        ...
    }
}

Reading a registry key in C#

see this http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C

Updated:

You can use RegistryKey class under Microsoft.Win32 namespace.

Some important functions of RegistryKey are as follows:

GetValue       //to get value of a key
SetValue       //to set value to a key
DeleteValue    //to delete value of a key
OpenSubKey     //to read value of a subkey (read-only)
CreateSubKey   //to create new or edit value to a subkey
DeleteSubKey   //to delete a subkey
GetValueKind   //to retrieve the datatype of registry key

MySql sum elements of a column

Try this:

select sum(a), sum(b), sum(c)
from your_table

Is there an equivalent method to C's scanf in Java?

Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:

71 5796 2489
88 1136 5298
42 420 842

Here's the code using findAll:

new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
        .forEach(result -> {
            int fst = Integer.parseInt(result.group(1));
            int snd = Integer.parseInt(result.group(2));
            int third = Integer.parseInt(result.group(3));
            int sum = fst + snd + third;
            System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
        });

Check if a given time lies between two times regardless of date

Using LocalTime would simply ignore the Date value:

public class TimeIntervalChecker {

static final LocalTime time1 = LocalTime.parse( "20:11:13"  ) ;
static final LocalTime time2 = LocalTime.parse( "14:49:00" ) ;

    public static void main(String[] args) throws java.lang.Exception {

        LocalTime nowUtcTime = LocalTime.now(Clock.systemUTC());

        if (nowUtcTime.isAfter(time1) && nowUtcTime.isBefore(time2)){
              System.out.println(nowUtcTime+" is after: "+ time1+" and before: "+ time2);
        } 

}

How can I make a program wait for a variable change in javascript?

Super dated, but certainly good ways to accomodate this. Just wrote this up for a project and figured I'd share. Similar to some of the others, varied in style.

var ObjectListener = function(prop, value) {

  if (value === undefined) value = null;

  var obj = {};    
  obj.internal = value;
  obj.watcher = (function(x) {});
  obj.emit = function(fn) {
    obj.watch = fn;
  };

  var setter = {};
  setter.enumerable = true;
  setter.configurable = true;
  setter.set = function(x) {
    obj.internal = x;
    obj.watcher(x);
  };

  var getter = {};
  getter.enumerable = true;
  getter.configurable = true;
  getter.get = function() {
    return obj.internal;
  };

  return (obj,
    Object.defineProperty(obj, prop, setter),
    Object.defineProperty(obj, prop, getter),
    obj.emit, obj);

};


user._licenseXYZ = ObjectListener(testProp);
user._licenseXYZ.emit(testLog);

function testLog() {
  return function() {
    return console.log([
        'user._licenseXYZ.testProp was updated to ', value
    ].join('');
  };
}


user._licenseXYZ.testProp = 123;

Possible to make labels appear when hovering over a point in matplotlib?

This solution works when hovering a line without the need to click it:

import matplotlib.pyplot as plt

# Need to create as global variable so our callback(on_plot_hover) can access
fig = plt.figure()
plot = fig.add_subplot(111)

# create some curves
for i in range(4):
    # Giving unique ids to each data member
    plot.plot(
        [i*1,i*2,i*3,i*4],
        gid=i)

def on_plot_hover(event):
    # Iterating over each data member plotted
    for curve in plot.get_lines():
        # Searching which data member corresponds to current mouse position
        if curve.contains(event)[0]:
            print "over %s" % curve.get_gid()

fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)           
plt.show()

How to pass parameters to a modal?

I tried as below.

I called ng-click to angularjs controller on Encourage button,

               <tr ng-cloak
                  ng-repeat="user in result.users">
                   <td>{{user.userName}}</rd>
                   <td>
                      <a class="btn btn-primary span11" ng-click="setUsername({{user.userName}})" href="#encouragementModal" data-toggle="modal">
                            Encourage
                       </a>
                  </td>
                </tr>

I set userName of encouragementModal from angularjs controller.

    /**
     * Encouragement controller for AngularJS
     * 
     * @param $scope
     * @param $http
     * @param encouragementService
     */
    function EncouragementController($scope, $http, encouragementService) {
      /**
       * set invoice number
       */
      $scope.setUsername = function (username) {
            $scope.userName = username;
      };
     }
    EncouragementController.$inject = [ '$scope', '$http', 'encouragementService' ];

I provided a place(userName) to get value from angularjs controller on encouragementModal.

<div id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

It worked and I saluted myself.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

  • isValidJsonString - check for valid json string

  • JSON data types - string, number, object (JSON object), array, boolean, null (https://www.json.org/json-en.html)

  • falsy values in javascript - false, 0, -0, 0n, ", null, undefined, NaN - (https://developer.mozilla.org/en-US/docs/Glossary/Falsy)

  • JSON.parse

    • works well for number , boolean, null and valid json String won't raise any error. please refer example below

      • JSON.parse(2) // 2
      • JSON.parse(null) // null
      • JSON.parse(true) // true
      • JSON.parse('{"name":"jhamman"}') // {name: "jhamman"}
      • JSON.parse('[1,2,3]') // [1, 2, 3]
    • break when you parse undefined , object, array etc

      • it gave Uncaught SyntaxError: Unexpected end of JSON input . please refer example below
      • JSON.parse({})
      • JSON.parse([])
      • JSON.parse(undefined)
      • JSON.parse("jack")
function isValidJsonString(jsonString){
    
    if(!(jsonString && typeof jsonString === "string")){
        return false;
    }

    try{
       JSON.parse(jsonString);
       return true;
    }catch(error){
        return false;
    }

}

Submit a form using jQuery

jQuery("a[id=atag]").click( function(){

    jQuery('#form-id').submit();      

            **OR**

    jQuery(this).parents("#form-id").submit();
});

What is difference between png8 and png24

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

Uncaught TypeError: .indexOf is not a function

I was getting e.data.indexOf is not a function error, after debugging it, I found that it was actually a TypeError, which meant, indexOf() being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf() method to make it work

e.data.toString().indexOf('<stringToBeMatchedToPosition>')

Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.

Why am I getting AttributeError: Object has no attribute

This may also occur if your using slots in class and have not added this new attribute in slots yet.

class xyz(object):
"""
class description

"""

__slots__ = ['abc', 'ijk']

def __init__(self):
   self.abc = 1
   self.ijk = 2
   self.pqr = 6 # This will throw error 'AttributeError: <name_of_class_object> object has no attribute 'pqr'

Black transparent overlay on image hover with only CSS?

.overlay didn't have a height or width and no content, and you can't hover over display:none.

I instead gave the div the same size and position as .image and changes RGBA value on hover.

http://jsfiddle.net/Zf5am/566/

.image { position: absolute; border: 1px solid black; width: 200px; height: 200px; z-index:1;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background:rgba(255,0,0,0); z-index: 200; width:200px; height:200px; }
.overlay:hover { background:rgba(255,0,0,.7); }

How to exit from Python without traceback?

Perhaps you're trying to catch all exceptions and this is catching the SystemExit exception raised by sys.exit()?

import sys

try:
    sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
    sys.exit(e)
except:
    # Cleanup and reraise. This will print a backtrace.
    # (Insert your cleanup code here.)
    raise

In general, using except: without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like SystemExit -- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with:

import sys
sys.exit(1) # Or something that calls sys.exit().

If you need to exit without raising SystemExit:

import os
os._exit(1)

I do this, in code that runs under unittest and calls fork(). Unittest gets when the forked process raises SystemExit. This is definitely a corner case!

Checking for a null int value from a Java ResultSet

Just an update with Java Generics.

You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.

Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required

public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
    final T value = rs.getObject(columnName, clazz);
    return rs.wasNull() ? null : value;
}

In this example, your code could look like below:

final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
    //null handling
} else {
    //use int value of columnValue with autoboxing
}

Happy to get feedback