Programs & Examples On #Uiq

ssh: check if a tunnel is alive

#!/bin/bash

# Check do we have tunnel to example.com server
lsof -i tcp@localhost:6000 > /dev/null

# If exit code wasn't 0 then tunnel doesn't exist.
if [ $? -eq 1 ]
then
  echo ' > You missing ssh tunnel. Creating one..'
  ssh -L 6000:localhost:5432 example.com
fi

echo ' > DO YOUR STUFF < '

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

Find p-value (significance) in scikit-learn LinearRegression

You can use scipy for p-value. This code is from scipy documentation.

>>> from scipy import stats
>>> import numpy as np
>>> x = np.random.random(10)
>>> y = np.random.random(10)
>>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

What are the alternatives now that the Google web search API has been deprecated?

Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.

To create a Google Custom Search engine that searches the entire web:

  1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
  2. Type a name and description for your search engine.
  3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
  4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
  5. Click any of the links under the Next steps section to navigate to your Control panel.
  6. In the left-hand menu, under Control Panel, click Basics.
  7. In the Search Preferences section, select Search the entire web but emphasize included sites.
  8. Click Save Changes.
  9. In the left-hand menu, under Control Panel, click Sites.
  10. Delete the site you entered during the initial setup process.

Now your custom search engine will search the entire web.

Pricing

  • Google Custom Search gives you 100 queries per day for free.
  • After that you pay $5 per 1000 queries.
  • There is a maximum of 10,000 queries per day.

Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing


  • The search quality is much lower than normal Google search (no synonyms, "intelligence" etc.)
  • It seems that Google is even planning to shut down this service completely.

C++ String array sorting

int z = sizeof(name)/sizeof(name[0]); //Get the array size

sort(name,name+z); //Use the start and end like this

for(int y = 0; y < z; y++){
    cout << name[y] << endl;
}

Edit :

Considering all "proper" naming conventions (as per comments) :

int N = sizeof(name)/sizeof(name[0]); //Get the array size

sort(name,name+N); //Use the start and end like this

for(int i = 0; i < N; i++){
    cout << name[i] << endl;
}

Note: Dietmar Kühl's answer is best in all respect, std::begin() & std::end() should be used for std::sort like functions with C++11, else they can be defined.

What does "@" mean in Windows batch scripts

The @ disables echo for that one command. Without it, the echo start eclipse.exe line would print both the intended start eclipse.exe and the echo start eclipse.exe line.

The echo off turns off the by-default command echoing.

So @echo off silently turns off command echoing, and only output the batch author intended to be written is actually written.

jQuery add required to input fields

Should not enclose true with double quote " " it should be like

$(document).ready(function() {            
   $('input').attr('required', true);   
});

Also you can use prop

jQuery(document).ready(function() {            
   $('input').prop('required', true);   
}); 

Instead of true you can try required. Such as

$('input').prop('required', 'required');

How do I auto size a UIScrollView to fit its content

Because a scrollView can have other scrollViews or different inDepth subViews tree, run in depth recursively is preferable. enter image description here

Swift 2

extension UIScrollView {
    //it will block the mainThread
    func recalculateVerticalContentSize_synchronous () {
        let unionCalculatedTotalRect = recursiveUnionInDepthFor(self)
        self.contentSize = CGRectMake(0, 0, self.frame.width, unionCalculatedTotalRect.height).size;
    }

    private func recursiveUnionInDepthFor (view: UIView) -> CGRect {
        var totalRect = CGRectZero
        //calculate recursevly for every subView
        for subView in view.subviews {
            totalRect =  CGRectUnion(totalRect, recursiveUnionInDepthFor(subView))
        }
        //return the totalCalculated for all in depth subViews.
        return CGRectUnion(totalRect, view.frame)
    }
}

Usage

scrollView.recalculateVerticalContentSize_synchronous()

Why isn't textarea an input[type="textarea"]?

So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in 
        my textarea without any problems.
    </textarea>
</body>
</html>

CSS rotate property in IE

Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!

I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)

All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.

Great answer @Spudley! Thanks for writing it!

How do I trim() a string in angularjs?

I insert this code in my tag and it works correctly:

ng-show="!Contract.BuyerName.trim()" >

SQL Server 2008- Get table constraints

You should use the current sys catalog views (if you're on SQL Server 2005 or newer - the sysobjects views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.

There are quite a few views you might be interested in:

  • sys.default_constraints for default constraints on columns
  • sys.check_constraints for check constraints on columns
  • sys.key_constraints for key constraints (e.g. primary keys)
  • sys.foreign_keys for foreign key relations

and a lot more - check it out!

You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:

SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name

How do I check if a string contains another string in Swift?

In Swift 4.2

Use

func contains(_ str: String) -> Bool

Example

let string = "hello Swift"
let containsSwift = string.contains("Swift")
print(containsSwift) // prints true

Truncate (not round off) decimal numbers in javascript

I'm a bit confused as to why there are so many different answers to such a fundamentally simple question; there are only two approaches which I saw which seemed to be worth looking at. I did a quick benchmark to see the speed difference using https://jsbench.me/.

This is the solution which is currently (9/26/2020) flagged as the answer:

_x000D_
_x000D_
function truncate(n, digits) {
    var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
        m = n.toString().match(re);
    return m ? parseFloat(m[1]) : n.valueOf();
};

[   truncate(5.467,2),
    truncate(985.943,2),
    truncate(17.56,2),
    truncate(0, 1),
    truncate(1.11, 1) + 22];
_x000D_
_x000D_
_x000D_

However, this is doing string and regex stuff, which is usually not very efficient, and there is a Math.trunc function which does exactly what the OP wants just with no decimals. Therefore, you can easily use that plus a little extra arithmetic to get the same thing.

Here is another solution I found on this thread, which is the one I would use:

_x000D_
_x000D_
function truncate(n, digits) {
    var step = Math.pow(10, digits || 0);
    var temp = Math.trunc(step * n);

    return temp / step;
}

[   truncate(5.467,2),
    truncate(985.943,2),
    truncate(17.56,2),
    truncate(0, 1),
    truncate(1.11, 1) + 22];
    
_x000D_
_x000D_
_x000D_

The first method is "99.92% slower" than the second, so the second is definitely the one I would recommend using.

Okay, back to finding other ways to avoid work...

screenshot of the benchmark

Get the content of a sharepoint folder with Excel VBA

I messed around with this problem for a bit, and found a very simple, 2-line solution, simply replacing the 'http' and all the forward slashes like this:

myFilePath = replace(myFilePath, "/", "\")
myFilePath = replace(myFilePath, "http:", "")

It might not work for everybody, but it worked for me

If you are using a secure site (or wish to cater for both) you may wish to add the following line:

myFilePath = replace(myFilePath, "https:", "")

How do I find the stack trace in Visual Studio?

Do you mean finding a stack trace of the thrown exception location? That's either Debug/Exceptions, or better - Ctrl-Alt-E. Set filters for the exceptions you want to break on.

There's even a way to reconstruct the thrower stack after the exception was caught, but it's really unpleasant. Much, much easier to set a break on the throw.

on change event for file input element

Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

Get user location by IP address

It's good sample for you:

public class IpProperties
    {
        public string Status { get; set; }
        public string Country { get; set; }
        public string CountryCode { get; set; }
        public string Region { get; set; }
        public string RegionName { get; set; }
        public string City { get; set; }
        public string Zip { get; set; }
        public string Lat { get; set; }
        public string Lon { get; set; }
        public string TimeZone { get; set; }
        public string ISP { get; set; }
        public string ORG { get; set; }
        public string AS { get; set; }
        public string Query { get; set; }
    }
 public string IPRequestHelper(string url)
    {
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

        StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
        string responseRead = responseStream.ReadToEnd();

        responseStream.Close();
        responseStream.Dispose();

        return responseRead;
    }

    public IpProperties GetCountryByIP(string ipAddress)
    {
        string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
        using (TextReader sr = new StringReader(ipResponse))
        {
            using (System.Data.DataSet dataBase = new System.Data.DataSet())
            {
                IpProperties ipProperties = new IpProperties();
                dataBase.ReadXml(sr);
                ipProperties.Status = dataBase.Tables[0].Rows[0][0].ToString();
                ipProperties.Country = dataBase.Tables[0].Rows[0][1].ToString();
                ipProperties.CountryCode = dataBase.Tables[0].Rows[0][2].ToString();
                ipProperties.Region = dataBase.Tables[0].Rows[0][3].ToString();
                ipProperties.RegionName = dataBase.Tables[0].Rows[0][4].ToString();
                ipProperties.City = dataBase.Tables[0].Rows[0][5].ToString();
                ipProperties.Zip = dataBase.Tables[0].Rows[0][6].ToString();
                ipProperties.Lat = dataBase.Tables[0].Rows[0][7].ToString();
                ipProperties.Lon = dataBase.Tables[0].Rows[0][8].ToString();
                ipProperties.TimeZone = dataBase.Tables[0].Rows[0][9].ToString();
                ipProperties.ISP = dataBase.Tables[0].Rows[0][10].ToString();
                ipProperties.ORG = dataBase.Tables[0].Rows[0][11].ToString();
                ipProperties.AS = dataBase.Tables[0].Rows[0][12].ToString();
                ipProperties.Query = dataBase.Tables[0].Rows[0][13].ToString();

                return ipProperties;
            }
        }
    }

And test:

var ipResponse = GetCountryByIP("your ip address or domain name :)");

How to prevent rm from reporting that a file was not found?

-f is the correct flag, but for the test operator, not rm

[ -f "$THEFILE" ] && rm "$THEFILE"

this ensures that the file exists and is a regular file (not a directory, device node etc...)

How do I use spaces in the Command Prompt?

Try to provide complex pathnames in double-quotes (and include file extensions at the end for files.)

For files:

call "C:\example file.exe"

For Directory:

cd "C:\Users\User Name\New Folder"

CMD interprets text with double quotes ("xyz") as one string and text within single quotes ('xyz') as a command. For example:

FOR %%A in ('dir /b /s *.txt') do ('command')

FOR %%A in ('dir /b /s *.txt') do (echo "%%A")

And one good thing, cmd is not* case sensitive like bash. So "New fiLE.txt" and "new file.TXT" is alike to it.

*Note: The %%A variables in above case is case-sensitive (%%A not equal to %%a).

JQUERY ajax passing value from MVC View to Controller

[HttpPost]
public ActionResult SaveComments(int id, string comments){
     var actions = new Actions(User.Identity.Name);
     var status = actions.SaveComments(id, comments);
     return Content(status);
}

Regex to check with starts with http://, https:// or ftp://

If you wanna do it in case-insensitive way, this is better:

System.out.println(test.matches("^(?i)(https?|ftp)://.*$")); 

Print empty line?

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character

print()

Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text

my_str = "hello world"
print(my_str + "\n")

If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")

print("hello world", end="\n\n")

But you probably don't need this last method, the two before are much clearer.

Open a facebook link by native Facebook app on iOS

swift 3

if let url = URL(string: "fb://profile/<id>") {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:],completionHandler: { (success) in
                print("Open fb://profile/<id>: \(success)")
            })
        } else {
            let success = UIApplication.shared.openURL(url)
            print("Open fb://profile/<id>: \(success)")
        }
 }

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

