Programs & Examples On #Win32com

win32com is a Python module to interact with Windows COM components.

ImportError: No module named win32com.client

in some cases where pywin32 is not the direct reference and other libraries require pywin32-ctypes to be installed; causes the "ImportError: No module named win32com" when application bundled with pyinstaller.

running following command solves on python 3.7 - pyinstaller 3.6

pip install pywin32==227

Can a java lambda have more than 1 parameter?

For something with 2 parameters, you could use BiFunction. If you need more, you can define your own function interface, like so:

@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
    public R apply(T t, U u, V v, W w);
}

If there is more than one parameter, you need to put parentheses around the argument list, like so:

FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
    // do something
    return "done something";
};

Access elements in json object like an array

I noticed a couple of syntax errors, but other than that, it should work fine:

var arr = [
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har."], //<- syntax error here
  ["57.586174","16.521841"], ["57.893162","16.406090"]
];


console.log(arr[4]);    //["57.893162","16.406090"]
console.log(arr[4][0]); //57.893162

Is there a command for formatting HTML in the Atom editor?

  1. Go to "Packages" in atom editor.
  2. Then in "Packages" view choose "Settings View".
  3. Choose "Install Packages/Themes".
  4. Search for "Atom Beautify" and install it.

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Since late 2012, it is usually under /usr/share/tomcat7.

Prior to that, it was usually found under /opt/tomcat7.

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

Entity Framework Refresh context?

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

Comparing strings in C# with OR in an if statement

use if (testString.Equals(testString2)).

What are the basic rules and idioms for operator overloading?

The General Syntax of operator overloading in C++

You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.

Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: . :: sizeof typeid .* and the only ternary operator in C++, ?:

Among the operators that can be overloaded in C++ are these:

  • arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
  • bit manipulation: & | ^ << >> and &= |= ^= <<= >>= (all binary infix); ~ (unary prefix)
  • boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
  • memory management: new new[] delete delete[]
  • implicit conversion operators
  • miscellany: = [] -> ->* , (all binary infix); * & (all unary prefix) () (function call, n-ary infix)

However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.

In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @3, applied to an object x, is invoked either as operator@(x) or as x.operator@(). A binary infix operator @, applied to the objects x and y, is called either as operator@(x,y) or as x.operator@(y).4

Operators that are implemented as non-member functions are sometimes friend of their operand’s type.

1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.

2 This is covered in a later part of this FAQ.

3 The @ is not a valid operator in C++ which is why I use it as a placeholder.

4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.


Continue to The Three Basic Rules of Operator Overloading in C++.

How can I force gradle to redownload dependencies?

Deleting all the caches makes download all the dependacies again. so it take so long time and it is boring thing wait again again to re download all the dependancies.

How ever i could be able to resolve this below way.

Just delete groups which need to be refreshed.

Ex : if we want to refresh com.user.test group

rm -fr ~/.gradle/caches/modules-2/files-2.1/com.user.test/

then remove dependency from build.gradle and re add it. then it will refresh dependencies what we want.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Since .NET 4.5 the Validators use data-attributes and bounded Javascript to do the validation work, so .NET expects you to add a script reference for jQuery.

There are two possible ways to solve the error:


Disable UnobtrusiveValidationMode:

Add this to web.config:

<configuration>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
</configuration>

It will work as it worked in previous .NET versions and will just add the necessary Javascript to your page to make the validators work, instead of looking for the code in your jQuery file. This is the common solution actually.


Another solution is to register the script:

In Global.asax Application_Start add mapping to your jQuery file path:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition
    {
        Path = "~/scripts/jquery-1.7.2.min.js",
        DebugPath = "~/scripts/jquery-1.7.2.js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
    });
}

Some details from MSDN:

ValidationSettings:UnobtrusiveValidationMode Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic.

If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

Chrome Dev Tools - Modify javascript and reload

The Resource Override extension allows you to do exactly that:

  • create a file rule for the url you want to replace
  • edit the js/css/etc in the extension
  • reload as often as you want :)

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

How do you clear the SQL Server transaction log?

Try this:

USE DatabaseName

GO

DBCC SHRINKFILE( TransactionLogName, 1)

BACKUP LOG DatabaseName WITH TRUNCATE_ONLY

DBCC SHRINKFILE( TransactionLogName, 1)

GO 

how to rotate text left 90 degree and cell size is adjusted according to text in html

Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.

Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).

enter image description here

By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.

