Programs & Examples On #Svn update

0

How to hide iOS status bar

I did the following and it seems to work (even in iOS 8):

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {

        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

I had the same problem. SSMS launches the 32bit version of the import and export wizard which has this issue. Try launching the 64bit version application and it should work fine.

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

Unicode character for "X" cancel / close?

As @Haza pointed out the times symbol can be used. Twitter Bootstrap maps this to a close icon for dismissing content like modals and alerts.

<button class="close">&times;</button>

How do I convert an enum to a list in C#?

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public static List<NameValue> EnumToList<T>()
{
    var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); 
    var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); 
    List<NameValue> lst = null;
    for (int i = 0; i < array.Length; i++)
    {
        if (lst == null)
            lst = new List<NameValue>();
        string name = array2[i];
        T value = array[i];
        lst.Add(new NameValue { Name = name, Value = value });
    }
    return lst;
}

Convert Enum To a list more information available here.

datetimepicker is not a function jquery

 $(document).ready(function(){
    $("#example1").datetimepicker({
      allowMultidate: true,
      multidateSeparator: ','
    });
 });

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

In Chart.js set chart title, name of x axis and y axis?

just use this:

<script>
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["1","2","3","4","5","6","7","8","9","10","11",],
      datasets: [{
        label: 'YOUR LABEL',
        backgroundColor: [
          "#566573",
          "#99a3a4",
          "#dc7633",
          "#f5b041",
          "#f7dc6f",
          "#82e0aa",
          "#73c6b6",
          "#5dade2",
          "#a569bd",
          "#ec7063",
          "#a5754a"
        ],
        data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],            
      },]
    },
    //HERE COMES THE AXIS Y LABEL
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }
  });
</script>

How to implement if-else statement in XSLT?

You have to reimplement it using <xsl:choose> tag:

       <xsl:choose>
         <xsl:when test="$CreatedDate > $IDAppendedDate">
           <h2> mooooooooooooo </h2>
         </xsl:when>
         <xsl:otherwise>
          <h2> dooooooooooooo </h2>
         </xsl:otherwise>
       </xsl:choose>

HttpGet with HTTPS : SSLPeerUnverifiedException

Your local JVM or remote server may not have the required ciphers. go here

https://www.oracle.com/java/technologies/javase-jce8-downloads.html

and download the zip file that contains: US_export_policy.jar and local_policy.jar

replace the existing files (you need to find the existing path in your JVM).

on a Mac, my path was here. /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/security

this worked for me.

How to update the value of a key in a dictionary in Python?

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

How to place a file on classpath in Eclipse?

Just to add. If you right-click on an eclipse project and select Properties, select the Java Build Path link on the left. Then select the Source Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src folder is the classpath folder.

How to position the div popup dialog to the center of browser screen?

I write a code in jquery. It isnt seen an easy way. But i hope it is useful for you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style type="text/css">

.popup{
    border: 4px solid #6b6a63;
    width: 800px;
    border-radius :7px;
    margin : auto;
    padding : 20px;
    position:fixed;
}

</style>

<div id="popup" class="popup">
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
    var popup_height = document.getElementById('popup').offsetHeight;
    var popup_width = document.getElementById('popup').offsetWidth;
    $(".popup").css('top',(($(window).height()-popup_height)/2));
    $(".popup").css('left',(($(window).width()-popup_width)/2));
});
</script>

ReCaptcha API v2 Styling

Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:

Click here to preview

.g-recaptcha-outer{
    text-align: center;
    border-radius: 2px;
    background: #f9f9f9;
    border-style: solid;
    border-color: #37474f;
    border-width: 1px;
    border-bottom-width: 2px;
}
.g-recaptcha-inner{
    width: 154px;
    height: 82px;
    overflow: hidden;
    margin: 0 auto;
}
.g-recaptcha{
    position:relative;
    left: -2px;
    top: -1px;
}

<div class="g-recaptcha-outer">
    <div class="g-recaptcha-inner">
        <div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
    </div>
</div>

Can't load AMD 64-bit .dll on a IA 32-bit platform

Try this:

  1. Download and install a 32-bit JDK.
  2. Go to eclipse click on your project (Run As ? Run Configurations...) under Java Application branch.
  3. Go to the JRE tab and select Alternate JRE. Click on Installed JRE button, add your 32-bit JRE and select.

Reading string by char till end of line C/C++

If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example

unsigned int count = 0;
while ( 1 )
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
      if ( c == EOF ) break;
   }
   else
   {
      ++count;
   }
}    

or maybe it would be better to rewrite the code using do-while loop. For example

unsigned int count = 0;
do
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
   }
   else
   {
      ++count;
   }
} while ( c != EOF );

Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.

But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.

bodyParser is deprecated express 4

Want zero warnings? Use it like this:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

Explanation: The default value of the extended option has been deprecated, meaning you need to explicitly pass true or false value.

How to define constants in ReactJS

well, there are many ways to do this in javascript just like other says. I don't think there's a way to do it in react. here's what I would do:

in a js file:

module.exports = {
    small_square: 's',
    large_square: 'q'
}

in your react file:

'use strict';

var Constant = require('constants');
....
var something = Constant.small_square;

something for you to consider, hope this helps

Converting a sentence string to a string array of words in Java

You can just split your string like that using this regular expression

String l = "sofia, malgré tout aimait : la laitue et le choux !" <br/>
l.split("[[ ]*|[,]*|[\\.]*|[:]*|[/]*|[!]*|[?]*|[+]*]+");

how to get all child list from Firebase android

Works Like a Charm

final DatabaseReference senderDb = FirebaseDatabase.getInstance().getReference(Constant.NODE_MESSAGE).child(myId + "_" + otherId);

    senderDb.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                DatabaseReference objRef = senderDb.child( childDataSnapshot.getKey());
                Map<String,Object> taskMap = new HashMap<String,Object>();
                taskMap.put("is_read", "1");
                objRef.updateChildren(taskMap); //should I use setValue()...?
                Log.v("Testing",""+ childDataSnapshot.getKey()); //displays the key for the node
            }

            //notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

Is it possible to have different Git configuration for different projects?

The .git/config file in a particular clone of a repository is local to that clone. Any settings placed there will only affect actions for that particular project.

(By default, git config modifies .git/config, not ~/.gitconfig - only with --global does it modify the latter.)

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

add item to dropdown list in html using javascript

i think you have only defined the function. you are not triggering it anywhere.

please do

window.onload = addList();

or trigger it on some other event

after its definition

see this fiddle

How to check if a file exists in Documents folder?

Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.

NSFileManager Class Reference

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.

Source: Apple Developer API Reference

From the secure coding guide.

To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

DP size of any device is (actual resolution / density conversion factor).

Density conversion factor for density buckets are as follows:

ldpi: 0.75
mdpi: 1.0 (base density)
hdpi: 1.5
xhdpi: 2.0
xxhdpi: 3.0
xxxhdpi: 4.0

Examples of resolution/density conversion to DP:

  • ldpi device of 240 X 320 px will be of 320 X 426.66 DP. 240 / 0.75 = 320 dp 320 / 0.75 = 426.66 dp

  • xxhdpi device of 1080 x 1920 pixels (Samsung S4, S5) will be of 360 X 640 dp. 1080 / 3 = 360 dp 1920 / 3 = 640 dp

This image show more:

Density

For more details about DIP read here.

How can I get a count of the total number of digits in a number?

The answer of Steve is correct, but it doesn't work for integers less than 1.

Here an updated version that does work for negatives:

int digits = n == 0 ? 1 : Math.Floor(Math.Log10(Math.Abs(n)) + 1)

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.

The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter

1) reset

reset Resets the namespace by removing all names defined by the user, if called without arguments.

in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.

reset in out

Another interesting one is array that only removes numpy Arrays:

reset array

2) reset_selective

Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.

Clean Array Example:

In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']

Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html

How do I measure a time interval in C?

If your Linux system supports it, clock_gettime(CLOCK_MONOTONIC) should be a high resolution timer that is unaffected by system date changes (e.g. NTP daemons).

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

How to call code behind server method from a client side JavaScript function?

In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

aspx code:

    <asp:Button runat="server" id="btnResponse1" Text="" 
    style="display: none; width:100%; height:100%"
    OnClick="btnResponses_Clicked" />

    <div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>    

C# code behind:

protected void btnResponses_Clicked(object sender, EventArgs e)
{
    if(sender == btnResponse1)
    {
        //Your code behind logic for that button goes here
    }
}

Android textview outline text

I've written a class to perform text with outline and still support all the other attributes and drawing of a normal text view.

it basically uses the super.onDraw(Canves canvas) on the TextView but draws twice with different styles.

hope this helps.

public class TextViewOutline extends TextView {

    // constants
    private static final int DEFAULT_OUTLINE_SIZE = 0;
    private static final int DEFAULT_OUTLINE_COLOR = Color.TRANSPARENT;

    // data
    private int mOutlineSize;
    private int mOutlineColor;
    private int mTextColor;
    private float mShadowRadius;
    private float mShadowDx;
    private float mShadowDy;
    private int mShadowColor;

    public TextViewOutline(Context context) {
        this(context, null);
    }

    public TextViewOutline(Context context, AttributeSet attrs) {
        super(context, attrs);
        setAttributes(attrs);
    }

    private void setAttributes(AttributeSet attrs){ 
        // set defaults
        mOutlineSize = DEFAULT_OUTLINE_SIZE;
        mOutlineColor = DEFAULT_OUTLINE_COLOR;   
        // text color   
        mTextColor = getCurrentTextColor();
        if(attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.TextViewOutline);
            // outline size
            if (a.hasValue(R.styleable.TextViewOutline_outlineSize)) {
                mOutlineSize = (int) a.getDimension(R.styleable.TextViewOutline_outlineSize, DEFAULT_OUTLINE_SIZE);
            }
            // outline color
            if (a.hasValue(R.styleable.TextViewOutline_outlineColor)) {
                mOutlineColor = a.getColor(R.styleable.TextViewOutline_outlineColor, DEFAULT_OUTLINE_COLOR);
            }
            // shadow (the reason we take shadow from attributes is because we use API level 15 and only from 16 we have the get methods for the shadow attributes)
            if (a.hasValue(R.styleable.TextViewOutline_android_shadowRadius) 
                    || a.hasValue(R.styleable.TextViewOutline_android_shadowDx)
                    || a.hasValue(R.styleable.TextViewOutline_android_shadowDy) 
                    || a.hasValue(R.styleable.TextViewOutline_android_shadowColor)) {
                mShadowRadius = a.getFloat(R.styleable.TextViewOutline_android_shadowRadius, 0);
                mShadowDx = a.getFloat(R.styleable.TextViewOutline_android_shadowDx, 0);
                mShadowDy = a.getFloat(R.styleable.TextViewOutline_android_shadowDy, 0);
                mShadowColor = a.getColor(R.styleable.TextViewOutline_android_shadowColor, Color.TRANSPARENT);
            }

            a.recycle();
        }