PowerShell script to return members of multiple security groups

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

checking for typeof error in JS

Thanks @Trott for your code, I just used the same code and added with a real time working example for the benefit of others.

_x000D_
_x000D_
<html>_x000D_
<body >_x000D_
_x000D_
<p>The **instanceof** operator returns true if the specified object is an instance of the specified object.</p>_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
 var myError = new Error("TypeError: Cannot set property 'innerHTML' of null"); // error type when element is not defined_x000D_
 myError instanceof Error // true_x000D_
 _x000D_
 _x000D_
 _x000D_
 _x000D_
 function test(){_x000D_
 _x000D_
 var v1 = document.getElementById("myid").innerHTML ="zunu"; // to change with this_x000D_
 _x000D_
 try {_x000D_
    var v1 = document.getElementById("myidd").innerHTML ="zunu"; // exception caught_x000D_
    } _x000D_
    _x000D_
 catch (e) {_x000D_
    if (e instanceof Error) {_x000D_
   console.error(e.name + ': ' + e.message) // error will be displayed at browser console_x000D_
    }_x000D_
  }_x000D_
  finally{_x000D_
  var v1 = document.getElementById("myid").innerHTML ="Text Changed to Zunu"; // finally innerHTML changed to this._x000D_
 }_x000D_
 _x000D_
 }_x000D_
 _x000D_
</script>_x000D_
<p id="myid">This text will change</p>_x000D_
<input type="button" onclick="test();">_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

C++ string to double conversion

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}

AJAX POST and Plus Sign ( + ) -- How to Encode?

The hexadecimal value you are looking for is %2B

To get it automatically in PHP run your string through urlencode($stringVal). And then run it rhough urldecode($stringVal) to get it back.

If you want the JavaScript to handle it, use escape( str )

Edit

After @bobince's comment I did more reading and he is correct. Use encodeURIComponent(str) and decodeURIComponent(str). Escape will not convert the characters, only escape them with \'s

how to get multiple checkbox value using jquery

Try this

<input name="selector[]" id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" />
<input name="selector[]" id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" />
<input name="selector[]" id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" />
<input name="selector[]" id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" />
<input type="button" id="save_value" name="save_value" value="Save" />

function

    $(function(){
      $('#save_value').click(function(){
        var val = [];
        $(':checkbox:checked').each(function(i){
          val[i] = $(this).val();
        });
      });
    });

Change URL and redirect using jQuery

tell you the true, I still don't get what you need, but

window.location(url);

should be

window.location = url;

a search on window.location reference will tell you that.

The executable was signed with invalid entitlements

There are pretty good instructions in the 'Portal Program'. If you log into

http://developer.apple.com/iphone

Then click Distribution on the left, and click the

Creating and Downloading a Distribution Provisioning Profile for Ad Hoc Distribution

link at the bottom.

Here's the key bit:

For Ad Hoc Distribution, complete the following:

  • In the File Menu, select New File -> iPhone OS -> Code Signing -> Entitlements. Name the file “Entitlements.plist" and click ‘Finish’. This creates a copy of the default entitlements file within the project.
  • Select the new Entitlments.plist file and uncheck the “get-task-allow” property. Save the Entitlements.plist file. (in Xcode 4, get-task-allow is called "Can be debugged" )
  • Select the Target and open the Build settings inspector. In the ‘Code Signing Entitlements’ build setting, type in the filename of the new Entitlements.plist file including the extension. There is no need to specify a path unless you have put the Entitlements.plist file somewhere other than the top level of the project.
  • Click ‘Build’. (Note: Your binary must contain a flattened, square-image icon that is 57x57 pixels. This icon is displayed on the iPhone or iPod touch home screen.)

How to dynamically add rows to a table in ASP.NET?

You can use the asp:Table in your web form and build it via code:

http://msdn.microsoft.com/en-us/library/7bewx260.aspx

Also, check out asp.net for tutorials and such.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How To Check If A Key in **kwargs Exists?

You can discover those things easily by yourself:

def hello(*args, **kwargs):
    print kwargs
    print type(kwargs)
    print dir(kwargs)

hello(what="world")

Create a table without a header in Markdown

You may be able to hide a heading if you can add the following CSS:

<style>
    th {
        display: none;
    }
</style>

This is a bit heavy-handed and doesn’t distinguish between tables, but it may do for a simple task.

How do I use cx_freeze?

I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:

from cx_Freeze import setup, Executable
import sys

productName = "ProductName"
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
    sys.argv += ['--install-script', 'install.py']

exe = Executable(
      script="main.py",
      base="Win32GUI",
      targetName="Product.exe"
     )
setup(
      name="Product.exe",
      version="1.0",
      author="Me",
      description="Copyright 2012",
      executables=[exe],
      scripts=[
               'install.py'
               ]
      ) 

grep a file, but show several surrounding lines?

I normally use

grep searchstring file -C n # n for number of lines of context up and down

Many of the tools like grep also have really great man files too. I find myself referring to grep's man page a lot because there is so much you can do with it.

man grep

Many GNU tools also have an info page that may have more useful information in addition to the man page.

info grep

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How to assign a value to a TensorFlow variable?

Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializer need not be called explicitly since the assign operation does it for you in the background.

Example:

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34 

However, this will not initialize all variables, but it will only initialize the variable on which assign was executed on.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

Batch files - number of command line arguments

The last answer was two years ago now, but I needed a version for more than nine command line arguments. May be another one also does...

@echo off
setlocal

set argc_=1
set arg0_=%0
set argv_=

:_LOOP
set arg_=%1
if defined arg_ (
  set arg%argc_%_=%1
  set argv_=%argv_% %1
  set /a argc_+=1
  shift
  goto _LOOP
)
::dont count arg0
set /a argc_-=1
echo %argc_% arg(s)

for /L %%i in (0,1,%argc_%) do (
  call :_SHOW_ARG arg%%i_ %%arg%%i_%%
)

echo converted to local args
call :_LIST_ARGS %argv_%
exit /b


:_LIST_ARGS
setlocal
set argc_=0
echo arg0=%0

:_LOOP_LIST_ARGS
set arg_=%1
if not defined arg_ exit /b
set /a argc_+=1
call :_SHOW_ARG arg%argc_% %1
shift
goto _LOOP_LIST_ARGS


:_SHOW_ARG
echo %1=%2
exit /b

The solution is the first 19 lines and converts all arguments to variables in a c-like style. All other stuff just probes the result and shows conversion to local args. You can reference arguments by index in any function.

How can I delete a user in linux when the system says its currently used in a process

It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this

image description here

Why does pycharm propose to change method to static