_x000D_
_x000D_
td {_x000D_
    border: 1px black solid;_x000D_
    padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
     -moz-transform: rotate(-90.0deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(-90.0deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(-90.0deg);  /* Saf3.1+, Chrome */_x000D_
             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
         margin-left: -10em;_x000D_
         margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
</table>
_x000D_
_x000D_
_x000D_

One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.

Have fun playing around with this on jsFiddle.

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

How do I set <table> border width with CSS?

Doing borders on tables with css is a bit more complicated (but not as much, see this jsfiddle as example):

_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
table td {_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>test</td>_x000D_
    <td>test</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

What is the difference between server side cookie and client side cookie?

What is the difference between creating cookies on the server and on the client?

What you are referring to are the 2 ways in which cookies can be directed to be set on the client, which are:

  • By server
  • By client ( browser in most cases )

By server: The Set-cookie response header from the server directs the client to set a cookie on that particular domain. The implementation to actually create and store the cookie lies in the browser. For subsequent requests to the same domain, the browser automatically sets the Cookie request header for each request, thereby letting the server have some state to an otherwise stateless HTTP protocol. The Domain and Path cookie attributes are used by the browser to determine which cookies are to be sent to a server. The server only receives name=value pairs, and nothing more.

By Client: One can create a cookie on the browser using document.cookie = cookiename=cookievalue. However, if the server does not intend to respond to any random cookie a user creates, then such a cookie serves no purpose.

Are these called server side cookies and client side cookies?

Cookies always belong to the client. There is no such thing as server side cookie.

Is there a way to create cookies that can only be read on the server or on the client?

Since reading cookie values are upto the server and client, it depends if either one needs to read the cookie at all. On the client side, by setting the HttpOnly attribute of the cookie, it is possible to prevent scripts ( mostly Javscript ) from reading your cookies , thereby acting as a defence mechanism against Cookie theft through XSS, but sends the cookie to the intended server only.

Therefore, in most of the cases since cookies are used to bring 'state' ( memory of past user events ), creating cookies on client side does not add much value, unless one is aware of the cookies the server uses / responds to.

References: Wikipedia

python inserting variable string as file name

Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')

Another option - the f-string formatting (ref):

f = open(f"{name}.csv", 'wb') 

What does "-ne" mean in bash?

This is one of those things that can be difficult to search for if you don't already know where to look.

[ is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.

There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.

[ is equivalent to the test command, except that [ requires ] as its last argument, and test does not.

Assuming the bash documentation is installed on your system, if you type info bash and search for 'test' or '[' (the apostrophes are part of the search), you'll find the documentation for the [ command, also known as the test command. If you use man bash instead of info bash, search for ^ *test (the word test at the beginning of a line, following some number of spaces).

Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, != is the string inequality operator.

You can also find bash documentation on the web.

The official definition of the test command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).

Excel: last character/string match in a string

How about creating a custom function and using that in your formula? VBA has a built-in function, InStrRev, that does exactly what you're looking for.

Put this in a new module:

Function RSearch(str As String, find As String)
    RSearch = InStrRev(str, find)
End Function

And your function will look like this (assuming the original string is in B1):

=LEFT(B1,RSearch(B1,"\"))

How to enable scrolling on website that disabled scrolling?

Try this:

window.onmousewheel = document.onmousewheel = null
window.ontouchmove = null 
window.onwheel = null 

What is the difference between C++ and Visual C++?

VC++ is not actually a language but is commonly referred to like one. When VC++ is referred to as a language, it usually means Microsoft's implementation of C++, which contains various knacks that do not exist in regular C++, such as the __super keyword. It is similar to the various GNU extensions to the C language that are implemented in GCC.

Git: copy all files in a directory from another branch

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

git checkout master -- dirname

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

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

Density conversion factor for density buckets are as follows:

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

Examples of resolution/density conversion to DP:

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

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

This image show more:

Density

For more details about DIP read here.

Export database schema into SQL file

enter image description here

In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data

javac: file not found: first.java Usage: javac <options> <source files>

Sometimes this issue occurs, If you are creating a java file for the first time in your system. The Extension of your Java file gets saved as the text file.

e.g Example.java.txt (wrong extension)

You need to change the text file extension to java file.

It should be like:

Example.java (right extension)

@class vs. #import

Use a forward declaration in the header file if needed, and #import the header files for any classes you're using in the implementation. In other words, you always #import the files you're using in your implementation, and if you need to reference a class in your header file use a forward declaration as well.

The exception to this is that you should #import a class or formal protocol you're inheriting from in your header file (in which case you wouldn't need to import it in the implementation).

CSS file not refreshing in browser

The reason this occurs is because the file is stored in the "cache" of the browser – so there is no need for the browser to request the sheet again. This occurs for most files that your HTML links to – whether they're CDNs or on your server, for example, a stylesheet. A hard refresh will reload the page and send new GET requests to the server (and to external b if needed).

You can also empty the caches in most browsers with the following keyboard shortcuts.

Safari: Cmd+Alt+e

Chrome and Edge: Shift+Cmd+Delete (Mac) and Ctrl+Shift+Del (Windows)

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

Gson library in Android Studio

Add following dependency or download Gson jar file

implementation 'com.google.code.gson:gson:2.8.6'

Follow github repo for documentation and more.

Which Eclipse version should I use for an Android app?

Released in June 2012, Eclipse for Mobile Developers is an awesome starting point for developers looking to focus on Android development. I've used it for several projects since August and haven't been disappointed.

How to install pywin32 module in windows 7

I disagree with the accepted answer being "the easiest", particularly if you want to use virtualenv.

You can use the Unofficial Windows Binaries instead. Download the appropriate wheel from there, and install it with pip:

pip install pywin32-219-cp27-none-win32.whl

(Make sure you pick the one for the right version and bitness of Python).

You might be able to get the URL and install it via pip without downloading it first, but they're made it a bit harder to just grab the URL. Probably better to download it and host it somewhere yourself.

Disabling the button after once click

protected void Page_Load(object sender, EventArgs e)
    {
        // prevent user from making operation twice
        btnSave.Attributes.Add("onclick", 
                               "this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");

        // ... etc. 
    }

How to get the html of a div on another page with jQuery ajax?

Ok, You should "construct" the html and find the .content div.

like this:

$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html($(data).find('#content').html());
   }
});

Simple!

how can I enable PHP Extension intl?

You can find the answer here: http://www.dorusomcutean.com/how-to-install-php-7-2-on-windows/

In that blog post, I'm showing how to install PHP on Windows and how to enable extensions. Hope that it helps anyone who encounters this problem again.

Quicksort: Choosing the pivot

If you are sorting a random-accessible collection (like an array), it's general best to pick the physical middle item. With this, if the array is all ready sorted (or nearly sorted), the two partitions will be close to even, and you'll get the best speed.

If you are sorting something with only linear access (like a linked-list), then it's best to choose the first item, because it's the fastest item to access. Here, however,if the list is already sorted, you're screwed -- one partition will always be null, and the other have everything, producing the worst time.

However, for a linked-list, picking anything besides the first, will just make matters worse. It pick the middle item in a listed-list, you'd have to step through it on each partition step -- adding a O(N/2) operation which is done logN times making total time O(1.5 N *log N) and that's if we know how long the list is before we start -- usually we don't so we'd have to step all the way through to count them, then step half-way through to find the middle, then step through a third time to do the actual partition: O(2.5N * log N)

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

async await return Task

You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:

public async Task<object> MethodName()
{
    return await Task.FromResult<object>(null);
}

Here is an example with no return value:

public async Task MethodName()
{
    await Task.CompletedTask;
}

Read these:

TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx

Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx

text box input height

Use CSS:

<input type="text" class="bigText"  name=" item" align="left" />

.bigText {
    height:30px;
}

Dreamweaver is a poor testing tool. It is not a browser.

Display html text in uitextview

For Swift3

    let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"

    let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)

    UITextView_Message.attributedText = theAttributedString

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

how to change the default positioning of modal in bootstrap?

I get a better result setting this class:

.modal-dialog {
  position: absolute;
  top: 50px;
  right: 100px;
  bottom: 0;
  left: 0;
  z-index: 10040;
  overflow: auto;
  overflow-y: auto;
}

With bootstrap 3.3.7.

(all credits to msnfreaky for the idea...)

APT command line interface-like yes/no input?

One-liner with Python 3.8 and above:

while res:= input("When correct, press enter to continue...").lower() not in {'y','yes','Y','YES',''}: pass

What is a practical, real world example of the Linked List?

I'm assuming you want a more metaphorical explanation than the book definition, instead of examples of how you could use a linked list.

A linked list is kind of like a scavenger hunt. You have a clue, and that clue has a pointer to place to find the next clue. So you go to the next place and get another piece of data, and another pointer. To get something in the middle, or at the end, the only way to get to it is to follow this list from the beginning (or to cheat ;) )

Changing nav-bar color after scrolling?

Check jquery waypoints here

Fiddle for example JSFiddle

When is scrolled to certain div, change your background color in jquery.

MVC 4 client side validation not working

I had an issue with validation, the form posts then it validates,

This Doesn't work with jquery cdn

    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

This Works without jquery cdn

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Hope helps someone.

Maven: add a dependency to a jar by relative path

I've previously written about a pattern for doing this.

It is very similar to the solution proposed by Pascal, though it moves all such dependencies into a dedicated repository module so that you don't have to repeat it everywhere the dependency is used if it is a multi-module build.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

ORA-01008: not all variables bound. They are bound

The solution in my situation was similar answer to Charles Burns; and the problem was related to SQL code comments.

I was building (or updating, rather) an already-functioning SSRS report with Oracle datasource. I added some more parameters to the report, tested it in Visual Studio, it works great, so I deployed it to the report server, and then when the report is executed the report on the server I got the error message:

"ORA-01008: not all variables bound"

I tried quite a few different things (TNSNames.ora file installed on the server, Removed single line comments, Validate dataset query mapping). What it came down to was I had to remove a comment block directly after the WHERE keyword. The error message was resolved after moving the comment block after the WHERE CLAUSE conditions. I have other comments in the code also. It was just the one after the WHERE keyword causing the error.

SQL with error: "ORA-01008: not all variables bound"...

WHERE
/*
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE=100
    AND OHH.MASTER_ORDER_NBR IS NULL
*/

    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND OHH.MASTER_ORDER_NBR IS NULL
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto) 

SQL executes successfully on the report server...

WHERE
    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND OHH.MASTER_ORDER_NBR IS NULL
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto)   
/*
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE=100
    AND OHH.MASTER_ORDER_NBR IS NULL
*/

Here is what the dataset parameter mapping screen looks like.

enter image description here

How to recursively find and list the latest modified files in a directory with subdirectories and times

I have this alias in my .profile that I use quite often:

$ alias | grep xlogs
xlogs='sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R'

So it does what you are looking for (with exception it doesn't traverse change date/time multiple levels) - looks for latest files (*.log and *.trc files in this case); also it only finds files modified in the last day, and then sorts by time and pipes the output through less:

sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R

PS.: Notice I don't have root on some of the servers, but always have sudo, so you may not need that part.

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I am using this solution:

  1. Create a separate repository that holds folder node_modules. If you have native modules that should be build for specific platform then create a separate repository for each platform.

  2. Attach these repositories to your project repository with git submodule:

    git submodule add .../your_project_node_modules_windows.git node_modules_windows

    git submodule add .../your_project_node_modules_linux_x86_64 node_modules_linux_x86_64

  3. Create a link from platform-specific node_modules to node_modules directory and add node_modules to .gitignore.

  4. Run npm install.

  5. Commit submodule repository changes.

  6. Commit your project repository changes.

So you can easily switch between node_modules on different platforms (for example, if you are developing on OS X and deploying to Linux).

PHP Converting Integer to Date, reverse of strtotime

Yes you can convert it back. You can try:

date("Y-m-d H:i:s", 1388516401);

The logic behind this conversion from date to an integer is explained in strtotime in PHP:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

For example, strtotime("1970-01-01 00:00:00") gives you 0 and strtotime("1970-01-01 00:00:01") gives you 1.

This means that if you are printing strtotime("2014-01-01 00:00:01") which will give you output 1388516401, so the date 2014-01-01 00:00:01 is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.

Convert character to ASCII code in JavaScript

str.charCodeAt(index)

Using charCodeAt() The following example returns 65, the Unicode value for A.

'ABC'.charCodeAt(0) // returns 65

How to merge many PDF files into a single one?

You can also use Ghostscript to merge different PDFs. You can even use it to merge a mix of PDFs, PostScript (PS) and EPS into one single output PDF file:

gs \
  -o merged.pdf \
  -sDEVICE=pdfwrite \
  -dPDFSETTINGS=/prepress \
   input_1.pdf \
   input_2.pdf \
   input_3.eps \
   input_4.ps \
   input_5.pdf

However, I agree with other answers: for your use case of merging PDF file types only, pdftk may be the best (and certainly fastest) option.

Update:
If processing time is not the main concern, but if the main concern is file size (or a fine-grained control over certain features of the output file), then the Ghostscript way certainly offers more power to you. To highlight a few of the differences:

  • Ghostscript can 'consolidate' the fonts of the input files which leads to a smaller file size of the output. It also can re-sample images, or scale all pages to a different size, or achieve a controlled color conversion from RGB to CMYK (or vice versa) should you need this (but that will require more CLI options than outlined in above command).
  • pdftk will just concatenate each file, and will not convert any colors. If each of your 16 input PDFs contains 5 subsetted fonts, the resulting output will contain 80 subsetted fonts. The resulting PDF's size is (nearly exactly) the sum of the input file bytes.

Dropdown select with images

You don't even need javascript to do this!

I hope this got you intrigued so here it goes. First, the html structure:

<div id="image-dropdown">
    <input type="radio" id="line1" name="line-style" value="1" checked="checked" />
    <label for="line1"></label>
    <input type="radio" id="line2" name="line-style" value="2" />
    <label for="line2"></label>
    ...
</div>

Whaaat? Radio buttons? Correct. We'll style them to look like a dropdown list with images, because that's what you're after! The trick is in knowing that when labels are correctly linked to inputs (that "for" attribute and target element id), the input will implicitly become active; click on a label = click on a radio button. Here comes comes slightly abbreviated css with comments inline:

#image-dropdown {
    /*style the "box" in its minimzed state*/
    border:1px solid black; width:200px; height:50px; overflow:hidden;
    /*animate the dropdown collapsing*/
    transition: height 0.1s;
}
#image-dropdown:hover {
    /*when expanded, the dropdown will get native means of scrolling*/
    height:200px; overflow-y:scroll;
    /*animate the dropdown expanding*/
    transition: height 0.5s;
}
#image-dropdown input {
    /*hide the nasty default radio buttons!*/
    position:absolute;top:0;left:0;opacity:0;
}
#image-dropdown label {
    /*style the labels to look like dropdown options*/
    display:none; margin:2px; height:46px; opacity:0.2; 
    background:url("http://www.google.com/images/srpr/logo3w.png") 50% 50%;}
