Programs & Examples On #Html agility pack

HTML Agility Pack is an open-source HTML parser that builds a read/write DOM and supports Linq, plain XPATH or XSLT.

How to use HTML Agility pack

try this

string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());

private string ParseHmlBody(string html)
        {
            string body = string.Empty;
            try
            {
                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);
                var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
                body = htmlBody.OuterHtml;
            }
            catch (Exception ex)
            {

                dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
            }
            return body;
        }

Html Agility Pack get all elements by class

You can use the following script:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);

HTML Agility pack - parsing tables

Line from above answer:

HtmlDocument doc = new HtmlDocument();

This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument any more.

Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb and check out this link for some sample code.

select dept names who have more than 2 employees whose salary is greater than 1000

hope this helps

select DeptName from DEPARTMENT inner join EMPLOYEE using (DeptId) where Salary>1000 group by DeptName having count(*)>2

Way to ng-repeat defined number of times instead of repeating over array?

Easiest answer: 2 lines of code

JS (in your AngularJS controller)

$scope.range = new Array(MAX_REPEATS); // set MAX_REPEATS to the most repetitions you will ever need in a single ng-repeat that makes use of this strategy

HTML

<div ng-repeat="i in range.slice(0,repeatCount) track by $index"></div>

...where repeatCount is the number of repetitions that should appear in this location.

Could not find server 'server name' in sys.servers. SQL Server 2014

I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"

Insert data into table with result from another select query

Below is an example of such a query:

INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

How to fix 'Microsoft Excel cannot open or save any more documents'

I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.

Way 01:

Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.

Way 02:

This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.

How do I set the request timeout for one controller action in an asp.net mvc application

I had to add "Current" using .NET 4.5:

HttpContext.Current.Server.ScriptTimeout = 300;

Cannot start session without errors in phpMyAdmin

Ok,

I'm using windows 7 ultimate and WAMP 2.4 server The tmp folder was missing, so I created one and this solved my problem. Check the php.ini file for the correct path: session.save_path

What is difference between cacerts and keystore?

cacerts is where Java stores public certificates of root CAs. Java uses cacerts to authenticate the servers.

Keystore is where Java stores the private keys of the clients so that it can share it to the server when the server requests client authentication.

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

Find the unique values in a column and then sort them

sort sorts inplace so returns nothing:

In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a

Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)

So you have to call print a again after the call to sort.

Eg.:

In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)

[1 2 3 6 8]

How add spaces between Slick carousel item

An improvement based on the post by Dishan TD (which removes the vertical margin as well):

  .slick-slide{
    margin-left:  15px;
    margin-right:  15px;
  }

  .slick-list {
    margin-left: -15px;
    margin-right: -15px;
    pointer-events: none;
  }

Note: the pointer-events was necessary in my case, to be able to click on the left arrow.

Bind TextBox on Enter-key press

I personally think having a Markup Extension is a cleaner approach.

public class UpdatePropertySourceWhenEnterPressedExtension : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new DelegateCommand<TextBox>(textbox => textbox.GetBindingExpression(TextBox.TextProperty).UpdateSource());
    }
}


<TextBox x:Name="TextBox"
             Text="{Binding Text}">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter"
                        Command="{markupExtensions:UpdatePropertySourceWhenEnterPressed}" 
                        CommandParameter="{Binding ElementName=TextBox}"/>
        </TextBox.InputBindings>
</TextBox>

Checking for NULL pointer in C/C++

The C Programming Language (K&R) would have you check for null == ptr to avoid an accidental assignment.

PHP - remove <img> tag from string

Try dropping the \ in front of the >.

Edit: I just tested your regex and it works fine. This is what I used:

<?
    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;
?>

The result is:

this is something with an (image)  in it.

Highlight a word with jQuery

You can use my highlight plugin jQuiteLight, that can also work with regular expressions.

To install using npm type:

npm install jquitelight --save

To install using bower type:

bower install jquitelight 

Usage:

// for strings
$(".element").mark("query here");
// for RegExp
$(".element").mark(new RegExp(/query h[a-z]+/));

More advanced usage here

Creating a list/array in excel using VBA to get a list of unique names in a column

I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes

How to auto adjust the <div> height according to content in it?

For me after trying everything the below css worked:

float: left; width: 800px;

Try in chrome by inspecting element before putting it in css file.

Error 1022 - Can't write; duplicate key in table

This can also arise in connection with a bug in certain versions of Percona Toolkit's online-schema-change tool. To mutate a large table, pt-osc first creates a duplicate table and copies all the records into it. Under some circumstances, some versions of pt-osc 2.2.x will try to give the constraints on the new table the same names as the constraints on the old table.

A fix was released in 2.3.0.

See https://bugs.launchpad.net/percona-toolkit/+bug/1498128 for more details.

Android button onClickListener

This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html

public void startActivity (Intent intent) -- Used to launch a new activity.

So suppose you have two Activity class --

  1. PresentActivity -- This is your current activity from which you want to go the second activity.

  2. NextActivity -- This is your next Activity on which you want to move.

So the Intent would be like this

Intent(PresentActivity.this, NextActivity.class)

Finally this will be the complete code

public class PresentActivity extends Activity {
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.content_layout_id);

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              // Perform action on click   
              Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);

              // currentContext.startActivity(activityChangeIntent);

              PresentActivity.this.startActivity(activityChangeIntent);
            }
          });
  }
}

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

In addition to @Connor Leech's answer.

If you want to create a new custom typography type of your own, define the following in your css file.

.text-foo {
  .text-emphasis-variant(#FFFFFF);
}

The mixin text-emphasis-variant is defined in Bootstrap's mixins.less file.

Squaring all elements in a list

array = [1,2,3,4,5]
def square(array):
    result = map(lambda x: x * x,array)
    return list(result)
print(square(array))

Regex for allowing alphanumeric,-,_ and space

Try this regex:

/^[a-z\d\-_\s]+$/i

How to change border color of textarea on :focus

There is an input:focus as there is a textarea:focus

input:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}
textarea:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}

C++ Structure Initialization

You can just initialize via a constructor:

struct address {
  address() : city("Hamilton"), prov("Ontario") {}
  int street_no;
  char *street_name;
  char *city;
  char *prov;
  char *postal_code;
};

How can I convert a zero-terminated byte array to string?

The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.

Find the location of the first zero-byte using a binary search, then slice.

You can find the zero-byte like this:

package main

import "fmt"

func FirstZero(b []byte) int {
    min, max := 0, len(b)
    for {
        if min + 1 == max { return max }
        mid := (min + max) / 2
        if b[mid] == '\000' {
            max = mid
        } else {
            min = mid
        }
    }
    return len(b)
}
func main() {
    b := []byte{1, 2, 3, 0, 0, 0}
    fmt.Println(FirstZero(b))
}

It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.

What is a 'multi-part identifier' and why can't it be bound?

Actually sometimes when you are updating one table from another table's data, I think one of the common issues that cause this error, is when you use your table abbreviations incorrectly or when they are not needed. The correct statement is below:

Update Table1
Set SomeField = t2.SomeFieldValue 
From Table1 t1 
Inner Join Table2 as t2
    On t1.ID = t2.ID

Notice that SomeField column from Table1 doesn't have the t1 qualifier as t1.SomeField but is just SomeField.

If one tries to update it by specifying t1.SomeField the statement will return the multi-part error that you have noticed.

How to call a .NET Webservice from Android using KSOAP2?

You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use   IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
    e.printStackTrace();
} //Next task is to get Response and format that response

SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");

for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
    obj3 = (SoapObject) obj2.getProperty(i);
    obj3.getProperty(0).toString(); //value of column 1
    obj3.getProperty(1).toString(); //value of column 2
    //like that you will get value from each column
}

If you have any problem regarding this you can write me..

Angular directives - when and how to use compile, controller, pre-link and post-link

Compile function

Each directive's compile function is only called once, when Angular bootstraps.

Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.

Primarily, this is done for optimisation purposes; consider the following markup:

<tr ng-repeat="raw in raws">
    <my-raw></my-raw>
</tr>

The <my-raw> directive will render a particular set of DOM markup. So we can either:

  • Allow ng-repeat to duplicate the source template (<my-raw>), and then modify the markup of each instance template (outside the compile function).
  • Modify the source template to involve the desired markup (in the compile function), and then allow ng-repeat to duplicate it.

If there are 1000 items in the raws collection, the latter option may be faster than the former one.

Do:

  • Manipulate markup so it serves as a template to instances (clones).

Do not

  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

I was getting below error when trying to create a new component under a folder.