PyCharm "thinks" that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

  1. running code before Compilation : use controller
  2. running code after Compilation : use Link

Angular convention : write business logic in controller and DOM manipulation in link.

Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives

<animal>
<panther>
<leopard></leopard>
</panther> 
</animal>

and you want to access animal from inside of "leopard" directive.

http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication

Windows ignores JAVA_HOME: how to set JDK as default?

In my case I had Java 7 and 8 (both x64) installed and I want to redirect to java 7 but everything is set to use Java 8. Java uses the PATH environment variable:

C:\ProgramData\Oracle\Java\javapath

as the first option to look for its folder runtime (is a hidden folder). This path contains 3 symlinks that can't be edited.

In my pc, the PATH environment variable looks like this:

C:\ProgramData\Oracle\Java\javapath;C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;

In my case, It should look like this:

C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;

I had to cut and paste the symlinks to somewhere else so java can't find them, and I can restore them later.

After setting the JAVA_HOME and JRE_HOME environment variables to the desired java folders' runtimes (in my case it is Java 7), the command java -version should show your desired java runtime. I remark there's no need to mess with the registry.

Tested on Win7 x64.

Possible reason for NGINX 499 error codes

In my case, I have setup like

AWS ELB >> ECS(nginx) >> ECS(php-fpm).

I had configured the wrong AWS security group for ECS(php-fpm) service, so Nginx wasn't able to reach out to php-fpm task container. That's why i was getting errors in nginx task log

499 0 - elb-healthchecker/2.0

Health check was configured as to check php-fpm service and confirm it's up and give back a response.

ORA-00904: invalid identifier

I had this error when trying to save an entity through JPA.

It was because I had a column with @JoinColumn annotation that didn't have @ManyToOne annotation.

Adding @ManyToOne fixed the issue.

How can I parse a YAML file from a Linux shell script?

Moving my answer from How to convert a json response into yaml in bash, since this seems to be the authoritative post on dealing with YAML text parsing from command line.

I would like to add details about the yq YAML implementation. Since there are two implementations of this YAML parser lying around, both having the name yq, it is hard to differentiate which one is in use, without looking at the implementations' DSL. There two available implementations are

  1. kislyuk/yq - The more often talked about version, which is a wrapper over jq, written in Python using the PyYAML library for YAML parsing
  2. mikefarah/yq - A Go implementation, with its own dynamic DSL using the go-yaml v3 parser.

Both are available for installation via standard installation package managers on almost all major distributions

  1. kislyuk/yq - Installation instructions
  2. mikefarah/yq - Installation instructions

Both the versions have some pros and cons over the other, but a few valid points to highlight (adopted from their repo instructions)

kislyuk/yq

  1. Since the DSL is the adopted completely from jq, for users familiar with the latter, the parsing and manipulation becomes quite straightforward
  2. Supports mode to preserve YAML tags and styles, but loses comments during the conversion. Since jq doesn't preserve comments, during the round-trip conversion, the comments are lost.
  3. As part of the package, XML support is built in. An executable, xq, which transcodes XML to JSON using xmltodict and pipes it to jq, on which you can apply the same DSL to perform CRUD operations on the objects and round-trip the output back to XML.
  4. Supports in-place edit mode with -i flag (similar to sed -i)

mikefarah/yq

  1. Prone to frequent changes in DSL, migration from 2.x - 3.x
  2. Rich support for anchors, styles and tags. But lookout for bugs once in a while
  3. A relatively simple Path expression syntax to navigate and match yaml nodes
  4. Supports YAML->JSON, JSON->YAML formatting and pretty printing YAML (with comments)
  5. Supports in-place edit mode with -i flag (similar to sed -i)
  6. Supports coloring the output YAML with -C flag (not applicable for JSON output) and indentation of the sub elements (default at 2 spaces)
  7. Supports Shell completion for most shells - Bash, zsh (because of powerful support from spf13/cobra used to generate CLI flags)

My take on the following YAML (referenced in other answer as well) with both the versions

root_key1: this is value one
root_key2: "this is value two"

drink:
  state: liquid
  coffee:
    best_served: hot
    colour: brown
  orange_juice:
    best_served: cold
    colour: orange

food:
  state: solid
  apple_pie:
    best_served: warm

root_key_3: this is value three

Various actions to be performed with both the implementations (some frequently used operations)

  1. Modifying node value at root level - Change value of root_key2
  2. Modifying array contents, adding value - Add property to coffee
  3. Modifying array contents, deleting value - Delete property from orange_juice
  4. Printing key/value pairs with paths - For all items under food

Using kislyuk/yq

  1. yq -y '.root_key2 |= "this is a new value"' yaml
    
  2. yq -y '.drink.coffee += { time: "always"}' yaml
    
  3. yq -y 'del(.drink.orange_juice.colour)' yaml
    
  4. yq -r '.food|paths(scalars) as $p | [($p|join(".")), (getpath($p)|tojson)] | @tsv' yaml
    

Which is pretty straightforward. All you need is to transcode jq JSON output back into YAML with the -y flag.

Using mikefarah/yq

  1.  yq w yaml root_key2 "this is a new value"
    
  2.  yq w yaml drink.coffee.time "always"
    
  3.  yq d yaml drink.orange_juice.colour
    
  4.  yq r yaml --printMode pv "food.**"
    

As of today Dec 21st 2020, yq v4 is in beta and supports much powerful path expressions and supports DSL similar to using jq. Read the transition notes - Upgrading from V3

Which passwordchar shows a black dot (•) in a winforms textbox?

I was also wondering how to store it cleanly in a variable. As using

char c = '•';

is not very good practice (I guess). I found out the following way of storing it in a variable

char c = (char)0x2022;// or 0x25cf depending on the one you choose

or even cleaner

char c = '\u2022';// or "\u25cf"

https://msdn.microsoft.com/en-us/library/aa664669%28v=vs.71%29.aspx

same for strings

string s = "\u2022";

https://msdn.microsoft.com/en-us/library/362314fe.aspx

How to add a Try/Catch to SQL Stored Procedure

Transact-SQL is a bit more tricky that C# or C++ try/catch blocks, because of the added complexity of transactions. A CATCH block has to check the xact_state() function and decide whether it can commit or has to rollback. I have covered the topic in my blog and I have an article that shows how to correctly handle transactions in with a try catch block, including possible nested transactions: Exception handling and nested transactions.

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
                 @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

$watch an object

The reason why your code doesn't work is because $watch by default does reference check. So in a nutshell it make sure that the object which is passed to it is new object. But in your case you are just modifying some property of form object not creating a new one. In order to make it work you can pass true as the third parameter.

$scope.$watch('form', function(newVal, oldVal){
    console.log('invoked');
}, true);

It will work but You can use $watchCollection which will be more efficient then $watch because $watchCollection will watch for shallow properties on form object. E.g.

$scope.$watchCollection('form', function (newVal, oldVal) {
    console.log(newVal, oldVal);
});

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Had similar issue with React Native latest versions 0.50 and up.

For me it was a difference between:

import App from './app'

and

import App from './app/index.js'

(the latter fixed the issue). Took me hours to catch this weird, hard to notice nuance :(

What is the difference between Swing and AWT?

As far as when AWT may be more useful than Swing -

  • you may be targeting an older JVM or platform that doesn't support Swing. This used to really come into play if you were building Applets - you wanted to target the lowest common denominator so people wouldn't have to install a newer Java plugin. I'm not sure what the current most widely installed version of the Java plugin is - this may be different today.
  • some people prefer the native look of AWT over Swing's 'not quite there' platform skins. (There are better 3rd party native looking skins than Swing's implementations BTW) Lots of people preferred using AWT's FileDialog over Swing's FileChooser because it gave the platform file dialog most people were used to rather than the 'weird' custom Swing one.

SQLite with encryption/password protection

SQLite has hooks built-in for encryption which are not used in the normal distribution, but here are a few implementations I know of:

  • SEE - The official implementation.
  • wxSQLite - A wxWidgets style C++ wrapper that also implements SQLite's encryption.
  • SQLCipher - Uses openSSL's libcrypto to implement.
  • SQLiteCrypt - Custom implementation, modified API.
  • botansqlite3 - botansqlite3 is an encryption codec for SQLite3 that can use any algorithms in Botan for encryption.
  • sqleet - another encryption implementation, using ChaCha20/Poly1305 primitives. Note that wxSQLite mentioned above can use this as a crypto provider.

The SEE and SQLiteCrypt require the purchase of a license.

Disclosure: I created botansqlite3.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

This fixed it:

  1. Remove Gemfile.lock rm Gemfile.lock
  2. run bundle install again

EDIT: DON'T DO IT IN PRODUCTION!

For production go to this answer: https://stackoverflow.com/posts/54083113/revisions

Center form submit buttons HTML / CSS

One simple solution if only one button needs to be centered is something like:

<input type='submit' style='display:flex; justify-content:center;' value='Submit'>

You can use a similar style to handle several buttons.

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