#image-dropdown:hover label{
    /*this is how labels render in the "expanded" state.
     we want to see only the selected radio button in the collapsed menu,
     and all of them when expanded*/
    display:block;
}
#image-dropdown input:checked + label {
    /*tricky! labels immediately following a checked radio button
      (with our markup they are semantically related) should be fully opaque
      and visible even in the collapsed menu*/
    opacity:1 !important; display:block;
}

Full example here: http://jsfiddle.net/NDCSR/1/

NB1: you'll probably need to use it with position:absolute inside a container with position:relative +high z-index.

NB2: when adding more backgrounds for individual line styles, consider having the selectors based on the "for" attribute of the label like so:

label[for=linestyle2] {background-image:url(...);}

I lose my data when the container exits

You need to commit the changes you make to the container and then run it. Try this:

sudo docker pull ubuntu

sudo docker run ubuntu apt-get install -y ping

Then get the container id using this command:

sudo docker ps -l

Commit changes to the container:

sudo docker commit <container_id> iman/ping 

Then run the container:

sudo docker run iman/ping ping www.google.com

This should work.

How to check whether a int is not null or empty?

I think you can initialize the variables a value like -1, because if the int type variables is not initialized it can't be used. When you want to check if it is not the value you want you can check if it is -1.

Can an Option in a Select tag carry multiple values?

What about html data attributes? That's the easiest way. Reference from w3school

In your case

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  alert('value a is:' + $("select option:selected").data('valuea') +_x000D_
    '\nvalue b is:' + $("select option:selected").data('valueb')_x000D_
  )_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>_x000D_
<select name="Testing">_x000D_
  <option value="1" data-valuea="2010" data-valueb="2011"> One_x000D_
    <option value="2" data-valuea="2122" data-valueb="2123"> Two_x000D_
      <option value="3" data-valuea="0" data-valueb="1"> Three_x000D_
</select>
_x000D_
_x000D_
_x000D_

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If you have a version of find (such as GNU find) that supports -printf then there's no need to call stat repeatedly:

find /some/dir -printf "%T+\n" | sort -nr | head -n 1

or

find /some/dir -printf "%TY-%Tm-%Td %TT\n" | sort -nr | head -n 1

If you don't need recursion, though:

stat --printf="%y\n" *

Foreach loop in C++ equivalent of C#

ranged based for:

std::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
for(const std::string& str : strarr) {
  listbox.items.add(str);
}

pre c++11

std::string strarr[] = {"ram", "mohan", "sita"};
for(int i = 0; i < 3; ++i) {
  listbox.items.add(strarr[i]);
}

or

std::string strarr[] = {"ram", "mohan", "sita"};
std::vector<std::string> strvec(strarr, strarr + 3);
std::vector<std::string>::iterator itr = strvec.begin();
while(itr != strvec.end()) {
  listbox.items.add(*itr);
  ++itr;
}

Using Boost:

boost::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
BOOST_FOREACH(std::string & str, strarr) {
  listbox.items.add(str);
}

SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

UPDATE B SET
     COLUMN1 = A.COLUMN1,
     COLUMN2 = A.COLUMN2,
     COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

UPDATE B SET
    (COLUMN1, COLUMN2, COLUMN3) =
               (SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

UPDATE B SET
     COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
     COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
     COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)

How to change column datatype in SQL database without losing data

Go to Tool-Option-designers-Table and Database designers and Uncheck Prevent saving optionenter image description here

How to change MySQL data directory?

If you are using SE linux, set it to permissive mode by editing /etc/selinux/config and changing SELINUX=enforcing to SELINUX=permissive

How to obtain the query string from the current URL with JavaScript?

For React Native, React, and For Node project, below one is working

yarn add  query-string

import queryString from 'query-string';

const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");

console.log(parsed.offset) will display 10

Difference between git pull and git pull --rebase

git pull = git fetch + git merge against tracking upstream branch

git pull --rebase = git fetch + git rebase against tracking upstream branch

If you want to know how git merge and git rebase differ, read this.

"Non-static method cannot be referenced from a static context" error

setLoanItem() isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.

Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.

You probably want to pass in a media object on which to call the method:

public void loanItem(Media m) {
    m.setLoanItem("Yes");
}

Align image in center and middle within div

For center horizontally Just put

#over img {
    display: block;
    margin: 0 auto;
    clear:both;
}

Another method:

#over img {
    display: inline-block;
    text-align: center;
}

For center vertically Just put:

   #over img {

           vertical-align: middle;
        }

Read .mat files in Python

First save the .mat file as:

save('test.mat', '-v7')

After that, in Python, use the usual loadmat function:

import scipy.io as sio
test = sio.loadmat('test.mat')

Twitter - share button, but with image

You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy

This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.

Purpose of ESI & EDI registers?

In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:

The SSE2 MASKMOVDQU (and the upcoming AVX VMASKMOVDQU) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.

remove item from array using its name / value

Try this.(IE8+)

//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

Export pictures from excel file into jpg using VBA

Here is another cool way to do it- using en external viewer that accepts command line switches (IrfanView in this case) : * I based the loop on what Michal Krzych has written above.

Sub ExportPicturesToFiles()
    Const saveSceenshotTo As String = "C:\temp\"
    Const pictureFormat As String = ".jpg"

    Dim pic As Shape
    Dim sFileName As String
    Dim i As Long

    i = 1

    For Each pic In ActiveSheet.Shapes
        pic.Copy
        sFileName = saveSceenshotTo & Range("A" & i).Text & pictureFormat

        Call ExportPicWithIfran(sFileName)

        i = i + 1
    Next
End Sub

Public Sub ExportPicWithIfran(sSaveAsPath As String)
    Const sIfranPath As String = "C:\Program Files\IrfanView\i_view32.exe"
    Dim sRunIfran As String

    sRunIfran = sIfranPath & " /clippaste /convert=" & _
                            sSaveAsPath & " /killmesoftly"

    ' Shell is no good here. If you have more than 1 pic, it will
    ' mess things up (pics will over run other pics, becuase Shell does
    ' not make vba wait for the script to finish).
    ' Shell sRunIfran, vbHide

    ' Correct way (it will now wait for the batch to finish):
    call MyShell(sRunIfran )
End Sub

Edit:

  Private Sub MyShell(strShell As String)
  ' based on:
    ' http://stackoverflow.com/questions/15951837/excel-vba-wait-for-shell-command-to-complete
   ' by Nate Hekman

    Dim wsh As Object
    Dim waitOnReturn As Boolean:
    Dim windowStyle As VbAppWinStyle

    Set wsh = VBA.CreateObject("WScript.Shell")
    waitOnReturn = True
    windowStyle = vbHide

    wsh.Run strShell, windowStyle, waitOnReturn