        PFLog.d("mOutlineSize = " + mOutlineSize);
        PFLog.d("mOutlineColor = " + mOutlineColor);
    }

    private void setPaintToOutline(){
        Paint paint = getPaint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(mOutlineSize);
        super.setTextColor(mOutlineColor);
        super.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy,  mShadowColor);
    }

    private void setPaintToRegular() {
        Paint paint = getPaint();
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(0);
        super.setTextColor(mTextColor);
        super.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
    } 

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setPaintToOutline();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public void setTextColor(int color) {
        super.setTextColor(color);
        mTextColor = color;
    } 

    @Override
    public void setShadowLayer(float radius, float dx, float dy, int color) {
        super.setShadowLayer(radius, dx, dy, color);
        mShadowRadius = radius;
        mShadowDx = dx;
        mShadowDy = dy;
        mShadowColor = color;
    }

    public void setOutlineSize(int size){
        mOutlineSize = size;
    }

    public void setOutlineColor(int color){
       mOutlineColor = color;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        setPaintToOutline();
        super.onDraw(canvas);
        setPaintToRegular();
        super.onDraw(canvas);
    }

}

attr.xml

<declare-styleable name="TextViewOutline">
    <attr name="outlineSize" format="dimension"/>
    <attr name="outlineColor" format="color|reference"/>
    <attr name="android:shadowRadius"/>
    <attr name="android:shadowDx"/>
    <attr name="android:shadowDy"/>
    <attr name="android:shadowColor"/>
</declare-styleable>

Regex select all text between tags

_x000D_
_x000D_
var str = "Lorem ipsum <pre>text 1</pre> Lorem ipsum <pre>text 2</pre>";_x000D_
    str.replace(/<pre>(.*?)<\/pre>/g, function(match, g1) { console.log(g1); });
_x000D_
_x000D_
_x000D_

Since accepted answer is without javascript code, so adding that:

What's the difference between KeyDown and KeyPress in .NET?

KeyPress is a higher level of abstraction than KeyDown (and KeyUp). KeyDown and KeyUp are hardware related: the actual action of a key on the keyboard. KeyPress is more "I received a character from the keyboard".

check if jquery has been loaded, then load it if false

Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.

<script type="text/javascript">
if (typeof jQuery == 'undefined') {
  document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');        
  } 
</script>

How to add bootstrap to an angular-cli project

I see lot of the solutions don't work anymore with the new versions of Angular-CLI.

You can try to add the following link tag at top and script tags at the bottom in your app.component.html.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">


<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

But if you want to use ngx-bootstrap then run the following command in your project directory

ng add ngx-bootstrap

Test it out with following as the content of your app.component.html

<button type="button" class="btn btn-outline-primary">Primary</button>
<button type="button" class="btn btn-outline-secondary">Secondary</button>
<button type="button" class="btn btn-outline-success">Success</button>
<button type="button" class="btn btn-outline-danger">Danger</button>
<button type="button" class="btn btn-outline-warning">Warning</button>
<button type="button" class="btn btn-outline-info">Info</button>
<button type="button" class="btn btn-outline-light">Light</button>
<button type="button" class="btn btn-outline-dark">Dark</button>

How to add a default include path for GCC in Linux?

just a note: CPLUS_INCLUDE_PATH and C_INCLUDE_PATH are not the equivalent of LD_LIBRARY_PATH. LD_LIBRARY_PATH serves the ld (the dynamic linker at runtime) whereas the equivalent of the former two that serves your C/C++ compiler with the location of libraries is LIBRARY_PATH.

no match for ‘operator<<’ in ‘std::operator

Obviously, the standard library provided operator does not know what to do with your user defined type mystruct. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator << to take your user defined data type.

Substitute a comma with a line break in a cell

You can also do this without VBA from the find/replace dialogue box. My answer was at https://stackoverflow.com/a/6116681/509840 .

Most efficient way to map function over numpy array

I've tested all suggested methods plus np.array(map(f, x)) with perfplot (a small project of mine).

Message #1: If you can use numpy's native functions, do that.

If the function you're trying to vectorize already is vectorized (like the x**2 example in the original post), using that is much faster than anything else (note the log scale):

enter image description here

If you actually need vectorization, it doesn't really matter much which variant you use.

enter image description here


Code to reproduce the plots:

import numpy as np
import perfplot
import math


def f(x):
    # return math.sqrt(x)
    return np.sqrt(x)


vf = np.vectorize(f)


def array_for(x):
    return np.array([f(xi) for xi in x])


def array_map(x):
    return np.array(list(map(f, x)))


def fromiter(x):
    return np.fromiter((f(xi) for xi in x), x.dtype)


def vectorize(x):
    return np.vectorize(f)(x)


def vectorize_without_init(x):
    return vf(x)


perfplot.show(
    setup=np.random.rand,
    n_range=[2 ** k for k in range(20)],
    kernels=[f, array_for, array_map, fromiter, vectorize, vectorize_without_init],
    xlabel="len(x)",
)

Laravel 5 How to switch from Production mode

In Laravel the default environment is always production.

What you need to do is to specify correct hostname in bootstrap/start.php for your enviroments eg.:

/*
|--------------------------------------------------------------------------
| Detect The Application Environment
|--------------------------------------------------------------------------
|
| Laravel takes a dead simple approach to your application environments
| so you can just specify a machine name for the host that matches a
| given environment, then we will automatically detect it for you.
|
*/

$env = $app->detectEnvironment(array(
    'local' => array('homestead'),
    'profile_1' => array('hostname_for_profile_1')
));

Convert character to ASCII code in JavaScript

If you have only one char and not a string, you can use:

'\n'.charCodeAt();

omitting the 0...

It used to be significantly slower than 'n'.charCodeAt(0), but I've tested it now and I do not see any difference anymore (executed 10 billions times with and without the 0). Tested for performance only in Chrome and Firefox.

Free Barcode API for .NET

There is a "3 of 9" control on CodeProject: Barcode .NET Control

$_SERVER['HTTP_REFERER'] missing

Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:

$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";

Troubleshooting BadImageFormatException

When I faced this issue the following solved it for me:

I was calling a OpenCV dll from inside another exe, my dll did not contained the already needed opencv dlls like highgui, features2d, and etc available in the folder of my exe file. I copied all these to the directory of my exe project and it suddenly worked.

Python concatenate text files

  import os
  files=os.listdir()
  print(files)
  print('#',tuple(files))
  name=input('Enter the inclusive file name: ')
  exten=input('Enter the type(extension): ')
  filename=name+'.'+exten
  output_file=open(filename,'w+')
  for i in files:
    print(i)
    j=files.index(i)
    f_j=open(i,'r')
    print(f_j.read())
    for x in f_j:
      outfile.write(x)

A html space is showing as %2520 instead of %20

When you are trying to visit a local filename through firefox browser, you have to force the file:\\\ protocol (http://en.wikipedia.org/wiki/File_URI_scheme) or else firefox will encode your space TWICE. Change the html snippet from this:

<img src="C:\Documents and Settings\screenshots\Image01.png"/>

to this:

<img src="file:\\\C:\Documents and Settings\screenshots\Image01.png"/>

or this:

<img src="file://C:\Documents and Settings\screenshots\Image01.png"/>

Then firefox is notified that this is a local filename, and it renders the image correctly in the browser, correctly encoding the string once.

Helpful link: http://support.mozilla.org/en-US/questions/900466

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

git: Your branch is ahead by X commits

Use

git pull --rebase

The --rebase option means that git will move your local commit aside, synchronise with the remote and then try to apply your commits from the new state.

Is it possible to Turn page programmatically in UIPageViewController?

This code worked nicely for me, thanks.

This is what i did with it. Some methods for stepping forward or backwards and one for going directly to a particular page. Its for a 6 page document in portrait view. It will work ok if you paste it into the implementation of the RootController of the pageViewController template.

-(IBAction)pageGoto:(id)sender {

    //get page to go to
    NSUInteger pageToGoTo = 4;

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers   objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //get the page(s) to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo - 1) storyboard:self.storyboard];

    DataViewController *secondPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, secondPageViewController, nil];


    //check which direction to animate page turn then turn page accordingly
    if (retreivedIndex < (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
    }

    if (retreivedIndex > (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];
    }

}


-(IBAction)pageFoward:(id)sender {

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex < 5){

        //get the page to go to
        DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex + 1) storyboard:self.storyboard];

        //put it(or them if in landscape view) in an array
        NSArray *theViewControllers = nil;    
        theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

        //add page view
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    }

}


-(IBAction)pageBack:(id)sender {


    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex > 0){

    //get the page to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex - 1) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

    //add page view
    [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];

    }

}

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

How to create a file name with the current date & time in Python?

Change this line

filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")

To

filename1 = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

Note the extra datetime. Alternatively, change your import datetime to from datetime import datetime

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

Running PowerShell as another user, and launching a script

Here's also nice way to achieve this via UI.

0) Right click on PowerShell icon when on task bar

1) Shift + right click on Windows PowerShell

2) "Run as different user"

Pic

How to rename a single column in a data.frame?

Try:

colnames(x)[2] <- 'newname2'

Converting between java.time.LocalDateTime and java.util.Date

If you are on android and using threetenbp you can use DateTimeUtils instead.

ex:

Date date = DateTimeUtils.toDate(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

you can't use Date.from since it's only supported on api 26+

How to Apply Mask to Image in OpenCV?

While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:

inputMat.copyTo(outputMat, maskMat);

All objects are of type cv::Mat.

Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.

Also be aware that the .copyTo() function does not clear the output before copying.

If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.

Converting Varchar Value to Integer/Decimal Value in SQL Server

The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2), it should work

 SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table

OR

 SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table

How to close off a Git Branch?