error: More than one module matches. Use skip-import option to skip importing the component into the closest module.

I have used below command and new component got created successfully under a folder.

 ng g c folderName/my_newComponent ---module ../app

Is it possible to write to the console in colour in .NET?

Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:

public class ConsoleWriter
{
    private static object _MessageLock= new object();

    public void WriteMessage(string message)
    {
        lock (_MessageLock)
        {
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ResetColor();
        }
    }
}

How to decrease prod bundle size?

Its works 100% ng build --prod --aot --build-optimizer --vendor-chunk=true

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

AngularJS $http-post - convert binary to excel file and download

There is no way (to my knowledge) to trigger the download window in your browser from Javascript. The only way to do it is to redirect the browser to a url that streams the file to the browser.

If you can modify your REST service, you might be able to solve it by changing so the POST request doesn't respond with the binary file, but with a url to that file. That'll get you the url in Javascript instead of the binary data, and you can redirect the browser to that url, which should prompt the download without leaving the original page.

Setting focus to a textbox control

Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form

Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Me.Show()
    TextBox1.Select()
End Sub

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

Kotlin's List missing "add", "remove", Map missing "put", etc?

Apparently, the default List of Kotlin is immutable. To have a List that could change, one should use MutableList as below

class TempClass {
    var myList: MutableList<Int>? = null
    fun doSomething() {
        myList = ArrayList<Int>()
        myList!!.add(10)
        myList!!.remove(10)
    }
}

Updated Nonetheless, it is not recommended to use MutableList unless for a list that you really want to change. Refers to https://hackernoon.com/read-only-collection-in-kotlin-leads-to-better-coding-40cdfa4c6359 for how Read-only collection provides better coding.

How to Flatten a Multidimensional Array?

/**
 * For merging values of a multidimensional array into one 
 *
 * $array = [
 *     0 => [
 *         0 => 'a1',
 *         1 => 'b1',
 *         2 => 'c1',
 *         3 => 'd1'
 *     ],
 *     1 => [
 *         0 => 'a2',
 *         1 => 'b2',
 *         2 => 'c2',
 *     ]
 * ];
 *
 * becomes : 
 *
 * $array = [
 *     0 => 'a1',
 *     1 => 'b1',
 *     2 => 'c1',
 *     3 => 'd1',
 *     4 => 'a2',
 *     5 => 'b2',
 *     6 => 'c2',
 *     
 * ]
 */
array_reduce
(
    $multiArray
    , function ($lastItem, $currentItem) {
        $lastItem = $lastItem ?: array();
        return array_merge($lastItem, array_values($currentItem));
    }
);

Gist snippet

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

How to convert a column of DataTable to a List

I do just like below, after you set your column AsEnumarable you can sort, order or how you want.

 _dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();

How to copy part of an array to another array in C#?

int[] a = {1,2,3,4,5};

int [] b= new int[a.length]; //New Array and the size of a which is 4

Array.Copy(a,b,a.length);

Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.

iPad browser WIDTH & HEIGHT standard

There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.

That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.

More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.

On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.

Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.

How to run two jQuery animations simultaneously?

I believe I found the solution in the jQuery documentation:

Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it outside the queue, meaning it will automatically start without waiting for its turn.

$( "p" ).animate({
  left: "50px", opacity: 1
}, { duration: 500, queue: false }); 

simply add: queue: false.

How to calculate time elapsed in bash script?

Following on from Daniel Kamil Kozar's answer, to show hours/minutes/seconds:

echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"

So the full script would be:

date1=$(date +"%s")
date2=$(date +"%s")
DIFF=$(($date2-$date1))
echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"

Extract a substring according to a pattern

If you are using data.table then tstrsplit() is a natural choice:

tstrsplit(string, ":")[[2]]
[1] "E001" "E002" "E003"

Send request to curl with post data sourced from a file

Most of answers are perfect here, but when I landed here for my particular problem, I have to upload binary file (XLSX spread sheet) using POST method, I see one thing missing, i.e. usually its not just file you load, you may have more form data elements, like comment to file or tags to file etc as was my case. Hence, I would like to add it here as it was my use case, so that it could help others.

curl -POST -F comment=mycomment -F file_type=XLSX -F file_data=@/your/path/to/file.XLSX http://yourhost.example.com/api/example_url

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

Avoid dropdown menu close on click inside

For closing the dropdown only if a click event was triggered outside the bootstrap dropdown, this is what worked for me:

JS file:

    $('.createNewElement').on('click.bs.dropdown.data-api', '.tags-btn-group.keep-open-dropdown', function (e) {
        var target = $(e.target);
        if (target.hasClass("dropdown-menu") || target.parents(".dropdown-menu").length) {
            e.stopPropagation();
        }
    });

HTML file:

<!-- button: -->
<div class="createNewElement">
                <div class="btn-group tags-btn-group keep-open-dropdown">

                    <div class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">OPEN DROPDOWN</div>

                    <ul class="dropdown-menu">
                        WHAT EVER YOU WANT HERE...
                    </ul>

                </div>
</div>

Why doesn't Python have a sign function?

Only correct answer compliant with the Wikipedia definition

The definition on Wikipedia reads:

sign definition

Hence,

sign = lambda x: -1 if x < 0 else (1 if x > 0 else (0 if x == 0 else NaN))

Which for all intents and purposes may be simplified to:

sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)

This function definition executes fast and yields guaranteed correct results for 0, 0.0, -0.0, -4 and 5 (see comments to other incorrect answers).

Note that zero (0) is neither positive nor negative.

Check Postgres access for a user

You could query the table_privileges table in the information schema:

SELECT table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee = 'MY_USER'

How to convert a std::string to const char* or char*?

Just see this:

string str1("stackoverflow");
const char * str2 = str1.c_str();

However, note that this will return a const char *.

For a char *, use strcpy to copy it into another char array.

REST API Best practice: How to accept list of parameter values as input

I will side with nategood's answer as it is complete and it seemed to have please your needs. Though, I would like to add a comment on identifying multiple (1 or more) resource that way:

http://our.api.com/Product/101404,7267261

In doing so, you:

Complexify the clients by forcing them to interpret your response as an array, which to me is counter intuitive if I make the following request: http://our.api.com/Product/101404

Create redundant APIs with one API for getting all products and the one above for getting 1 or many. Since you shouldn't show more than 1 page of details to a user for the sake of UX, I believe having more than 1 ID would be useless and purely used for filtering the products.

It might not be that problematic, but you will either have to handle this yourself server side by returning a single entity (by verifying if your response contains one or more) or let clients manage it.

Example

I want to order a book from Amazing. I know exactly which book it is and I see it in the listing when navigating for Horror books:

  1. 10 000 amazing lines, 0 amazing test
  2. The return of the amazing monster
  3. Let's duplicate amazing code
  4. The amazing beginning of the end

After selecting the second book, I am redirected to a page detailing the book part of a list:

--------------------------------------------
Book #1
--------------------------------------------
    Title: The return of the amazing monster
    Summary:
    Pages:
    Publisher:
--------------------------------------------

Or in a page giving me the full details of that book only?

---------------------------------
The return of the amazing monster
---------------------------------
Summary:
Pages:
Publisher:
---------------------------------

My Opinion

I would suggest using the ID in the path variable when unicity is guarantied when getting this resource's details. For example, the APIs below suggest multiple ways to get the details for a specific resource (assuming a product has a unique ID and a spec for that product has a unique name and you can navigate top down):

/products/{id}
/products/{id}/specs/{name}

The moment you need more than 1 resource, I would suggest filtering from a larger collection. For the same example:

/products?ids=

Of course, this is my opinion as it is not imposed.

Why is lock(this) {...} bad?

Because if people can get at your object instance (ie: your this) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on this internally, so this may cause problems (possibly a deadlock)

In addition to this, it's also bad practice, because it's locking "too much"

For example, you might have a member variable of List<int>, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

How do I make a batch file terminate upon encountering an error?

No matter how I tried, the errorlevel always stays 0 even when msbuild failed. So I built my workaround:

Build Project and save log to Build.log

SET Build_Opt=/flp:summary;logfile=Build.log;append=true

msbuild "myproj.csproj" /t:rebuild /p:Configuration=release /fl %Build_Opt%

search for "0 Error" string in build log, set the result to var

FOR /F "tokens=* USEBACKQ" %%F IN (`find /c /i "0 Error" Build.log`) DO (
    SET var=%%F
)
echo %var%

get the last character, which indicates how many lines contains the search string

set result=%var:~-1%

echo "%result%"