How to use format() on a moment.js duration?

convert duration to ms and then to moment:

moment.utc(duration.as('milliseconds')).format('HH:mm:ss')

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

Create a txt file using batch file in a specific folder

This code written above worked for me as well. Although, you can use the code I am writing here:

@echo off

@echo>"d:\testing\dblank.txt

If you want to write some text to dblank.txt then add the following line in the end of your code

@echo Writing text to dblank.txt> dblank.txt

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:

Suppose you had a PL/SQL procedure like this to check for the existence of a location record:

   PROCEDURE chk_location_exists
   (
      p_location_id IN location.gie_location_id%TYPE
   )
   AS
      l_cnt INTEGER := 0;
   BEGIN
      SELECT COUNT(*)
        INTO l_cnt
        FROM location
       WHERE gie_location_id = p_location_id;

       IF l_cnt = 0
       THEN
          raise_application_error(
             gc_entity_not_found,
             'The associated location record could not be found.');
       END IF;
   END;

The raise_application_error allows you to raise a specific error code. In your package header, you can define: gc_entity_not_found INTEGER := -20001;

If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.

Then on the client side, you can do something like this (this example is for C#):

/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;

And you can execute your code in a try/catch

try
{
   // call the chk_location_exists SP
}
catch (Exception e)
{
    if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
    {
        // create an EntityNotFoundException with message indicating that entity was not found in
        // database; use the message of the OracleException, which will indicate the table corresponding
        // to the entity which wasn't found and also the exact line in the PL/SQL code where the application
        // error was raised
        return new EntityNotFoundException(
            "A required entity was not found in the database: " + e.Message);
    }
}

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

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

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Then number of columns must match between both parts of the union.

In order to build the full path, you need to "aggregate" all values of the Location column. You still need to select the id and other columns inside the CTE in order to be able to join properly. You get "rid" of them by simply not selecting them in the outer select:

with q as 
(
   select ID, PartOf_LOC_id, Location, ' > ' + Location as path
   from tblLocation 
   where ID = 1 

   union all

   select child.ID, child.PartOf_LOC_id, Location, parent.path + ' > ' + child.Location 
   from tblLocation child
     join q parent on parent.ID = t.LOC_PartOf_ID
)
select path
from q;

Call asynchronous method in constructor?

Try to replace this:

myLongList.ItemsSource = writings;

with this

Dispatcher.BeginInvoke(() => myLongList.ItemsSource = writings);

Create thumbnail image

Here is an example to convert high res image into thumbnail size-

protected void Button1_Click(object sender, EventArgs e)
{
    //----------        Getting the Image File
    System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/profile/Avatar.jpg"));

    //----------        Getting Size of Original Image
    double imgHeight = img.Size.Height;
    double imgWidth = img.Size.Width;

    //----------        Getting Decreased Size
    double x = imgWidth / 200;
    int newWidth = Convert.ToInt32(imgWidth / x);
    int newHeight = Convert.ToInt32(imgHeight / x);

    //----------        Creating Small Image
    System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    System.Drawing.Image myThumbnail = img.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);

    //----------        Saving Image
    myThumbnail.Save(Server.MapPath("~/profile/NewImage.jpg"));
}
public bool ThumbnailCallback()
{
    return false;
}

Source- http://iknowledgeboy.blogspot.in/2014/03/c-creating-thumbnail-of-large-image-by.html

Why aren't Xcode breakpoints functioning?

Solution for me with XCode 9.4.1 (did not stop at any breakpoint):

Under build Target -> Build Settings -> Optimization Level: Switched from "Optimize for speed" -> "No optimization" (now it's slower but works)

There is already an open DataReader associated with this Command which must be closed first

Well for me it was my own bug. I was trying to run an INSERT using SqlCommand.executeReader() when I should have been using SqlCommand.ExecuteNonQuery(). It was opened and never closed, causing the error. Watch out for this oversight.

How can I retrieve Id of inserted entity using Entity framework?

There are two strategies:

  1. Use Database-generated ID (int or GUID)

    Cons:

    You should perform SaveChanges() to get the ID for just saved entities.

    Pros:

    Can use int identity.

  2. Use client generated ID - GUID only.

    Pros: Minification of SaveChanges operations. Able to insert a big graph of new objects per one operation.

    Cons:

    Allowed only for GUID

add string to String array

As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.

It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Note that this implementation is not synchronized.

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");

Using Mockito to mock classes with generic parameters

I agree that one shouldn't suppress warnings in classes or methods as one could overlook other, accidentally suppressed warnings. But IMHO it's absolutely reasonable to suppress a warning that affects only a single line of code.

@SuppressWarnings("unchecked")
Foo<Bar> mockFoo = mock(Foo.class);

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Completing the solution of Ranadheer, using Server.MapPath to locate the file

System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);

Datatable select with multiple conditions

    protected void FindCsv()
    {
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
    }

React Native Error: ENOSPC: System limit for number of file watchers reached

I solved this issue by using sudo ie

sudo yarn start

or

sudo npm start

Permission denied at hdfs

I've solved this problem by using following steps

su hdfs
hadoop fs -put /usr/local/input-data/ /input
exit

How to get the integer value of day of week

day1= (int)ClockInfoFromSystem.DayOfWeek;

Count distinct values

Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

Imagine you have the table customer_pets like this:

+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+

then

SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets

would return:

+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+

as you need.

Use Font Awesome Icon in Placeholder

Teocci solution is as simple as it can be, thus, no need to add any CSS, just add class="fas" for Font Awesome 5, since it adds proper CSS font declaration to the element.

Here's an example for search box within Bootstrap navbar, with search icon added to the both input-group and placeholder (for the sake of demontration, of course, no one would use both at the same time). Image: https://i.imgur.com/v4kQJ77.png "> Code:

<form class="form-inline my-2 my-lg-0">
    <div class="input-group mb-3">
        <div class="input-group-prepend">
            <span class="input-group-text"><i class="fas fa-search"></i></span>
        </div>
        <input type="text" class="form-control fas text-right" placeholder="&#xf002;" aria-label="Search string">
        <div class="input-group-append">
            <button class="btn btn-success input-group-text bg-success text-white border-0">Search</button>
        </div>
    </div>
</form>

Chrome hangs after certain amount of data transfered - waiting for available socket

The message:

Waiting for available socket...

is shown, because you've reached a limit on the ssl_socket_pool either per Host, Proxy or Group.

Here are the maximum number of HTTP connections which you can make with a Chrome browser:

  • The maximum number of connections per proxy is 32 connections. This can be changed in Policy List.
  • Maximum per Host: 6 connections.

    This is likely hardcoded in the source code of the web browser, so you can't change it.

  • Total 256 HTTP connections pooled per browser.

Source: Enterprise networking for Chrome devices

The above limits can be checked or flushed at chrome://net-internals/#sockets (or in real-time at chrome://net-internals/#events&q=type:SOCKET%20is:active).


Your issue with audio can be related to Chrome bug 162627 where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).

Much older issue related to HTML5 video request stay pending, then it's probably related to Issue #234779 which has been fixed 2014. And related to SPDY which can be found in Issue 324653: SPDY issue: waiting for available sockets, but this was already fixed in 2014, so probably it's not related.

Other related issue now marked as duplicate can be found in Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+ which was related to the problem with the media player code leaving a bunch of paused requests hanging around.


This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like Sophos or Kaspersky), so check for Network activity in DevTools.

What is the lifetime of a static variable in a C++ function?

FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.

C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if

... which is another reason not to rely on the destruction order!

Displaying the Indian currency symbol on a website

Image approach is not bad either. It hardly takes 400Bytes.
Download from here http://i.stack.imgur.com/vJZ9m.png

<span class="rupee"></span>

Well i found it better than webrupee.

For colors edit the image as below

    .rupee{
    background-position:left;
    width: 10px; 
    height: 14px;
    background-image: url('rupee.png');
    display:block; 
    background-repeat: no-repeat;
}

Using Apache POI how to read a specific excel column

Please be aware, that iterating through the columns using row cell iterator ( Iterator<Cell> cellIterator = row.cellIterator();) may lead to silent skipping columns. I have just encountered a document that was exposing such behaviour.

Iterating using indexes in a for loop and using row.getCell(i) was not skipping columns and was returning values at the correct column indexes.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Find the process and terminate it. On Windows do a Control+Alt+Delete and then find the "Java(TM) Platform SE Binary" process under the Processes Tab. For example: enter image description here

On Ubuntu, you can use "ps aux | grep java" to find the process and "kill -9 PID_NUMBER" to kill the process.

OR

If you're using a Spring boot application, go to application.properties and add this:

server.port = 8081

How to hide reference counts in VS2013?

I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators or CodeLens, and can be located under

Tools ? Options ? Text Editor ? All Languages ? CodeLens

(for RC/final version)

or

Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators

(for preview version)

That was according to this link. It seems to be pretty well hidden.

In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:

editor options

documented in the Q&A section of the msdn CodeLens documentation