End Sub

"Cross origin requests are only supported for HTTP." error when loading a local file

Experienced this when I downloaded a page for offline view.

I just had to remove the integrity="*****" and crossorigin="anonymous" attributes from all <link> and <script> tags

Single line if statement with 2 actions

You can write that in single line, but it's not something that someone would be able to read. Keep it like you already wrote it, it's already beautiful by itself.

If you have too much if/else constructs, you may think about using of different datastructures, like Dictionaries (to look up keys) or Collection (to run conditional LINQ queries on it)

Why does an onclick property set with setAttribute fail to work in IE?

There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.

See here for details:

http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

Android Bitmap to Base64 String

All of these answers are inefficient as they needlessly decode to a bitmap and then recompress the bitmap. When you take a photo on Android, it is stored as a jpeg in the temp file you specify when you follow the android docs.

What you should do is directly convert that file to a Base64 string. Here is how to do that in easy copy-paste (in Kotlin). Note you must close the base64FilterStream to truly flush its internal buffer.

fun convertImageFileToBase64(imageFile: File): String {

    return FileInputStream(imageFile).use { inputStream ->
        ByteArrayOutputStream().use { outputStream ->
            Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
                inputStream.copyTo(base64FilterStream)
                base64FilterStream.close()
                outputStream.toString()
            }
        }
    }
}

As a bonus, your image quality should be slightly improved, due to bypassing the re-compressing.

How to add a tooltip to an svg graphic?

You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

What is the proper way to display the full InnerException?

To pretty print just the Messages part of deep exceptions, you could do something like this:

public static string ToFormattedString(this Exception exception)
{
    IEnumerable<string> messages = exception
        .GetAllExceptions()
        .Where(e => !String.IsNullOrWhiteSpace(e.Message))
        .Select(e => e.Message.Trim());
    string flattened = String.Join(Environment.NewLine, messages); // <-- the separator here
    return flattened;
}

public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
    yield return exception;

    if (exception is AggregateException aggrEx)
    {
        foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
        {
            yield return innerEx;
        }
    }
    else if (exception.InnerException != null)
    {
        foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
        {
            yield return innerEx;
        }
    }
}

This recursively goes through all inner exceptions (including the case of AggregateExceptions) to print all Message property contained in them, delimited by line break.

E.g.

var outerAggrEx = new AggregateException(
    "Outer aggr ex occurred.",
    new AggregateException("Inner aggr ex.", new FormatException("Number isn't in correct format.")),
    new IOException("Unauthorized file access.", new SecurityException("Not administrator.")));
Console.WriteLine(outerAggrEx.ToFormattedString());

Outer aggr ex occurred.
Inner aggr ex.
Number isn't in correct format.
Unauthorized file access.
Not administrator.


You will need to listen to other Exception properties for more details. For e.g. Data will have some information. You could do:

foreach (DictionaryEntry kvp in exception.Data)

To get all derived properties (not on base Exception class), you could do:

exception
    .GetType()
    .GetProperties()
    .Where(p => p.CanRead)
    .Where(p => p.GetMethod.GetBaseDefinition().DeclaringType != typeof(Exception));

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

Get a UTC timestamp

You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/

Change the "No file chosen":

I'm pretty sure you cannot change the default labels on buttons, they are hard-coded in browsers (each browser rendering the buttons captions its own way). Check out this button styling article

how to loop through json array in jquery?

var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function() {
  $.each(this, function(key, val){
    alert(val);//here data 
      alert (key); //here key

  });
});

Elastic Search: how to see the indexed data

Probably the easiest way to explore your ElasticSearch cluster is to use elasticsearch-head.

You can install it by doing:

cd elasticsearch/
./bin/plugin -install mobz/elasticsearch-head

Then (assuming ElasticSearch is already running on your local machine), open a browser window to:

http://localhost:9200/_plugin/head/

Alternatively, you can just use curl from the command line, eg:

Check the mapping for an index:

curl -XGET 'http://127.0.0.1:9200/my_index/_mapping?pretty=1' 

Get some sample docs:

curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1' 

See the actual terms stored in a particular field (ie how that field has been analyzed):

curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1'  -d '
 {
    "facets" : {
       "my_terms" : {
          "terms" : {
             "size" : 50,
             "field" : "foo"
          }
       }
    }
 }

More available here: http://www.elasticsearch.org/guide

UPDATE : Sense plugin in Marvel

By far the easiest way of writing curl-style commands for Elasticsearch is the Sense plugin in Marvel.

It comes with source highlighting, pretty indenting and autocomplete.

Note: Sense was originally a standalone chrome plugin but is now part of the Marvel project.

Access an arbitrary element in a dictionary in Python

How about, this. Not mentioned here yet.

py 2 & 3

a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2

Java equivalent to Explode and Implode(PHP)

Good alternatives are the String.split and StringUtils.join methods.

Explode :

String[] exploded="Hello World".split(" ");

Implode :

String imploded=StringUtils.join(new String[] {"Hello", "World"}, " ");

Keep in mind though that StringUtils is in an external library.

How to use OKHTTP to make a post request?

OkHttp POST request with token in header

       RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("search", "a")
            .addFormDataPart("model", "1")
            .addFormDataPart("in", "1")
            .addFormDataPart("id", "1")
            .build();
    OkHttpClient client = new OkHttpClient();
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url("https://somedomain.com/api")
            .post(requestBody)
            .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIkMnkkMTAkZzZrLkwySlFCZlBmN1RTb3g3bmNpTzltcVwvemRVN2JtVC42SXN0SFZtbzZHNlFNSkZRWWRlIiwic3ViIjo0NSwiaWF0IjoxNTUwODk4NDc0LCJleHAiOjE1NTM0OTA0NzR9.tefIaPzefLftE7q0yKI8O87XXATwowEUk_XkAOOQzfw")
            .addHeader("cache-control", "no-cache")
            .addHeader("Postman-Token", "7e231ef9-5236-40d1-a28f-e5986f936877")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            if (response.isSuccessful()) {
                final String myResponse = response.body().string();

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("response", myResponse);
                        progress.hide();
                    }
                });
            }
        }
    });

What is the Python equivalent of static variables inside a function?

Instead of creating a function having a static local variable, you can always create what is called a "function object" and give it a standard (non-static) member variable.

Since you gave an example written C++, I will first explain what a "function object" is in C++. A "function object" is simply any class with an overloaded operator(). Instances of the class will behave like functions. For example, you can write int x = square(5); even if square is an object (with overloaded operator()) and not technically not a "function." You can give a function-object any of the features that you could give a class object.

# C++ function object
class Foo_class {
    private:
        int counter;     
    public:
        Foo_class() {
             counter = 0;
        }
        void operator() () {  
            counter++;
            printf("counter is %d\n", counter);
        }     
   };
   Foo_class foo;

In Python, we can also overload operator() except that the method is instead named __call__:

Here is a class definition:

class Foo_class:
    def __init__(self): # __init__ is similair to a C++ class constructor
        self.counter = 0
        # self.counter is like a static member
        # variable of a function named "foo"
    def __call__(self): # overload operator()
        self.counter += 1
        print("counter is %d" % self.counter);
foo = Foo_class() # call the constructor

Here is an example of the class being used:

from foo import foo

for i in range(0, 5):
    foo() # function call

The output printed to the console is:

counter is 1
counter is 2
counter is 3
counter is 4
counter is 5

If you want your function to take input arguments, you can add those to __call__ as well:

# FILE: foo.py - - - - - - - - - - - - - - - - - - - - - - - - -

class Foo_class:
    def __init__(self):
        self.counter = 0
    def __call__(self, x, y, z): # overload operator()
        self.counter += 1
        print("counter is %d" % self.counter);
        print("x, y, z, are %d, %d, %d" % (x, y, z));
foo = Foo_class() # call the constructor

# FILE: main.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

from foo import foo

for i in range(0, 5):
    foo(7, 8, 9) # function call

# Console Output - - - - - - - - - - - - - - - - - - - - - - - - - - 

counter is 1
x, y, z, are 7, 8, 9
counter is 2
x, y, z, are 7, 8, 9
counter is 3
x, y, z, are 7, 8, 9
counter is 4
x, y, z, are 7, 8, 9
counter is 5
x, y, z, are 7, 8, 9

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How can I switch my git repository to a particular commit

To create a new branch (locally):

  • With the commit hash (or part of it)

    git checkout -b new_branch 6e559cb
    
  • or to go back 4 commits from HEAD

    git checkout -b new_branch HEAD~4
    

Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch


For discarding the last three commits, see Lunaryorn's answer below.


For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.

Create a global variable in TypeScript