if string not found, then error > 0, build failed

if "%result%"=="0" ( echo "build failed" )

That solution was inspired by Mechaflash's post at How to set commands output as a variable in a batch file

and https://ss64.com/nt/syntax-substring.html

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

How do I remove a key from a JavaScript object?

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));

How to use OpenCV SimpleBlobDetector

You may store the parameters for the blob detector in a file, but this is not necessary. Example:

// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value

// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)

// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);

// extract the x y coordinates of the keypoints: 

for (int i=0; i<keypoints.size(); i++){
    float X = keypoints[i].pt.x; 
    float Y = keypoints[i].pt.y;
}

String comparison technique used by Python

Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).

To reply to the comment

What? How else can ordering be defined other than left-to-right?

by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.

And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.

Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!

Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).

What USB driver should we use for the Nexus 5?

There are multiple hardware revisions of Nexus 5. So, the accepted answer doesn't work for all devices (it didn't work for me).

  1. Open Device Manager, right click and Properties. Now go to the "Details" tab And now select the property "Hardware Ids". Note down the PID and VID.

  2. Download the Google driver

  3. Update the android_winusb.inf with above VID and PID

    %CompositeAdbInterface% = USB_Install, USB\VID_18D1&**PID_4EE1**
    
  4. Now in Device Manager, find Nexus 5, and update the driver software, and browse to the location where you downloaded.

  5. The driver should be installed, and you should be see the device in ADB.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Oracle's error message should be somewhat longer. It usually looks like this:

ORA-00001: unique constraint (TABLE_UK1) violated

The name in parentheses is the constrait name. It tells you which constraint was violated.

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

How many times a substring occurs

Risking a downvote because 2+ others have already provided this solution. I even upvoted one of them. But mine is probably the easiest for newbies to understand.

def count_substring(string, sub_string):
    slen  = len(string)
    sslen = len(sub_string)
    range_s = slen - sslen + 1
    count = 0
    for i in range(range_s):
        if (string[i:i+sslen] == sub_string):
            count += 1
    return count

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.

The HttpClient is an interface for this class and other classes.

You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient.

This answer was given in the context of httpclient-4.3.

How to change language of app when user selects language?

Udhay's sample code works well. Except the question of Sofiane Hassaini and Chirag SolankI, for the re-entrance, it doesn't work. I try to call Udhay's code without restart the activity in onCreate() , before super.onCreate(savedInstanceState);. Then it is OK! Only a little problem, the menu strings still not changed to the set Locale.

    public void setLocale(String lang) { //call this in onCreate()
      Locale myLocale = new Locale(lang); 
      Resources res = getResources(); 
      DisplayMetrics dm = res.getDisplayMetrics(); 
      Configuration conf = res.getConfiguration(); 
      conf.locale = myLocale; 
      res.updateConfiguration(conf, dm); 
      //Intent refresh = new Intent(this, AndroidLocalize.class); 
      //startActivity(refresh); 
      //finish();
    } 

phpmyadmin "Not Found" after install on Apache, Ubuntu

Finally I got the solution

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin
sudo service apache2 reload

More about https://askubuntu.com/questions/55280/phpmyadmin-is-not-working-after-i-installed-it

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

How to create a DateTime equal to 15 minutes ago?

only the below code in Python 3.7 worked for me

from datetime import datetime,timedelta    
print(datetime.now()-timedelta(seconds=900))

TortoiseGit save user authentication / credentials

If you're going to downvote this answer

I wrote this a few months prior to the inclusion of git-credential in TortoiseGit. Given the number of large security holes found in the last few years and how much I've learned about network security, I would HIGHLY recommend you use a unique (minimum 2048-bit RSA) SSH key for every server you connect to.

The below syntax is still available, though there are far better tools available today like git-credential that the accepted answer tells you how to use. Do that instead.


Try changing the remote URL to https://[email protected]/username/repo.git where username is your github username and repo is the name of your repository.

If you also want to store your password (not recommended), the URL would look like this: https://username:[email protected]/username/repo.git.

There's also another way to store the password from this github help article: https://help.github.com/articles/set-up-git#password-caching

HTTP GET Request in Node.js Express

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

JavaScript property access: dot notation vs. brackets?

You need to use brackets if the property names has special characters:

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;

Other than that, I suppose it's just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it's a property rather than an array element (although of course JavaScript does not have associative arrays anyway).

concat scope variables into string in angular directive expression

It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.

In general, I suggest calling a function on ng-click like so:

<a ng-click="navigateToPath()">click me</a>

obj.val1 & obj.val2 should be available on your controller's $scope, you dont need to pass those into a function from the markup.

then, in your controller:

$scope.navigateToPath = function(){
   var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
   $location.path(path)       
}

Sending HTML email using Python

You might try using my mailer module.

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)

Can't find out where does a node.js app running and can't kill it

List node process:

$ ps -e|grep node

Kill the process using

$kill -9 XXXX

Here XXXX is the process number

Finding the 'type' of an input element

Check the type property. Would that suffice?

How do I print the content of a .txt file in Python?

with open("filename.txt", "w+") as file:
  for line in file:
    print line

This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop

Android dependency has different version for the compile and runtime

Use this code in your buildscript (build.gradle root):

subprojects {
  project.configurations.all {
     resolutionStrategy.eachDependency { details ->
        if (details.requested.group == 'com.android.support'
              && !details.requested.name.contains('multidex') ) {
           details.useVersion "version which should be used - in your case 26.0.0-beta2"
        }
     }
  }
}

Error 1046 No database Selected, how to resolve?

jst create a new DB in mysql.Select that new DB.(if you r using mysql phpmyadmin now on the top it'l be like 'Server:...* >> Database ).Now go to import tab select file.Import!

Difference Between Schema / Database in MySQL

As defined in the MySQL Glossary:

In MySQL, physically, a schema is synonymous with a database. You can substitute the keyword SCHEMA instead of DATABASE in MySQL SQL syntax, for example using CREATE SCHEMA instead of CREATE DATABASE.

Some other database products draw a distinction. For example, in the Oracle Database product, a schema represents only a part of a database: the tables and other objects owned by a single user.

Get Path from another app (WhatsApp)