after complete the code first merge branch to master then delete that branch

git checkout master
git merge <branch-name>
git branch -d <branch-name>

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

Calling a PHP function from an HTML form in the same file

This is the better way that I use to create submit without loading in a form.

You can use some CSS to stylise the iframe the way you want.

A php result will be loaded into the iframe.

<form method="post" action="test.php" target="view">
  <input type="text" name="anyname" palceholder="Enter your name"/>
  <input type="submit" name="submit" value="submit"/>
  </form>
<iframe name="view" frameborder="0" style="width:100%">
  </iframe>

Storing and retrieving datatable from session

A simple solution for a very common problem

                 // DECLARATION
                HttpContext context = HttpContext.Current;
                DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;

                // TRY TO ADD rows with the info into the DataTable
                try
                {
                    // Add new Serial Code into DataTable dt_ShoppingBasket
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_ShoppingBasket;
                }
                catch (Exception)
                {
                    // IF FAIL (EMPTY OR DOESN'T EXIST) - 
                    // Create new Instance, 
                    DataTable dt_ShoppingBasket= new DataTable();

                    // Add column and Row with the info
                    dt_ShoppingBasket.Columns.Add("Serial");
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_PanierCommande;
                }



                // PRINT TESTS
                DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;

                foreach (DataRow row in dt_To_Print.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        Debug.WriteLine("DATATABLE IN SESSION: " + item);
                    }
                }

Spring: Why do we autowire the interface and not the implemented class?

How does spring know which polymorphic type to use.

As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).

Do I need @Qualifier or @Resource?

Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.

Why do we autowire the interface and not the implemented class?

Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Your bean configuration should look like this:

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component as follows:

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Then worker in MyRunner will be injected with an instance of type B.

Use of document.getElementById in JavaScript

the line

age=document.getElementById("age").value;

says 'the variable I called 'age' has the value of the element with id 'age'. In this case the input field.

The line

voteable=(age<18)?"Too young":"Old enough";

says in a variable I called 'voteable' I store the value following the rule :

"If age is under 18 then show 'Too young' else show 'Old enough'"

The last line tell to put the value of 'voteable' in the element with id 'demo' (in this case the 'p' element)

Server unable to read htaccess file, denying access to be safe

Set group of your public directory to nobody.

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

NoClassDefFoundError is a linkage error basically. It occurs when you try and instantiate an object (statically with "new") and it's not found when it was during compilation.

ClassNotFoundException is more general and is a runtime exception when you try to use a class that doesn't exist. For example, you have a parameter in a function accepts an interface and someone passes in a class that implements that interface but you don't have access to the class. It also covers case of dynamic class loading, such as using loadClass() or Class.forName().

How to change color of Android ListView separator line?

Use android:divider="#FF0000" and android:dividerHeight="2px" for ListView.

<ListView 
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0099FF"
android:dividerHeight="2px"/>

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

How to convert a string of numbers to an array of numbers?

A more shorter solution: map and pass the arguments to Number:

_x000D_
_x000D_
var a = "1,2,3,4";_x000D_
var b = a.split(',');_x000D_
console.log(b);_x000D_
var c = b.map(Number);_x000D_
console.log(c);
_x000D_
_x000D_
_x000D_

How to run multiple SQL commands in a single SQL connection?

Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection

public static class SQLTest
    {
        public static void NpgsqlCommand()
        {
            using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
            {
                NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
                NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
                command1.Connection.Open();
                command1.ExecuteNonQuery();
                command2.ExecuteNonQuery();
                command2.Connection.Close();
            }
        }
    }

How to search for a string in an arraylist

Better way is to use matches() method on every String element of the array. This will help you to search any pattern through regular expressions.

Border color on default input style

I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;

Example: http://jsfiddle.net/vmzLW/

Which keycode for escape key with jQuery

I'm was trying to do the same thing and it was bugging the crap out of me. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Alert works fine. But in my case, I wanted to go back in the history which did not work. Finally figured out that I had to force the propagation of the event to stop as shown below...

if (keyCode == 27)
{
    history.back();

    if (window.event)
    {
        // IE works fine anyways so this isn't really needed
        e.cancelBubble = true;
        e.returnValue = false;
    }
    else if (e.stopPropagation)
    {
        // In firefox, this is what keeps the escape key from canceling the history.back()
        e.stopPropagation();
        e.preventDefault();
    }

    return (false);
}

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try f.seek(0) and maybe the problem goes away.

Reset textbox value in javascript

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

What is a correct MIME type for .docx, .pptx, etc.?

Swift4

 func mimeTypeForPath(path: String) -> String {
        let url = NSURL(fileURLWithPath: path)
        let pathExtension = url.pathExtension

        if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
            if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
                return mimetype as String
            }
        }
        return "application/octet-stream"
    }

Execute a large SQL script (with GO commands)

If you don't want to use SMO (which is better than the solution below, but i want to give an alternative...) you can split your query with this function.

It is:

  • Comment proof (example --GO or /* GO */)
  • Only works on a new line, just as in SSMS (example /* test /* GO works and select 1 as go not
  • String proof (example print 'no go ')

    private List<string> SplitScriptGo(string script)
    {
        var result = new List<string>();
        int pos1 = 0;
        int pos2 = 0;
        bool whiteSpace = true;
        bool emptyLine = true;
        bool inStr = false;
        bool inComment1 = false;
        bool inComment2 = false;
    
        while (true)
        {
            while (pos2 < script.Length && Char.IsWhiteSpace(script[pos2]))
            {
                if (script[pos2] == '\r' || script[pos2] == '\n')
                {
                    emptyLine = true;
                    inComment1 = false;
                }
    
                pos2++;
            }
    
            if (pos2 == script.Length)
                break;
    
            bool min2 = (pos2 + 1) < script.Length;
            bool min3 = (pos2 + 2) < script.Length;
    
            if (!inStr && !inComment2 && min2 && script.Substring(pos2, 2) == "--")
                inComment1 = true;
    
            if (!inStr && !inComment1 && min2 && script.Substring(pos2, 2) == "/*")
                inComment2 = true;
    
            if (!inComment1 && !inComment2 && script[pos2] == '\'')
                inStr = !inStr;
    
            if (!inStr && !inComment1 && !inComment2 && emptyLine
                && (min2 && script.Substring(pos2, 2).ToLower() == "go")
                && (!min3 || char.IsWhiteSpace(script[pos2 + 2]) || script.Substring(pos2 + 2, 2) == "--" || script.Substring(pos2 + 2, 2) == "/*"))
            {
                if (!whiteSpace)
                    result.Add(script.Substring(pos1, pos2 - pos1));
    
                whiteSpace = true;
                emptyLine = false;
                pos2 += 2;
                pos1 = pos2;
            }
            else
            {
                pos2++;
                whiteSpace = false;
    
                if (!inComment2)
                    emptyLine = false;
            }
    
            if (!inStr && inComment2 && pos2 > 1 && script.Substring(pos2 - 2, 2) == "*/")
                inComment2 = false;
        }
    
        if (!whiteSpace)
            result.Add(script.Substring(pos1));
    
        return result;
    }
    

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

Darken background image on hover

If you want to darken the image, use an overlay element with rgba and opacity properties which will darken your image...

Demo

<div><span></span></div>

div {
    background-image: url(http://im.tech2.in.com/gallery/2012/dec/stockimage_070930177527_640x360.jpg);
    height: 400px;
    width: 400px;
}

div span {
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: rgba(0,0,0,.5);
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
}

div:hover span {
    opacity: 1;
}

Note: Am also using CSS3 transitions for smooth dark effect


If anyone one to save an extra element in the DOM than you can use :before or :after pseudo as well..

Demo 2

div {
    background-image: url(http://im.tech2.in.com/gallery/2012/dec/stockimage_070930177527_640x360.jpg);
    height: 400px;
    width: 400px;
}

div:after {
    content: "";
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: rgba(0,0,0,.5);
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
}

div:hover:after {
    opacity: 1;
}

Using some content over the darkened overlay of the image

Here am using CSS Positioning techniques with z-index to overlay content over the darkened div element. Demo 3

div {
    background-image: url(http://im.tech2.in.com/gallery/2012/dec/stockimage_070930177527_640x360.jpg);
    height: 400px;
    width: 400px;
    position: relative;
}

div:after {
    content: "";
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: rgba(0,0,0,.5);
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
    top: 0;
    left: 0;
    position: absolute;
}

div:hover:after {
    opacity: 1;
}

div p {
    color: #fff;
    z-index: 1;
    position: relative;
}

Add Foreign Key relationship between two Databases

You would need to manage the referential constraint across databases using a Trigger.


Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.

Example:

Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin

   If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
      -- Handle the Referential Error Here
   END

END

Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

How do I replace text in a selection?

ST2 has a feature for changing multiple selections at once.

  1. Double click the first instance of 0 that you want to change.
  2. Press the key for Find->Quick Add Next* to select the next instance of 0, and repeat until you've selected all the instances of 0 that you want to change.
    If this method selects an instance that you want to skip, press the key for Find->Quick Skip Next.
  3. Verify that the multiple highlighted fields are what you want to replace. Next, type in '255' and it should modify all of the selected instances simultaneously.

*Look at the Find menu on the menu bar to find the correct shortcut key for your system. For vanilla Windows, the menu tells you that Find->Quick Add Next is Ctrl+D and Find->Quick Skip Next is Ctrl+K,Ctrl+D.

How do you load custom UITableViewCells from Xib files?

I dont know if there is a canonical way, but here's my method:

  • Create a xib for a ViewController
  • Set the File Owner class to UIViewController
  • Delete the view and add an UITableViewCell
  • Set the Class of your UITableViewCell to your custom class
  • Set the Identifier of your UITableViewCell
  • Set the outlet of your view controller view to your UITableViewCell

And use this code:

MyCustomViewCell *cell = (MyCustomViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
  UIViewController* c = [[UIViewController alloc] initWithNibName:CellIdentifier bundle:nil];
  cell = (MyCustomViewCell *)c.view;
  [c release];
}

In your example, using

[nib objectAtIndex:0]

may break if Apple changes the order of items in the xib.

In JavaScript can I make a "click" event fire programmatically for a file input element?

I know this is old, and all these solutions are hacks around browser security precautions with real value.

That said, as of today, fileInput.click() works in current Chrome (36.0.1985.125 m) and current Firefox ESR (24.7.0), but not in current IE (11.0.9600.17207). Overlaying a file field with opacity 0 on top of a button works, but I wanted a link element as the visible trigger, and hover underlining doesn't quite work in any browser. It flashes on then disappears, probably the browser thinking through whether hover styling actually applies or not.

But I did find a solution that works in all those browsers. I won't claim to have tested every version of every browser, or that I know it'll continue to work forever, but it appears to meet my needs now.

It's simple: Position the file input field offscreen (position: absolute; top: -5000px), put a label element around it, and trigger the click on the label, instead of the file field itself.

Note that the link does need to be scripted to call the click method of the label, it doesn't do that automatically, like when you click on text inside a label element. Apparently the link element captures the click, and it doesn't make it through to the label.

Note also that this doesn't provide a way to show the currently selected file, since the field is offscreen. I wanted to submit immediately when a file was selected, so that's not a problem for me, but you'll need a somewhat different approach if your situation is different.

How do I get the position selected in a RecyclerView?

No need to have your ViewHolder implementing View.OnClickListener. You can get directly the clicked position by setting a click listener in the method onCreateViewHolder of RecyclerView.Adapter here is a sample of code :

public class ItemListAdapterRecycler extends RecyclerView.Adapter<ItemViewHolder>
{

    private final List<Item> items;

    public ItemListAdapterRecycler(List<Item> items)
    {
        this.items = items;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);

        view.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                int currentPosition = getClickedPosition(view);
                Log.d("DEBUG", "" + currentPosition);
            }
        });

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder, int position)
    {
        ...
    }

    @Override
    public int getItemCount()
    {
        return items.size();
    }

    private int getClickedPosition(View clickedView)
    {
        RecyclerView recyclerView = (RecyclerView) clickedView.getParent();
        ItemViewHolder currentViewHolder = (ItemViewHolder) recyclerView.getChildViewHolder(clickedView);
        return currentViewHolder.getAdapterPosition();
    }

}