I spent couple hours to figure out proper way to do it. In my case I'm trying to define global "log" variable so the steps were:

1) configure your tsconfig.json to include your defined types (src/types folder, node_modules - is up to you):

...other stuff...
"paths": {
  "*": ["node_modules/*", "src/types/*"]
}

2) create file src/types/global.d.ts with following content (no imports! - this is important), feel free to change any to match your needs + use window interface instead of NodeJS if you are working with browser:

/**
 * IMPORTANT - do not use imports in this file!
 * It will break global definition.
 */
declare namespace NodeJS {
    export interface Global {
        log: any;
    }
}

declare var log: any;

3) now you can finally use/implement log where its needed:

// in one file
global.log = someCoolLogger();
// in another file
log.info('hello world');
// or if its a variable
global.log = 'INFO'

How to set the height of table header in UITableView?

If you programatically set the tableHeaderView, then just set it inside viewDidLayoutSubviews.

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        setupTableViewHeader()
    }

    private func setupTableViewHeader() {
        // Something you do to set it up programatically...
        tableView.tableHeaderView = MyHeaderView.instanceFromNib() 
    }

If you didn't set it programatically, you need to do similar to what @Kris answered based on this link

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        sizeHeaderToFit()
    }

    private func sizeHeaderToFit() {
        if let headerView = tableView.tableHeaderView {
            headerView.setNeedsLayout()
            headerView.layoutIfNeeded()

            let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
            var frame = headerView.frame
            frame.size.height = height
            headerView.frame = frame

            tableView.tableHeaderView = headerView
        }
    }

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

Maintaining Session through Angular.js

Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.

PHP Page: session.php

if (!isset($_SESSION))
{    
    session_start();
}    

$_SESSION['variable'] = "hello world";

$sessions = array();

$sessions['variable'] = $_SESSION['variable'];

header('Content-Type: application/json');
echo json_encode($sessions);

Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.

JS All Together

var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {      
    Session.then(function(response){
        $rootScope.session = response;
    });
}]);

 app.factory('Session', function($http) {    
    return $http.get('/session.php').then(function(result) {       
        return result.data; 
    });
}); 
  • Do a simple get to get sessions using a factory.
  • If you want to make it post to make the page not visible when you just go to it in the browser you can, I'm just simplifying it
  • Add the factory to the controller
  • I use rootScope because it is a session variable that I use throughout all my code.

HTML

Inside your html you can reference your session

<html ng-app="StarterApp">

<body ng-controller="AppCtrl">
{{ session.variable }}
</body>

href="javascript:" vs. href="javascript:void(0)"

Why have all the click events as a href links?

If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

Eclipse - Failed to create the java virtual machine

You can do a workaround as below:

Create a shortcut for eclipse and right click on the short cut and go to properties of the shortcut.

In the target box update the string:

-vm "C:\Program Files\Java\jdk1.6.0_07\bin"

the path will change according to your java installed directory.

So after changing the target string will be something like below.

D:\adt-bundle-windows-x86-20131030\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_07\bin"

Click apply and try clicking the Eclipse shortcut.

identifier "string" undefined?

#include <string> would be the correct c++ include, also you need to specify the namespace with std::string or more generally with using namespace std;

Regular Expression for alphanumeric and underscores

There's a lot of verbosity in here, and I'm deeply against it, so, my conclusive answer would be:

/^\w+$/

\w is equivalent to [A-Za-z0-9_], which is pretty much what you want. (unless we introduce unicode to the mix)

Using the + quantifier you'll match one or more characters. If you want to accept an empty string too, use * instead.

Get single row result with Doctrine NativeQuery

->getSingleScalarResult() will return a single value, instead of an array.

How to remove hashbang from url?

You should add mode history to your router like the below

export default new Router({
  mode: 'history',
  routes: [
    {
     ...
    }
  ]
}) 

Having services in React application

Service is not limited to Angular, even in Angular2+,

Service is just collection of helper functions...

And there are many ways to create them and reuse them across the application...

1) They can be all separated function which are exported from a js file, similar as below:

export const firstFunction = () => {
   return "firstFunction";
}

export const secondFunction = () => {
   return "secondFunction";
}
//etc

2) We can also use factory method like, with collection of functions... with ES6 it can be a class rather than a function constructor:

class myService {

  constructor() {
    this._data = null;
  }

  setMyService(data) {
    this._data = data;
  }

  getMyService() {
    return this._data;
  }

}

In this case you need make an instance with new key...

const myServiceInstance = new myService();

Also in this case, each instance has it's own life, so be careful if you want to share it across, in that case you should export only the instance you want...

3) If your function and utils not gonna be shared, you can even put them in React component, in this case, just as function in your react component...

class Greeting extends React.Component {
  getName() {
    return "Alireza Dezfoolian";
  }

  render() {
    return <h1>Hello, {this.getName()}</h1>;
  }
}

4) Another way you may handle things, could be using Redux, it's a temporary store for you, so if you have it in your React application, it can help you with many getter setter functions you use... It's like a big store that keep tracks of your states and can share it across your components, so can get rid of many pain for getter setter stuffs we use in the services...

It's always good to do a DRY code and not repeating what needs to be used to make the code reusable and readable, but don't try to follow Angular ways in React app, as mentioned in item 4, using Redux can reduces your need of services and you limit using them for some reuseable helper functions like item 1...

'dependencies.dependency.version' is missing error, but version is managed in parent

I had the same error, I forgot to add the child dependencies in the <dependencyManagement>. For example in the parent pom:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.sw.system4</groupId>
            <artifactId>system4-data</artifactId><!-- child artifact id -->
            <version>${project.version}</version>
        <dependency>

        <!-- add all third party libraries ... -->

    </dependencies>
<dependencyManagement>

How can I convince IE to simply display application/json rather than offer to download it?

I use Fiddler with JSONViewer plugin to inspect JSON. I don't think it is possible to make IE behave without fiddling with registry perhaps. Here's some information.

Working with select using AngularJS's ng-options

In CoffeeScript:

#directive
app.directive('select2', ->
    templateUrl: 'partials/select.html'
    restrict: 'E'
    transclude: 1
    replace: 1
    scope:
        options: '='
        model: '='
    link: (scope, el, atr)->
        el.bind 'change', ->
            console.log this.value
            scope.model = parseInt(this.value)
            console.log scope
            scope.$apply()
)
<!-- HTML partial -->
<select>
  <option ng-repeat='o in options'
          value='{{$index}}' ng-bind='o'></option>
</select>

<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>

<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar problem but it had to do with the structure and class of the object. I would check how dih_y2$MemberID is formatted.

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

How to generate a random string of a fixed length in Go?

func Rand(n int) (str string) {
    b := make([]byte, n)
    rand.Read(b)
    str = fmt.Sprintf("%x", b)
    return
}

How to download a branch with git?

Create a new directory, and do a clone instead.

git clone (address of origin) (name of branch)

Is null check needed before calling instanceof?

Using a null reference as the first operand to instanceof returns false.

How to generate javadoc comments in Android Studio

Android Studio -> Preferences -> Editor -> Intentions -> Java -> Declaration -> Enable "Add JavaDoc"

And, While selecting Methods to Implement (Ctrl/Cmd + i), on the left bottom, you should be seeing checkbox to enable Copy JavaDoc.

How to refer to Excel objects in Access VBA?

I dissent from both the answers. Don't create a reference at all, but use late binding:

  Dim objExcelApp As Object
  Dim wb As Object

  Sub Initialize()
    Set objExcelApp = CreateObject("Excel.Application")
  End Sub

  Sub ProcessDataWorkbook()
     Set wb = objExcelApp.Workbooks.Open("path to my workbook")
     Dim ws As Object
     Set ws = wb.Sheets(1)

     ws.Cells(1, 1).Value = "Hello"
     ws.Cells(1, 2).Value = "World"

     'Close the workbook
     wb.Close
     Set wb = Nothing
  End Sub

You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().

This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.

Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

DataTables fixed headers misaligned with columns in wide tables

I fixed the same issue in my application by adding below code in the css -

.dataTables_scrollHeadInner
{
     width: 640px !important;
}

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

jQuery datepicker set selected date, on the fly

In Html you can add your input field with a date picker like this

<input class="form-control date-picker fromDates" id="myDate" type="text">

and then in java script, initialize your datepicker and set your value to the date like this,

$('.fromDates').datepicker({
                maxDate: '0',
                dateFormat: "dd/mm/yy",
                changeYear: true,
                changeMonth: true,
                yearRange: "-100:+0"
            });

var myDateVal = moment('${value}').format('DD/MM/YYYY');
$('#myDate').datepicker().datepicker('setDate', myDateVal );

(In here fromdate attribute shows the previous dates of the current date)

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

How do you set up use HttpOnly cookies in PHP