removeEventListener on anonymous functions in JavaScript

A version of Otto Nascarella's solution that works in strict mode is:

button.addEventListener('click', function handler() {
      ///this will execute only once
      alert('only once!');
      this.removeEventListener('click', handler);
});

Filtering array of objects with lodash based on property value

lodash also has a remove method

var myArr = [
    { name: "john", age: 23 },
    { name: "john", age: 43 },
    { name: "jim", age: 101 },
    { name: "bob", age: 67 }
];

var onlyJohn = myArr.remove( person => { return person.name == "john" })

Mockito: InvalidUseOfMatchersException

Do not use Mockito.anyXXXX(). Directly pass the value to the method parameter of same type. Example:

A expected = new A(10);

String firstId = "10w";
String secondId = "20s";
String product = "Test";
String type = "type2";
Mockito.when(service.getTestData(firstId, secondId, product,type)).thenReturn(expected);

public class A{
   int a ;
   public A(int a) {
      this.a = a;
   }
}

How do I exit a WPF application programmatically?

Another way you can do this:

System.Diagnostics.Process.GetCurrentProcess().Kill();

This will force kill your application. It always works, even in a multi-threaded application.

Note: Just be careful not to lose unsaved data in another thread.

Removing elements from an array in C

Try this simple code:

#include <stdio.h>
#include <conio.h>
void main(void)
{ 
    clrscr();
    int a[4], i, b;
    printf("enter nos ");
    for (i = 1; i <= 5; i++) {
        scanf("%d", &a[i]);
    }
    for(i = 1; i <= 5; i++) {
        printf("\n%d", a[i]);
    }
    printf("\nenter element you want to delete ");
    scanf("%d", &b);
    for (i = 1; i <= 5; i++) {
        if(i == b) {
            a[i] = i++;
        }
        printf("\n%d", a[i]);
    }
    getch();
}

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Increase days to php current Date()

a day is 86400 seconds.

$tomorrow = date('y:m:d', time() + 86400);

Searching for UUIDs in text with regex

By definition, a UUID is 32 hexadecimal digits, separated in 5 groups by hyphens, just as you have described. You shouldn't miss any with your regular expression.

http://en.wikipedia.org/wiki/Uuid#Definition

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

Counting unique values in a column in pandas dataframe like in Qlik?

Or get the number of unique values for each column:

df.nunique()

dID    3
hID    5
mID    3
uID    5
dtype: int64

New in pandas 0.20.0 pd.DataFrame.agg

df.agg(['count', 'size', 'nunique'])

         dID  hID  mID  uID
count      8    8    8    8
size       8    8    8    8
nunique    3    5    3    5

You've always been able to do an agg within a groupby. I used stack at the end because I like the presentation better.

df.groupby('mID').agg(['count', 'size', 'nunique']).stack()


             dID  hID  uID
mID                       
A   count      5    5    5
    size       5    5    5
    nunique    3    5    5
B   count      2    2    2
    size       2    2    2
    nunique    2    2    2
C   count      1    1    1
    size       1    1    1
    nunique    1    1    1

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Accessing localhost (xampp) from another computer over LAN network - how to?

Go to xampp-control in the Taskbar

xampp-control -> Apache --> Config --> httpd.conf

Notepad will open with the config file

Search for

Listen 80

One line above it, there will be something like this: 12.34.56:80

Change it

12.34.56:80 --> <your_ip_address eg:192.168.1.5>:80

Restart the apache service and check it, Hopefully it should work...

Android view pager with page indicator

you have to do following:

1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.

After importing if you want to make following type of screen then follow below steps -

Screen Shot

change in

Sample circles Default

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter

 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>

How to convert list to string

L = ['L','O','L']
makeitastring = ''.join(map(str, L))

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

Day Name from Date in JS

I'm not a fan of over-complicated solutions if anyone else comes up with something better, please let us know :)

any-name.js

var today = new Date().toLocaleDateString(undefined, {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    weekday: 'long'
});
any-name.html
<script>
    document.write(today);
</script>

How to convert currentTimeMillis to a date in Java?

Below is my solution to get date from miliseconds to date format. You have to use Joda Library to get this code run.

import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class time {

    public static void main(String args[]){

        String str = "1431601084000";
        long geTime= Long.parseLong(str);
        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
        calendar.setTimeInMillis(geTime);
        DateTime jodaTime = new DateTime(geTime, 
               DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
        DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd");
        System.out.println("Get Time : "+parser1.print(jodaTime));

   }
}

How to handle iframe in Selenium WebDriver using java

Selenium Web Driver Handling Frames
It is impossible to click iframe directly through XPath since it is an iframe. First we have to switch to the frame and then we can click using xpath.

driver.switchTo().frame() has multiple overloads.

  1. driver.switchTo().frame(name_or_id)
    Here your iframe doesn't have id or name, so not for you.

  2. driver.switchTo().frame(index)
    This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)

  3. driver.switchTo().frame(iframe_element)
    The most common one. You locate your iframe like other elements, then pass it into the method.

driver.switchTo().defaultContent(); [parentFrame, defaultContent, frame]

// Based on index position:
int frameIndex = 0;
List<WebElement> listFrames = driver.findElements(By.tagName("iframe"));
System.out.println("list frames   "+listFrames.size());
driver.switchTo().frame(listFrames.get( frameIndex ));

// XPath|CssPath Element:
WebElement frameCSSPath = driver.findElement(By.cssSelector("iframe[title='Fill Quote']"));
WebElement frameXPath = driver.findElement(By.xpath(".//iframe[1]"));
WebElement frameTag = driver.findElement(By.tagName("iframe"));

driver.switchTo().frame( frameCSSPath ); // frameXPath, frameTag


driver.switchTo().frame("relative=up"); // focus to parent frame.
driver.switchTo().defaultContent(); // move to the most parent or main frame

// For alert's
Alert alert = driver.switchTo().alert(); // Switch to alert pop-up
alert.accept();
alert.dismiss();

XML Test:

<html>
    <IFame id='1'>...       parentFrame() « context remains unchanged. <IFame1>
    |
     -> <IFrame id='2'>...  parentFrame() « Change focus to the parent context. <IFame1>
</html>

</html>
<frameset cols="50%,50%">
    <Fame id='11'>...     defaultContent() « driver focus to top window/first frame. <html>
    |
     -> <Frame id='22'>... defaultContent() « driver focus to top window/first frame. <Fame11> 
                           frame("relative=up") « focus to parent frame. <Fame11>
</frameset>
</html>

Conversion of RC to Web-Driver Java commands. link.


<frame> is an HTML element which defines a particular area in which another HTML document can be displayed. A frame should be used within a <frameset>. « Deprecated. Not for use in new websites.

What is the difference between C# and .NET?

C# is a language, .NET is an application framework. The .NET libraries can run on the CLR and thus any language which can run on the CLR can also use the .NET libraries.

If you are familiar with Java, this is similar... Java is a language built on top of the JVM... though any of the pre-assembled Java libraries can be used by another language built on top of the JVM.

What is the difference between HTML tags and elements?

lets put this in a simple term. An element is a set of opening and closing tags in use.

Element

<h1>...</h1>

Tag H1 opening tag

<h1>

H1 closing tag

</h1>

How do I make text bold in HTML?

You're nearly there!

For a bold text, you should have this: <b> bold text</b> or <strong>bold text</strong> They have the same result.

Working example - JSfiddle

window.location (JS) vs header() (PHP) for redirection

A better way to set the location in JS is via:

window.location.href = 'https://stackoverflow.com';

Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.

Implementing autocomplete

I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

How to enable C++11 in Qt Creator?

If you are using an earlier version of QT (<5) try this

QMAKE_CXXFLAGS += -std=c++0x

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

You would need to set DATEFIRST. Take a look at this article. I believe this should help.

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql

Turn a simple socket into an SSL socket

There are several steps when using OpenSSL. You must have an SSL certificate made which can contain the certificate with the private key be sure to specify the exact location of the certificate (this example has it in the root). There are a lot of good tutorials out there.

Some includes:

#include <openssl/applink.c>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

You will need to initialize OpenSSL:

void InitializeSSL()
{
    SSL_load_error_strings();
    SSL_library_init();
    OpenSSL_add_all_algorithms();
}

void DestroySSL()
{
    ERR_free_strings();
    EVP_cleanup();
}

void ShutdownSSL()
{
    SSL_shutdown(cSSL);
    SSL_free(cSSL);
}

Now for the bulk of the functionality. You may want to add a while loop on connections.

int sockfd, newsockfd;
SSL_CTX *sslctx;
SSL *cSSL;

InitializeSSL();
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0)
{
    //Log and Error
    return;
}
struct sockaddr_in saiServerAddress;
bzero((char *) &saiServerAddress, sizeof(saiServerAddress));
saiServerAddress.sin_family = AF_INET;
saiServerAddress.sin_addr.s_addr = serv_addr;
saiServerAddress.sin_port = htons(aPortNumber);

bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

listen(sockfd,5);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

sslctx = SSL_CTX_new( SSLv23_server_method());
SSL_CTX_set_options(sslctx, SSL_OP_SINGLE_DH_USE);
int use_cert = SSL_CTX_use_certificate_file(sslctx, "/serverCertificate.pem" , SSL_FILETYPE_PEM);

int use_prv = SSL_CTX_use_PrivateKey_file(sslctx, "/serverCertificate.pem", SSL_FILETYPE_PEM);

cSSL = SSL_new(sslctx);
SSL_set_fd(cSSL, newsockfd );
//Here is the SSL Accept portion.  Now all reads and writes must use SSL
ssl_err = SSL_accept(cSSL);
if(ssl_err <= 0)
{
    //Error occurred, log and close down ssl
    ShutdownSSL();
}

You are then able read or write using:

SSL_read(cSSL, (char *)charBuffer, nBytesToRead);
SSL_write(cSSL, "Hi :3\n", 6);

Update The SSL_CTX_new should be called with the TLS method that best fits your needs in order to support the newer versions of security, instead of SSLv23_server_method(). See: OpenSSL SSL_CTX_new description

TLS_method(), TLS_server_method(), TLS_client_method(). These are the general-purpose version-flexible SSL/TLS methods. The actual protocol version used will be negotiated to the highest version mutually supported by the client and the server. The supported protocols are SSLv3, TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3.

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

Looking at current hacky solutions in here, I feel I have to describe a proper solution after all.

First, you need to install the cygwin package ca-certificates via Cygwin's setup.exe to get the certificates.

Do NOT use curl or similar hacks to download certificates (as a neighboring answer advices) because that's fundamentally insecure and may compromise the system.

Second, you need to tell wget where your certificates are, since it doesn't pick them up by default in Cygwin environment. If you can do that either with the command-line parameter --ca-directory=/usr/ssl/certs (best for shell scripts) or by adding ca_directory = /usr/ssl/certs to ~/.wgetrc file.

You can also fix that by running ln -sT /usr/ssl /etc/ssl as pointed out in another answer, but that will work only if you have administrative access to the system. Other solutions I described do not require that.

Add item to Listview control

I have done it like this and it seems to work:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
        var listViewItem = new ListViewItem(row); 
        listView1.Items.Add(listViewItem);
    }
}

Opening a .ipynb.txt File

go to cmd get into file directory and type jupyter notebook filename.ipynb in my case it open code editor and provide local host connection string copy that string and paste in any browser!done

Iterating through a golang map

For example,

package main

import "fmt"

func main() {
    type Map1 map[string]interface{}
    type Map2 map[string]int
    m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
    //m = map[foo:map[first: 1] boo: map[second: 2]]
    fmt.Println("m:", m)
    for k, v := range m {
        fmt.Println("k:", k, "v:", v)
    }
}

Output:

m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]

Calling a Variable from another Class

I would suggest to use a variable instead of a public field:

public class Variables
{
   private static string name = "";

   public static string Name
   { 
        get { return name; }
        set { name = value; }

   }
}

From another class, you call your variable like this:

public class Main
{
    public void DoSomething()
    {
         string var = Variables.Name;
    }
}

Using Mockito to test abstract classes

If you just need to test some of the concrete methods without touching any of the abstracts, you can use CALLS_REAL_METHODS (see Morten's answer), but if the concrete method under test calls some of the abstracts, or unimplemented interface methods, this won't work -- Mockito will complain "Cannot call real method on java interface."

(Yes, it's a lousy design, but some frameworks, e.g. Tapestry 4, kind of force it on you.)

The workaround is to reverse this approach -- use the ordinary mock behavior (i.e., everything's mocked/stubbed) and use doCallRealMethod() to explicitly call out the concrete method under test. E.g.

public abstract class MyClass {
    @SomeDependencyInjectionOrSomething
    public abstract MyDependency getDependency();

    public void myMethod() {
        MyDependency dep = getDependency();
        dep.doSomething();
    }
}

public class MyClassTest {
    @Test
    public void myMethodDoesSomethingWithDependency() {
        MyDependency theDependency = mock(MyDependency.class);

        MyClass myInstance = mock(MyClass.class);

        // can't do this with CALLS_REAL_METHODS
        when(myInstance.getDependency()).thenReturn(theDependency);

        doCallRealMethod().when(myInstance).myMethod();
        myInstance.myMethod();

        verify(theDependency, times(1)).doSomething();
    }
}

Updated to add:

For non-void methods, you'll need to use thenCallRealMethod() instead, e.g.:

when(myInstance.myNonVoidMethod(someArgument)).thenCallRealMethod();

Otherwise Mockito will complain "Unfinished stubbing detected."

How to get the path of the batch script in Windows?

I am working on a Windows 7 machine and I have ended up using the lines below to get the absolute folder path for my bash script.

I got to this solution after looking at http://www.linuxjournal.com/content/bash-parameter-expansion.

#Get the full aboslute filename.
filename=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder

How to set image on QPushButton?

QPushButton *button = new QPushButton;
button->setIcon(QIcon(":/icons/..."));
button->setIconSize(QSize(65, 65));

CSS: how do I create a gap between rows in a table?

In my opinion, the easiest way to do is adding padding to your tag.

td {
 padding: 10px 0
}

Hope this will help you! Cheer!

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

In Visual Studio 2019 below are the steps:

  1. Create webform1.aspx
  2. Copy your aspx code and paste in webform1.aspx
  3. Compile your project you should have designer code inside webform1.aspx.designer.cs
  4. Now you can copy designer code and use in your original webform.

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

https://reactjs.org/docs/composition-vs-inheritance.html

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />
  )
}

const Child = ({ componentToPassDown }) => { 
  return (
    <>
     {componentToPassDown}  
    </>
  )
}

Spring RequestMapping for controllers that produce and consume JSON

As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping as a meta-annotation. So:

Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:

@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

Yes, there is such a way. You can create a meta annotation like following:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "method")
    RequestMethod[] method() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "params")
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "headers")
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "consumes")
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "produces")
    String[] produces() default {};
}

Then you can use the default settings or even override them as you want:

@JsonRequestMapping(method = POST)
public String defaultSettings() {
    return "Default settings";
}

@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
    return json;
}

You can read more about AliasFor in spring's javadoc and github wiki.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

There seem to be many things that cause this. For me it was a lowercase rewrite rule in IIS. Changed the problem files (js and png) to lowercase and problem went away.

How do I compare a value to a backslash?

Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.

Code-

if (len(s)<=3):
    return s
elif s[-3:]=="ing":
    return s+"ly"
else: return s + "ing"

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

Finding elements not in a list

Using list comprehension:

print [x for x in item if x not in Z]

or using filter function :

filter(lambda x: x not in Z, item)

Using set in any form may create a bug if the list being checked contains non-unique elements, e.g.:

print item

Out[39]: [0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print Z

Out[40]: [3, 4, 5, 6]

set(item) - set(Z)

Out[41]: {0, 1, 2, 7, 8, 9}

vs list comprehension as above

print [x for x in item if x not in Z]

Out[38]: [0, 1, 1, 2, 7, 8, 9]

or filter function:

filter(lambda x: x not in Z, item)

Out[38]: [0, 1, 1, 2, 7, 8, 9]

vagrant login as root by default

Note: Only use this method for local development, it's not secure. You can setup password and ssh config while provisioning the box. For example with debian/stretch64 box this is my provision script:

config.vm.provision "shell", inline: <<-SHELL
    echo -e "vagrant\nvagrant" | passwd root
    echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
    sed -in 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
    service ssh restart
SHELL

This will set root password to vagrant and permit root login with password. If you are using private_network say with ip address 192.168.10.37 then you can ssh with ssh [email protected]

You may need to change that echo and sed commands depending on the default sshd_config file.

javascript if number greater than number

You're comparing strings. JavaScript compares the ASCII code for each character of the string.

To see why you get false, look at the charCodes:

"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57

The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.

The fix is to treat the strings as numbers. You can use a number of methods:

parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes


+"1300"
> 1300


Number("1300")
> 1300

JavaScript blob filename without link

Late, but since I had the same problem I add my solution:

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);
        window.location.assign(exportUrl);
        URL.revokeObjectURL(exportUrl);
    }
}

Properties file in python (similar to Java Properties)

This is a one-to-one replacement of java.util.Propeties

From the doc:

  def __parse(self, lines):
        """ Parse a list of lines and create
        an internal property dictionary """

        # Every line in the file must consist of either a comment
        # or a key-value pair. A key-value pair is a line consisting
        # of a key which is a combination of non-white space characters
        # The separator character between key-value pairs is a '=',
        # ':' or a whitespace character not including the newline.
        # If the '=' or ':' characters are found, in the line, even
        # keys containing whitespace chars are allowed.

        # A line with only a key according to the rules above is also
        # fine. In such case, the value is considered as the empty string.
        # In order to include characters '=' or ':' in a key or value,
        # they have to be properly escaped using the backslash character.

        # Some examples of valid key-value pairs:
        #
        # key     value
        # key=value
        # key:value
        # key     value1,value2,value3
        # key     value1,value2,value3 \
        #         value4, value5
        # key
        # This key= this value
        # key = value1 value2 value3

        # Any line that starts with a '#' is considerered a comment
        # and skipped. Also any trailing or preceding whitespaces
        # are removed from the key/value.

        # This is a line parser. It parses the
        # contents like by line.