What is the meaning of <> in mysql query?

In MySQL, <> means Not Equal To, just like !=.

mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1

see the docs for more info

Setting the Textbox read only property to true using JavaScript

Using asp.net, I believe you can do it this way :

myTextBox.Attributes.Add("readonly","readonly")

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

Finding the max value of an attribute in an array of objects

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

You can use a formula like:

(weekday + 5) % 7 + 1

If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want.

addition: for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula is :

(weekday  + @@DATEFIRST + 5) % 7 + 1

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How to delete a line from a text file in C#?

For very large files I'd do something like this

string tempFile = Path.GetTempFileName();

using(var sr = new StreamReader("file.txt"))
using(var sw = new StreamWriter(tempFile))
{
    string line;

    while((line = sr.ReadLine()) != null)
    {
         if(line != "removeme")
             sw.WriteLine(line);
    }
}

File.Delete("file.txt");
File.Move(tempFile, "file.txt");

Update I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using LINQ and deferred execution

var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme");

File.WriteAllLines(tempFile, linesToKeep);

File.Delete(fileName);
File.Move(tempFile, fileName);

The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.

A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.

File.WriteAllLines(fileName, 
    File.ReadLines(fileName).Where(l => l != "removeme").ToList());

Note that The .ToList is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded.

ERROR 1049 (42000): Unknown database 'mydatabasename'

If dump file contains:

CREATE DATABASE mydatabasename;
USE mydatabasename; 

You may just use in CLI:

mysql -uroot –pmypassword < mydatabase.sql

It works.

printing a two dimensional array in python

In addition to the simple print answer, you can actually customise the print output through the use of the numpy.set_printoptions function.

Prerequisites:

>>> import numpy as np
>>> inf = np.float('inf')
>>> A = np.array([[0,1,4,inf,3],[1,0,2,inf,4],[4,2,0,1,5],[inf,inf,1,0,3],[3,4,5,3,0]])

The following option:

>>> np.set_printoptions(infstr="(infinity)")

Results in:

>>> print(A)
[[        0.         1.         4. (infinity)         3.]
 [        1.         0.         2. (infinity)         4.]
 [        4.         2.         0.         1.         5.]
 [(infinity) (infinity)         1.         0.         3.]
 [        3.         4.         5.         3.         0.]]

The following option:

>>> np.set_printoptions(formatter={'float': "\t{: 0.0f}\t".format})

Results in:

>>> print(A)
[[   0       1       4       inf     3  ]
 [   1       0       2       inf     4  ]
 [   4       2       0       1       5  ]
 [   inf     inf     1       0       3  ]
 [   3       4       5       3       0  ]]


If you just want to have a specific string output for a specific array, the function numpy.array2string is also available.

Is there a pure CSS way to make an input transparent?

In case you just need the existence of it you could also throw it off the screen with display: fixed; right: -1000px;. It is useful when you need an input for copying to clipboard. :)

Elegant way to check for missing packages and install them?

You can simply use the setdiff function to get the packages that aren't installed and then install them. In the sample below, we check if the ggplot2 and Rcpp packages are installed before installing them.

unavailable <- setdiff(c("ggplot2", "Rcpp"), rownames(installed.packages()))
install.packages(unavailable)

In one line, the above can be written as:

install.packages(setdiff(c("ggplot2", "Rcpp"), rownames(installed.packages())))

MySQL LEFT JOIN Multiple Conditions

Correct answer is simply:

SELECT a.group_id
FROM a 
LEFT JOIN b ON a.group_id=b.group_id  and b.user_id = 4
where b.user_id is null
  and a.keyword like '%keyword%'