Note that PHP session cookies don't use httponly by default.

To do that:

$sess_name = session_name();
if (session_start()) {
    setcookie($sess_name, session_id(), null, '/', null, null, true);
}

A couple of items of note here:

  • You have to call session_name() before session_start()
  • This also sets the default path to '/', which is necessary for Opera but which PHP session cookies don't do by default either.

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

echo date( "Y-m-d H:i:s", strtotime("2016-10-10 15:00:00")+(60*30) );//2016-10-10 15:30:00

or

echo date( "H:i:s", strtotime("15:00:00")+(60*30) ); // 15:30:00

or

echo date( "H:i:s", strtotime(date("H:i:s"))+(60*30) ); // 15:30:00

How to Inspect Element using Safari Browser

in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

What's the best way to break from nested loops in JavaScript?

I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that Object.keys() enumerates only an object's own enumerable properties, whereas "a for-in loop enumerates properties in the prototype chain as well".

Close to the OP's solution:

    Args.forEach(function (arg) {
        // This guard is not necessary,
        // since writing an empty string to document would not change it.
        if (!getAnchorTag(arg))
            return;

        document.write(getAnchorTag(arg));
    });

    function getAnchorTag (name) {
        var res = '';

        Object.keys(Navigation.Headings).some(function (Heading) {
            return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
                if (name == Navigation.Headings[Heading][Item].Name) {
                    res = ("<a href=\""
                                 + Navigation.Headings[Heading][Item].URL + "\">"
                                 + Navigation.Headings[Heading][Item].Name + "</a> : ");
                    return true;
                }
            });
        });

        return res;
    }

Solution that reduces iterating over the Headings/Items:

    var remainingArgs = Args.slice(0);

    Object.keys(Navigation.Headings).some(function (Heading) {
        return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
            var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);

            if (i === -1)
                return;

            document.write("<a href=\""
                                         + Navigation.Headings[Heading][Item].URL + "\">"
                                         + Navigation.Headings[Heading][Item].Name + "</a> : ");
            remainingArgs.splice(i, 1);

            if (remainingArgs.length === 0)
                return true;
            }
        });
    });

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

How to clear a textbox using javascript

Onfous And onblur Text box with javascript

   <input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';" onblur="if(this.value=='') this.value='A new value';"/>

Determine if variable is defined in Python

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42

callback to handle completion of pipe

Streams are EventEmitters so you can listen to certain events. As you said there is a finish event for request (previously end).

 var stream = request(...).pipe(...);
 stream.on('finish', function () { ... });

For more information about which events are available you can check the stream documentation page.

Property getters and setters

Update for Swift 5.1

As of Swift 5.1 you can now get your variable without using get keyword. For example:

var helloWorld: String {
"Hello World"
}

Difference between setUp() and setUpBeforeClass()

From the Javadoc:

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

How to use doxygen to create UML class diagrams from C++ source

Quote from this post (it's written by the author of doxygen himself) :

run doxygen -g and change the following options of the generated Doxyfile:

    EXTRACT_ALL            = YES
    HAVE_DOT               = YES
    UML_LOOK               = YES

run doxygen again

How can I download HTML source in C#

You can download files with the WebClient class:

using System.Net;

using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Or you can get the file content without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}

generate a random number between 1 and 10 in c

You need a different seed at every execution.

You can start to call at the beginning of your program:

srand(time(NULL));

Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

Find nearest value in numpy array

If you don't want to use numpy this will do it:

def find_nearest(array, value):
    n = [abs(i-value) for i in array]
    idx = n.index(min(n))
    return array[idx]

Get multiple elements by Id

More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

Printing with sed or awk a line following a matching pattern

If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.

sed '/pattern/ { N; s/.*\n//; q }; d'

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

After trying out every solution I could find:

  • Turning off strict ssl: npm config set strict-ssl=false
  • Changing the registry to http instead of https: npm config set registry http://registry.npmjs.org/
  • Changing my cafile setting: npm config set cafile /path/to/your/cert.pem
  • Stop rejecting unknown CAs: set NODE_TLS_REJECT_UNAUTHORIZED=0

The solution that seems to be working the best for me now is to use the NODE_EXTRA_CA_CERTS environment variable which extends the existing CAs rather than replacing them with the cafile option in your .npmrc file. You can set it by entering this in your terminal: NODE_EXTRA_CA_CERTS=path/to/your/cert.pem

Of course, setting this variable every time can be annoying, so I added it to my bash profile so that it will be set every time I open terminal. If you don’t already have a ~/.bash_profile file, create one. Then at the end of that file add export NODE_EXTRA_CA_CERTS=path/to/your/cert.pem. Then, remove the cafile setting in your .npmrc.

how to use free cloud database with android app?

Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.

Here are some providers which have a "free-tier" (may change in future):

  1. Firebase (Google) - https://firebase.google.com/
  2. AWS Mobile (Amazon) - https://aws.amazon.com/mobile/
  3. Azure Mobile (Microsoft) - https://azure.microsoft.com/en-in/services/app-service/mobile/
  4. MongoDB Realm (MongoDB) - https://www.mongodb.com/realm
  5. Back4app (Popular) - https://www.back4app.com/

Open source solutions:

  1. Parse - http://parseplatform.org/
  2. Apache User Grid - https://usergrid.apache.org/
  3. SupaBase (under development) - https://supabase.io/

'\r': command not found - .bashrc / .bash_profile

May be you used notepad++ for creating/updating this file.

EOL(Edit->EOL Conversion) Conversion by default is Windows.

Change EOL Conversion in Notepad++

Edit -> EOL Conversion -> Unix (LF)

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).

There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

I was getting following error on a fedora 18 box:


1. /usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory compilation terminated.

I Installed glibc.i686 and glibc-devel.i686, then compilation failed with following error:

2. /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.7.2/libgcc_s.so when searching for -lgcc_s /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status

Solution:

I installed (yum install) glibc.i686 glibc-devel.i386 and libgcc.i686 to get rid of the compilation issue.

Now compilation for 32 bit (-m32) works fine.

Assert a function/method was not called using Mock

This should work for your case;

assert not my_var.called, 'method should not have been called'

Sample;

>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been

Dart SDK is not configured

Many answers here, but I believe most are missing the point.

You're running this command from a shell, and most if not all answers are related to running inside an IDE. There's a difference.

If you're using the shell to run your Dart / Flutter commands, make sure you've set up the environment variables necessary for the commands to know where to look for the right tools.

Personally, as I mostly work on a laptop, I've offloaded my main drive from all the space required by the development tools, moving everything to an external drive as described in this answer, so I have to tell the system where I've placed the various components.

Same goes for running commands from the command line vs. from an IDE, as an IDE can store this configuration, while the shell will not, unless you store it in the shell's startup files.

I use macOS, Homebrew and the ZShell, and I like to have the Dart SDK as a separate install, so I can track the DEV branch for Dart via Homebrew, while my Flutter install is using the BETA branch.

So, in my ~/.zprofile I have:

export HOMEBREW_PREFIX="$(brew --prefix)"

# Android / Java, Dart / Flutter related
export FLUTTER_ROOT="${SSD}/Lib/flutter" # Path to your main Flutter install
export DART_SDK="${HOMEBREW_PREFIX}/opt/dart/libexec" # Separate Dart SDK install
export JAVA_HOME="/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home" # JDK
export ANDROID_SDK_ROOT="${SSD}/Lib/android/sdk" # Top-level Android SDK directory
export ANDROID_HOME="${SSD}/Lib/android/sdk" # Same as above, needed by other tools I use
export ANDROID_AVD_HOME="${SSD}/Lib/android/avd" # Path to the moved emulators etc

Then I make sure that the $PATH variable is set up in the right order, so when I do Dart specific commands, the up-to-date Dart DEV branch is being used, while Flutter commands will use the Flutter BETA branch.

If you're using Zsh or Bash, add the additional paths at the end of .zshrc or .bashrc respectively, as these are called for every Terminal / Shell you start after login:

# Prepending to already established PATH

export PATH="\
/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin:\
${HOME}/.pub-cache/bin:\
${HOMEBREW_PREFIX}/opt/dart/libexec/bin:\
${SSD}/Lib/flutter/.pub-cache/bin:\
${SSD}/Lib/flutter/bin:\
${SSD}/Lib/android/sdk/platform-tools:\
${SSD}/Lib/android/sdk/tools/bin:\
${SSD}/Lib/android/sdk/emulator:\
${PATH}"

# If you're using Zsh, add this to clean up duplicate entries building up from running this 
# in every Terminal you launch:
# Remove duplicates from $PATH
typeset -aU path;