Powershell: How can I stop errors from being displayed in a script?

In some cases you can pipe after the command a Out-Null

command | Out-Null

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

Is there something like Codecademy for Java

Check out javapassion, they have a number of courses that encompass web programming, and were free (until circumstances conspired to make the website need to support itself).

Even with the nominal fee, you get a lot for an entire year. It's a bargain compared to the amount of time you'll be investing.

The other options are to look to Oracle's online tutorials, they lack the glitz of Codeacademy, but are surprisingly good. I haven't read the one on web programming, that might be embedded in the Java EE tutorial(s), which is not tuned for a new beginner to Java.

Android LinearLayout Gradient Background

I would check your alpha channel on your gradient colors. For me, when I was testing my code out I had the alpha channel set wrong on the colors and it did not work for me. Once I got the alpha channel set it all worked!

how to define ssh private key for servers fetched by dynamic inventory in files

You can simply define the key to use directly when running the command:

ansible-playbook \
        \ # Super verbose output incl. SSH-Details:
    -vvvv \
        \ # The Server to target: (Keep the trailing comma!)
    -i "000.000.0.000," \
        \ # Define the key to use:
    --private-key=~/.ssh/id_rsa_ansible \
        \ # The `env` var is needed if `python` is not available:
    -e 'ansible_python_interpreter=/usr/bin/python3' \ # Needed if `python` is not available
        \ # Dry–Run:
    --check \
    deploy.yml

Copy/ Paste:

ansible-playbook -vvvv --private-key=/Users/you/.ssh/your_key deploy.yml

How do I create an Android Spinner as a popup?

Try this:

Spinner popupSpinner = new Spinner(context, Spinner.MODE_DIALOG);

See this link for more details.

In Chrome 55, prevent showing Download button for HTML 5 video

May be the best way to utilize "download" button is to use JavaScript players, such as Videojs (http://docs.videojs.com/) or MediaElement.js (http://www.mediaelementjs.com/)

They do not have download button by default as a rule and moreover allow you to customize visible control buttons of the player.

Scroll part of content in fixed position container

Set the scrollable div to have a max-size and add overflow-y: scroll; to it's properties.

Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.

How do I call ::CreateProcess in c++ to launch a Windows executable?

There is an example at http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx

Just replace the argv[1] with your constant or variable containing the program.

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

C++ program converts fahrenheit to celsius

The answer has already been found although I would also like to share my answer:

int main(void)
{
using namespace std;

short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;

}

int convert(short nT)
{
return nT * 1.8 + 32;
}

This is a more proper way to do this; however, it is slightly more complex then what you were going for.

Suppress console output in PowerShell

It is a duplicate of this question, with an answer that contains a time measurement of the different methods.

Conclusion: Use [void] or > $null.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

datetimepicker is not a function jquery

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

Running an Excel macro via Python?

I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:

#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl

def runMacro():

    if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):

    # DispatchEx is required in the newest versions of Python.
    excel_macro = wincl.DispatchEx("Excel.application")
    excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
    workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
    excel_macro.Application.Run\
        ("ThisWorkbook.Template2G")
    #Save the results in case you have generated data
    workbook.Save()
    excel_macro.Application.Quit()  
    del excel_macro

How to control the line spacing in UILabel

SWIFT 3 useful extension for set space between lines more easily :)

extension UILabel
{
    func setLineHeight(lineHeight: CGFloat)
    {
        let text = self.text
        if let text = text 
        {

            let attributeString = NSMutableAttributedString(string: text)
            let style = NSMutableParagraphStyle()

           style.lineSpacing = lineHeight
           attributeString.addAttribute(NSParagraphStyleAttributeName,
                                        value: style,
                                        range: NSMakeRange(0, text.characters.count))

           self.attributedText = attributeString
        }
    }
}

Make Div Draggable using CSS

You can take a look at HTML 5, but I don't think you can restrict the area within you can drag it, just the destination:

http://www.w3schools.com/html/html5_draganddrop.asp

And if you don't mind using some great library, I would encourage you to try Dragula.

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

How to create a label inside an <input> element?

use this

style:

<style type="text/css">
    .defaultLabel_on { color:#0F0; }
    .defaultLabel_off { color:#CCC; }
</style>

html:

javascript:

function defaultLabelClean() {
    inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)  {
        if (inputs[i].value == inputs[i].getAttribute("innerLabel")) {
            inputs[i].value = '';
        }
    }
}

function defaultLabelAttachEvents(element, label) {
    element.setAttribute("innerLabel", label);
    element.onfocus = function(e) {
        if (this.value==label) {
            this.className = 'defaultLabel_on';
            this.value = '';
        }
    }
    element.onblur = function(e) {
        if (this.value=='') {
            this.className = 'defaultLabel_off';
            this.value = element.getAttribute("innerLabel");
        }
    }

    if (element.value=='') {
        element.className = 'defaultLabel_off';
        element.value = element.getAttribute("innerLabel");
    }
}


defaultLabelAttachEvents(document.getElementById('MYID'), "MYLABEL");

Just remember to call defaultLabelClean() function before submit form.

good work

How to get the first word in the string

If you want to feel especially sly, you can write it as this:

(firstWord, rest) = yourLine.split(maxsplit=1)

This is supposed to bring the best from both worlds:

I kind of fell in love with this solution and it's general unpacking capability, so I had to share it.

Grant SELECT on multiple tables oracle

You can do it with dynamic query, just run the following script in pl-sql or sqlplus:

select 'grant select on user_name_owner.'||table_name|| 'to user_name1 ;' from dba_tables t where t.owner='user_name_owner'

and then execute result.

How can I reload .emacs after changing it?

Here is a quick and easy way to quick test your config. You can also use C-x C-e at the end of specific lisp to execute certain function individually.

C-x C-e runs the command eval-last-sexp (found in global-map), which is an interactive compiled Lisp function.

It is bound to C-x C-e.

(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)

Evaluate sexp before point; print value in the echo area. Interactively, with prefix argument, print output into current buffer.

Normally, this function truncates long output according to the value of the variables ‘eval-expression-print-length’ and ‘eval-expression-print-level’. With a prefix argument of zero, however, there is no such truncation. Such a prefix argument also causes integers to be printed in several additional formats (octal, hexadecimal, and character).

If ‘eval-expression-debug-on-error’ is non-nil, which is the default, this command arranges for all errors to enter the debugger.

SQL: Insert all records from one table to another table without specific the columns

You should not ever want to do this. Select * should not be used as the basis for an insert as the columns may get moved around and break your insert (or worse not break your insert but mess up your data. Suppose someone adds a column to the table in the select but not the other table, you code will break. Or suppose someone, for reasons that surpass understanding but frequently happen, decides to do a drop and recreate on a table and move the columns around to a different order. Now your last_name is is the place first_name was in originally and select * will put it in the wrong column in the other table. It is an extremely poor practice to fail to specify columns and the specific mapping of one column to the column you want in the table you are interested in.

Right now you may have several problems, first the two structures don't match directly or second the table being inserted to has an identity column and so even though the insertable columns are a direct match, the table being inserted to has one more column than the other and by not specifying the database assumes you are going to try to insert to that column. Or you might have the same number of columns but one is an identity and thus can't be inserted into (although I think that would be a different error message).

How to semantically add heading to a list

a <div> is a logical division in your content, semantically this would be my first choice if I wanted to group the heading with the list:

<div class="mydiv">
    <h3>The heading</h3>
    <ul>
       <li>item</li>
       <li>item</li>
       <li>item</li>
    </ul>
</div>

then you can use the following css to style everything together as one unit

.mydiv{}
.mydiv h3{}
.mydiv ul{}
.mydiv ul li{}
etc...

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

Replace Multiple String Elements in C#

string input = "it's worth a lot of money, if you can find a buyer.";
for (dynamic i = 0, repl = new string[,] { { "'", "''" }, { "money", "$" }, { "find", "locate" } }; i < repl.Length / 2; i++) {
    input = input.Replace(repl[i, 0], repl[i, 1]);
}

Symfony - generate url with parameter in controller

make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;

you should also check app/console debug:router in terminal to see what name symfony has named the route

in my case it used a minus instead of an underscore

i.e blog-show

$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);

Specifying number of decimal places in Python

This standard library solution likely has not been mentioned because the question is so dated. While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.

I recommend you use the standard library locale.currency object. It seems to have been created to address this problem of currency representation.

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'

locale.currency(mealPrice)

Currency generalizes to other countries as well.

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

Your not applying Date formator. rather you are just parsing the date. to get output in this format

yyyy-MM-dd HH:mm:ss.SSSSSS

we have to use format() method here is full example:- Here is full example:- it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {

public static void main(String args[]) throws ParseException {

    SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
     Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");  
    System.out.println(thisDate);
    System.out.println("----------------------------"); 
    System.out.println("After applying formating :");
    String strDateOutput = changeFormat.format(temp);
    System.out.println(strDateOutput);

}

}

Working example screen

How do I find the caller of a method using stacktrace or reflection?

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

According to the Javadocs:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to experiment to determine which index you want (probably stackTraceElements[1] or [2]).

How can I submit a form using JavaScript?

You can use the below code to submit the form using JavaScript:

document.getElementById('FormID').submit();

SQL LIKE condition to check for integer?

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?' 

This will match a title starting with one or more digits and an optional space

Explain ggplot2 warning: "Removed k rows containing missing values"

Just for the shake of completing the answer given by eipi10.

I was facing the same problem, without using scale_y_continuous nor coord_cartesian.

The conflict was coming from the x axis, where I defined limits = c(1, 30). It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error

Removed 8 rows containing missing values (geom_bar)

Adjusting the limits of the x axis to limits = c(0, 31) solved the problem.

In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space

How do I initialize a dictionary of empty lists in Python?

Use defaultdict instead:

from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way you don't have to initialize all the keys you want to use to lists beforehand.

What is happening in your example is that you use one (mutable) list:

alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data

would output {0: [1, 2], 1: [1, 2]}.

Use JavaScript to place cursor at end of text in text input element

This problem is interesting. The most confusing thing about it is that no solution I found solved the problem completely.

+++++++ SOLUTION +++++++

  1. You need a JS function, like this:

    function moveCursorToEnd(obj) {
    
      if (!(obj.updating)) {
        obj.updating = true;
        var oldValue = obj.value;
        obj.value = '';
        setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
      }
    
    }
    
  2. You need to call this guy in the onfocus and onclick events.

    <input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this)">
    