protected void onCreate(Bundle savedInstanceState) { /* * Your OnCreate */ Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType();

//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {viewhekper(intent);//Handle text being sent}

How can I determine the current CPU utilization from the shell?

Try this command:

cat /proc/stat

This will be something like this:

cpu  55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0

More details:

http://www.mail-archive.com/[email protected]/msg01690.html http://www.linuxhowtos.org/System/procstat.htm

How do I disable the resizable property of a textarea?

CSS 3 has a new property for UI elements that will allow you to do this. The property is the resize property. So you would add the following to your stylesheet to disable resizing of all textarea elements:

textarea { resize: none; }

This is a CSS 3 property; use a compatibility chart to see browser compatibility.

Personally, I would find it very annoying to have resizing disabled on textarea elements. This is one of those situations where the designer is trying to "break" the user's client. If your design can't accommodate a larger textarea, you might want to reconsider how your design works. Any user can add textarea { resize: both !important; } to their user stylesheet to override your preference.

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

Assignment makes pointer from integer without cast

C strings are not anything like Java strings. They're essentially arrays of characters.

You are getting the error because strToLower returns a char. A char is a form of integer in C. You are assigning it into a char[] which is a pointer. Hence "converting integer to pointer".

Your strToLower makes all its changes in place, there is no reason for it to return anything, especially not a char. You should "return" void, or a char*.

On the call to strToLower, there is also no need for assignment, you are essentially just passing the memory address for cString1.

In my experience, Strings in C are the hardest part to learn for anyone coming from Java/C# background back to C. People can get along with memory allocation (since even in Java you often allocate arrays). If your eventual goal is C++ and not C, you may prefer to focus less on C strings, make sure you understand the basics, and just use the C++ string from STL.

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

How to catch curl errors in PHP

you can generate curl error after its execution

$url = 'http://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

and here are curl error code

if someone need more information about curl errors

<?php

    $error_codes=array(
    [1] => 'CURLE_UNSUPPORTED_PROTOCOL',
    [2] => 'CURLE_FAILED_INIT',
    [3] => 'CURLE_URL_MALFORMAT',
    [4] => 'CURLE_URL_MALFORMAT_USER',
    [5] => 'CURLE_COULDNT_RESOLVE_PROXY',
    [6] => 'CURLE_COULDNT_RESOLVE_HOST',
    [7] => 'CURLE_COULDNT_CONNECT',
    [8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
    [9] => 'CURLE_REMOTE_ACCESS_DENIED',
    [11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
    [13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
    [14]=>'CURLE_FTP_WEIRD_227_FORMAT',
    [15] => 'CURLE_FTP_CANT_GET_HOST',
    [17] => 'CURLE_FTP_COULDNT_SET_TYPE',
    [18] => 'CURLE_PARTIAL_FILE',
    [19] => 'CURLE_FTP_COULDNT_RETR_FILE',
    [21] => 'CURLE_QUOTE_ERROR',
    [22] => 'CURLE_HTTP_RETURNED_ERROR',
    [23] => 'CURLE_WRITE_ERROR',
    [25] => 'CURLE_UPLOAD_FAILED',
    [26] => 'CURLE_READ_ERROR',
    [27] => 'CURLE_OUT_OF_MEMORY',
    [28] => 'CURLE_OPERATION_TIMEDOUT',
    [30] => 'CURLE_FTP_PORT_FAILED',
    [31] => 'CURLE_FTP_COULDNT_USE_REST',
    [33] => 'CURLE_RANGE_ERROR',
    [34] => 'CURLE_HTTP_POST_ERROR',
    [35] => 'CURLE_SSL_CONNECT_ERROR',
    [36] => 'CURLE_BAD_DOWNLOAD_RESUME',
    [37] => 'CURLE_FILE_COULDNT_READ_FILE',
    [38] => 'CURLE_LDAP_CANNOT_BIND',
    [39] => 'CURLE_LDAP_SEARCH_FAILED',
    [41] => 'CURLE_FUNCTION_NOT_FOUND',
    [42] => 'CURLE_ABORTED_BY_CALLBACK',
    [43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
    [45] => 'CURLE_INTERFACE_FAILED',
    [47] => 'CURLE_TOO_MANY_REDIRECTS',
    [48] => 'CURLE_UNKNOWN_TELNET_OPTION',
    [49] => 'CURLE_TELNET_OPTION_SYNTAX',
    [51] => 'CURLE_PEER_FAILED_VERIFICATION',
    [52] => 'CURLE_GOT_NOTHING',
    [53] => 'CURLE_SSL_ENGINE_NOTFOUND',
    [54] => 'CURLE_SSL_ENGINE_SETFAILED',
    [55] => 'CURLE_SEND_ERROR',
    [56] => 'CURLE_RECV_ERROR',
    [58] => 'CURLE_SSL_CERTPROBLEM',
    [59] => 'CURLE_SSL_CIPHER',
    [60] => 'CURLE_SSL_CACERT',
    [61] => 'CURLE_BAD_CONTENT_ENCODING',
    [62] => 'CURLE_LDAP_INVALID_URL',
    [63] => 'CURLE_FILESIZE_EXCEEDED',
    [64] => 'CURLE_USE_SSL_FAILED',
    [65] => 'CURLE_SEND_FAIL_REWIND',
    [66] => 'CURLE_SSL_ENGINE_INITFAILED',
    [67] => 'CURLE_LOGIN_DENIED',
    [68] => 'CURLE_TFTP_NOTFOUND',
    [69] => 'CURLE_TFTP_PERM',
    [70] => 'CURLE_REMOTE_DISK_FULL',
    [71] => 'CURLE_TFTP_ILLEGAL',
    [72] => 'CURLE_TFTP_UNKNOWNID',
    [73] => 'CURLE_REMOTE_FILE_EXISTS',
    [74] => 'CURLE_TFTP_NOSUCHUSER',
    [75] => 'CURLE_CONV_FAILED',
    [76] => 'CURLE_CONV_REQD',
    [77] => 'CURLE_SSL_CACERT_BADFILE',
    [78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
    [79] => 'CURLE_SSH',
    [80] => 'CURLE_SSL_SHUTDOWN_FAILED',
    [81] => 'CURLE_AGAIN',
    [82] => 'CURLE_SSL_CRL_BADFILE',
    [83] => 'CURLE_SSL_ISSUER_ERROR',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [85] => 'CURLE_RTSP_CSEQ_ERROR',
    [86] => 'CURLE_RTSP_SESSION_ERROR',
    [87] => 'CURLE_FTP_BAD_FILE_LIST',
    [88] => 'CURLE_CHUNK_FAILED');

    ?>

How to remove decimal part from a number in C#

here is a trick

a =  double.Parse(a.ToString().Split(',')[0])

Count the number occurrences of a character in a string

"Without using count to find you want character in string" method.

import re

def count(s, ch):

   pass

def main():

   s = raw_input ("Enter strings what you like, for example, 'welcome': ")  

   ch = raw_input ("Enter you want count characters, but best result to find one character: " )

   print ( len (re.findall ( ch, s ) ) )

main()

Python Inverse of a Matrix

If you hate numpy, get out RPy and your local copy of R, and use it instead.

(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)

Making a triangle shape using xml definitions?

May I help you without using XML ?


Simply,

Custom Layout ( Slice ) :

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;

public class Slice extends View {

    Paint mPaint;

    Path mPath;

    public enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    public Slice(Context context) {
        super(context);
        create();
    }

    public Slice(Context context, AttributeSet attrs) {
        super(context, attrs);
        create();
    }

    public void setColor(int color) {
        mPaint.setColor(color);
        invalidate();
    }

    private void create() {
        mPaint = new Paint();
        mPaint.setStyle(Style.FILL);
        mPaint.setColor(Color.RED);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPath = calculate(Direction.SOUTH);
        canvas.drawPath(mPath, mPaint);
    }

    private Path calculate(Direction direction) {
        Point p1 = new Point();
        p1.x = 0;
        p1.y = 0;

        Point p2 = null, p3 = null;

        int width = getWidth();

        if (direction == Direction.NORTH) {
            p2 = new Point(p1.x + width, p1.y);
            p3 = new Point(p1.x + (width / 2), p1.y - width);
        } else if (direction == Direction.SOUTH) {
            p2 = new Point(p1.x + width, p1.y);
            p3 = new Point(p1.x + (width / 2), p1.y + width);
        } else if (direction == Direction.EAST) {
            p2 = new Point(p1.x, p1.y + width);
            p3 = new Point(p1.x - width, p1.y + (width / 2));
        } else if (direction == Direction.WEST) {
            p2 = new Point(p1.x, p1.y + width);
            p3 = new Point(p1.x + width, p1.y + (width / 2));
        }

        Path path = new Path();
        path.moveTo(p1.x, p1.y);
        path.lineTo(p2.x, p2.y);
        path.lineTo(p3.x, p3.y);

        return path;
    }
}

Your Activity ( Example ) :

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

public class Layout extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Slice mySlice = new Slice(getApplicationContext());
        mySlice.setBackgroundColor(Color.WHITE);
        setContentView(mySlice, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    }
}

Working Example :

enter image description here


Another absolutely simple Calculate function you may interested in ..

private Path Calculate(Point A, Point B, Point C) {
    Path Pencil = new Path();
    Pencil.moveTo(A.x, A.y);
    Pencil.lineTo(B.x, B.y);
    Pencil.lineTo(C.x, C.y);
    return Pencil;
}

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

Find an element in a list of tuples

If you just want the first number to match you can do it like this:

[item for item in a if item[0] == 1]

If you are just searching for tuples with 1 in them:

[item for item in a if 1 in item]

Javascript - Get Image height

Well...there are several ways to interpret this question.

The first way and the way I think you mean is to simply alter the display size so all images display the same size. For this, I would actually use CSS and not JavaScript. Simply create a class that has the appropriate width and height values set, and make all <img> tags use this class.

A second way is that you want to preserve the aspect ration of all the images, but scale the display size to a sane value. There is a way to access this in JavaScript, but I'll need a bit to write up a quick code sample.

The third way, and I hope you don't mean this way, is to alter the actual size of the image. This is something you'd have to do on the server side, as not only is JavaScript unable to create images, but it wouldn't make any sense, as the full sized image has already been sent.

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

In Linux Kernel, present pages are physical pages of RAM which kernel can see. Literally, present pages is total size of RAM in 4KB unit.

grep present /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

The 'MemTotal' form /proc/meminfo is the total size of memory managed by buddy system.And we can also compute it like this:

grep managed /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

SVN Repository Search

I do like TRAC - this plugin might be helpful for your task: http://trac-hacks.org/wiki/RepoSearchPlugin

Sorting int array in descending order

If it's not a big/long array just mirror it:

for( int i = 0; i < arr.length/2; ++i ) 
{ 
  temp = arr[i]; 
  arr[i] = arr[arr.length - i - 1]; 
  arr[arr.length - i - 1] = temp; 
}

How do I check if an object has a specific property in JavaScript?

OK, it looks like I had the right answer unless if you don't want inherited properties:

if (x.hasOwnProperty('key'))

Here are some other options to include inherited properties:

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)

How to redirect both stdout and stderr to a file

The simplest syntax to redirect both is:

command &> logfile

If you want to append to the file instead of overwrite:

command &>> logfile

converting Java bitmap to byte array

In order to avoid OutOfMemory error for bigger files, I would solve the task by splitting a bitmap into several parts and merging their parts' bytes.

private byte[] getBitmapBytes(Bitmap bitmap)
{
    int chunkNumbers = 10;
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    byte[] imageBytes = new byte[bitmapSize];
    int rows, cols;
    int chunkHeight, chunkWidth;
    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight() / rows;
    chunkWidth = bitmap.getWidth() / cols;

    int yCoord = 0;
    int bitmapsSizes = 0;

    for (int x = 0; x < rows; x++)
    {
        int xCoord = 0;
        for (int y = 0; y < cols; y++)
        {
            Bitmap bitmapChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight);
            byte[] bitmapArray = getBytesFromBitmapChunk(bitmapChunk);
            System.arraycopy(bitmapArray, 0, imageBytes, bitmapsSizes, bitmapArray.length);
            bitmapsSizes = bitmapsSizes + bitmapArray.length;
            xCoord += chunkWidth;

            bitmapChunk.recycle();
            bitmapChunk = null;
        }
        yCoord += chunkHeight;
    }

    return imageBytes;
}


private byte[] getBytesFromBitmapChunk(Bitmap bitmap)
{
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapSize);
    bitmap.copyPixelsToBuffer(byteBuffer);
    byteBuffer.rewind();
    return byteBuffer.array();
}

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Redirect after Login on WordPress

I was searching "How to Fix WordPress Login Page Refreshing and Redirecting Issue?" and did not find any good fix. From this Stackoverflow question, I have got my help. I would like to share it with others so that in case they need it, they get the help.

On my website, when I was entering email and password, I was redirecting again and again to wp-admin and asked for passwords. This code helped me to fix the issue:

function admin_default_page() {
  return '/';
}

add_filter('login_redirect', 'admin_default_page');

casting Object array to Integer array error

Or do the following:

...

  Integer[] integerArray = new Integer[integerList.size()];
  integerList.toArray(integerArray);

  return integerArray;

}

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

DateDiff to output hours and minutes

If you want 08:30 ( HH:MM) format then try this,

SELECT EmplID
    , EmplName
    , InTime
    , [TimeOut]
    , [DateVisited]
    ,  RIGHT('0' + CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60),2) + ':' +
      RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
      as TotalHours from times Order By EmplID, DateVisited