# Not sure, but in Bash, to remove duplicates you could do something like:
echo -n $PATH | awk -v RS=: '!($0 in a) {a[$0]; printf("%s%s", length(a) > 1 ? ":" : "", $0)}'

Now, that was a mouthful of stuff, but this is the way I maintain the order of operations...

No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.

How to stop EditText from gaining focus at Activity startup in Android

I had tried several answers individually but the focus is still at the EditText. I only managed to solve it by using two of the below solution together.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLayout"
  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true" >

( Reference from Silver https://stackoverflow.com/a/8639921/15695 )

and remove

 <requestFocus />

at EditText

( Reference from floydaddict https://stackoverflow.com/a/9681809 )

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Should you always favor xrange() over range()?

xrange() is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.

Unless I specifically need a list for something, I always favor xrange()

PHP + curl, HTTP POST sample code?

If you try to login on site with cookies.

This code:

if ($server_output == "OK") { ... } else { ... }

May not works if you try to login, because many sites returns status 200, but the post is not successful.

Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.

Also the post can be successful, but the status can be redirect instead 200.

To be sure the post is successful try this:

Follow location after the post, so it will go to the page where the post do redirect to:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

And than check if new cookies existing in the request:

if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 

{echo 'post successful'; }

else { echo 'not successful'; }

How to get the public IP address of a user in C#

This is what I use:

protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}

"uip" is the name of the label in the aspx page that shows the user IP.

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

relative path in require_once doesn't work

I just came across this same problem, where it was all working fine, up until the point I had an includes within another includes.

require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')

Solution 1. (undesired hardcoding of my public html folder name, but it works):

require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';

Solution 2. (undesired comment above about DIR only working since php 5.3, but it works):

require_once __DIR__. '/../script/pdocrud.php';

Solution 3. (I can't see any downsides, and it works perfectly in my php 5.3):

require_once dirname(__FILE__). '/../script/pdocrud.php';

How to run a PowerShell script from a batch file

Small sample test.cmd

<# :
  @echo off
    powershell /nologo /noprofile /command ^
         "&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
  exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...

Hexadecimal string to byte array in C

Following is the solution I wrote up for performance reasons:

void hex2bin(const char* in, size_t len, unsigned char* out) {

  static const unsigned char TBL[] = {
     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  58,  59,  60,  61,
    62,  63,  64,  10,  11,  12,  13,  14,  15,  71,  72,  73,  74,  75,
    76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
    90,  91,  92,  93,  94,  95,  96,  10,  11,  12,  13,  14,  15
  };

  static const unsigned char *LOOKUP = TBL - 48;

  const char* end = in + len;

  while(in < end) *(out++) = LOOKUP[*(in++)] << 4 | LOOKUP[*(in++)];

}

Example:

unsigned char seckey[32];

hex2bin("351aaaec0070d13d350afae2bc43b68c7e590268889869dde489f2f7988f3fee", 64, seckey);

/*
  seckey = {
     53,  26, 170, 236,   0, 112, 209,  61,  53,  10, 250, 226, 188,  67, 182, 140, 
    126,  89,   2, 104, 136, 152, 105, 221, 228, 137, 242, 247, 152, 143,  63, 238
  };
*/

If you don't need to support lowercase:

static const unsigned char TBL[] = {
     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  58,  59,
    60,  61,  62,  63,  64,  10,  11,  12,  13,  14,  15
};

Change values of select box of "show 10 entries" of jquery datatable

$(document).ready(function() {
    $('#example').dataTable( {
    "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
    "pageLength": 25
    } );
} );

aLengthMenu : This parameter allows you to readily specify the entries in the length drop down menu that DataTables shows when pagination is enabled. It can be either a 1D array of options which will be used for both the displayed option and the value, or a 2D array which will use the array in the first position as the value, and the array in the second position as the displayed options (useful for language strings such as 'All').

Update

Since DataTables v1.10, the options you are looking for are pageLength and lengthMenu

Shorthand if/else statement Javascript

var x = y !== undefined ? y : 1;

Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, ""), which may be why it "didn't work" for you. Also, if y is a global variable, if it's truly not defined you may run into an error unless you access it as window.y.


As vol7ron suggests in the comments, you can also use typeof to avoid the need to refer to global vars as window.<name>:

var x = typeof y != "undefined" ? y : 1;

Gradle does not find tools.jar

I've tried most of the top options but it seems that I had something wrong with my environment setup so they didn't help. What solved the issue for me was to re-install jdk1.8.0_201 and jre1.8.0_201 and this solved the error for me. Hope that helps someone.

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

Find the nth occurrence of substring in a string

Solution without using loops and recursion.

Use the required pattern in compile method and enter the desired occurrence in variable 'n' and the last statement will print the starting index of the nth occurrence of the pattern in the given string. Here the result of finditer i.e. iterator is being converted to list and directly accessing the nth index.

import re
n=2
sampleString="this is history"
pattern=re.compile("is")
matches=pattern.finditer(sampleString)
print(list(matches)[n].span()[0])

Password Protect a SQLite DB. Is it possible?

You can use the built-in encryption of the sqlite .net provider (System.Data.SQLite). See more details at http://web.archive.org/web/20070813071554/http://sqlite.phxsoftware.com/forums/t/130.aspx

To encrypt an existing unencrypted database, or to change the password of an encrypted database, open the database and then use the ChangePassword() function of SQLiteConnection:

// Opens an unencrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
// Encrypts the database. The connection remains valid and usable afterwards.
cnn.ChangePassword("mypassword");

To decrypt an existing encrypted database call ChangePassword() with a NULL or "" password:

// Opens an encrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3;Password=mypassword");
cnn.Open();
// Removes the encryption on an encrypted database.
cnn.ChangePassword(null);

To open an existing encrypted database, or to create a new encrypted database, specify a password in the ConnectionString as shown in the previous example, or call the SetPassword() function before opening a new SQLiteConnection. Passwords specified in the ConnectionString must be cleartext, but passwords supplied in the SetPassword() function may be binary byte arrays.

// Opens an encrypted database by calling SetPassword()
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.SetPassword(new byte[] { 0xFF, 0xEE, 0xDD, 0x10, 0x20, 0x30 });
cnn.Open();
// The connection is now usable

By default, the ATTACH keyword will use the same encryption key as the main database when attaching another database file to an existing connection. To change this behavior, you use the KEY modifier as follows:

If you are attaching an encrypted database using a cleartext password:

// Attach to a database using a different key than the main database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY 'mypassword'", cnn);
cmd.ExecuteNonQuery();

To attach an encrypted database using a binary password:

// Attach to a database encrypted with a binary key
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY X'FFEEDD102030'", cnn);
cmd.ExecuteNonQuery();

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I think this can be generalized like this:

Denote S, M as the initial values for the sum of arithmetic series and multiplication.

S = 1 + 2 + 3 + 4 + ... n=(n+1)*n/2
M = 1 * 2 * 3 * 4 * .... * n 

I should think about a formula to calculate this, but that is not the point. Anyway, if one number is missing, you already provided the solution. However, if two numbers are missing then, let's denote the new sum and total multiple by S1 and M1, which will be as follows:

S1 = S - (a + b)....................(1)

Where a and b are the missing numbers.

M1 = M - (a * b)....................(2)

Since you know S1, M1, M and S, the above equation is solvable to find a and b, the missing numbers.

Now for the three numbers missing:

S2 = S - ( a + b + c)....................(1)

Where a and b are the missing numbers.

M2 = M - (a * b * c)....................(2)

Now your unknown is 3 while you just have two equations you can solve from.

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

Your solution might be to add the original IP and/or hostname also:

ALLOWED_HOSTS = [
  'localhost',
  '127.0.0.1',
  '111.222.333.444',
  'mywebsite.com']

The condition to be satisfied is that the host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) should match one of the values in ALLOWED_HOSTS.

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

Use multiple @font-face rules in CSS

@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Thin.otf);
    font-weight: 200;
}
@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Light.otf);
    font-weight: 300;
}
@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Regular.otf);
    font-weight: normal;
}
@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Bold.otf);
    font-weight: bold;
}
h3, h4, h5, h6 {
    font-size:2em;
    margin:0;
    padding:0;
    font-family:Kaffeesatz;
    font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

Check for database connection, otherwise display message

Please check this:

$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';

$connection = mysqli_connect($servername,$username,$password);

if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}

/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");

if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}

mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");

$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)"; 
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/

Using a batch to copy from network drive to C: or D: drive

Most importantly you need to mount the drive

net use z: \\yourserver\sharename

Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:

  • right click Properties
  • click on General tab
  • change account under

"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.

Then run your batch script with the following changes

copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

Enter the password you use to open you Mac session and click on "Always allow" until all alerts are closed. The other buttons do not work...

Fill DataTable from SQL Server database

Try with following:

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