Here we are checking user_id = 4 (your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.

From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.

demo here

How to use custom font in a project written in Android Studio

https://i.stack.imgur.com/i6XNU.png

  1. Select File>New>Folder>Assets Folder

  2. Click finish

  3. Right click on assets and create a folder called fonts

  4. Put your font file in assets > fonts

  5. Use code below to change your textView's font

    TextView textView = (TextView) findViewById(R.id.textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/yourfont.ttf");
    textView.setTypeface(typeface);
    

how to know status of currently running jobs

EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,''

Notice the column Running, obviously 1 means that it is currently running, and [Current Step]. This returns job_id to you, so you'll need to look these up, e.g.:

SELECT top 100 *
 FROM   msdb..sysjobs
 WHERE  job_id IN (0x9DAD1B38EB345D449EAFA5C5BFDC0E45, 0xC00A0A67D109B14897DD3DFD25A50B80, 0xC92C66C66E391345AE7E731BFA68C668)

Running Composer returns: "Could not open input file: composer.phar"

I've reach to this problem when trying to install composer on a Window 7 machine from http://getcomposer.org/download page. As there was an existing compose version (provided by acquia Dev Desktop tool) the installation fails and the only chance was to fix this issue manually. (or to remove Dev Desktop tool composer).

Anyway the error message is quite straightforward (Could not open input file: composer.phar), we should then tell the system where the file is located.

Edit composer.bat file and should look like:

@SET PATH=C:\Program Files (x86)\DevDesktop\php5_4;%PATH%
php.exe composer.phar %*

See that composer.phar doesn´t have a file path. When standing in a different folder than the one where composer.phar is located the system won´t be able to find it. So, just complete the composer.phar file path:

@SET PATH=C:\Program Files (x86)\DevDesktop\php5_4;;%PATH%
SET composerScript=composer.phar
php.exe "%~dp0%composerScript%" %*

Reopen your window console and that should do the trick.

EDIT: this has an issue because it always uses %~dp0%composerScript% folder as composer execution. Then all configurations are done in that folder (besides standing on your current project folder) and not in your project folder.

So far I haven't found a was to make a manual composer installation to work globally on Windows. Perhaps you should go ahead with composer for windows installation mentioned above.

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

Auto Increment after delete in MySQL

I got a very simple but tricky method.

While deleting a row, you can preserve the IDs into another temporary table. After that, when you will insert new data into the main table then you can search and pick IDs from the temporary table. So use a checking here. If the temporary table has no IDs then calculate maximum ID into the main table and set the new ID as: new_ID = old_max_ID+1.

NB: You can not use auto-increment feature here.

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

Changing the space between each item in Bootstrap navbar

You can change this in your CSS with the property padding:

.navbar-nav > li{
  padding-left:30px;
  padding-right:30px;
}

Also you can set margin

.navbar-nav > li{
  margin-left:30px;
  margin-right:30px;
}

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Differences:

  1. The return type of RenderPartial is void, where as Partial returns MvcHtmlString

  2. Syntax for invoking Partial() and RenderPartial() methods in Razor views

    @Html.Partial("PartialViewName")
    @{ Html.RenderPartial("PartialViewName"); }

  3. Syntax for invoking Partial() and RenderPartial() methods in webform views

[%: Html.Partial("PartialViewName") %]
[% Html.RenderPartial("PartialViewName"); %]

The following are the 2 common interview questions related to Partial() and RenderPartial() When would you use Partial() over RenderPartial() and vice versa?

The main difference is that RenderPartial() returns void and the output will be written directly to the output stream, where as the Partial() method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().

Which one is better for performance?

From a performance perspective, rendering directly to the output stream is better. RenderPartial() does exactly the same thing and is better for performance over Partial().

How to do a JUnit assert on a message in a logger

Mocking is an option here, although it would be hard, because loggers are generally private static final - so setting a mock logger wouldn't be a piece of cake, or would require modification of the class under test.

You can create a custom Appender (or whatever it's called), and register it - either via a test-only configuration file, or runtime (in a way, dependent on the logging framework). And then you can get that appender (either statically, if declared in configuration file, or by its current reference, if you are plugging it runtime), and verify its contents.

List of all special characters that need to be escaped in a regex

on the other side of the coin, you should use "non-char" regex that looks like this if special characters = allChars - number - ABC - space in your app context.

String regepx = "[^\\s\\w]*";

SQL query to find Nth highest salary from a salary table

Let there be table salaries containing

+----------+--------+--------+
| emp      | salary | deptno |
+----------+--------+--------+
| ep1      |     10 | dp1    |
| ep2      |     20 | dp2    |
| ep3      |     30 | dp2    |
| ep4      |     40 | dp1    |
| ep5      |     50 | dp1    |
| ep6      |     60 | dp3    |
| ep7      |     70 | dp3    |
+----------+--------+--------+

By Nested Queries: (where you can change offset 0/1/2... for first, second and third... place respectively)

 select
      *
    from
      salaries as t1 
    where 
      t1.salary = (select 
                   salary
                 from 
                   salaries
                 where 
                 salaries.deptno = t1.deptno ORDER by salary desc limit 1 offset 1);

or might be by creating rank: (where you can change rank= 1/2/3... for first, second and third... place respectively)

SET @prev_value = NULL;
SET @rank_count = 0;
select * from 
(SELECT
  s.*, 
  CASE 
      WHEN @prev_value = deptno THEN @rank_count := @rank_count + 1
      WHEN @prev_value := deptno THEN @rank_count := 1 
      ELSE @rank_count := 1 
  END as rank
FROM salaries s
ORDER BY deptno, salary desc) as t
having t.rank = 2;

RegEx: Grabbing values between quotation marks

A supplementary answer for the subset of Microsoft VBA coders only one uses the library Microsoft VBScript Regular Expressions 5.5 and this gives the following code

Sub TestRegularExpression()

    Dim oRE As VBScript_RegExp_55.RegExp    '* Tools->References: Microsoft VBScript Regular Expressions 5.5
    Set oRE = New VBScript_RegExp_55.RegExp

    oRE.Pattern = """([^""]*)"""


    oRE.Global = True

    Dim sTest As String
    sTest = """Foo Bar"" ""Another Value"" something else"

    Debug.Assert oRE.test(sTest)

    Dim oMatchCol As VBScript_RegExp_55.MatchCollection
    Set oMatchCol = oRE.Execute(sTest)
    Debug.Assert oMatchCol.Count = 2

    Dim oMatch As Match
    For Each oMatch In oMatchCol
        Debug.Print oMatch.SubMatches(0)

    Next oMatch

End Sub

Comparing chars in Java

The first statement you have is probably not what you want... 'A'|'B'|'C' is actually doing bitwise operation :)

Your second statement is correct, but you will have 21 ORs.

If the 21 characters are "consecutive" the above solutions is fine.

If not you can pre-compute a hash set of valid characters and do something like

if (validCharHashSet.contains(symbol))...

MySQL with Node.js

connect the mysql database by installing a library. here, picked the stable and easy to use node-mysql module.

npm install [email protected]

var http = require('http'),
   mysql = require('mysql');

var sqlInfo = {
   host: 'localhost',
   user: 'root',
   password: 'urpass',
   database: 'dbname'
}
client = mysql.createConnection(sqlInfo);

client.connect();

For NodeJS mysql connecting and querying example

Auto reloading python Flask app upon code changes

Use this method:

app.run(debug=True)

It will auto-reload the flask app when a code change happens.

Sample code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
   return "Hello World"


if __name__ == '__main__':
  app.run(debug=True)

Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R to reload the page quickly.

Autowiring two beans implementing same interface - how to set default bean to autowire?

What about @Primary?

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

@Primary
public class HibernateDeviceDao implements DeviceDao

Or if you want your Jdbc version to be used by default:

<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">

@Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.

How to calculate the number of days between two dates?

I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:

// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours  / 24;

alert(timeDifferenceInDays);

You can skip some steps in the code, I have written it so to make it easy to understand.

You'll find a running example here: http://jsfiddle.net/matKX/

How can I start pagenumbers, where the first section occurs in LaTex?

I use

\pagenumbering{roman}

for everything in the frontmatter and then switch over to

\pagenumbering{arabic}

for the actual content. With pdftex, the page numbers come out right in the PDF file.

How to do a background for a label will be without color?

You are right. but here is the simplest way for making the back color of the label transparent In the properties window of that label select Web.. In Web select Transparent :)

Display two fields side by side in a Bootstrap Form

Just put two inputs inside a div with class form-group and set display flex on the div style

<form method="post">
<div class="form-group" style="display: flex;"><input type="text" class="form-control" name="nome" placeholder="Nome e sobrenome" style="margin-right: 4px;" /><input type="text" class="form-control" style="margin-left: 4px;" name="cpf" placeholder="CPF" /></div>
<div class="form-group" style="display: flex;"><input type="email" class="form-control" name="email" placeholder="Email" style="margin-right: 4px;" /><input type="tel" class="form-control" style="margin-left: 4px;" name="telephone" placeholder="Telefone" /></div>
<div class="form-group"><input type="password" class="form-control" name="password" placeholder="Password" /></div>
<div class="form-group"><input type="password" class="form-control" name="password-repeat" placeholder="Password (repeat)" /></div>
<div class="form-group">
    <div class="form-check"><label class="form-check-label"><input type="checkbox" class="form-check-input" />I agree to the license terms.</label></div>
</div>
<div class="form-group"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></div><a class="already" href="#">You already have an account? Login here.</a></form>

How to concatenate string variables in Bash

bla=hello
laber=kthx
echo "${bla}ohai${laber}bye"

Will output

helloohaikthxbye

This is useful when $blaohai leads to a variable not found error. Or if you have spaces or other special characters in your strings. "${foo}" properly escapes anything you put into it.

What is the best (and safest) way to merge a Git branch into master?

I would use the rebase method. Mostly because it perfectly reflects your case semantically, ie. what you want to do is to refresh the state of your current branch and "pretend" as if it was based on the latest.

So, without even checking out master, I would:

git fetch origin
git rebase -i origin/master
# ...solve possible conflicts here

Of course, just fetching from origin does not refresh the local state of your master (as it does not perform a merge), but it is perfectly ok for our purpose - we want to avoid switching around, for the sake of saving time.

How to return the output of stored procedure into a variable in sql server

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.

If no return is explicitly set, then the stored procedure returns zero.

   CREATE PROCEDURE GetImmediateManager
      @employeeID INT,
      @managerID INT OUTPUT
   AS
   BEGIN
     SELECT @managerID = ManagerID 
     FROM HumanResources.Employee 
     WHERE EmployeeID = @employeeID

     if @@rowcount = 0 -- manager not found?
       return 1;
   END

And you call it this way:

DECLARE @return_status int;
DECLARE @managerID int;

EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
  print N'Immediate manager not found!';
else 
  print N'ManagerID is ' + @managerID;
go

You should use the return value for status codes only. To return data, you should use output parameters.

If you want to return a dataset, then use an output parameter of type cursor.

more on RETURN statement

How to center a subview of UIView

Another solution with PureLayout using autoCenterInSuperview.

// ...
UIView *innerView = [UIView newAutoLayoutView];
innerView.backgroundColor = [UIColor greenColor];
[innerView autoSetDimensionsToSize:CGSizeMake(100, 30)];

[outerview addSubview:innerView];

[innerView autoCenterInSuperview];

This is it how it looks like:

Center with PureLayout

The difference between Classes, Objects, and Instances

Class is a template or type. An object is an instance of the class.

For example:

public class Tweet {

}

Tweet newTweet = new Tweet();

Tweet is a class and newTweet is an object of the class.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

SQL Server copy all rows from one table into another i.e duplicate table

Either you can use RAW SQL:

INSERT INTO DEST_TABLE (Field1, Field2) 
SELECT Source_Field1, Source_Field2 
FROM SOURCE_TABLE

Or use the wizard:

  1. Right Click on the Database -> Tasks -> Export Data
  2. Select the source/target Database
  3. Select source/target table and fields
  4. Copy the data

Then execute:

TRUNCATE TABLE SOURCE_TABLE

What is the difference between a token and a lexeme?

Let's see the working of a lexical analyser ( also called Scanner )

Let's take an example expression :

INPUT : cout << 3+2+3;

FORMATTING PERFORMED BY SCANNER :  {cout}|space|{<<}|space|{3}{+}{2}{+}{3}{;} 

not the actual output though .

SCANNER SIMPLY LOOKS REPEATEDLY FOR A LEXEME IN SOURCE-PROGRAM TEXT UNTIL INPUT IS EXHAUSTED

Lexeme is a substring of input that forms a valid string-of-terminals present in grammar . Every lexeme follows a pattern which is explained at the end ( the part that reader may skip at last )

( Important rule is to look for the longest possible prefix forming a valid string-of-terminals until next whitespace is encountered ... explained below )

LEXEMES :

  1. cout
  2. <<

( although "<" is also valid terminal-string but above mentioned rule shall select the pattern for lexeme "<<" in order to generate token returned by scanner )

  1. 3
  2. +
  3. 2
  4. ;

TOKENS : Tokens are returned one at a time ( by Scanner when requested by Parser ) each time Scanner finds a (valid) lexeme. Scanner creates ,if not already present, a symbol-table entry ( having attributes : mainly token-category and few others ) , when it finds a lexeme, in order to generate it's token

'#' denotes a symbol table entry . I have pointed to lexeme number in above list for ease of understanding but it technically should be actual index of record in symbol table.

The following tokens are returned by scanner to parser in specified order for above example.

  1. < identifier , #1 >

  2. < Operator , #2 >

  3. < Literal , #3 >

  4. < Operator , #4 >

  5. < Literal , #5 >

  6. < Operator , #4 >

  7. < Literal , #3 >

  8. < Punctuator , #6 >

As you can see the difference , a token is a pair unlike lexeme which is a substring of input.

And first element of the pair is the token-class/category

Token Classes are listed below:

  • KEYWORDS
  • IDENTIFIERS
  • LITERALS
  • PUNCTUATORS
  • OPERATORS
  • And one more thing , Scanner detects whitespaces , ignores them and does not form any token for a whitespace at all. Not all delimiters are whitespaces, a whitespace is one form of delimiter used by scanners for it's purpose . Tabs , Newlines , Spaces , Escaped Characters in input all are collectively called Whitespace delimiters. Few other delimiters are ';' ',' ':' etc, which are widely recognised as lexemes that form token.

    Total number of tokens returned are 8 here , however only 6 symbol table entries are made for lexemes . Lexemes are also 8 in total ( see definition of lexeme )

    --- You can skip this part

    A ***pattern*** is a rule ( say, a regular expression ) that is used to check if a string-of-terminals is valid or not.

    If a substring of input composed only of grammar terminals is following the rule specified by any of the listed patterns , it is validated as a lexeme and selected pattern will identify the category of lexeme, else a lexical error is reported due to either (i) not following any of the rules or (ii) input consists of a bad terminal-character not present in grammar itself.

    for example :
    
    1. No Pattern Exists : In C++ , "99Id_Var" is grammar-supported string-of-terminals but is not recognised by any of patterns hence lexical error is reported .
    
    2. Bad Input Character : $,@,unicode characters may not be supported as a valid character in few programming languages.`
    

    Catch KeyError in Python

    If you don't want to handle error just NoneType and use get() e.g.:

    manager.connect.get("")
    

    NameError: name 'datetime' is not defined

    You need to import the module datetime first:

    >>> import datetime
    

    After that it works:

    >>> import datetime
    >>> date = datetime.date.today()
    >>> date
    datetime.date(2013, 11, 12)
    

    Using HTML5/JavaScript to generate and save a file

    Simple Solution!

    _x000D_
    _x000D_
    <a download="My-FileName.txt" href="data:application/octet-stream,HELLO-WORLDDDDDDDD">Click here</a>
    _x000D_
    _x000D_
    _x000D_

    Works in all Modern browsers.

    What is the 'realtime' process priority setting for?

    It basically is higher/greater in everything else. A keyboard is less of a priority than the real time process. This means the process will be taken into account faster then keyboard and if it can't handle that, then your keyboard is slowed.

    Creating a search form in PHP to search a database?

    try this out let me know what happens.

    Form:

    <form action="form.php" method="post"> 
    Search: <input type="text" name="term" /><br /> 
    <input type="submit" value="Submit" /> 
    </form> 
    

    Form.php:

    $term = mysql_real_escape_string($_REQUEST['term']);    
    
    $sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
    $r_query = mysql_query($sql);
    
    while ($row = mysql_fetch_array($r_query)){ 
    echo 'Primary key: ' .$row['PRIMARYKEY']; 
    echo '<br /> Code: ' .$row['Code']; 
    echo '<br /> Description: '.$row['Description']; 
    echo '<br /> Category: '.$row['Category']; 
    echo '<br /> Cut Size: '.$row['CutSize'];  
    } 
    

    Edit: Cleaned it up a little more.

    Final Cut (my test file):

    <?php
    $db_hostname = 'localhost';
    $db_username = 'demo';
    $db_password = 'demo';
    $db_database = 'demo';
    
    // Database Connection String
    $con = mysql_connect($db_hostname,$db_username,$db_password);
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db($db_database, $con);
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title></title>
        </head>
        <body>
    <form action="" method="post">  
    Search: <input type="text" name="term" /><br />  
    <input type="submit" value="Submit" />  
    </form>  
    <?php
    if (!empty($_REQUEST['term'])) {
    
    $term = mysql_real_escape_string($_REQUEST['term']);     
    
    $sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
    $r_query = mysql_query($sql); 
    
    while ($row = mysql_fetch_array($r_query)){  
    echo 'Primary key: ' .$row['PRIMARYKEY'];  
    echo '<br /> Code: ' .$row['Code'];  
    echo '<br /> Description: '.$row['Description'];  
    echo '<br /> Category: '.$row['Category'];  
    echo '<br /> Cut Size: '.$row['CutSize'];   
    }  
    
    }
    ?>
        </body>
    </html>
    

    "java.lang.OutOfMemoryError : unable to create new native Thread"

    First of all I wouldn't blame that much the OS/VM.. rather the developer who wrote the code that creates sooo many Threads. Basically somewhere in your code (or 3rd party) a lot of threads are created without control.

    Carefully review the stacktraces/code and control the number of threads that get created. Normally your app shouldn't need a large amount of threads, if it does it's a different problem.

    Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

    There is also someone who managed to modify CR for VS.NET 2010 to install on 2012, using MS ORCA in this thread: http://scn.sap.com/thread/3235515 . I couldn't get it to work myself, though.

    How to change language of app when user selects language?

    Kotlin solution using context extension

    fun Context.applyNewLocale(locale: Locale): Context {
        val config = this.resources.configuration
        val sysLocale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.locales.get(0)
        } else {
            //Legacy
            config.locale
        }
        if (sysLocale.language != locale.language) {
            Locale.setDefault(locale)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                config.setLocale(locale)
            } else {
                //Legacy
                config.locale = locale
            }
            resources.updateConfiguration(config, resources.displayMetrics)
        }
        return this
    }
    

    Usage

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(newBase?.applyNewLocale(Locale("es", "MX")))
    }
    

    AngularJS Dropdown required validation

    You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

    HTML:

            <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
            <input type="text" name="txtServiceName" ng-model="ServiceName" required>
    <span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
    <br/>
              <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                      ng-model="ServiceID" 
                      ng-options="service.ServiceID as service.ServiceName for service in services"
                      required> 
                <option value="">Select Service</option> 
              </select> 
              <span ng-show="myForm.service_id.$error.required">Select service</span>
    
            </form>
    
        Controller:
    
            function Ctrl($scope) {
              $scope.services = [
                {ServiceID: 1, ServiceName: 'Service1'},
                {ServiceID: 2, ServiceName: 'Service2'},
                {ServiceID: 3, ServiceName: 'Service3'}
              ];
    
        $scope.save = function(myForm) {
        console.log('Selected Value: '+ myForm.service_id.$modelValue);
        alert('Data Saved! without validate');
        };
            }
    

    Here's a working plunker.

    php, mysql - Too many connections to database error

    If you need to increase MySQL Connections without MySQL restart do like below, also if you don't know configuration file, below use the mysqlworkbench or phpmyadmin or command prompt to run below queries.

    mysql> show variables like 'max_connections';
    +-----------------+-------+
    | Variable_name   | Value |
    +-----------------+-------+
    | max_connections | 151   |
    +-----------------+-------+
    1 row in set (0.00 sec)
    
    mysql> SET GLOBAL max_connections = 250;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> show variables like 'max_connections';
    +-----------------+-------+
    | Variable_name   | Value |
    +-----------------+-------+
    | max_connections | 250   |
    +-----------------+-------+
    1 row in set (0.00 sec)
    

    These settings will change at MySQL Restart.


    For permanent changes add below line in my.cnf and restart MySQL.

    max_connections = 151
    

    How can I get javascript to read from a .json file?

    NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

    If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

    _x000D_
    _x000D_
    var xmlhttp = new XMLHttpRequest();_x000D_
    xmlhttp.onreadystatechange = function() {_x000D_
        if (this.readyState == 4 && this.status == 200) {_x000D_
            var myObj = JSON.parse(this.responseText);_x000D_
            document.getElementById("demo").innerHTML = myObj.name;_x000D_
        }_x000D_
    };_x000D_
    xmlhttp.open("GET", "json_demo.txt", true);_x000D_
    xmlhttp.send();
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
    _x000D_
    <h2>Use the XMLHttpRequest to get the content of a file.</h2>_x000D_
    <p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>_x000D_
    _x000D_
    <p id="demo"></p>_x000D_
    _x000D_
    _x000D_
    <p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>_x000D_
    _x000D_
    </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

    Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    Here's a summary:

    The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

    Here's the example used:

    _x000D_
    _x000D_
    var json = '{"result":true, "count":42}';_x000D_
    obj = JSON.parse(json);_x000D_
    _x000D_
    console.log(obj.count);_x000D_
    // expected output: 42_x000D_
    _x000D_
    console.log(obj.result);_x000D_
    // expected output: true
    _x000D_
    _x000D_
    _x000D_

    Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

    Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

    If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

    Since it isn't working, I'd try using XMLHttpRequests

    You could also try AJAX requests:

    $.ajax({
        'async': false,
        'global': false,
        'url': "/jsonfile.json",
        'dataType': "json",
        'success': function (data) {
            // do stuff with data
        }
    });
    

    Documentation: http://api.jquery.com/jquery.ajax/

    How to dynamically create a class?

    You can also dynamically create a class by using DynamicExpressions.

    Since 'Dictionary's have compact initializers and handle key collisions, you will want to do something like this.

      var list = new Dictionary<string, string> {
        {
          "EmployeeID",
          "int"
        }, {
          "EmployeeName",
          "String"
        }, {
          "Birthday",
          "DateTime"
        }
      };
    

    Or you might want to use a JSON converter to construct your serialized string object into something manageable.

    Then using System.Linq.Dynamic;

      IEnumerable<DynamicProperty> props = list.Select(property => new DynamicProperty(property.Key, Type.GetType(property.Value))).ToList();
    
      Type t = DynamicExpression.CreateClass(props);
    

    The rest is just using System.Reflection.

      object obj = Activator.CreateInstance(t);
      t.GetProperty("EmployeeID").SetValue(obj, 34, null);
      t.GetProperty("EmployeeName").SetValue(obj, "Albert", null);
      t.GetProperty("Birthday").SetValue(obj, new DateTime(1976, 3, 14), null);
    }  
    

    How to run Java program in command prompt

    All you need to do is:

    • Build the mainjava class using the class path if any (optional)

      javac *.java [ -cp "wb.jar;"]

    • Create Manifest.txt file with content is:

      Main-Class: mainjava

    • Package the jar file for mainjava class

      jar cfm mainjava.jar Manifest.txt *.class

    Then you can run this .jar file from cmd with class path (optional) and put arguments for it.

    java [-cp "wb.jar;"] mainjava arg0 arg1 
    

    HTH.

    View a file in a different Git branch without changing branches

    Add the following to your ~/.gitconfig file

    [alias]
      cat = "!git show \"$1:$2\" #"
    

    And then try this

    git cat BRANCHNAME FILEPATH
    

    Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show command.

    Printing an int list in a single line python3

    If you write

    a = [1, 2, 3, 4, 5]
    print(*a, sep = ',')
    

    You get this output: 1,2,3,4,5

    How to list all available Kafka brokers in a cluster?

    If you are using new version of Kafka e.g. 5.3.3, you can use

    kafka-broker-api-versions  --bootstrap-server BROKER | grep 9092
    

    You just need to pass one of the brokers

    Replace CRLF using powershell

    This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:

    • Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).

    • Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.

    • A future version of PowerShell Core will have a
      Convert-TextFile cmdlet with a -LineEnding parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.

    In PSv5+, PowerShell-native solutions are now possible, because Set-Content now supports the -NoNewline switch, which prevents undesired appending of a platform-native newline[1] :

    # Convert CRLFs to LFs only.
    # Note:
    #  * (...) around Get-Content ensures that $file is read *in full*
    #    up front, so that it is possible to write back the transformed content
    #    to the same file.
    #  * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
    #     expect.
    ((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
    

    The above relies on Get-Content's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.

    Caveats:

    • You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding; without -Encoding:

      • In Windows PowerShell, you'll get "ANSI" encoding, your system's single-byte, 8-bit legacy encoding, such as Windows-1252 on US-English systems.
      • In PowerShell Core, you'll get UTF-8 encoding without a BOM.
    • The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.

    • There's a risk of file corruption, if the process of writing back to the input file gets interrupted.


    [1] In fact, if there are multiple strings to write, -NoNewline also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.

    how to drop database in sqlite?

    You can drop tables by issuing an SQL Command as you would normally. If you want to drop the whole database you'll have to delete the file. You can delete the file located under

    data/data/com.your.app.name/database/[databasefilename]

    you can do this from the eclipse view called "FileBrowser" out of the "Android" Category for example. Or directly on your emulator or phone.

    vertical divider between two columns in bootstrap

    If you are still seeking for the best solution in 2018, I found the way this works perfectly if you have at least one free pseudo element( ::after or ::before ).

    You just have to add class to your row like this: <div class="row vertical-divider ">

    And add this to your CSS:

    .row.vertical-divider [class*='col-']:not(:last-child)::after {
      background: #e0e0e0;
      width: 1px;
      content: "";
      display:block;
      position: absolute;
      top:0;
      bottom: 0;
      right: 0;
      min-height: 70px;
    }
    

    Any row with this class will now have vertical divider between all of the columns it contains...

    You can see how this works in this example.

    How do I iterate and modify Java Sets?

    You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

    Set<Integer> set = new TreeSet<Integer>();
        set.add(1);
        set.add(2);
        set.add(3);
    
        //good way:
        Iterator<Integer> iterator = set.iterator();
        while(iterator.hasNext()) {
            Integer setElement = iterator.next();
            if(setElement==2) {
                iterator.remove();
            }
        }
    
        //bad way:
        for(Integer setElement:set) {
            if(setElement==2) {
                //might work or might throw exception, Java calls it indefined behaviour:
                set.remove(setElement);
            } 
        }
    

    As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

    Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

    https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

    stipulate, amongst others, that (emphasis mine):

    "For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

    "Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

    To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

    This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

    Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.

    GetFiles with multiple extensions

    I'm not sure if that is possible. The MSDN GetFiles reference says a search pattern, not a list of search patterns.

    I might be inclined to fetch each list separately and "foreach" them into a final list.

    svn cleanup: sqlite: database disk image is malformed

    no need to worry for a directory lock guys.

    Just you need to do is, If sqllite3 is not installed, type below command,

    >sudo apt-get install sqlite3
    

    Open SVN database by typing this command,

    >sqlite3 .svn/wc.db 
    

    Now just you need to do is to remove locks entries from SVN DB.

    sqlite>  select * from wc_lock;
    1|-1           
    sqlite>  delete from wc_lock;
    sqlite>  select * from wc_lock;
    sqlite>  .q
    

    Process Completed. You can work on your SVN repository, do commit, update, add, remove operations without issue.

    :-)

    Is this very likely to create a memory leak in Tomcat?

    The key "Transactional Resources" looks like you are talking to the database without a proper transaction. Make sure transaction management is configured properly and no invocation path to the DAO exists that doesn't run under a @Transactional annotation. This can easily happen when you configured transaction management on the Controller level but are invoking DAOs in a timer or are using @PostConstruct annotations. I wrote it up here http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

    Edit: It looks like this is (also?) a bug with spring-data-jpa which has been fixed with v1.4.3. I looked it up in the spring-data-jpa sources of LockModeRepositoryPostProcessor which sets the "Transactional Resources" key. In 1.4.3 it also clears the key again.

    automating telnet session using bash scripts

    Use ssh for that purpose. Generate keys without using a password and place it to .authorized_keys at the remote machine. Create the script to be run remotely, copy it to the other machine and then just run it remotely using ssh.

    I used this approach many times with a big success. Also note that it is much more secure than telnet.

    Copy Notepad++ text with formatting?

    Select the Text

    From the menu, go to Plugins > NPPExport > Copy RTF to clipboard

    In MS Word go to Edit > Paste Special

    This will open the Paste Special dialog box. Select the Paste radio button and from the list select Formatted Text (RTF)

    You should be able to see the Formatted Text.

    How do I get an OAuth 2.0 authentication token in C#

    Here is a complete example. Right click on the solution to manage nuget packages and get Newtonsoft and RestSharp:

    using Newtonsoft.Json.Linq;
    using RestSharp;
    using System;
    
    
    namespace TestAPI
    {
        class Program
        {
            static void Main(string[] args)
            {
                String id = "xxx";
                String secret = "xxx";
    
                var client = new RestClient("https://xxx.xxx.com/services/api/oauth2/token");
                var request = new RestRequest(Method.POST);
                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("content-type", "application/x-www-form-urlencoded");
                request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
    
                dynamic resp = JObject.Parse(response.Content);
                String token = resp.access_token;            
    
                client = new RestClient("https://xxx.xxx.com/services/api/x/users/v1/employees");
                request = new RestRequest(Method.GET);
                request.AddHeader("authorization", "Bearer " + token);
                request.AddHeader("cache-control", "no-cache");
                response = client.Execute(request);
            }        
        }
    }
    

    Practical uses for the "internal" keyword in C#

    The internal keyword is heavily used when you are building a wrapper over non-managed code.

    When you have a C/C++ based library that you want to DllImport you can import these functions as static functions of a class, and make they internal, so your user only have access to your wrapper and not the original API so it can't mess with anything. The functions being static you can use they everywhere in the assembly, for the multiple wrapper classes you need.

    You can take a look at Mono.Cairo, it's a wrapper around cairo library that uses this approach.

    How to delete a specific file from folder using asp.net

    Check the GridView1.SelectedRow is not null:

    if (GridView1.SelectedRow == null) return;
    string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
    

    How do I pass the this context to a function?

    You can use the bind function to set the context of this within a function.

    function myFunc() {
      console.log(this.str)
    }
    const myContext = {str: "my context"}
    const boundFunc = myFunc.bind(myContext);
    boundFunc(); // "my context"
    

    Execute a batch file on a remote PC using a batch file on local PC

    Use microsoft's tool for remote commands executions: PsExec

    If there isn't your bat-file on remote host, copy it first. For example:

    copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\
    

    And then execute:

    psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat
    

    Note: filepath for psexec is path to file on remote server, not your local.

    Please initialize the log4j system properly. While running web service

    You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator

    public class FooImpl implements Foo {
    
        private static final Logger LOGGER = Logger.getLogger(FooBar.class);
    
        public Object createObject() {
            BasicConfigurator.configure();
            LOGGER.info("something");
            return new Object();
        }
    }
    

    So under the table, configure do:

      configure() {
        Logger root = Logger.getRootLogger();
        root.addAppender(new ConsoleAppender(
               new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
      }
    

    Can not find the tag library descriptor of springframework

    If you want direct link:

    https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/src/main/resources/META-INF/spring-form.tld

    Or from repos:

    JCenter : link

    Maven Central : link

    And if you need as Gradle dependency:

    compile 'org.springframework:spring-webmvc:4.1.6.RELEASE

    More information about spring-form: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/spring-form.tld.html

    Scroll to the top of the page using JavaScript?

    You dont need JQuery. Simply you can call the script

    window.location = '#'
    

    on click of the "Go to top" button

    Sample demo:

    output.jsbin.com/fakumo#

    PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.

    Use a.empty, a.bool(), a.item(), a.any() or a.all()

    As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

    It would go something like this:

    mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
    

    In order to avoid that, you can build series for lower and upper limits:

    low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
    high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
    

    Now you can slice it as follows:

    mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
    df[mask]
    Out: 
         dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
    17                        136          62              97                15   
    69                        110          85              96                18   
    72                        105          85              97                16   
    161                       126          57              99                16   
    286                       127          84              99                12   
    435                        92          67              96                13   
    499                       110          66              97                15   
    
         systolic blood pressure  temperature  
    17                       141           37  
    69                       155           38  
    72                       154           36  
    161                      153           36  
    286                      156           37  
    435                      155           36  
    499                      149           36  
    

    And for assignment you can use np.where:

    df['class'] = np.where(mask, 'excellent', 'critical')
    

    Common MySQL fields and their appropriate data types

    Someone's going to post a much better answer than this, but just wanted to make the point that personally I would never store a phone number in any kind of integer field, mainly because:

    1. You don't need to do any kind of arithmetic with it, and
    2. Sooner or later someone's going to try to (do something like) put brackets around their area code.

    In general though, I seem to almost exclusively use:

    • INT(11) for anything that is either an ID or references another ID
    • DATETIME for time stamps
    • VARCHAR(255) for anything guaranteed to be under 255 characters (page titles, names, etc)
    • TEXT for pretty much everything else.

    Of course there are exceptions, but I find that covers most eventualities.

    How can I get the number of records affected by a stored procedure?

    For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

    Remove non-numeric characters (except periods and commas) from a string

    If letters are always in the beginning or at the end, you can simply just use trim...no regex needed

    $string = trim($string, "a..zA..Z"); // this also take care of lowercase
    
    "AR3,373.31" --> "3,373.31"
    "12.322,11T" --> "12.322,11"
    "12.322,11"  --> "12.322,11"
    

    Concatenating variables and strings in React

    the best way to concat props/variables:

    var sample = "test";    
    var result = `this is just a ${sample}`;    
    //this is just a test
    

    Check if a radio button is checked jquery

    if($("input:radio[name=test]").is(":checked")){
      //Code to append goes here
    }
    

    How to transform numpy.matrix or array to scipy sparse matrix

    You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

    >>> import numpy as np
    >>> from scipy import sparse
    >>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
    >>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])
    
    >>> A
    array([[1, 2, 0],
           [0, 0, 3],
           [1, 0, 4]])
    
    >>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
    >>> sB = sparse.csr_matrix(B)
    
    >>> sA
    <3x3 sparse matrix of type '<type 'numpy.int32'>'
            with 5 stored elements in Compressed Sparse Row format>
    
    >>> print sA
      (0, 0)        1
      (0, 1)        2
      (1, 2)        3
      (2, 0)        1
      (2, 2)        4
    

    How to position a div in bottom right corner of a browser?

    This snippet works in IE7 at least

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Test</title>
    <style>
      #foo {
        position: fixed;
        bottom: 0;
        right: 0;
      }
    </style>
    </head>
    <body>
      <div id="foo">Hello World</div>
    </body>
    </html>
    

    Error 405 (Method Not Allowed) Laravel 5

    This might help someone so I'll put my inputs here as well.

    I've encountered the same (or similar) problem. Apparently, the problem was the POST request was blocked by Modsec by the following rules: 350147, 340147, 340148, 350148

    After blocking the request, I was redirected to the same endpoint but as a GET request of course and thus the 405.

    I whitelisted those rules and voila, the 405 error was gone.

    Hope this helps someone.

    Android: disabling highlight on listView click

    RoflcoptrException's answer should do the trick,but for some reason it did not work for me, So I am posting the solution which worked for me, hope it helps someone

    <ListView 
    android:listSelector="@android:color/transparent" 
    android:cacheColorHint="@android:color/transparent"
    />
    

    Expand div to max width when float:left is set

    this usage may solve your problem.

    width: calc(100% - 100px);
    

    _x000D_
    _x000D_
    <!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    _x000D_
    <head>_x000D_
      <meta charset="UTF-8" />_x000D_
      <title>Content with Menu</title>_x000D_
      <style>_x000D_
        .content .left {_x000D_
          float: left;_x000D_
          width: 100px;_x000D_
          background-color: green;_x000D_
        }_x000D_
        _x000D_
        .content .right {_x000D_
          float: left;_x000D_
          width: calc(100% - 100px);_x000D_
          background-color: red;_x000D_
        }_x000D_
      </style>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <div class="content">_x000D_
        <div class="left">_x000D_
          <p>Hi, Flo!</p>_x000D_
        </div>_x000D_
        <div class="right">_x000D_
          <p>is</p>_x000D_
          <p>this</p>_x000D_
          <p>what</p>_x000D_
          <p>you are looking for?</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    What is the correct format to use for Date/Time in an XML file

    I always use the ISO 8601 format (e.g. 2008-10-31T15:07:38.6875000-05:00) -- date.ToString("o"). It is the XSD date format as well. That is the preferred format and a Standard Date and Time Format string, although you can use a manual format string if necessary if you don't want the 'T' between the date and time: date.ToString("yyyy-MM-dd HH:mm:ss");

    EDIT: If you are using a generated class from an XSD or Web Service, you can just assign the DateTime instance directly to the class property. If you are writing XML text, then use the above.

    how to print json data in console.log

    I used '%j' option in console.log to print JSON objects

    console.log("%j", jsonObj);
    

    Run all SQL files in a directory

    You can create a single script that calls all the others.

    Put the following into a batch file:

    @echo off
    echo.>"%~dp0all.sql"
    for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"
    

    When you run that batch file it will create a new script named all.sql in the same directory where the batch file is located. It will look for all files with the extension .sql in the same directory where the batch file is located.

    You can then run all scripts by using sqlplus user/pwd @all.sql (or extend the batch file to call sqlplus after creating the all.sql script)

    Given the lat/long coordinates, how can we find out the city/country?

    The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.

    Try this link to see an example of the output (this is in json, output is also available in XML)

    https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true

    Streaming via RTSP or RTP in HTML5

    Technically 'Yes'

    (but not really...)

    HTML 5's <video> tag is protocol agnostic—it does not care. You place the protocol in the src attribute as part of the URL. E.g.:

    <video src="rtp://myserver.com/path/to/stream">
        Your browser does not support the VIDEO tag and/or RTP streams.
    </video>
    

    or maybe

    <video src="http://myserver.com:1935/path/to/stream/myPlaylist.m3u8">
        Your browser does not support the VIDEO tag and/or RTP streams.
    </video>
    

    That said, the implementation of the <video> tag is browser specific. Since it is early days for HTML 5, I expect frequently changing support (or lack of support).

    From the W3C's HTML5 spec (The video element):

    User agents may support any video and audio codecs and container formats

    Remove all newlines from inside a string

    strip only removes characters from the beginning and end of a string. You want to use replace:

    str2 = str.replace("\n", "")
    re.sub('\s{2,}', ' ', str) # To remove more than one space 
    

    EOFError: EOF when reading a line

    convert your inputs to ints:

    width = int(input())
    height = int(input())
    

    PHP: If internet explorer 6, 7, 8 , or 9

    I do this

    $u = $_SERVER['HTTP_USER_AGENT'];
    
    $isIE7  = (bool)preg_match('/msie 7./i', $u );
    $isIE8  = (bool)preg_match('/msie 8./i', $u );
    $isIE9  = (bool)preg_match('/msie 9./i', $u );
    $isIE10 = (bool)preg_match('/msie 10./i', $u );
    
    if ($isIE9) {
        //do ie9 stuff
    }
    

    Get restaurants near my location

    Is this what you are looking for?

    https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
    

    types is optional

    How do you express binary literals in Python?

    I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().

    EDIT: lbrandy's answer is correct in all cases.

    How to convert map to url query string?

    Using EntrySet and Streams:

    map
      .entrySet()
      .stream()
      .map(e -> e.getKey() + "=" + e.getValue())
      .collect(Collectors.joining("&"));
    

    Where does forever store console.log output?

    Forever, by default, will put logs into a random file in ~/.forever/ folder.

    You should run forever list to see the running processes and their corresponding log file.

    Sample output

    >>> forever list
    info:    Forever processes running
    data:        uid  command       script forever pid  logfile                         uptime
    data:    [0] 6n71 /usr/bin/node app.js 2233    2239 /home/vagrant/.forever/6n71.log 0:0:0:1.590
    

    However, it's probably best to specify with -l as mentioned by bryanmac.

    How can I slice an ArrayList out of an ArrayList in Java?

    In Java, it is good practice to use interface types rather than concrete classes in APIs.

    Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

    This is what your code should look like:

    List input = new ArrayList(...);
    
    public void doSomething(List input) {
       List inputA = input.subList(0, input.size()/2);
       ...
    }
    
    this.doSomething(input);
    

    Your proposed "solution" to the problem was/is this:

    new ArrayList(input.subList(0, input.size()/2))
    

    That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


    If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

    1. It would be a lot of work to design, implement and test.
    2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
    3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

    The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

    Get height of div with no height set in css

    Just a note in case others have the same problem.

    I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().

    var currentHeight = 0;
    $(window).load(function() {
        //get the natural page height -set it in variable above.
    
        currentHeight = $('#js_content_container').outerHeight();
    
        console.log("set current height on load = " + currentHeight)
        console.log("content height function (should be 374)  = " + contentHeight());   
    
    });
    

    PHP class: Global variable as property in class

    If you want to access a property from inside a class you should:

    private $classNumber = 8;
    

    How to throw RuntimeException ("cannot find symbol")

    Just for others: be sure it is new RuntimeException, not new RuntimeErrorException which needs error as an argument.

    Graphical DIFF programs for linux

    Subclipse for Eclipse has an excellent graphical diff plugin if you are using SVN (subversion) source control.

    Conversion failed when converting date and/or time from character string in SQL SERVER 2008

    Seems like last_accessed_on, is a date time, and you are converting '23-07-2014 09:37:00' to a varchar. This would not work, and give you conversion errors. Try

    last_accessed_on= convert(datetime,'23-07-2014 09:37:00', 103)  
    

    I think you can avoid the cast though, and update with '23-07-2014 09:37:00'. It should work given that the format is correct.

    Your query is not going to work because in last_accessed_on (which is DateTime2 type), you are trying to pass a Varchar value.

    You query would be

    UPDATE  student_queues SET  Deleted=0 ,  last_accessed_by='raja', last_accessed_on=convert(datetime,'23-07-2014 09:37:00', 103)  
     WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
    

    Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

    Agree with David. To add on, it may not be the case that we want to groupBy all columns other than the column(s) in aggregate function i.e, if we want to remove duplicates purely based on a subset of columns and retain all columns in the original dataframe. So the better way to do this could be using dropDuplicates Dataframe api available in Spark 1.4.0

    For reference, see: https://spark.apache.org/docs/1.4.0/api/scala/index.html#org.apache.spark.sql.DataFrame

    Any way to replace characters on Swift String?

    I think Regex is the most flexible and solid way:

    var str = "This is my string"
    let regex = try! NSRegularExpression(pattern: " ", options: [])
    let output = regex.stringByReplacingMatchesInString(
        str,
        options: [],
        range: NSRange(location: 0, length: str.characters.count),
        withTemplate: "+"
    )
    // output: "This+is+my+string"
    

    How to tag an older commit in Git?

    OK, You can simply do:

    git tag -a <tag> <commit-hash>
    

    So if you want to add tag: 1.0.2 to commit e50f795, just simply do:

    git tag -a 1.0.2 e50f795
    

    Also you add a message at the end, using -m, something like this:

    git tag -a 1.0.2 e50f795 -m "my message"
    

    After all, you need to push it to the remote, to do that, simply do:

    git push origin 1.0.2 
    

    If you have many tags which you don't want to mention them one by one, just simply do:

    git push origin --tags
    

    to push all tags together...

    Also, I created the steps in the image below, for more clarification of the steps: creating tag on a commit hash

    You can also dd the tag in Hub or using tools like SourceTree, to avoid the previous steps, I logged-in to my Bitbucket in this case and doing it from there:

    1. Go to your branch and find the commit you want to add the tag to and click on it:

    find your commit in bitbucket

    1. In the commit page, on the right, find where it says No tags and click on the + icon:

    find where it says No tags

    1. In the tag name box, add your tag:

    add tag name

    1. Now you see that the tag has successfully created:

    enter image description here

    MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

    For me, It was not specifying the -p parameter when entering mysql.

    mysql -p
    

    I had no problem, but it was wrong to invoke mysql without a password.

    Program to find prime numbers

    There are some very optimal ways to implement the algorithm. But if you don't know much about maths and you simply follow the definition of prime as the requirement: a number that is only divisible by 1 and by itself (and nothing else), here's a simple to understand code for positive numbers.

    public bool IsPrime(int candidateNumber)
    {
        int fromNumber = 2;
        int toNumber = candidateNumber - 1;
    
        while(fromNumber <= toNumber)
        {
            bool isDivisible = candidateNumber % fromNumber == 0;
            if (isDivisible)
            {
                return false;
            }
    
            fromNumber++;
        }
        return true;
    }
    

    Since every number is divisible by 1 and by itself, we start checking from 2 onwards until the number immediately before itself. That's the basic reasoning.