Postgres user does not exist?

OS X tends to prefix the system account names with "_"; you don't say what version of OS X you're using, but at least in 10.8 and 10.9 the _postgres user exists in a default install. Note that you won't be able to su to this account (except as root), since it doesn't have a password. sudo -u _postgres, on the other hand, should work fine.

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

Adding 30 minutes to time formatted as H:i in PHP

I usually take a slightly different track to achieve this:

$startTime = date("H:i",time() - 1800);
$endTime = date("H:i",time() + 1800);

Where 1800 seconds = 30 minutes.

Chrome: Uncaught SyntaxError: Unexpected end of input

The issue for me was that I was doing $.ajax with dataType: "json" for a POST request that was returning an HTTP 201 (created) and no request body. The fix was to simply remove that key/value.

Text not wrapping inside a div element

I found this helped where my words were breaking part way through the word in a WooThemes Testimonial plugin.

.testimonials-text {
    white-space: normal;
}

play with it here http://nortronics.com.au/recomendations/

<blockquote class="testimonials-text" itemprop="reviewBody">

<a href="http://www.jacobs.com/" class="avatar-link">

<img width="100" height="100" src="http://nortronics.com.au/wp-content/uploads/2015/11/SKM-100x100.jpg" class="avatar wp-post-image" alt="SKM Sinclair Knight Merz">

</a>
<p>Tim continues to provide high-level technical applications advice and support for a very challenging IP video application. He has shown he will go the extra mile to ensure all avenues are explored to identify an innovative and practical solution.<br>Tim manages to do this with a very helpful and professional attitude which is much appreciated.
</p>
</blockquote>

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

complex if statement in python

This should do it:

elif var == 80 or var == 443 or 1024 <= var <= 65535:

Run cURL commands from Windows console

Install git command line from here. When you install git in windows you will automatically get curl with it. You can check the installed version of curl using curl --version like this.

enter image description here

This is a sample curl request which sends a string in a JSON object and get it encoded.

curl https://api.base62.io/encode \ --request POST \ --header "Content-Type: application/json" \ --data '{ "data": "Hello world!" }'

enter image description here

Do I need to compile the header files in a C program?

I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have

typedef enum{
    a,
    b,
    c
}test_t

and in test.c we have

void foo()
{
    test_t test;
    ...
}

during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.

How to find the socket buffer size of linux

Whilst, as has been pointed out, it is possible to see the current default socket buffer sizes in /proc, it is also possible to check them using sysctl (Note: Whilst the name includes ipv4 these sizes also apply to ipv6 sockets - the ipv6 tcp_v6_init_sock() code just calls the ipv4 tcp_init_sock() function):

 sysctl net.ipv4.tcp_rmem
 sysctl net.ipv4.tcp_wmem

However, the default socket buffers are just set when the sock is initialised but the kernel then dynamically sizes them (unless set using setsockopt() with SO_SNDBUF). The actual size of the buffers for currently open sockets may be inspected using the ss command (part of the iproute package), which can also provide a bunch more info on sockets like congestion control parameter etc. E.g. To list the currently open TCP (t option) sockets and associated memory (m) information:

ss -tm

Here's some example output:

State       Recv-Q Send-Q        Local Address:Port        Peer Address:Port
ESTAB       0      0             192.168.56.102:ssh        192.168.56.1:56328
skmem:(r0,rb369280,t0,tb87040,f0,w0,o0,bl0,d0)

Here's a brief explanation of skmem (socket memory) - for more info you'll need to look at the kernel sources (e.g. sock.h):

r:sk_rmem_alloc
rb:sk_rcvbuf          # current receive buffer size
t:sk_wmem_alloc
tb:sk_sndbuf          # current transmit buffer size
f:sk_forward_alloc
w:sk_wmem_queued      # persistent transmit queue size
o:sk_omem_alloc
bl:sk_backlog
d:sk_drops

Can Selenium WebDriver open browser windows silently in the background?

For running without any browser, you can run it in headless mode.

I show you one example in Python that is working for me right now

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome

Is jQuery $.browser Deprecated?

"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."

From http://api.jquery.com/jQuery.browser/

Can a shell script set environment variables of the calling shell?

I created a solution using pipes, eval and signal.

parent() {
    if [ -z "$G_EVAL_FD" ]; then
            die 1 "Rode primeiro parent_setup no processo pai"
    fi
    if [ $(ppid) = "$$" ]; then
            "$@"
    else
            kill -SIGUSR1 $$
            echo "$@">&$G_EVAL_FD
    fi
}
parent_setup() {
    G_EVAL_FD=99
    tempfile=$(mktemp -u)
    mkfifo "$tempfile"
    eval "exec $G_EVAL_FD<>'$tempfile'"
    rm -f "$tempfile"
    trap "read CMD <&$G_EVAL_FD; eval \"\$CMD\"" USR1
}
parent_setup #on parent shell context
( A=1 ); echo $A # prints nothing
( parent A=1 ); echo $A # prints 1

It might work with any command.

Html5 Full screen video

You can use html5 video player which has full screen playback option. This is a very good html5 player to have a look.
http://sublimevideo.net/

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

You may get day, month and year and may concatenate them or may use MM-dd-yyyy format as given below.

Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);



Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1   = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1  = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);



LocalDateTime ldt1 = LocalDateTime.now();  
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy3 = ldt1.format(format1);  
System.out.println("Formatted Date 3: " + mmddyyyy3);  



LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);



LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy5 = ldt3.format(format2);   
System.out.println("Formatted Date 5: " + mmddyyyy5); 



Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3  = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);



Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4  = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);



Date date4 = new Date();
int day5   = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5  = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);



Date date5 = new Date();
int day6   = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6  = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);`enter code here`
System.out.println("Formatted Date 9: " + mmddyyyy9);

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

How do I wrap text in a span?

You should use white-space with display table