IT WORKS ON ALL DEVICES AN BROWSERS!!!!

C Program to find day of week given date

#include<stdio.h>
static char day_tab[2][13] = {
        {0,31,28,31,30,31,30,31,31,30,31,30,31},
        {0,31,29,31,30,31,30,31,31,30,31,30,31}
        };
int main()
{
     int year,month;
     scanf("%d%d%d",&year,&month,&day);
     printf("%d\n",day_of_year(year,month,day));
     return 0;
}
int day_of_year(int year ,int month,int day)
{
        int i,leap;
        leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
        if(month < 1 || month >12)
        return -1;
        if (day <1 || day > day_tab[leap][month])
        return -1;
        for(i= 1;i<month ; i++)
        {
                day += day_tab[leap][year];
        }
        return day;
}

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How can I get the current time in C#?

DateTime.Now is what you're searching for...

Is there a way to create key-value pairs in Bash script?

If you can use a simple delimiter, a very simple oneliner is this:

for i in a,b c_s,d ; do 
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Hereby i is filled with character sequences like "a,b" and "c_s,d". each separated by spaces. After the do we use parameter substitution to extract the part before the comma , and the part after it.

Remove property for all objects in array

You can follow this, more readable, not expectation raise due to key not found :

data.map((datum)=>{
                    return {
                        'id':datum.id,
                        'title':datum.login,
                    }

Check if string ends with certain pattern

This is really simple, the String object has an endsWith method.

From your question it seems like you want either /, , or . as the delimiter set.

So:

String str = "This.is.a.great.place.to.work.";

if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
     // ... 

You can also do this with the matches method and a fairly simple regex:

if (str.matches(".*([.,/])work\\1$"))

Using the character class [.,/] specifying either a period, a slash, or a comma, and a backreference, \1 that matches whichever of the alternates were found, if any.

Pandas: Return Hour from Datetime Column Directly

For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour!

linux execute command remotely

I think this article explains well:

Running Commands on a Remote Linux / UNIX Host

Google is your best friend ;-)

log4net vs. Nlog

A key consideration that hasn't been much discussed is support and updates.

Log4Net hasn't been updated since version 1.2.10 was published April 19, 2006.

In contrast, NLog has been actively supported since 2006 will soon release NLog 2.0 supporting many platforms that didn't exist when log4net was last updated such as:

  • NET Framework 2.0 SP1 and above, 3.5 & 4.0 (Client and Extended profiles)
  • Silverlight 2.0, 3.0, 4.0
  • .NET Compact Framework 2.0, 3.5
  • Mono 2.x profile

ADB not recognising Nexus 4 under Windows 7

To enable USB debugging, go to settings, about phone and then at the bottom tap build number seven times. This will enable the developer settings where you can enable USB debugging.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

How can I return the current action in an ASP.NET MVC view?

In MVC you should provide the View with all data, not let the View collect its own data so what you can do is to set the CSS class in your controller action.

ViewData["CssClass"] = "bold";

and pick out this value from your ViewData in your View

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

Is there an XSL "contains" directive?

It should be something like...

<xsl:if test="contains($hhref, '1234')">

(not tested)

See w3schools (always a good reference BTW)

Detect & Record Audio in Python

You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.

How can I format the output of a bash command in neat columns

Since AIX doesn't have a "column" command, I created the simplistic script below. It would be even shorter without the doc & input edits... :)

#!/usr/bin/perl
#       column.pl: convert STDIN to multiple columns on STDOUT
#       Usage: column.pl column-width number-of-columns  file...
#
$width = shift;
($width ne '') or die "must give column-width and number-of-columns\n";
$columns = shift;
($columns ne '') or die "must give number-of-columns\n";
($x = $width) =~ s/[^0-9]//g;
($x eq $width) or die "invalid column-width: $width\n";
($x = $columns) =~ s/[^0-9]//g;
($x eq $columns) or die "invalid number-of-columns: $columns\n";

$w = $width * -1; $c = $columns;
while (<>) {
        chomp;
        if ( $c-- > 1 ) {
                printf "%${w}s", $_;
                next;
        }
        $c = $columns;
        printf "%${w}s\n", $_;
}
print "\n";

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

You should write textcolor in xml as

android:textColor="@color/text_color"

or

android:textColor="#FFFFFF"

CSS transition fade in

I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS

div {
  opacity:0;
  transition:opacity 1s linear;*
}
div.SomeClass {
  opacity:1;
}

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

How to reset the use/password of jenkins on windows?

You can try to re-set your Jenkins security:

  1. Stop the Jenkins service
  2. Open the config.xml with a text editor (i.e notepad++), maybe be in C:\jenkins\config.xml (could backup it also).
  3. Find this <useSecurity>true</useSecurity> and change it to <useSecurity>false</useSecurity>
  4. Start Jenkins service

You might create an admin user and enable security again.

How to install CocoaPods?

On macOS Mojave with Xcode 10.3, I got scary warnings from the gem route with or without -n /usr/local/bin:

xcodeproj's executable "xcodeproj" conflicts with /usr/local/bin/xcodeproj
Overwrite the executable? [yN] 

What works for me is still Homebrew, just

brew install cocoapods

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I use both windows and linux, but the solution core.autocrlf true didn't help me. I even got nothing changed after git checkout <filename>.

So I use workaround to substitute git status - gitstatus.sh

#!/bin/bash

git status | grep modified | cut -d' ' -f 4 | while read x; do
 x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
 x2="$(cat $x | md5sum | cut -d' ' -f 1 )"

 if [ "$x1" != "$x2" ]; then
    echo "$x NOT IDENTICAL"
 fi
done

I just compare md5sum of a file and its brother at repository.

Example output:

$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL

How to convert an image to base64 encoding?

Very simple and to be commonly used:

function getDataURI($imagePath) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($imagePath);
    return 'data:'.$type.';base64,'.base64_encode(file_get_contents($imagePath));
}

//Use the above function like below:
echo '<img src="'.getDataURI('./images/my-file.svg').'" alt="">';
echo '<img src="'.getDataURI('./images/my-file.png').'" alt="">';

Note: The Mime-Type of the file will be added automatically (taking help from this PHP documentation).

Unable to compile simple Java 10 / Java 11 project with Maven

If you are using spring boot then add these tags in pom.xml.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

and

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    `<maven.compiler.release>`10</maven.compiler.release>
</properties>

You can change java version to 11 or 13 as well in <maven.compiler.release> tag.

Just add below tags in pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.release>11</maven.compiler.release>
</properties>

You can change the 11 to 10, 13 as well to change java version. I am using java 13 which is latest. It works for me.

"Logging out" of phpMyAdmin?

The second button from the left. The one on the right of the house in the image you posted is your logout button.

For your error message try this link in the documentation: http://wiki.phpmyadmin.net/pma/Configuration_storage

Make certain you have a phpadmin control user account created. This is covered in the second paragraph in on the documentation page in the link.