How do I resize an image using PIL and maintain its aspect ratio?

If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?

For example, half the original size

half = 0.5
out = im.resize( [int(half * s) for s in im.size] )

How to store images in mysql database using php

insert image zh

-while we insert image in database using insert query

$Image = $_FILES['Image']['name'];
    if(!$Image)
    {
      $Image="";
    }
    else
    {
      $file_path = 'upload/';
      $file_path = $file_path . basename( $_FILES['Image']['name']);    
      if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) 
     { 
}
}

Enable/Disable a dropdownbox in jquery

$(document).ready(function() {
 $('#chkdwn2').click(function() {
   if ($('#chkdwn2').prop('checked')) {
      $('#dropdown').prop('disabled', true);
   } else {
      $('#dropdown').prop('disabled', false);  
   }
 });
});

making use of .prop in the if statement.

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

Reading/parsing Excel (xls) files with Python

I highly recommend xlrd for reading .xls files.

voyager mentioned the use of COM automation. Having done this myself a few years ago, be warned that doing this is a real PITA. The number of caveats is huge and the documentation is lacking and annoying. I ran into many weird bugs and gotchas, some of which took many hours to figure out.

UPDATE: For newer .xlsx files, the recommended library for reading and writing appears to be openpyxl (thanks, Ikar Pohorský).

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Turns out that I had this problem and it was because I used "tabs" to indent lines instead of spaces. Just posting, in case it helps anyone.

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

css label width not taking effect

label's default display mode is inline, which means it automatically sizes itself to it's content. To set a width you'll need to set display:block and then do some faffing to get it positioned correctly (probably involving float)

index.php not loading by default

For info : in some Apache2 conf you must add the DirectoryIndex command in mods_enabled/dir.conf (it's not located in apache2.conf)

Explanation of the UML arrows

Here's some explanations from the Visual Studio 2015 docs:

UML Class Diagrams: Reference: https://msdn.microsoft.com/library/dd409437%28VS.140%29.aspx

UML class diagram

5: Association: A relationship between the members of two classifiers.

5a: Aggregation: An association representing a shared ownership relationship. The Aggregation property of the owner role is set to Shared.

5b: Composition: An association representing a whole-part relationship. The Aggregation property of the owner role is set to Composite.

9: Generalization: The specific classifier inherits part of its definition from the general classifier. The general classifier is at the arrow end of the connector. Attributes, associations, and operations are inherited by the specific classifier. Use the Inheritance tool to create a generalization between two classifiers.

Package diagram

13: Import: A relationship between packages, indicating that one package includes all the definitions of another.

14: Dependency: The definition or implementation of the dependent classifier might change if the classifier at the arrowhead end is changed.

Realization relationship

15: Realization: The class implements the operations and attributes defined by the interface. Use the Inheritance tool to create a realization between a class and an interface.

16: Realization: An alternative presentation of the same relationship. The label on the lollipop symbol identifies the interface.

UML Class Diagrams: Guidelines: http://msdn.microsoft.com/library/dd409416%28VS.140%29.aspx

Properties of an Association

Aggregation: This appears as a diamond shape at one end of the connector. You can use it to indicate that instances at the aggregating role own or contain instances of the other.

Is Navigable: If true for only one role, an arrow appears in the navigable direction. You can use this to indicate navigability of links and database relations in the software.


Generalization: Generalization means that the specializing or derived type inherits attributes, operations, and associations of the general or base type. The general type appears at the arrowhead end of the relationship.

Realization: Realization means that a class implements the attributes and operations specified by the interface. The interface is at the arrow end of the connector.

Let me know if you have more questions.

Javascript loop through object array?

The suggested for loop is quite fine but you have to check the properties with hasOwnProperty. I'd rather suggest using Object.keys() that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

_x000D_
_x000D_
var data = {_x000D_
    "messages": [{_x000D_
        "msgFrom": "13223821242",_x000D_
        "msgBody": "Hi there"_x000D_
    }, {_x000D_
        "msgFrom": "Bill",_x000D_
        "msgBody": "Hello!"_x000D_
    }]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
    console.log('message index '+ index);_x000D_
    Object.keys(message).forEach(function(prop) {    _x000D_
        console.log(prop + " = " + message[prop]);_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

Insert into a MySQL table or update if exists

When using SQLite:

REPLACE into table (id, name, age) values(1, "A", 19)

Provided that id is the primary key. Or else it just inserts another row. See INSERT (SQLite).

jQuery: Best practice to populate drop down?

Below is the Jquery way of populating a drop down list whose id is "FolderListDropDown"

$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        var elem = $("<option></option>");
        elem.attr("value", result[i].ImageFolderID);
        elem.text(result[i].Name);
        elem.appendTo($("select#FolderListDropDown"));
     }
});

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

Best font for coding

Inconsolata (http://www.levien.com/type/myfonts/inconsolata.html) is a great monospaced font for programming. Earlier versions tend to act weird on OS X, but the newer versions work out very well.

How to get different colored lines for different plots in a single figure?

Setting them later

If you don't know the number of the plots you are going to plot you can change the colours once you have plotted them retrieving the number directly from the plot using .lines, I use this solution:

Some random data

import matplotlib.pyplot as plt
import numpy as np

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)


for i in range(1,15):
    ax1.plot(np.array([1,5])*i,label=i)

The piece of code that you need:

colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired   
colors = [colormap(i) for i in np.linspace(0, 1,len(ax1.lines))]
for i,j in enumerate(ax1.lines):
    j.set_color(colors[i])
  

ax1.legend(loc=2)

The result is the following:enter image description here

What exactly is Apache Camel?

If you are aware of Enterprise Integration Patterns, Apache Camel is one integration framework which implements all EIPs.

And you can deploy Camel as a standalone application in a web-container.

Basically, if you have to integrate several applications with different protocols and technologies, you can use Camel.

How to implement a Map with multiple keys?

What about you declare the following "Key" class:

public class Key {
   public Object key1, key2, ..., keyN;

   public Key(Object key1, Object key2, ..., Object keyN) {
      this.key1 = key1;
      this.key2 = key2;
      ...
      this.keyN = keyN;
   }

   @Override   
   public boolean equals(Object obj) {
      if (!(obj instanceof Key))
        return false;
      Key ref = (Key) obj;
      return this.key1.equals(ref.key1) && 
          this.key2.equals(ref.key2) &&
          ...
          this.keyN.equals(ref.keyN)
   }

    @Override
    public int hashCode() {
        return key1.hashCode() ^ key2.hashCode() ^ 
            ... ^ keyN.hashCode();
    }

}

Declaring the Map

Map<Key, Double> map = new HashMap<Key,Double>();

Declaring the key object

Key key = new Key(key1, key2, ..., keyN)

Filling the map

map.put(key, new Double(0))

Getting the object from the map

Double result = map.get(key);

Oracle: how to add minutes to a timestamp?

Based on what you're asking for, you want the HH24:MI format for to_char.

calculating the difference in months between two dates

Old question I know, but might help someone. I've used @Adam accepted answer above, but then checked if the difference is 1 or -1 then check to see if it is a full calendar month's difference. So 21/07/55 and 20/08/55 would not be a full month, but 21/07/55 and 21/07/55 would be.

/// <summary>
/// Amended date of birth cannot be greater than or equal to one month either side of original date of birth.
/// </summary>
/// <param name="dateOfBirth">Date of birth user could have amended.</param>
/// <param name="originalDateOfBirth">Original date of birth to compare against.</param>
/// <returns></returns>
public JsonResult ValidateDateOfBirth(string dateOfBirth, string originalDateOfBirth)
{
    DateTime dob, originalDob;
    bool isValid = false;

    if (DateTime.TryParse(dateOfBirth, out dob) && DateTime.TryParse(originalDateOfBirth, out originalDob))
    {
        int diff = ((dob.Month - originalDob.Month) + 12 * (dob.Year - originalDob.Year));

        switch (diff)
        {
            case 0:
                // We're on the same month, so ok.
                isValid = true;
                break;
            case -1:
                // The month is the previous month, so check if the date makes it a calendar month out.
                isValid = (dob.Day > originalDob.Day);
                break;
            case 1:
                // The month is the next month, so check if the date makes it a calendar month out.
                isValid = (dob.Day < originalDob.Day);
                break;
            default:
                // Either zero or greater than 1 month difference, so not ok.
                isValid = false;
                break;
        }
        if (!isValid)
            return Json("Date of Birth cannot be greater than one month either side of the date we hold.", JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json("Date of Birth is invalid.", JsonRequestBehavior.AllowGet);
    }
    return Json(true, JsonRequestBehavior.AllowGet);
}

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

git diff file against its last change

If you are fine using a graphical tool this works very well:

gitk <file>

gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!