Example:
    legend {
        display:table; /* Enable line-wrapping in IE8+ */
        white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
    }

Drawing circles with System.Drawing

You should use DrawEllipse:

//
// Summary:
//     Draws an ellipse defined by a bounding rectangle specified by coordinates
//     for the upper-left corner of the rectangle, a height, and a width.
//
// Parameters:
//   pen:
//     System.Drawing.Pen that determines the color, width,
//      and style of the ellipse.
//
//   x:
//     The x-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   y:
//     The y-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   width:
//     Width of the bounding rectangle that defines the ellipse.
//
//   height:
//     Height of the bounding rectangle that defines the ellipse.
//
// Exceptions:
//   System.ArgumentNullException:
//     pen is null.
public void DrawEllipse(Pen pen, int x, int y, int width, int height);

Multiline for WPF TextBox

The only property corresponding in WPF to the

Winforms property: TextBox.Multiline = true

is the WPF property: TextBox.AcceptsReturn = true.

<TextBox AcceptsReturn="True" ...... />

All other settings, such as VerticalAlignement, WordWrap etc., only control how the TextBox interacts in the UI but do not affect the Multiline behaviour.

FIX CSS <!--[if lt IE 8]> in IE

Also, the comment tag

<comment></comment> 

is only supported in IE 8 and below, so if that's exactly what you're trying to target, you could wrap them in comment tag. They're the same as

<!--[if lte IE 8]><![endif]-->

In which lte means "less than or equal to".

See: Conditional Comments.

How to play videos in android from assets folder or raw folder?

It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)

here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working

Why use 'virtual' for class properties in Entity Framework model definitions?

It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.

Edit to clarify "create a proxy around": By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".

The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.

If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.

Edit to describe why properties would be marked as virtual

Properties such as:

 public ICollection<RSVP> RSVPs { get; set; }

Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.

//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
    return _RSVPs;
}

public void set_RSVPs(RSVP value)
{
    _RSVPs = value;
}

private RSVP _RSVPs;

That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get and set functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:

 public virtual ICollection<RSVP> RSVPs;

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

For .NET 2.0 you could implement a class which inherits from Dictionary and implements ICloneable.

public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable
{
    public IDictionary<TKey, TValue> Clone()
    {
        CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();

        foreach (KeyValuePair<TKey, TValue> pair in this)
        {
            clone.Add(pair.Key, (TValue)pair.Value.Clone());
        }

        return clone;
    }
}

You can then clone the dictionary simply by calling the Clone method. Of course this implementation requires that the value type of the dictionary implements ICloneable, but otherwise a generic implementation isn't practical at all.

Exploitable PHP functions

This is not an answer per se, but here's something interesting:

$y = str_replace('z', 'e', 'zxzc');
$y("malicious code");

In the same spirit, call_user_func_array() can be used to execute obfuscated functions.

How can I format a list to print each element on a separate line in python?

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)
10
12
14

Python - Join with newline

When you print it with this print 'I\nwould\nexpect\nmultiple\nlines' you would get:

I
would
expect
multiple
lines

The \n is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.

How to subtract days from a plain Date?

A few of the existing solutions were close, but not quite exactly what I wanted. This function works with both positive or negative values and handles boundary cases.

function addDays(date, days) {
    return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate() + days,
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    );
}

How do I get the project basepath in CodeIgniter

Following are the build-in constants you can use as per your requirements for getting the paths in Codeigniter:

EXT: The PHP file extension

FCPATH: Path to the front controller (this file) (root of CI)

SELF: The name of THIS file (index.php)

BASEPATH: Path to the system folder

APPPATH: The path to the “application” folder

Thanks.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

None of these worked for me.

My class libraries were definitely all referencing both System.Core and Microsoft.CSharp. Web Application was 4.0 and couldn't upgrade to 4.5 due to support issues.

I was encountering the error compiling a razor template using the Razor Engine, and only encountering it intermittently, like after web application has been restarted.

The solution that worked for me was manually loading the assembly then reattempting the same operation...

        bool retry = true;
        while (retry)
        {
            try
            {
                string textTemplate = File.ReadAllText(templatePath);
                Razor.CompileWithAnonymous(textTemplate, templateFileName);
                retry = false;
            }
            catch (TemplateCompilationException ex)
            {
                LogTemplateException(templatePath, ex);
                retry = false;

                if (ex.Errors.Any(e  => e.ErrorNumber == "CS1969"))
                {
                    try
                    {
                        _logger.InfoFormat("Attempting to manually load the Microsoft.CSharp.RuntimeBinder.Binder");
                        Assembly csharp = Assembly.Load("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        Type type = csharp.GetType("Microsoft.CSharp.RuntimeBinder.Binder");
                        retry = true;
                    }
                    catch(Exception exLoad)
                    {
                        _logger.Error("Failed to manually load runtime binder", exLoad);
                    }
                }

                if (!retry)
                    throw;
            }
        }

Hopefully this might help someone else out there.

jQuery: If this HREF contains

Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

How to remove the first character of string in PHP?

Exec time for the 3 answers :

Remove the first letter by replacing the case

$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by ?, but ok for echo

Exec time for 1.000.000 tests : 0.39602184295654 sec


Remove the first letter with substr()

$str = "hello";
$str = substr($str, 1);

Exec time for 1.000.000 tests : 5.153294801712 sec


Remove the first letter with ltrim()

$str = "hello";
$str= ltrim ($str,'h');

Exec time for 1.000.000 tests : 5.2393000125885 sec


Remove the first letter with preg_replace()

$str = "hello";
$str = preg_replace('/^./', '', $str);

Exec time for 1.000.000 tests : 6.8543920516968 sec

SQL GROUP BY CASE statement with aggregate function

My guess is that you don't really want to GROUP BY some_product.

The answer to: "Is there a way to GROUP BY a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY a column alias.

The SELECT clause, where column aliases are assigned, is not processed until after the GROUP BY clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.

Inline view:

select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
   from ...
   group by col1, col2 ... ) T
group by some_product ...

CTE:

with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
   from ...
   group by col1, col2 ... )
select ...
from T
group by some_product ... 

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

DataColumn Name from DataRow (not DataTable)

You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:

static class Extensions
{
    public static string GetColumn(this DataRow Row, int Ordinal)
    {
        return Row.Table.Columns[Ordinal].ColumnName;
    }
}

Then call it using:

string MyColumnName = MyRow.GetColumn(5);

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I saw it's solved, but I still want to share a solution which worked for me.

.env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]

MySQL admin:

 SELECT user, host FROM mysql.user

Thank you, spencer7593

Console:

php artisan cache:clear
php artisan config:cache

Now it works for me.

Laracasts answers

How to discard all changes made to a branch?

Note: You CANNOT UNDO this.

Try git checkout -f this will discard any local changes which are not committed in ALL branches and master.

Composer install error - requires ext_curl when it's actually enabled

I ran into the same issue trying to install Dropbox SDK.

CURL was indeed enabled on my system but this meant by the php.ini in the wamp\bin\apache folder.

I simply had to manually edit the php.ini situated in wamp\bin\php, uncomment the extension=php_curl.dll line, restart Wamp and it worked perfectly.

Why there are those 2 php.ini and only one is used is still a mystery for me...

Hope it's helpul to someone!

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

I had to close and re-open my windows console (or open a new console), and then open the SDK manager (ran android), after which a bunch of updates and installs had to complete.

Programmatically find the number of cores on a machine

you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

How do I disable orientation change on Android?

You need to modify AndroidManifest.xml as Intrications (previously Ashton) mentioned and make sure the activity handles the onConfigurationChanged event as you want it handled. This is how it should look:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Spring Boot Configure and Use Two DataSources

My requirement was slightly different but used two data sources.

I have used two data sources for same JPA entities from same package. One for executing DDL at the server startup to create/update tables and another one is for DML at runtime.

The DDL connection should be closed after DDL statements are executed, to prevent further usage of super user previlleges anywhere in the code.

Properties

spring.datasource.url=jdbc:postgresql://Host:port
ddl.user=ddluser
ddl.password=ddlpassword
dml.user=dmluser
dml.password=dmlpassword
spring.datasource.driver-class-name=org.postgresql.Driver

Data source config classes

//1st Config class for DDL Data source

  public class DatabaseDDLConfig {
        @Bean
        public LocalContainerEntityManagerFactoryBean ddlEntityManagerFactoryBean() {
            LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
            PersistenceProvider persistenceProvider = new 
            org.hibernate.jpa.HibernatePersistenceProvider();
            entityManagerFactoryBean.setDataSource(ddlDataSource());
            entityManagerFactoryBean.setPackagesToScan(new String[] { 
            "com.test.two.data.sources"});
            HibernateJpaVendorAdapter vendorAdapter = new 
            HibernateJpaVendorAdapter();
            entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
            HashMap<String, Object> properties = new HashMap<>();
            properties.put("hibernate.dialect", 
            "org.hibernate.dialect.PostgreSQLDialect");
            properties.put("hibernate.physical_naming_strategy", 
            "org.springframework.boot.orm.jpa.hibernate.
            SpringPhysicalNamingStrategy");
            properties.put("hibernate.implicit_naming_strategy", 
            "org.springframework.boot.orm.jpa.hibernate.
            SpringImplicitNamingStrategy");
            properties.put("hibernate.hbm2ddl.auto", "update");
            entityManagerFactoryBean.setJpaPropertyMap(properties);
            entityManagerFactoryBean.setPersistenceUnitName("ddl.config");
            entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
            return entityManagerFactoryBean;
        }


    @Bean
    public DataSource ddlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("ddl.user");
        dataSource.setPassword(env.getProperty("ddl.password"));
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager ddlTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(ddlEntityManagerFactoryBean().getObject());
        return transactionManager;
    }
}

//2nd Config class for DML Data source

public class DatabaseDMLConfig {

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean dmlEntityManagerFactoryBean() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        PersistenceProvider persistenceProvider = new org.hibernate.jpa.HibernatePersistenceProvider();
        entityManagerFactoryBean.setDataSource(dmlDataSource());
        entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.two.data.sources" });
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        entityManagerFactoryBean.setJpaProperties(defineJpaProperties());
        entityManagerFactoryBean.setPersistenceUnitName("dml.config");
        entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
        return entityManagerFactoryBean;
    }

    @Bean
    @Primary
    public DataSource dmlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(envt.getProperty("spring.datasource.url"));
        dataSource.setUsername("dml.user");
        dataSource.setPassword("dml.password");
        return dataSource;
    }

    @Bean
    @Primary
    public PlatformTransactionManager dmlTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(dmlEntityManagerFactoryBean().getObject());
        return transactionManager;
    }


  }

//Usage of DDL data sources in code.

public class DDLServiceAtStartup {

//Import persistence unit ddl.config for ddl purpose.

@PersistenceUnit(unitName = "ddl.config")
private EntityManagerFactory entityManagerFactory;

public void executeDDLQueries() throws ContentServiceSystemError {
    try {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.createNativeQuery("query to create/update table").executeUpdate();
        entityManager.flush();
        entityManager.getTransaction().commit();
        entityManager.close();

        //Close the ddl data source to avoid from further use in code.
        entityManagerFactory.close();
    } catch(Exception ex) {}
}

//Usage of DML data source in code.

public class DDLServiceAtStartup {
  @PersistenceUnit(unitName = "dml.config")
  private EntityManagerFactory entityManagerFactory;

  public void createRecord(User user) {
     userDao.save(user);
  }
}

Where can I find the error logs of nginx, using FastCGI and Django?

Errors are stored in the nginx log file. You can specify it in the root of the nginx configuration file:

error_log  /var/log/nginx/nginx_error.log  warn;

On Mac OS X with Homebrew, the log file was found by default at the following location:

/usr/local/var/log/nginx

How to get the Touch position in android?

@Override
public boolean onTouchEvent(MotionEvent event)
{
    int x = (int)event.getX();
    int y = (int)event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }

    return false;
}

The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.

How do I update Node.js?

The easy way to update node and npm :

npm install -g npm@latest

download the latest version of node js and update /install

How to enable external request in IIS Express?

There are three changes you might need to make.

  1. Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file. Typically:
    • VS 2015: $(solutionDir)\.vs\config\applicationhost.config
    • < VS 2015: %userprofile%\My Documents\IISExpress\config\applicationhost.config

Find your site's binding element, and add

    <binding protocol="http" bindingInformation="*:8080:*" />
  1. Setup the bit of Windows called 'http.sys'. As an administrator, run the command:
    netsh http add urlacl url=http://*:8080/ user=everyone

Where everyone is a windows group. Use double quotes for groups with spaces like "Tout le monde".

  1. Allow IIS Express through Windows firewall.

    Start / Windows Firewall with Advanced Security / Inbound Rules / New Rule...

    Program %ProgramFiles%\IIS Express\iisexpress.exe
    OR Port 8080 TCP

Now when you start iisexpress.exe you should see a message such as

Successfully registered URL "http://*:8080/" for site "hello world" application "/"

Check whether a string is not null and not empty

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
    ...
}

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Text inset for UITextField?

Overriding -textRectForBounds: will only change the inset of the placeholder text. To change the inset of the editable text, you need to also override -editingRectForBounds:

// placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 10, 10);
}

// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 10, 10);
}

Visual Studio window which shows list of methods

Since Visual Studio 2012, you can view the outline ( fields and methods) in the solution explorer by expanding the node corresponding to your file .

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I encountered this issue with a misconfigured xcconfig file.

The Pods-generated xcconfig was not correctly #included in the customise xcconfig that I was using. This caused $PODS_ROOT to not be set resulting in the failure of diff "/../Podfile.lock" "/Manifest.lock", for obvious reasons, which Pods misinterprets as a sync issue.

How to turn a String into a JavaScript function call?

I wanted to be able to take a function name as a string, call it, AND pass an argument to the function. I couldn't get the selected answer for this question to do that, but this answer explained it exactly, and here is a short demo.

function test_function(argument)    {
    alert('This function ' + argument); 
}

functionName = 'test_function';

window[functionName]('works!');

This also works with multiple arguments.

How do I use Assert to verify that an exception has been thrown?

This is going to depend on what test framework are you using?

In MbUnit, for example, you can specify the expected exception with an attribute to ensure that you are getting the exception you really expect.

[ExpectedException(typeof(ArgumentException))]

'Framework not found' in Xcode

Delete the framework that is causing the issue (by removing the reference).

Then add it again, following these steps for adding FBSDK frameworks and libraries:

  1. click project
  2. general settings
  3. linked framework and libraries
  4. click the plus button and add all that you want

OrderBy pipe issue

I've created an OrderBy pipe that does just what you need. It supports being able to sort on multiple columns of an enumerable of objects as well.

<li *ngFor="#todo in todos | orderBy : ['completed']">{{todo.name}} {{todo.completed}}</li>

This pipe does allow for adding more items to the array after rendering the page, and will sort the array with the updates dynamically.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

Enabling/Disabling Microsoft Virtual WiFi Miniport

In my case I had to uninstall and reinstall the wireless adapter driver to be able to execute the command

Pass Javascript variable to PHP via ajax

To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.

and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...

$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';

Then you can use an identifiable 'guest' user and render your code that much more readable :)

Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :

a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false

array_key_exists(a['one']) == true
array_key_exists(a['two']) == true

Bw sure you know which function you want to use for which purpose.

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

Python vs. Java performance (runtime speed)

Different languages do different things with different levels of efficiency.

The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.

Extract substring from a string

The best way to get substring in Android is using (as @user2503849 said) TextUtlis.substring(CharSequence, int, int) method. I can explain why. If you will take a look at the String.substring(int, int) method from android.jar (newest API 22), you will see:

public String substring(int start) {
    if (start == 0) {
        return this;
    }
    if (start >= 0 && start <= count) {
        return new String(offset + start, count - start, value);
    }
    throw indexAndLength(start);
}

Ok, than... How do you think the private constructor String(int, int, char[]) looks like?

String(int offset, int charCount, char[] chars) {
    this.value = chars;
    this.offset = offset;
    this.count = charCount;
}

As we can see it keeps reference to the "old" value char[] array. So, the GC can not free it.

In the newest Java it was fixed:

String(int offset, int charCount, char[] chars) {
    this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
    this.offset = offset;
    this.count = charCount;
}

Arrays.copyOfRange(...) uses native array copying inside.

That's it :)

Best regards!

How to make VS Code to treat other file extensions as certain language?

Following the steps on https://code.visualstudio.com/docs/customization/colorizer#_common-questions worked well for me:

To extend an existing colorizer, you would create a simple package.json in a new folder under .vscode/extensions and provide the extensionDependencies attribute specifying the customization you want to add to. In the example below, an extension .mmd is added to the markdown colorizer. Note that not only must the extensionDependency name match the customization but also the language id must match the language id of the colorizer you are extending.

{
    "name": "MyMarkdown",
    "version": "0.0.1",
    "engines": {
        "vscode": "0.10.x"
    },
    "publisher": "none",
    "extensionDependencies": [
        "markdown"
    ],
    "contributes": {
        "languages": [{
            "id": "markdown",
            "aliases": ["mmd"],
            "extensions": [".mmd"]
        }]
    }
}

How does a hash table work?

You take a bunch of things, and an array.

For each thing, you make up an index for it, called a hash. The important thing about the hash is that it 'scatter' a lot; you don't want two similar things to have similar hashes.

You put your things into the array at position indicated by the hash. More than one thing can wind up at a given hash, so you store the things in arrays or something else appropriate, which we generally call a bucket.

When you're looking things up in the hash, you go through the same steps, figuring out the hash value, then seeing what's in the bucket at that location and checking whether it's what you're looking for.

When your hashing is working well and your array is big enough, there will only be a few things at most at any particular index in the array, so you won't have to look at very much.

For bonus points, make it so that when your hash table is accessed, it moves the thing found (if any) to the beginning of the bucket, so next time it's the first thing checked.

Remove empty array elements

Just one line : Update (thanks to @suther):

$array_without_empty_values = array_filter($array);

How can I change IIS Express port for a site

Another fix for those who have IIS Installed:

Create a path on the IIS Server, and allocate your website/app there.

Go to propieties of the solution of the explorer, then in front of using the iisexpress from visual studio, make that vs uses your personal own IIS.

Solution Proprieties

Running a script inside a docker container using shell script

You could also mount a local directory into your docker image and source the script in your .bashrc. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)

I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)

Here is how you bind your current directory:

docker run -it -v $PWD:/scripts $my_docker_build /bin/bash

Now your current directory is bound to /scripts of your docker instance.

(Outdated) To save your .bashrc changes commit your working image with this command:

docker commit $container_id $my_docker_build

Update

To solve the issue to open up a new shell for every change I now do the following:

In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc". Inside zshrc I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.

BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.

setting JAVA_HOME & CLASSPATH in CentOS 6

It seems that you dont have any problem with the environmental variables.

Compile your file from src with

javac a/A.java

Then, run your program as

java a.A

Read file As String

It's very easy if you use Kotlin:

val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)

From readText() docs:

Gets the entire content of this file as a String using UTF-8 or specified charset. This method is not recommended on huge files. It has an internal limitation of 2 GB file size.

Check if a key exists inside a json object

I change your if statement slightly and works (also for inherited obj - look on snippet)

if(!("merchant_id" in thisSession)) alert("yeah");

_x000D_
_x000D_
var sessionA = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  merchant_id: "sam",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
var sessionB = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
_x000D_
var sessionCfromA = Object.create(sessionA); // inheritance_x000D_
sessionCfromA.name = 'john';_x000D_
_x000D_
_x000D_
if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");_x000D_
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");_x000D_
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");_x000D_
_x000D_
if ("merchant_id" in sessionA) alert("merchant_id in sessionA");_x000D_
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");_x000D_
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");
_x000D_
_x000D_
_x000D_

How do you return a JSON object from a Java Servlet

By Using Gson you can send json response see below code

You can see this code

@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
    Subject subject1 = new Subject(1, "Computer Fundamentals");
    Subject subject2 = new Subject(2, "Computer Graphics");
    Subject subject3 = new Subject(3, "Data Structures");
    Set subjects = new HashSet();
    subjects.add(subject1);
    subjects.add(subject2);
    subjects.add(subject3);
    student.setSubjects(subjects);
    Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
    student.setAddress(address);
    Gson gson = new Gson();
    String jsonData = gson.toJson(student);
    PrintWriter out = response.getWriter();
    try {
        out.println(jsonData);
    } finally {
        out.close();
    }

  }
}

helpful from json response from servlet in java

What's the best way to do a backwards loop in C/C#/C++?

In C# using Linq:

foreach(var item in myArray.Reverse())
{
    // do something
}

How do I vertically center an H1 in a div?

you can achieve vertical aligning with display:table-cell:

#section1 {
    height: 90%; 
    text-align:center; 
    display:table;
    width:100%;
}

#section1 h1 {display:table-cell; vertical-align:middle}

Example

Update - CSS3

For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:

#section1 {
    height: 90%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}

Updated fiddle

How to output an Excel *.xls file from classic ASP

You must specify the file to be downloaded (attachment) by the client in the http header:

Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"

http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html

Android getText from EditText field

Sample code for How to get text from EditText.

Android Java Syntax

EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();

Kotlin Syntax

val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()

Read data from a text file using Java

Try using java.io.BufferedReader like this.

java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Here is a complete answer that will hopefully help others...


I want to setup mysql replication using master and slave, and since the only thing I knew was that it uses log file(s) to synchronize, if the slave goes offline and gets out of sync, in theory it should only need to connect back to its master and keep reading the log file from where it left off, as user malonso mentioned.

So here are the test result after configuring the master and slave as mentioned by: http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html ...

Provided you use the recommended master/slave configuration and don't write to the slave, he and I where right (as far as mysql-server 5.x is concerned). I didn't even need to use "START SLAVE;", it just caught up to its master. But there is a default 88000 something retries every 60 second so I guess if you exhaust that you might have to start or restart the slave. Anyways, for those like me who wanted to know if having a slave going offline and back up again requires manual intervention.. no, it doesn't.

Maybe the original poster had corruption in the log-file(s)? But most probably not just a server going off-line for a day.


pulled from /usr/share/doc/mysql-server-5.1/README.Debian.gz which probably makes sense to non debian servers as well:

* FURTHER NOTES ON REPLICATION
===============================
If the MySQL server is acting as a replication slave, you should not
set --tmpdir to point to a directory on a memory-based filesystem or to
a directory that is cleared when the server host restarts. A replication
slave needs some of its temporary files to survive a machine restart so
that it can replicate temporary tables or LOAD DATA INFILE operations. If
files in the temporary file directory are lost when the server restarts,
replication fails.

you can use something sql like: show variables like 'tmpdir'; to find out.

Adding machineKey to web.config on web-farm sites

This should answer:

How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations

Web Farm Deployment Considerations

If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.

With manually generated key values, the settings should be similar to the following example.

<machineKey  
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
               AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"       

decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>

If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.

In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.

Setting Up the Machine Key Using IIS Manager

If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.

Start the management console and then select the web site. Open the machine key configuration: The IIS web site configuration panel

The machine key control panel has the following settings:

The machine key configuration panel

Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.

Click "Generate Keys" under "Actions" on the right side of the panel.

Click "Apply".

and add the following line to the web.config file in all the webservers under system.web tag if it does not exist.

<machineKey  
    validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
                   AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
    decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
    validation="SHA1"
    decryption="AES"
/>

Please make sure that you have a permanent backup of the machine keys and web.config file

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

How to use org.apache.commons package?

You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.

For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.

If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.

For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.

If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.

What is the best way to extract the first word from a string in Java?

To simplify the above:

text.substring(0, text.indexOf(' ')); 

Here is a ready function:

private String getFirstWord(String text) {

  int index = text.indexOf(' ');

  if (index > -1) { // Check if there is more than one word.

    return text.substring(0, index).trim(); // Extract first word.

  } else {

    return text; // Text is the first word itself.
  }
}

Speed tradeoff of Java's -Xms and -Xmx options

I have found that in some cases too much memory can slow the program down.

For example I had a hibernate based transform engine that started running slowly as the load increased. It turned out that each time we got an object from the db, hibernate was checking memory for objects that would never be used again.

The solution was to evict the old objects from the session.

Stuart

How to create full compressed tar file using Python?

Previous answers advise using the tarfile Python module for creating a .tar.gz file in Python. That's obviously a good and Python-style solution, but it has serious drawback in speed of the archiving. This question mentions that tarfile is approximately two times slower than the tar utility in Linux. According to my experience this estimation is pretty correct.

So for faster archiving you can use the tar command using subprocess module:

subprocess.call(['tar', '-czf', output_filename, file_to_archive])

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

How can I convert String to Int?

If you're looking for the long way, just create your one method:

static int convertToInt(string a)
    {
        int x = 0;

        Char[] charArray = a.ToCharArray();
        int j = charArray.Length;

        for (int i = 0; i < charArray.Length; i++)
        {
            j--;
            int s = (int)Math.Pow(10, j);

            x += ((int)Char.GetNumericValue(charArray[i]) * s);
        }
        return x;
    }

How to convert Base64 String to javascript file object like as from file input form?

const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })
  })

Base64 String -> Blob -> File.

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

Beware that such an operation is platform dependant in C.

Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608