Programs & Examples On #Coloranimation

Modulo operator in Python

In addition to the other answers, the `fmod` documentation has some interesting things to say on the subject:

`math.fmod(x, y)`

Return `fmod(x, y)`, as defined by the platform C library. Note that the Python expression `x % y` may not return the same result. The intent of the C standard is that `fmod(x, y)` be exactly (mathematically; to infinite precision) equal to `x - n*y` for some integer n such that the result has the same sign as `x` and magnitude less than `abs(y)`. Python’s `x % y` returns a result with the sign of `y` instead, and may not be exactly computable for float arguments. For example, `fmod(-1e-100, 1e100)` is `-1e-100`, but the result of Python’s `-1e-100 % 1e100` is `1e100-1e-100`, which cannot be represented exactly as a float, and rounds to the surprising `1e100`. For this reason, function `fmod()` is generally preferred when working with floats, while Python’s `x % y` is preferred when working with integers.

Abstract Class vs Interface in C++

I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:

``````class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}

virtual void Method1() = 0;
virtual void Method2() = 0;
};

class MyAbstractClass
{
public:
virtual ~MyAbstractClass();

virtual void Method1();
virtual void Method2();
void Method3();

virtual void Method4() = 0; // make MyAbstractClass not instantiable
};
``````

In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.

Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).

I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.

Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:

``````// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL;
// client code must derive from it
// and implement rendering and user input.
class OpenGLApp
{
public:
OpenGLApp();
virtual ~OpenGLApp();
...

// Run the app
void Run();

// <---- This behavior must be implemented by the client ---->

// Rendering
virtual void Render() = 0;

// Handle user input
// (returns false to quit, true to continue looping)
virtual bool HandleInput() = 0;

// <--------------------------------------------------------->

private:
//
// Some infrastructure code
//
...
void CreateRenderingWindow();
void CreateOpenGLContext();
void SwapBuffers();
};

class MyOpenGLDemo : public OpenGLApp
{
public:
MyOpenGLDemo();
virtual ~MyOpenGLDemo();

// Rendering
virtual void Render();  // implements rendering code

// Handle user input
virtual bool HandleInput(); // implements user input handling

//  ... some other stuff
};
``````

Refresh DataGridView when updating data source

Observablecollection :Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed. You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.

``````Observablecollection<ItemState> itemStates = new Observablecollection<ItemState>();

for (int i = 0; i < 10; i++) {
itemStates.Add(new ItemState { Id = i.ToString() });
}
dataGridView1.DataSource = itemStates;
``````

mysql select from n last rows

Starting from the answer given by @chaos, but with a few modifications:

• You should always use `ORDER BY` if you use `LIMIT`. There is no implicit order guaranteed for an RDBMS table. You may usually get rows in the order of the primary key, but you can't rely on this, nor is it portable.

• If you order by in the descending order, you don't need to know the number of rows in the table beforehand.

• You must give a correlation name (aka table alias) to a derived table.

Here's my version of the query:

``````SELECT `id`
FROM (
SELECT `id`, `val`
FROM `big_table`
ORDER BY `id` DESC
LIMIT \$n
) AS t
WHERE t.`val` = \$certain_number;
``````

Save image from url with curl PHP

try this:

``````function grab_image(\$url,\$saveto){
\$ch = curl_init (\$url);
curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(\$ch, CURLOPT_BINARYTRANSFER,1);
\$raw=curl_exec(\$ch);
curl_close (\$ch);
if(file_exists(\$saveto)){
}
\$fp = fopen(\$saveto,'x');
fwrite(\$fp, \$raw);
fclose(\$fp);
}
``````

and ensure that in php.ini allow_url_fopen is enable

How to get first two characters of a string in oracle query?

Just use SUBSTR function. It takes 3 parameters: String column name, starting index and length of substring:

``````select SUBSTR(OrderNo, 1, 2) FROM shipment;
``````

How do I declare a 2d array in C++ using new?

I presume from your static array example that you want a rectangular array, and not a jagged one. You can use the following:

``````int *ary = new int[sizeX * sizeY];
``````

Then you can access elements as:

``````ary[y*sizeX + x]
``````

Don't forget to use delete[] on `ary`.

How to remove border from specific PrimeFaces p:panelGrid?

The border is been set on the generated `tr` and `td` elements, not on the `table`. So, this should do:

``````.companyHeaderGrid.ui-panelgrid>*>tr,
border: none;
}
``````

How I found it? Just check the generated HTML output and all CSS style rules in the webdeveloper toolset of Chrome (rightclick, Inspect Element or press F12). Firebug and IE9 have a similar toolset. As to the confusion, just keep in mind that JSF/Facelets ultimately generates HTML and that CSS only applies on the HTML markup, not on the JSF source code. So to apply/finetune CSS you need to look in the client (webbrowser) side instead.

If you're still on PrimeFaces 4 or older, use below instead:

``````.companyHeaderGrid.ui-panelgrid>*>tr,
border: none;
}
``````

How to convert an array to object in PHP?

Little complicated but easy to extend technique:

Suppose you have an array

``````\$a = [
'name' => 'ankit',
'age' => '33',
'dob' => '1984-04-12'
];
``````

Suppose you have have a Person class which may have more or less attributes from this array. for example

``````class Person
{
private \$name;
private \$dob;
private \$age;
private \$company;
private \$city;
}
``````

If you still wanna change your array to the person object. You can use ArrayIterator Class.

``````\$arrayIterator = new \ArrayIterator(\$a); // Pass your array in the argument.
``````

Now you have iterator object.

Create a class extending FilterIterator Class; where you have to define the abstract method accept. Follow the example

``````class PersonIterator extends \FilterIterator
{
public function accept()
{
return property_exists('Person', parent::current());
}
}
``````

The above impelmentation will bind the property only if it exists in the class.

Add one more method in the class PersonIterator

``````public function getObject(Person \$object)
{
foreach (\$this as \$key => \$value)
{
\$object->{'set' . underscoreToCamelCase(\$key)}(\$value);
}
return \$object;
}
``````

Make sure you have mutators defined in your class. Now you are ready to call these function where you want to create object.

``````\$arrayiterator = new \ArrayIterator(\$a);
\$personIterator = new \PersonIterator(\$arrayiterator);

\$personIterator->getObject(); // this will return your Person Object.
``````

How to activate the Bootstrap modal-backdrop?

Just append a `div` with that class to `body`, then remove it when you're done:

``````// Show the backdrop
\$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
\$(".modal-backdrop").remove();
``````

Live Example:

_x000D_
_x000D_
``````\$("input").click(function() {_x000D_
var bd = \$('<div class="modal-backdrop"></div>');_x000D_
bd.appendTo(document.body);_x000D_
setTimeout(function() {_x000D_
bd.remove();_x000D_
}, 2000);_x000D_
});``````
_x000D_
``````<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">``````
_x000D_
_x000D_
_x000D_

Does mobile Google Chrome support browser extensions?

Extensions are not supported, see: https://developers.google.com/chrome/mobile/docs/faq .

Specifically:

Does Chrome for Android now support the embedded WebView for a hybrid native/web app?

A Chrome-based WebView is included in Android 4.4 (KitKat) and later. See the WebView overview for details.

Does Chrome for Android support apps and extensions?

Chrome apps and extensions are currently not supported on Chrome for Android. We have no plans to announce at this time.

Can I write and deploy web apps on Chrome for Android?

Though Chrome apps are not currently supported, we would love to see great interactive web sites accessible by URL.

ITextSharp insert text to an existing pdf

This worked for me and includes using OutputStream:

``````PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
using (Stream outStream = Response.OutputStream)
{
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);

document.Open();
try
{
PdfContentByte cb = writer.DirectContent;

cb.BeginText();
try
{
cb.SetFontAndSize(BaseFont.CreateFont(), 12);
cb.SetTextMatrix(110, 110);
cb.ShowText("aaa");
}
finally
{
cb.EndText();
}

}
finally
{
document.Close();
writer.Close();
}
}
``````

Print text in Oracle SQL Developer SQL Worksheet window

You could put your text in a select statement such as...

``````SELECT 'Querying Table1' FROM dual;
``````

How to change the timeout on a .NET WebClient object

You need to use `HttpWebRequest` rather than `WebClient` as you can't set the timeout on `WebClient` without extending it (even though it uses the `HttpWebRequest`). Using the `HttpWebRequest` instead will allow you to set the timeout.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

``````IEnumerable<string> e = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());
``````

Then you can call `ToList()`:

``````List<string> l = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();
``````

Xcode Error: "The app ID cannot be registered to your development team."

I was able to get the original bundle identifier to work on my paid team membership account (after having it assigned to my personal team) by revoking the personal team signing certificate that was assigned to the same account id.

1. On the Apple Developer website sign in with the paid account it, go to Certificates, IDs & Profiles.
2. Click the personal team certificate.
3. Click the Revoke button.
4. Go back to XCode and try signing again. A new certificate will be generated that should work with the bundle id.

This won't work if you still need the certificate for other apps.

Boxplot show the value of mean

You can use the output value from `stat_summary()`

``````ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
``````

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

Specify an SSH key for git push for a given domain

Configure your repository using `git config`. For example:

``````git config --add --local core.sshCommand 'ssh -i ~/.ssh/<<<PATH_TO_SSH_KEY>>>'
``````

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

What should be the package name of android app?

package name with 0 may cause problem for sharedPreference.

(OK) `con = createPackageContext("com.example.android.sf1", 0);`

(Problem but no error)

``````con = createPackageContext("com.example.android.sf01", 0);
``````

Java: Unresolved compilation problem

I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

extract digits in a simple way from a python string

This regular expression handles floats as well

``````import re
re_float = re.compile(r'\d*\.?\d+')
``````

You could also add a group to the expression that catches your weight units.

``````re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')
``````

You can access the named groups like this `re_banana.match("200 kgm").group('number')`.

How to convert date format to DD-MM-YYYY in C#

``````DateTime dt = DateTime.Now;

String.Format("{0:dd-MM-yyyy}", dt);
``````

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

``````import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()
``````

Here is the result.

How can I get a precise time, for example in milliseconds in Objective-C?

`CFAbsoluteTimeGetCurrent()` returns the absolute time as a `double` value, but I don't know what its precision is -- it might only update every dozen milliseconds, or it might update every microsecond, I don't know.

Is it possible to get multiple values from a subquery?

Here are two methods to get more than 1 column in a scalar subquery (or inline subquery) and querying the lookup table only once. This is a bit convoluted but can be the very efficient in some special cases.

1. You can use concatenation to get several columns at once:

``````SELECT x,
regexp_substr(yz, '[^^]+', 1, 1) y,
regexp_substr(yz, '[^^]+', 1, 2) z
FROM (SELECT a.x,
(SELECT b.y || '^' || b.z yz
FROM b
WHERE b.v = a.v)
yz
FROM a)
``````

You would need to make sure that no column in the list contain the separator character.

2. You could also use SQL objects:

``````CREATE OR REPLACE TYPE b_obj AS OBJECT (y number, z number);

SELECT x,
v.yz.y y,
v.yz.z z
FROM (SELECT a.x,
(SELECT b_obj(y, z) yz
FROM b
WHERE b.v = a.v)
yz
FROM a) v
``````

How can you test if an object has a specific property?

I've been using the following which returns the property value, as it would be accessed via `\$thing.\$prop`, if the "property" would be to exist and not throw a random exception. If the property "doesn't exist" (or has a null value) then `\$null` is returned: this approach functions in/is useful for strict mode, because, well, Gonna Catch 'em All.

I find this approach useful because it allows PS Custom Objects, normal .NET objects, PS HashTables, and .NET collections like Dictionary to be treated as "duck-typed equivalent", which I find is a fairly good fit for PowerShell.

Of course, this does not meet the strict definition of "has a property".. which this question may be explicitly limited to. If accepting the larger definition of "property" assumed here, the method can be trivially modified to return a boolean.

``````Function Get-PropOrNull {
param(\$thing, [string]\$prop)
Try {
\$thing.\$prop
} Catch {
}
}
``````

Examples:

``````Get-PropOrNull (Get-Date) "Date"                   # => Monday, February 05, 2018 12:00:00 AM
Get-PropOrNull (Get-Date) "flub"                   # => \$null
Get-PropOrNull (@{x="HashTable"}) "x"              # => "HashTable"
Get-PropOrNull ([PSCustomObject]@{x="Custom"}) "x" # => "Custom"
\$oldDict = New-Object "System.Collections.HashTable"
\$oldDict["x"] = "OldDict"
Get-PropOrNull \$d "x"                              # => "OldDict"
``````

And, this behavior might not [always] be desired.. ie. it's not possible to distinguish between `x.Count` and `x["Count"]`.

IF function with 3 conditions

Using `INDEX` and `MATCH` for binning. Easier to maintain if we have more bins.

``````=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))
``````

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

`import sun.misc.*;` Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.

`byte[] encVal = c.doFinal(Data.getBytes());` You are relying on the default character encoding here. Always specify what character encoding you are using: `byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));` Defaults might be different in different places.

As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.

Have a reloadData for a UITableView animate when changing

To reload all sections, not just one with custom duration.

User `duration` parameter of `UIView.animate` to set custom duration.

``````UIView.animate(withDuration: 0.4, animations: { [weak self] in
guard let `self` = self else { return }
let indexSet = IndexSet(integersIn: 0..<self.tableView.numberOfSections)
})
``````

Python/Django: log to console under runserver, log to file under Apache

You can configure logging in your `settings.py` file.

One example:

``````if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/my_log_file.log',
filemode = 'a'
)
``````

However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.

"Field has incomplete type" error

You are using a forward declaration for the type `MainWindowClass`. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

``````// forward declaration, details unknown
class A;

class B {
A *a;  // pointer to A, ok
};
``````

Or, if you can't use a pointer or reference....

``````// declaration of A
#include "A.h"

class B {
A a;  // ok, declaration of A is known
};
``````

At some point, the compiler needs to know the details of `A`.

If you are only storing a pointer to `A` then it doesn't need those details when you declare `B`. It needs them at some point (whenever you actually dereference the pointer to `A`), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class `A`.

``````// B.h

// forward declaration, details unknown
class A;

class B {
public:
void foo();
private:
A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
// here we need to know the declaration of A
a->whatever();
}
``````

SOAP Action WSDL

I have come across exactly the same problem when trying to write a client for the National Rail SOAP service with Perl.

The problem was caused because the Perl module that I'm using 'SOAP::Lite' inserts a '#' in the SOAPAction header ...

``````SOAPAction: "http://thalesgroup.com/RTTI/2008-02-20/ldb/#GetDepartureBoard"
``````

This is not interpreted correctly by .NET servers. I found this out from Example 3-19 in O'Reilly's Programming Web Services with SOAP . The solution was given below in section 3-20, namely you need to explicitly specify the format of the header with the 'on_action' method.

``````print SOAP::Lite
-> uri('urn:Example1')
-> on_action(sub{sprintf '%s/%s', @_ })
-> proxy('http://localhost:8080/helloworld/example1.asmx')
-> sayHello(\$name)
-> result . "\n\n";
``````

My guess is that soapclient.com is using SOAP::Lite behind the scenes and so are hitting the same problem when talking to National Rail.

The solution is to write your own client so that you have control over the format of the SOAPAction header ... but you've probably done that already.

You can just do `git merge <commit-number>` or `git cherry-pick <commit> <commit> ...`

As suggested by Ryan Stewart you may also create a branch from the current HEAD:

``````git branch brand-name
``````

Or just a tag:

``````git tag tag-name
``````

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: `intent.putExtra("key", value);`

Eg: `intent.putExtra("full_name", "Vishnu Sivan");`

`Intent intent=getIntent()` : It gets the Intent from the previous activity.

`fullname = intent.getStringExtra(“full_name”)` : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

``````Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);
``````

how can I enable scrollbars on the WPF Datagrid?

If any of the parent containers `RowDefinition` Height set to `"Auto"` also stoppers for scrollbars

Alternatively you may set Height "*"

Which happened in my case.

How to Implement DOM Data Binding in JavaScript

Things have changed a lot in the last 7 years, we have native web components in most browsers now. IMO the core of the problem is sharing state between elements, once you have that its trivial to update the ui when state changes and vice versa.

To share data between elements you can create a StateObserver class, and extend your web components from that. A minimal implementation looks something like this:

_x000D_
_x000D_
``````// create a base class to handle state_x000D_
class StateObserver extends HTMLElement {_x000D_
constructor () {_x000D_
super()_x000D_
StateObserver.instances.push(this)_x000D_
}_x000D_
stateUpdate (update) {_x000D_
StateObserver.lastState = StateObserver.state_x000D_
StateObserver.state = update_x000D_
StateObserver.instances.forEach((i) => {_x000D_
if (!i.onStateUpdate) return_x000D_
i.onStateUpdate(update, StateObserver.lastState)_x000D_
})_x000D_
}_x000D_
}_x000D_
_x000D_
StateObserver.instances = []_x000D_
StateObserver.state = {}_x000D_
StateObserver.lastState = {}_x000D_
_x000D_
// create a web component which will react to state changes_x000D_
class CustomReactive extends StateObserver {_x000D_
onStateUpdate (state, lastState) {_x000D_
if (state.someProp === lastState.someProp) return_x000D_
this.innerHTML = `input is: \${state.someProp}`_x000D_
}_x000D_
}_x000D_
customElements.define('custom-reactive', CustomReactive)_x000D_
_x000D_
class CustomObserved extends StateObserver {_x000D_
connectedCallback () {_x000D_
this.stateUpdate({ someProp: e.target.value })_x000D_
})_x000D_
}_x000D_
}_x000D_
customElements.define('custom-observed', CustomObserved)``````
_x000D_
``````<custom-observed>_x000D_
<input>_x000D_
</custom-observed>_x000D_
<br />_x000D_
<custom-reactive></custom-reactive>``````
_x000D_
_x000D_
_x000D_

fiddle here

I like this approach because:

• no dom traversal to find `data-` properties
• no Object.observe (deprecated)
• no Proxy (which provides a hook but no communication mechanism anyway)
• no dependencies, (other than a polyfill depending on your target browsers)
• it's reasonably centralised & modular... describing state in html, and having listeners everywhere would get messy very quickly.
• it's extensible. This basic implementation is 20 lines of code, but you could easily build up some convenience, immutability, and state shape magic to make it easier to work with.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

`JpaRepository` extends `PagingAndSortingRepository` which in turn extends `CrudRepository`.

Their main functions are:

Because of the inheritance mentioned above, `JpaRepository` will have all the functions of `CrudRepository` and `PagingAndSortingRepository`. So if you don't need the repository to have the functions provided by `JpaRepository` and `PagingAndSortingRepository` , use `CrudRepository`.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

``````Function getNumber
getNumber = "423"
End Function
``````

Margin between items in recycler view Android

If you want to do it in XML, jus set `paddingTop`and `paddingLeft` to your `RecyclerView` and equal amount of `layoutMarginBottom` and `layoutMarginRight` to the item you inflate into your `RecyclerView`(or vice versa).

Update Top 1 record in table sql server

It also works well ...

``````Update t
Set t.TIMESTAMP2 = '2013-12-12 15:40:31.593'
From
(
Select Top 1 TIMESTAMP2
From TX_Master_PCBA
Where SERIAL_NO IN ('0500030309')
Order By TIMESTAMP2 DESC
) t
``````

How to get a value of an element by name instead of ID

you can also use the class name.

``````\$(".yourclass").val();
``````

How can I capitalize the first letter of each word in a string?

Don't overlook the preservation of white space. If you want to process `'fred flinstone'` and you get `'Fred Flinstone'` instead of `'Fred Flinstone'`, you've corrupted your white space. Some of the above solutions will lose white space. Here's a solution that's good for Python 2 and 3 and preserves white space.

``````def propercase(s):
return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
``````

Should I use 'has_key()' or 'in' on Python dicts?

`in` wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:

``````\$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d'
10000000 loops, best of 3: 0.0983 usec per loop
\$ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)'
1000000 loops, best of 3: 0.21 usec per loop
``````

While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why `-mtimeit` is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)

``````Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;

confCollection["YourKey"].Value = "YourNewKey";

configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);
``````

OkHttp Post Body as JSON

Another approach is by using `FormBody.Builder()`.
Here's an example of callback:

``````Callback loginCallback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}

@Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
``````

Then, we create our own body:

``````RequestBody formBody = new FormBody.Builder()
.build();

OkHttpClient client = new OkHttpClient.Builder()
.build();
Request request = new Request.Builder()
.post(formBody)
.build();
``````

Finally, we call the server:

``````client.newCall(request).enqueue(loginCallback);
``````

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of `NSURL`:

``````NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
base64String]];

return [NSData dataWithContentsOfURL:URL];
``````

How to generate random colors in matplotlib?

I'm calling scatter inside a loop and want each plot in a different color.

Based on that, and on your answer: It seems to me that you actually want `n` distinct colors for your datasets; you want to map the integer indices `0, 1, ..., n-1` to distinct RGB colors. Something like:

Here is the function to do it:

``````import matplotlib.pyplot as plt

def get_cmap(n, name='hsv'):
'''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
RGB color; the keyword argument name must be a standard mpl colormap name.'''
return plt.cm.get_cmap(name, n)
``````

Usage in your pseudo-code snippet in the question:

``````cmap = get_cmap(len(data))
for i, (X, Y) in enumerate(data):
scatter(X, Y, c=cmap(i))
``````

I generated the figure in my answer with the following code:

``````import matplotlib.pyplot as plt

def get_cmap(n, name='hsv'):
'''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
RGB color; the keyword argument name must be a standard mpl colormap name.'''
return plt.cm.get_cmap(name, n)

def main():
N = 30
fig=plt.figure()
plt.axis('scaled')
ax.set_xlim([ 0, N])
ax.set_ylim([-0.5, 0.5])
cmap = get_cmap(N)
for i in range(N):
rect = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(i))
ax.set_yticks([])
plt.show()

if __name__=='__main__':
main()
``````

Tested with both Python 2.7 & matplotlib 1.5, and with Python 3.5 & matplotlib 2.0. It works as expected.

How to show PIL Image in ipython notebook

You can use IPython's `Module: display` to load the image. You can read more from the Doc.

``````from IPython.display import Image
pil_img = Image(filename='data/empire.jpg')
display(pil_img)
``````

updated

As OP's requirement is to use `PIL`, if you want to show inline image, you can use `matplotlib.pyplot.imshow` with `numpy.asarray` like this too:

``````from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image

%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))
``````

If you only require a preview rather than an inline, you may just use `show` like this:

``````pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()
``````

Generally i prefer the lambda syntax with LINQ, but `Join` is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

``````var query = db.Categories         // source
.Join(db.CategoryMaps,         // target
c => c.CategoryId,          // FK
cm => cm.ChildCategoryId,   // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category);  // select result
``````

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

If your problem persist with all those answers, try to change the file attribute to:

``````File.SetAttributes(yourfile, FileAttributes.Normal);
``````

``````require __DIR__.'/../bootstrap/autoload.php';
``````

in /public/index.php

When pasting in some debugging statements.

The name 'ViewBag' does not exist in the current context

I was having the same problem. Turned out I was missing the `./Views/Web.config` file, because I created the project from an empty ASP.NET application instead of using an ASP.NET MVC template.

For ASP.NET MVC 5, a vanilla `./Views/Web.config` file contains the following:

``````<?xml version="1.0"?>

<!-- https://stackoverflow.com/a/19899269/178082 -->
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
</namespaces>
</pages>
</system.web.webPages.razor>

<appSettings>
</appSettings>

<system.web>
<httpHandlers>
</httpHandlers>

<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
<controls>
</controls>
</pages>
</system.web>

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />

<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
``````

Adding a `./Views/Web.config` file containing this content fixed this problem for me.

How can I rename a conda environment?

You can't.

One workaround is to create clone environment, and then remove original one:

(remember about deactivating current environment with `deactivate` on Windows and `source deactivate` on macOS/Linux)

``````conda create --name new_name --clone old_name
conda remove --name old_name --all # or its alias: `conda env remove --name old_name`
``````

There are several drawbacks of this method:

1. it redownloads packages - you can use `--offline` flag to disable it,
2. time consumed on copying environment's files,
3. temporary double disk usage.

There is an open issue requesting this feature.

Converting file size in bytes to human-readable string

Another example similar to those here

``````function fileSize(b) {
var u = 0, s=1024;
while (b >= s || -b >= s) {
b /= s;
u++;
}
return (u ? b.toFixed(1) + ' ' : b) + ' KMGTPEZY'[u] + 'B';
}
``````

It measures negligibly better performance than the others with similar features.

how to enable sqlite3 for php?

one thing I want to add , before you try to install

``````apt-get install php5-sqlite
``````

or

``````apt-get install php5-sqlite3
``````

search the given package is available or not :-

`````` # apt-cache search 'php5'
``````

After that you get :-

``````php5-rrd - rrd module for PHP 5

php5-sasl - Cyrus SASL extension for PHP 5

php5-snmp - SNMP module for php5

**php5-sqlite - SQLite module for php5**

php5-svn - PHP Bindings for the Subversion Revision control system

php5-sybase - Sybase / MS SQL Server module for php5
``````

Here you get an idea about whether your version support or not .. in my system I get php5-sqlite - SQLite module for php5 so I prefer to install

``````**apt-get install php5-sqlite**
``````

Writing outputs to log file and console

I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:

``````2017-06-21 11:16:41+05:30 Fetching information about files in the directory...
``````

``````LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "\$(date --rfc-3339=seconds)" "\$line" | tee -a \$LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "\$(date --rfc-3339=seconds)" "\$line" | tee -a \$LOG_FILE; done >&2)
``````

Hope this helps somebody!

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:

``````>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'
``````

You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!

IE8 issue with Twitter Bootstrap 3

You got your CSS from CDN (bootstrapcdn.com) respond.js only works for local files. So try your website on IE8 with a local copy of bootstrap.css. Or read: CDN/X-Domain Setup

Update:

In addition, Internet Explorer 8 requires the use of respond.js to enable media query support.

For this reason the basic template contains these lines in the head section:

``````<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
``````

Changing the text on a label

Use the `config` method to change the value of the label:

``````top = Tk()

l = Label(top)
l.pack()

l.config(text = "Hello World", width = "50")
``````

AngularJS - ng-if check string empty value

If by "empty" you mean `undefined`, it is the way ng-expressions are interpreted. Then, you could use :

``````<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>
``````

What's the difference between a Future and a Promise?

In this example you can take a look at how Promises can be used in Java for creating asynchronous sequences of calls:

``````doSomeProcess()
.whenResult(result -> System.out.println(String.format("Result of some process is '%s'", result)))
.whenException(e -> System.out.println(String.format("Exception after some process is '%s'", e.getMessage())))
.map(String::toLowerCase)
.mapEx((result, e) -> e == null ? String.format("The mapped result is '%s'", result) : e.getMessage())
.whenResult(s -> System.out.println(s));
``````

How do I center an SVG in a div?

Answers above look incomplete as they are talking from css point of view only.

positioning of svg within viewport is affected by two svg attributes

1. viewBox: defines the rectangle area for svg to cover.
2. preserveAspectRatio: defined where to place the viewBox wrt viewport and how to strech it if viewport changes.

``````<svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet">
``````

Search and replace a particular string in a file using Perl

A one liner:

``````perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
``````

Sorting std::map using value

In this context, we should convert map to multimap. I think convert map to set is not good because we will lose many information in case of there is many duplicate values in the original map. Here is my solution, I defined the less than comparator that sort by value (cmp function). We can customize the cmp function as our demand.

``````std::map<int, double> testMap = { {1,9.1}, {2, 8.0}, {3, 7.0}, {4,10.5} };
auto cmp = [](const double &lhs,
const double &rhs)->bool
{
return lhs < rhs;
};
std::multimap<double, int, decltype(cmp)> mmap(cmp);
for (auto item : testMap)
mmap.insert(make_pair(item.second, item.first));
``````

Adding days to \$Date in PHP

All have to use bellow code:

``````\$nday = time() + ( 24 * 60 * 60);
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Day: '. date('Y-m-d', \$nday) ."\n";
``````

I had to add my `lib` directory in User Header Search Paths:

In my case the `lib` directory contains the `.a`-library file and some header files. These are included in the bridging header file. However, the swift compiler wouldn't find them. Only when I added `\${PROJECT_DIR}/lib` to the User Header Search Path it built the test target.

(I am using Xcode 6.2 on Mavericks 10.9.5)

Read and parse a Json File in C#

This can also be done in the following way:

``````JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
``````

How do I get logs/details of ansible-playbook module executions?

If you pass the `-v` flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:

``````\$ ansible-playbook -v playbook.yaml
``````

Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:

``````[defaults]
log_path=/path/to/logfile
``````

Ansible will look in several places for the config file:

• `ansible.cfg` in the current directory where you ran `ansible-playbook`
• `~/.ansible.cfg`
• `/etc/ansible/ansible.cfg`

How can I create a war file of my project in NetBeans?

It's possible that you already have a war file and don't know it - netbeans does most of the work for you and I believe it creates a distributable war file by default. If you created a web project and successfully built it, it will be in the "dist" directory off your project root.

There are two things to remember if you want to browse everything on your device.

1. You need to have a phone with root access in order to browse the data folder on an Android phone. That means either you have a developer device (ADP1 or an ION from Google I/O) or you've found a way to 'root' your phone some other way.
2. You need to be running ADB in root mode, do this by executing: `adb root`

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run `show dbs`.

You don't need to run the db.auth if you pass the auth in the command line:

``````mongo somewhere.mongolayer.com:10011/my_database -u username -p password
``````

Once you connect are you able to see collections?

``````> show collections
``````

If so all is well and you just don't have admin privileges to the database and can't run the `show dbs`

How do I validate a date in rails?

A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:

Inside your `model.rb`

``````validate :date_field_must_be_a_date_or_blank

# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
date_field_before_type_cast.to_date
rescue ArgumentError
end
``````

Make <body> fill entire screen?

Try using viewport (vh, vm) units of measure at the body level

html, body { margin: 0; padding: 0; } body { min-height: 100vh; }

Use vh units for horizontal margins, paddings, and borders on the body and subtract them from the min-height value.

I've had bizarre results using vh,vm units on elements within the body, especially when re-sizing.

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as \$iniData with 5 fields. If using ajax -

``````echo json_encode(\$iniData);
``````

In Javascript, use the following :

``````<script type="text/javascript">
\$.ajax({
type: "GET",
url: "ajaxCalls.php",
data: "dataType=ini",
success: function(msg)
{
var x = eval('(' + msg + ')');
\$('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
\$('#completed').html(x.completed);
\$('#running').html(x.running);
\$('#expired').html(x.expired);
\$('#balance').html(x.balance);
}
});
});
</script>
``````

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

Call this before the query:

``````set define off;
``````

Alternatively, hacky:

``````update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';
``````

From Tuning SQL*Plus:

SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

``````    <fb:visible-to-connection>
Fans will see this content.
<fb:else>
Non-fans will see this content.
</fb:else>
</fb:visible-to-connection>
``````

How to set session timeout dynamically in Java web applications?

Is there a way to set the session timeout programatically

There are basically three ways to set the session timeout value:

• by using the `session-timeout` in the standard `web.xml` file ~or~
• in the absence of this element, by getting the server's default `session-timeout` value (and thus configuring it at the server level) ~or~
• programmatically by using the `HttpSession. setMaxInactiveInterval(int seconds)` method in your Servlet or JSP.

But note that the later option sets the timeout value for the current session, this is not a global setting.

Table cell widths - fixing width, wrapping/truncating long words

Stack Overflow has solved a similar problem with long lines of code by using a DIV and having `overflow-x:auto`. CSS can't break up words for you.

Start script missing error when running npm start

It looks like you might not have defined a `start` script in your `package.json` file or your project does not contain a `server.js` file.

If there is a server.js file in the root of your package, then npm will default the start command to node server.js.

https://docs.npmjs.com/misc/scripts#default-values

You could either change the name of your application script to `server.js` or add the following to your `package.json`

``````"scripts": {
"start": "node your-script.js"
}
``````

Or ... you could just run `node your-script.js` directly

How to set column widths to a jQuery datatable?

Configuration Options:

``````\$(document).ready(function () {

\$("#companiesTable").dataTable({
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"bAutoWidth": false, // Disable the auto width calculation
"aoColumns": [
{ "sWidth": "30%" }, // 1st column width
{ "sWidth": "30%" }, // 2nd column width
{ "sWidth": "40%" } // 3rd column width and so on
]
});
});
``````

Specify the css for the table:

``````table.display {
margin: 0 auto;
width: 100%;
clear: both;
border-collapse: collapse;
}
``````

HTML:

``````<table id="companiesTable" class="display">
<tr>
<th>Company name</th>
<th>Town</th>
</tr>
<tbody>

<% for(Company c: DataRepository.GetCompanies()){ %>
<tr>
<td><%=c.getName()%></td>
<td><%=c.getTown()%></td>
</tr>
<% } %>

</tbody>
</table>
``````

It works for me!

Why is the use of alloca() not considered good practice?

alloca () is nice and efficient... but it is also deeply broken.

• broken scope behavior (function scope instead of block scope)
• use inconsistant with malloc (alloca()-ted pointer shouldn't be freed, henceforth you have to track where you pointers are coming from to free() only those you got with malloc())
• bad behavior when you also use inlining (scope sometimes goes to the caller function depending if callee is inlined or not).
• no stack boundary check
• undefined behavior in case of failure (does not return NULL like malloc... and what does failure means as it does not check stack boundaries anyway...)
• not ansi standard

In most cases you can replace it using local variables and majorant size. If it's used for large objects, putting them on the heap is usually a safer idea.

If you really need it C you can use VLA (no vla in C++, too bad). They are much better than alloca() regarding scope behavior and consistency. As I see it VLA are a kind of alloca() made right.

Of course a local structure or array using a majorant of the needed space is still better, and if you don't have such majorant heap allocation using plain malloc() is probably sane. I see no sane use case where you really really need either alloca() or VLA.

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

``````function readFile(file){
var def = \$.Deferred(), promise = def.promise();

//--- provide classic deferred interface

return promise;
}

var def = \$.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = \$.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();

var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });

promise.abort = function(){ return req.abort.apply(req, arguments); }

return promise;
}

var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = \$.md5 ? \$.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}

for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}

return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};

//----------
//---------- On submit form:
var form = \$("form");
var \$file = form.find("#file");
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, \$file[0].files[0].name];
});
``````

With FormData API you just have to add all fields of your form to FormData object and send it via \$.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

NuGet Package Restore Not Working

You have to choose one way of the following :

Re-installing a package by it's name in all solution's projects:

``````Update-Package –reinstall <packageName>
``````

Re-installing a package by it's name and ignoring it's dependencies in all solution's projects:

``````Update-Package –reinstall <packageName> -ignoreDependencies
``````

Re-installing a package by it's name in a project:

``````Update-Package –reinstall <packageName> <projectName>
``````

Re-installing all packages in a specific project:

``````Update-Package -reinstall -ProjectName <projectName>
``````

Re-installing all packages in a solution:

``````Update-Package -reinstall
``````

Rewrite all requests to index.php with nginx

Here is what worked for me to solve part 1 of this question:

``````    location / {
rewrite ^([^.]*[^/])\$ \$1/ permanent;
try_files \$uri \$uri/ /index.php =404;
include fastcgi_params;
fastcgi_pass php5-fpm-sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
fastcgi_intercept_errors on;
}
``````

rewrite ^([^.]*[^/])\$ \$1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.

try_files \$uri \$uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.

fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.

\$http.get(...).success is not a function

The `.success` syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use `then` method. The `then()` method takes two arguments: a `success` and an `error` callback which will be called with a response object.

Using the `then()` method, attach a `callback` function to the returned `promise`.

Something like this:

``````app.controller('MainCtrl', function (\$scope, \$http){
\$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){

},function (error){

});
}
``````

See reference here.

`Shortcut` methods are also available.

``````\$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
``````

The data you get from the response is expected to be in `JSON` format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that `.then()` call returns a `promise` (resolved with a value returned from a `callback`) while `.success()` is more traditional way of registering `callbacks` and doesn't return a `promise`.

Python Checking a string's first and last character

When you say `[:-1]` you are stripping the last element. Instead of slicing the string, you can apply `startswith` and `endswith` on the string object itself like this

``````if str1.startswith('"') and str1.endswith('"'):
``````

So the whole program becomes like this

``````>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi
``````

Even simpler, with a conditional expression, like this

``````>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
``````

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

``````string str = "True";
bool mybool = System.Convert.ToBoolean(str);
``````

boolean to string: true to True

``````bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();
``````

`bool.Parse` expects one parameter which in this case is str, even .

`Convert.ToBoolean` expects one parameter.

`bool.TryParse` expects two parameters, one entry (str) and one out (result).

If `TryParse` is true, then the conversion was correct, otherwise an error occurred

``````string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
//Correct conversion
}
else
{
//Incorrect, an error has occurred
}
``````

How to set max width of an image in CSS

You can write like this:

``````img{
width:100%;
max-width:600px;
}
``````

Check this http://jsfiddle.net/ErNeT/

Converting time stamps in excel to dates

If your file is really big try to use following formula: =A1 / 86400 + 25569

A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.

How to extract duration time from ffmpeg output?

ffmpeg is writing that information to `stderr`, not `stdout`. Try this:

``````ffmpeg -i file.mp4 2>&1 | grep Duration | sed 's/Duration: \(.*\), start/\1/g'
``````

Notice the redirection of `stderr` to `stdout`: `2>&1`

EDIT:

Your `sed` statement isn't working either. Try this:

``````ffmpeg -i file.mp4 2>&1 | grep Duration | awk '{print \$2}' | tr -d ,
``````

Constants in Objective-C

If you want to call something like this `NSString.newLine;` from objective c, and you want it to be static constant, you can create something like this in swift:

``````public extension NSString {
@objc public static let newLine = "\n"
}
``````

And you have nice readable constant definition, and available from within a type of your choice while stile bounded to context of type.

how to add background image to activity?

We can easily place the background image in PercentFrameLayout using the ImageView. We have to set the scaleType attribute value="fitXY" and in the foreground we can also display other view's like textview or button.

`````` <android.support.percent.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<ImageView
android:src="@drawable/logo"
android:id="@+id/im1"
android:scaleType="fitXY"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
<EditText android:layout_gravity="center_horizontal"
android:id="@+id/et1"
android:layout_height="wrap_content"
app:layout_widthPercent="50%"
app:layout_marginTopPercent="30%"
/>
<Button
android:layout_gravity="center_horizontal"
android:id="@+id/b1"
android:layout_height="wrap_content"
app:layout_widthPercent="50%"
app:layout_marginTopPercent="40%"/>
</android.support.percent.PercentFrameLayout>
``````

Scale iFrame css width 100% like an image

Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.

Check this link for example : http://jsfiddle.net/Masau/7WRHM/

HTML:

``````<div class="wrapper">
<div class="h_iframe">
<!-- a transparent image is preferable -->
<img class="ratio" src="http://placehold.it/16x9"/>
</div>
<p>Please scale the "result" window to notice the effect.</p>
</div>
``````

CSS:

``````html,body        {height:100%;}
.wrapper         {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe        {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}
``````

note: This only works with a fixed aspect-ratio.

Using jQuery to center a DIV on the screen

I'm expanding upon the great answer given by @TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in "no conflict" mode, like for instance in WordPress.

I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.

The other thing I do is speed this up a bit by caching the \$(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.

``````jQuery.fn.center = function (\$) {
var w = \$(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
``````

To use, you would do something like:

``````jQuery(document).ready(function(\$){
\$('#myelem').center();
});
``````

Remove Datepicker Function dynamically

Destroy the datepicker's instance when you don't want it and create new instance whenever necessary.

I know this is ugly but only this seems to be working...

Check this out

`````` \$("#ddlSearchType").change(function () {
if (\$(this).val() == "Required Date" || \$(this).val() == "Submitted Date") {
\$("#txtSearch").datepicker();

}
else {
\$("#txtSearch").datepicker("destroy");
}
});
``````

Difference between WebStorm and PHPStorm

Essentially, PHPStorm = WebStorm + PHP, SQL and more.

BUT (and this is a very important "but") because it is capable of parsing so much more, it quite often fails to parse Node.js dependencies, as they (probably) conflict with some other syntax it is capable of parsing.

The most notable example of that would be Mongoose model definition, where WebStorm easily recognizes mongoose.model method, whereas PHPStorm marks it as unresolved as soon as you connect Node.js plugin.

Surprisingly, it manages to resolve the method if you turn the plugin off, but leave the core modules connected, but then it cannot be used for debugging. And this happens to quite a few methods out there.

All this goes for PHPStorm 8.0.1, maybe in later releases this annoying bug would be fixed.

How do I supply an initial value to a text field?

``````class _YourClassState extends State<YourClass> {
TextEditingController _controller = TextEditingController();

@override
void initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send message...'),
),
);
}
}
``````

ImportError: No module named model_selection

I had the same problem while using Jupyter Notebook, no matter what I updated in Python 3, conda, I could not get in Jupyter:

``````import sklearn
print (sklearn.__version__)
0.17.1
``````

to SHOW scikit-learn-0.18.1

Finally, I removed Anaconda3 and Jupyter Notebook and reinstalled fresh. I got it to work.

http://ukitech.blogspot.com/2017/02/sklearnmodelselection.html

How to get text of an element in Selenium WebDriver, without including child element text?

``````def get_true_text(tag):
children = tag.find_elements_by_xpath('*')
original_text = tag.text
for child in children:
original_text = original_text.replace(child.text, '', 1)
return original_text
``````

Flex-box: Align last row to grid

One technique would be inserting a number of extra elements (as many as the max number of elements you ever expect to have in a row) that are given zero height. Space is still divided, but superfluous rows collapse to nothing:

http://codepen.io/dalgard/pen/Dbnus

_x000D_
_x000D_
``````body {_x000D_
}_x000D_
_x000D_
div {_x000D_
overflow: hidden;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
ul {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
margin: 0 -4px -4px 0;_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
li {_x000D_
flex: 1 0 200px;_x000D_
height: 200px;_x000D_
border-right: 4px solid black;_x000D_
border-bottom: 4px solid black;_x000D_
background-color: deeppink;_x000D_
}_x000D_
li:empty {_x000D_
height: 0;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
*,_x000D_
:before,_x000D_
:after {_x000D_
box-sizing: border-box;_x000D_
}``````
_x000D_
``````<div>_x000D_
<ul>_x000D_
<li>a</li>_x000D_
<li>b</li>_x000D_
<li>c</li>_x000D_
<li>d</li>_x000D_
<li>e</li>_x000D_
<li>f</li>_x000D_
<li>g</li>_x000D_
<li>h</li>_x000D_
<li>i</li>_x000D_
<li>j</li>_x000D_
<li>k</li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

In the future, this may become achievable through using multiple `::after(n)`.

Graphical DIFF programs for linux

There is DiffMerge from SourceGear. It's pretty good. Araxis Merge is one of the programs I miss from Windows. I wonder if it works under Wine ;) Might have to give it a try

How do I remove the passphrase for the SSH key without having to create a new key?

`\$ ssh-keygen -p` worked for me

Opened git bash. Pasted : `\$ ssh-keygen -p`

Hit enter for default location.

Enter old passphrase

Enter new passphrase - BLANK

Confirm new passphrase - BLANK

BOOM the pain of entering passphrase for git push was gone.

Thanks!

get string value from HashMap depending on key name

`````` HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(4, "DD");
``````

The Value mapped to Key `4` is `DD`

Filezilla FTP Server Fails to Retrieve Directory Listing

My experience is that the new version of Filezilla has this problem, but not the old versions. I was using Filezilla and everything was OK. After I upgraded to version 3.10, I faced this problem and I couldn't solve it. I uninstalled version 3.10 and reinstalled version 3.8 and the problem was gone! Now I am using version 3.8 and everything is OK. I prefer to face no problems even if I have to use old versions. ;)

Try installing the old version and do not upgrade, however odd that may sound.

Using .text() to retrieve only text not nested in child tags

Use an extra condition to check if innerHTML and innerText are the same. Only in those cases, replace the text.

``````\$(function() {
\$('body *').each(function () {
console.log(\$(this).html());
console.log(\$(this).text());
if(\$(this).text() === "Search" && \$(this).html()===\$(this).text())  {
\$(this).html("Find");
}
})
})
``````

http://jsfiddle.net/7RSGh/

Enter export password to generate a P12 certificate

The selected answer apparently does not work anymore in 2019 (at least for me).

I was trying to export a certificate using openssl (version 1.1.0) and the parameter `-password` doesn't work.

According to that link in the original answer (the same info is in `man openssl`), openssl has two parameter for passwords and they are `-passin` for the input parts and `-passout` for output files.

For the `-export` command, I used `-passin` for the password of my key file and `-passout` to create a new password for my P12 file.

So the complete command without any prompt was like below:

``````openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass:keypassphrase -passout pass:certificatepassword
``````

If you does not want a password, you can use `pass:` like below:

``````openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass: -passout pass:
``````

It will works fine with a key without password and the output certificate will be created without password too.

How do I read configuration settings from Symfony2 config.yml?

I learnt a easy way from code example of http://tutorial.symblog.co.uk/

1) notice the ZendeskBlueFormBundle and file location

``````# myproject/app/config/config.yml

imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }

framework:
``````

2) notice Zendesk_BlueForm.emails.contact_email and file location

``````# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml

parameters:
Zendesk_BlueForm.emails.contact_email: [email protected]
``````

3) notice how i get it in \$client and file location of controller

``````# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php

public function blueFormAction(\$name, \$arg1, \$arg2, \$arg3, Request \$request)
{
\$client = new ZendeskAPI(\$this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
...
}
``````

How to position text over an image in css

as Harry Joy points out, set the image as the div's background and then, if you only have one line of text you can set the line-height of the text to be the same as the div height and this will place your text in the center of the div.

If you have more than one line you'll want to set the display to be table-cell and vertical-alignment to middle.

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

Auto height of div

`div`'s will naturally resize in accordance with their content.

If you set no height on your div, it will expand to contain its conent.

An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.

Here's some ways to do this:

``````#wrapper{
overflow:hidden;
}
``````

Or

``````#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}
``````

How to show all rows by default in JQuery DataTable

Use:

``````\$('#example').dataTable({
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
``````

Or if using 1.10+

``````\$('#example').dataTable({
paging: false
});
``````

The option you should use is iDisplayLength:

``````\$('#adminProducts').dataTable({
'iDisplayLength': 100
});
``````

``````\$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
``````

It will Load by default all entries.

``````\$('#example').dataTable({
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
``````

Or if using 1.10+

``````\$('#example').dataTable({
paging: false
});
``````

If you want to load by default 25 not all do this.

``````\$('#example').dataTable({
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
``````

Why can't I use background image and color together?

use

``````background:red url(../images/samle.jpg) no-repeat left top;
``````

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

``````ifeq (yes, \${TEST})
CXXFLAGS := \${CXXFLAGS} -DDESKTOP_TEST
test:
\$(info ************  TEST VERSION ************)
else
release:
\$(info ************ RELEASE VERSIOIN **********)
endif
``````

What's the use of "enum" in Java?

Java programming language `enums` are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems(`Not typesafe, No namespace, Brittleness and Printed values are uninformative`) that exists with following int Enum pattern which was used prior to java 5.0 :

`public static final int SEASON_WINTER = 0;`

it also allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are `Comparable` and `Serializable`, and the serial form is designed to withstand arbitrary changes in the enum type. You can also use Enum in `switch` case.

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

``````Manifest-Version: 1.0
Main-Class: your.programs.MainClass
``````

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

``````String context = System.getProperty("myvar");
``````

See this question about argument passing in Java.

sed edit file in place

Very good examples. I had the challenge to edit in place many files and the -i option seems to be the only reasonable solution using it within the find command. Here the script to add "version:" in front of the first line of each file:

``````find . -name pkg.json -print -exec sed -i '.bak' '1 s/^/version /' {} \;
``````

How to send a stacktrace to log4j?

In Log4j 2, you can use Logger.catching() to log a stacktrace from an exception that was caught.

``````    try {
String msg = messages[messages.length];
logger.error("An exception should have been thrown");
} catch (Exception ex) {
logger.catching(ex);
}
``````

How can I time a code segment for testing performance with Pythons timeit?

Here is an example of how to time a function using `timeit`:

``````import timeit

def time_this(n):
return [str(i) for i in range(n)]

timeit.timeit(lambda: time_this(n=5000), number=1000)
``````

This will return the time in seconds it took to execute the `time_this()` function 1000 times.

jQuery datepicker, onSelect won't work

``````\$('.date-picker').datepicker({
autoclose : true,
todayHighlight : true,
clearBtn: true,
format: 'yyyy-mm-dd',
onSelect: function(value, date) {
},
startView: 0, maxViewMode: 0,minViewMode:0

}).on('changeDate',function(ev){
//this is right events ,trust me
}
});
``````

Use different Python version with virtualenv

These are the steps you can follow when you are on a shared hosting environment and need to install & compile Python from source and then create `venv` from your Python version. For Python 2.7.9. you would do something along these lines:

``````mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9
mkdir ~/.localpython
./configure --prefix=\$HOME/.localpython
make
make install
``````

virtual env

``````cd ~/src
wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63
tar -zxvf virtualenv-15.0.2.tar.gz
cd virtualenv-15.0.2/
~/.localpython/bin/python setup.py install
virtualenv ve -p \$HOME/.localpython/bin/python2.7
source ve/bin/activate
``````

Naturally, this can be applicable to any situation where you want to replicate the exact environment you work and deploy on.

Target WSGI script cannot be loaded as Python module

For me the issue was that the WSGI script wasn't executable.

``````sudo chmod a+x django.wsgi
``````

or just

``````sudo chmod u+x django.wsgi
``````

so long as you have the correct owner

Converting a String to a List of Words?

This is from my attempt on a coding challenge that can't use regex,

``````outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')
``````

The role of apostrophe seems interesting.

How to var_dump variables in twig templates?

For debugging Twig templates you can use the debug statement.

There you can set the debug setting explicitely.

Why don't self-closing script elements work?

Internet Explorer 8 and earlier do not support XHTML parsing. Even if you use an XML declaration and/or an XHTML doctype, old IE still parse the document as plain HTML. And in plain HTML, the self-closing syntax is not supported. The trailing slash is just ignored, you have to use an explicit closing tag.

Even browsers with support for XHTML parsing, such as IE 9 and later, will still parse the document as HTML unless you serve the document with a XML content type. But in that case old IE will not display the document at all!

To get total number of columns in a table in sql

This query gets the columns name

``````SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
``````

And this one gets the count

``````SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
``````

There seems to be a lot of confusion here. The answers I see so far don't correctly enforce the 1+ number/1+ lowercase/1+ uppercase rule, meaning that passwords like abc123, 123XYZ, or AB*&^# would still be accepted. Preventing all-lowercase, all-caps, or all-digits is not enough; you have to enforce the presence of at least one of each.

Try the following:

``````^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}\$
``````

If you also want to require at least one special character (which is probably a good idea), try this:

``````^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}\$
``````

The `.{8,15}` can be made more restrictive if you wish (for example, you could change it to `\S{8,15}` to disallow whitespace), but remember that doing so will reduce the strength of your password scheme.

I've tested this pattern and it works as expected. Tested on ReFiddle here: http://refiddle.com/110

Edit: One small note, the easiest way to do this is with 3 separate regexes and the string's `Length` property. It's also easier to read and maintain, so do it that way if you have the option. If this is for validation rules in markup, though, you're probably stuck with a single regex.

Wait for a void async method

If you can change the signature of your function to `async Task` then you can use the code presented here

How link to any local file with markdown syntax?

This is a old question, but to me it still doesn't seem to have a complete answer to the OP's question. The chosen answer about security being the possible issue is actually often not the problem when using the Firefox 'Markdown Viewer' plug-in in my experience. Also, the OP seems to be using MS-Windows, so there is the added issue of specifying different drives.

So, here is a little more complete yet simple answer for the 'Markdown Viewer' plug-in on Windows (and other Markdown renderers I've seen): just enter the local path as you would normally, and if it is an absolute path make sure to start it with a slash. So:

``````[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
``````

That last one was probably what the OP was looking for given their example. Note this can also be used to display directories rather than files.

Though late, I hope this helps!

How to set maximum fullscreen in vmware?

From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

It seems your VirtualBox installation doesn't work correctly. You should try to reinstall/upgrade VirtualBox so that during the installation process it fixes this "Interface not found" issue.

How to drop a list of rows from Pandas dataframe?

Consider an example dataframe

``````df =
index    column1
0           00
1           10
2           20
3           30
``````

we want to drop 2nd and 3rd index rows.

Approach 1:

``````df = df.drop(df.index[2,3])
or
df.drop(df.index[2,3],inplace=True)
print(df)

df =
index    column1
0           00
3           30

#This approach removes the rows as we wanted but the index remains unordered
``````

Approach 2

``````df.drop(df.index[2,3],inplace=True,ignore_index=True)
print(df)
df =
index    column1
0           00
1           30
#This approach removes the rows as we wanted and resets the index.
``````

Why do Twitter Bootstrap tables always have 100% width?

If you're using Bootstrap 4, use `.w-auto`.

Remove elements from collection while iterating

Let me give a few examples with some alternatives to avoid a `ConcurrentModificationException`.

Suppose we have the following collection of books

``````List<Book> books = new ArrayList<Book>();
``````

Collect and Remove

The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.

``````ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
if(book.getIsbn().equals(isbn)){
}
}
books.removeAll(found);
``````

This is supposing that the operation you want to do is "delete".

If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an `addAll` method at the end.

Using ListIterator

If you are working with lists, another technique consists in using a `ListIterator` which has support for removal and addition of items during the iteration itself.

``````ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
if(iter.next().getIsbn().equals(isbn)){
iter.remove();
}
}
``````

Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its `add` method to add new elements during iteration.

Using JDK >= 8

For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.

You could use the new `removeIf` method in the `Collection` base class:

``````ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));
``````

Or use the new stream API:

``````ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
.filter(b -> b.getIsbn().equals(other))
.collect(Collectors.toList());
``````

In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e. `books = filtered`) or used the filtered collection to `removeAll` the found elements from the original collection (i.e. `books.removeAll(filtered)`).

Use Sublist or Subset

There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:

``````books.subList(0,5).clear();
``````

Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.

Something similar could be achieved with sorted sets using `NavigableSet.subSet` method, or any of the slicing methods offered there.

Considerations:

What method you use might depend on what you are intending to do

• The collect and `removeAl` technique works with any Collection (Collection, List, Set, etc).
• The `ListIterator` technique obviously only works with lists, provided that their given `ListIterator` implementation offers support for add and remove operations.
• The `Iterator` approach would work with any type of collection, but it only supports remove operations.
• With the `ListIterator`/`Iterator` approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient.
• The JDK 8 streams example don't actually removed anything, but looked for the desired elements, and then we replaced the original collection reference with the new one, and let the old one be garbage collected. So, we iterate only once over the collection and that would be efficient.
• In the collect and `removeAll` approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it.
• I think it is worth mentioning that the remove method of the `Iterator` interface is marked as "optional" in Javadocs, which means that there could be `Iterator` implementations that throw `UnsupportedOperationException` if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.

Change string color with NSAttributedString?

With Swift 4, `NSAttributedStringKey` has a static property called `foregroundColor`. `foregroundColor` has the following declaration:

``````static let foregroundColor: NSAttributedStringKey
``````

The value of this attribute is a `UIColor` object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

The following Playground code shows how to set the text color of an `NSAttributedString` instance with `foregroundColor`:

``````import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
``````

The code below shows a possible `UIViewController` implementation that relies on `NSAttributedString` in order to update the text and text color of a `UILabel` from a `UISlider`:

``````import UIKit

enum Status: Int {

var display: (text: String, color: UIColor) {
switch self {
case .okay:     return ("Okay", .yellow)
case .good:     return ("Good", .green)
case .veryGood: return ("Very good", .blue)
}
}

static let maximumValue = Status.veryGood.rawValue
}
``````
``````final class ViewController: UIViewController {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var slider: UISlider!
var currentStatus: Status = Status.veryBad {
didSet {
// currentStatus is our model. Observe its changes to update our display
updateDisplay()
}
}

// Prepare slider
slider.minimumValue = Float(Status.minimumValue)
slider.maximumValue = Float(Status.maximumValue)

// Set display
updateDisplay()
}

func updateDisplay() {
let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
label.attributedText = attributedString
slider.value = Float(currentStatus.rawValue)
}

@IBAction func updateCurrentStatus(_ sender: UISlider) {
let value = Int(sender.value.rounded())
guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
currentStatus = status
}

}
``````

Note however that you don't really need to use `NSAttributedString` for such an example and can simply rely on `UILabel`'s `text` and `textColor` properties. Therefore, you can replace your `updateDisplay()` implementation with the following code:

``````func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}
``````

Check if current directory is a Git repository

Not sure if there is a publicly accessible/documented way to do this (there are some internal git functions which you can use/abuse in the git source itself)

You could do something like;

``````if ! git ls-files >& /dev/null; then
echo "not in git"
fi
``````

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

``````set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type

for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
``````

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to `3456`:

``````set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _

for each tcpProperty in tcpProperties
dim setValueResult, requestedValue

if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if

setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
``````

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

1. Use `LoginMode` property of `Microsoft.SqlServer.Management.Smo.Server` class, as described here.

2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named `SQLEXPRESS`, so for my SQL Server 2008 R2 Express instance the right registry key was `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer`.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

``````SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
``````

Please let me know if this works for you (fingers crossed!).

Table column sizing

As of Alpha 6 you can create the following sass file:

``````@each \$breakpoint in map-keys(\$grid-breakpoints) {
\$infix: breakpoint-infix(\$breakpoint, \$grid-breakpoints);

col, td, th {
@for \$i from 1 through \$grid-columns {
&.col#{\$infix}-#{\$i} {
flex: none;
position: initial;
}
}

@include media-breakpoint-up(\$breakpoint, \$grid-breakpoints) {
@for \$i from 1 through \$grid-columns {
&.col#{\$infix}-#{\$i} {
width: 100% / \$grid-columns * \$i;
}
}
}
}
}
``````

Python: how to print range a-z?

``````list(string.ascii_lowercase)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
``````

Bash Templating: How to build configuration files from templates with Bash?

``````eval "cat <<EOF >outputfile
\$( cat template.in )
EOF
" 2> /dev/null
``````

DateTime.ToString() format that can be used in a filename or extension?

I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with

``````DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35
``````

When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.

Node JS Error: ENOENT

use "temp" in lieu of "tmp"

"/temp/test.png"

it worked for me after i realized the tmp is a temporary folder that didn't exist on my computer, but my temp was my temporary folder

///

EDIT:

I also created a new folder "tmp" in my C: drive and everything worked perfectly. The book may have missed mentioning that small step

check out http://webchat.freenode.net/?channels=node.js to chat with some of the node.js community

How do I run a program with a different working directory from current, from Linux shell?

If you want to perform this inside your program then I would do something like:

``````#include <unistd.h>
int main()
{
if(chdir("/c") < 0 )
{
printf("Failed\n");
return -1 ;
}

}
``````

PHP foreach change original array values

Try this

``````function checkForm(\$fields){
foreach(\$fields as \$field){
if(\$field['required'] && strlen(\$_POST[\$field['name']]) <= 0){
\$field['value'] = "Some error";
}
}
return \$field;
}
``````

android listview get selected item

``````final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

}
});
``````

I hope this fixes your problem.

Bring a window to the front in WPF

Well, since this is such a hot topic... here is what works for me. I got errors if I didn't do it this way because Activate() will error out on you if you cannot see the window.

Xaml:

``````<Window ....
Topmost="True"
....
ContentRendered="mainWindow_ContentRendered"> .... </Window>
``````

Codebehind:

``````private void mainWindow_ContentRendered(object sender, EventArgs e)
{
this.Topmost = false;
this.Activate();
}
``````

This was the only way for me to get the window to show on top. Then activate it so you can type in the box without having to set focus with the mouse. control.Focus() wont work unless the window is Active();

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

``````sub myhandler(eventsource)
process(eventsource.value)
end sub

for each cell
cell.setEventHandler(myHandler)
``````

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

Change column type in pandas

Here is a function that takes as its arguments a DataFrame and a list of columns and coerces all data in the columns to numbers.

``````# df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
# dependencies: pandas

def coerce_df_columns_to_numeric(df, column_list):
df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
``````

``````import pandas as pd

def coerce_df_columns_to_numeric(df, column_list):
df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col1','col2','col3'])

coerce_df_columns_to_numeric(df, ['col2','col3'])
``````

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

``````class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
int myMember;

public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
}

// Provide implementation for the second method
void Concrete::method2()
{
}

int main(void)
{
Interface *f = new Concrete();

f->method1();
f->method2();

delete f;

return 0;
}
``````

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

You need to close all your connexions for example: If you make an INSERT INTO statement you need to close the statement and your connexion in this way:

``````statement.close();
Connexion.close():
``````

And if you make a SELECT statement you need to close the statement, the connexion and the resultset in this way:

``````resultset.close();
statement.close();
Connexion.close();
``````

I did this and it worked

What exactly is the meaning of an API?

1) What is an API?

API is a contract. A promise to perform described services when asked in specific ways.

2) How is it used?

According to the rules specified in the contract. The whole point of an API is to define how it's used.

3) When and where is it used?

It's used when 2 or more separate systems need to work together to achieve something they can't do alone.

How do you generate a random double uniformly distributed between 0 and 1 from C++?

``````double randDouble()
{
double out;
out = (double)rand()/(RAND_MAX + 1); //each iteration produces a number in [0, 1)
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;

return out;
}
``````

Not quite as fast as `double X=((double)rand()/(double)RAND_MAX);`, but with better distribution. That algorithm gives only RAND_MAX evenly spaced choice of return values; this one gives RANDMAX^6, so its distribution is limited only by the precision of double.

If you want a long double just add a few iterations. If you want a number in [0, 1] rather than [0, 1) just make line 4 read `out = (double)rand()/(RAND_MAX);`.

Android SDK installation doesn't find JDK

It is bug in the Android installer. Download the latest installer and try it. Then it will work.

What exactly is Apache Camel?

If you have 5 to 10 minutes, I generally recommend people to read this Integration with Apache Camel by Jonathan Anstey. It's a well written piece which gives a brief introduction to and overview of some of Camel's concepts, and it implements a use case with code samples. In it, Jonathan writes:

Apache Camel is an open source Java framework that focuses on making integration easier and more accessible to developers. It does this by providing:

• concrete implementations of all the widely used Enterprise Integration Patterns (EIPs)
• connectivity to a great variety of transports and APIs
• easy to use Domain Specific Languages (DSLs) to wire EIPs and transports together

There is also a free chapter of Camel in Action (Camel in Action, 2nd ed. is here) which introduces Camel in the first chapter. Jonathan is a co-author on that book with me.

Disable JavaScript error in WebBrowser control

I just found this :

`````` private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value)
{
FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (field != null)
{
object axIWebBrowser2 = field.GetValue(webBrowser);
if (axIWebBrowser2 != null)
{
axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value });
return true;
}
}

return false;
}
``````

usage example to set webBrowser to silent : TrySetSuppressScriptErrors(webBrowser,true)

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can simply write in Ajax Success like below :

`````` \$.ajax({
type: "POST",
url: '@Url.Action("GetUserList", "User")',
data: { id: \$("#UID").val() },
success: function (data) {
window.location.href = '@Url.Action("Dashboard", "User")';
},
error: function () {
}
});
``````

Can a normal Class implement multiple interfaces?

Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior. I am attaching a detailed class diagram and shell interfaces and classes.

Ceremonial example:

``````public interface Mammal {
void move();
boolean possessIntelligence();
}
``````
``````public interface Animal extends Mammal {
void liveInJungle();
}

``````
``````public interface Human extends Mammal, TwoLeggedMammal, Omnivore, Hunter {
void liveInCivilization();
}
``````
``````public interface Carnivore {
void eatMeat();
}
``````
``````public interface Herbivore {
void eatPlant();
}
``````
``````public interface Omnivore extends Carnivore, Herbivore {
void eatBothMeatAndPlant();
}
``````
``````public interface FourLeggedMammal {
void moveWithFourLegs();
}
``````
``````public interface TwoLeggedMammal {
void moveWithTwoLegs();
}
``````
``````public interface Hunter {
void huntForFood();
}
``````
``````public class Kangaroo implements Animal, Herbivore, TwoLeggedMammal {
@Override
public void liveInJungle() {
System.out.println("I live in Outback country");
}

@Override
public void move() {
moveWithTwoLegs();
}

@Override
public void moveWithTwoLegs() {
System.out.println("I like to jump");
}

@Override
public void eat() {
eatPlant();
}

@Override
public void eatPlant() {
System.out.println("I like this grass");
}

@Override
public boolean possessIntelligence() {
return false;
}
}

``````
``````public class Lion implements Animal, FourLeggedMammal, Hunter, Carnivore {
@Override
public void liveInJungle() {
System.out.println("I am king of the jungle!");

}

@Override
public void move() {
moveWithFourLegs();
}

@Override
public void moveWithFourLegs() {
System.out.println("I like to run sometimes.");
}

@Override
public void eat() {
eatMeat();
}

@Override
public void eatMeat() {
System.out.println("I like deer meat");
}

@Override
public boolean possessIntelligence() {
return false;
}

@Override
public void huntForFood() {
System.out.println("My females hunt often");
}
}
``````
``````public class Teacher implements Human {
@Override
public void liveInCivilization() {
System.out.println("I live in an apartment");
}

@Override
public void moveWithTwoLegs() {
System.out.println("I wear shoes and walk with two legs one in front of the other");
}

@Override
public void move() {
moveWithTwoLegs();
}

@Override
public boolean possessIntelligence() {
return true;
}

@Override
public void huntForFood() {
System.out.println("My ancestors used to but now I mostly rely on cattle");
}

@Override
public void eat() {
eatBothMeatAndPlant();
}

@Override
public void eatBothMeatAndPlant() {
eatPlant();
eatMeat();
}

@Override
public void eatMeat() {
System.out.println("I like this bacon");
}

@Override
public void eatPlant() {
System.out.println("I like this broccoli");
}
}
``````

C++, How to determine if a Windows Process is running?

You can never check and see if a process is running, you can only check to see if a process was running at some point in the recent past. A process is an entity that is not controlled by your application and can exit at any moment in time. There is no way to guaranteed that a process will not exit in between the check to see if it's running and the corresponding action.

The best approach is to just do the action required and catch the exception that would be thrown if the process was not running.

How to Get a Sublist in C#

Would it be as easy as running a LINQ query on your List?

``````List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();
``````

How to scale a BufferedImage

Unfortunately the performance of getScaledInstance() is very poor if not problematic.

The alternative approach is to create a new BufferedImage and and draw a scaled version of the original on the new one.

``````BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, original.getWidth(),
original.getHeight(), null);
g.dispose();
``````

newWidth,newHeight indicate the new BufferedImage size and have to be properly calculated. In case of factor scaling:

``````int newWidth = new Double(original.getWidth() * widthFactor).intValue();
int newHeight = new Double(original.getHeight() * heightFactor).intValue();
``````

EDIT: Found the article illustrating the performance issue: The Perils of Image.getScaledInstance()

What is App.config in C#.NET? How to use it?

Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below ConfigurationSettings.AppSettings["Key"]

How to convert byte array to string and vice versa?

Using `new String(byOriginal)` and converting back to `byte[]` using `getBytes()` doesn't guarantee two `byte[]` with equal values. This is due to a call to `StringCoding.encode(..)` which will encode the `String` to `Charset.defaultCharset()`. During this encoding, the encoder might choose to replace unknown characters and do other changes. Hence, using `String.getBytes()` might not return an equal array as you've originally passed to the constructor.

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

``````\$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
``````

What is the "continue" keyword and how does it work in Java?

Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop. Consider the following Program. '

``````public class ContinueBreak {
public static void main(String[] args) {
String[] table={"aa","bb","cc","dd"};
for(String ss:table){
if("bb".equals(ss)){
continue;
}
System.out.println(ss);
if("cc".equals(ss)){
break;
}
}
System.out.println("Out of the loop.");
}

}
``````

It will print: aa cc Out of the loop.

If you use break in place of continue(After if.), it will just print aa and out of the loop.

If the condition "bb" equals ss is satisfied: For Continue: It goes to next iteration i.e. "cc".equals(ss). For Break: It comes out of the loop and prints "Out of the loop. "

How to fully delete a git repository created with init?

Alternative to killing TortoiseGit:

• Open the TortoiseGit-Settings (right click to any folder, TortoiseGit → Settings)
• Go to the Icon Overlays option.
• Change the Status Cache from Default to None
• Now you can delete the directory (either with Windows Explorer or `rmdir /S /Q`)
• Set back the Status Cache from None to Default and you should be fine again...

ScriptManager.RegisterStartupScript code not working - why?

You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code

``````ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);
``````

Convert int to char in java

if you want to print ascii characters based on their ascii code and do not want to go beyond that (like unicode characters), you can define your variable as a byte, and then use the (char) convert. i.e.:

``````public static void main(String[] args) {
byte b = 65;
for (byte i=b; i<=b+25; i++) {
System.out.print((char)i + ", ");
}
``````

BTW, the ascii code for the letter 'A' is 65

List append() in for loop

No need to re-assign.

``````a=[]
for i in range(5):
a.append(i)
a
``````

How to check if JavaScript object is JSON

I wrote an npm module to solve this problem. It's available here:

`object-types`: a module for finding what literal types underly objects

Install

``````  npm install --save object-types
``````

Usage

``````const objectTypes = require('object-types');

objectTypes({});
//=> 'object'

objectTypes([]);
//=> 'array'

objectTypes(new Object(true));
//=> 'boolean'
``````

Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types

How can I get a file's size in C++?

Using standard library:

Assuming that your implementation meaningfully supports SEEK_END:

``````fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file
``````

Linux/POSIX:

You can use `stat` (if you know the filename), or `fstat` (if you have the file descriptor).

Here is an example for stat:

``````#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;
``````

Win32:

You can use GetFileSize or GetFileSizeEx.

How to create unique keys for React elements?

There are many ways in which you can create `unique keys`, the simplest method is to use the index when iterating arrays.

Example

``````    var lists = this.state.lists.map(function(list, index) {
return(
<div key={index}>
<div key={list.name} id={list.name}>
</div>
</div>
)
});
``````

Wherever you're lopping over data, here `this.state.lists.map`, you can pass second parameter `function(list, index)` to the callback as well and that will be its `index` value and it will be unique for all the items in the array.

And then you can use it like

`<div key={index}>`

You can do the same here as well

``````    var savedLists = this.state.savedLists.map(function(list, index) {
var list_data = list.data;
list_data.map(function(data, index) {
return (
<li key={index}>{data}</li>
)
});
return(
<div key={index}>
<h2>{list.name}</h2>
<ul>
{list_data}
</ul>
</div>
)
});
``````

Edit

However, As pointed by the user Martin Dawson in the comment below, This is not always ideal.

So whats the solution then?

Many

• You can create a function to generate unique keys/ids/numbers/strings and use that
• You can make use of existing npm packages like uuid, uniqid, etc
• You can also generate random number like `new Date().getTime();` and prefix it with something from the item you're iterating to guarantee its uniqueness
• Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

``````const generateKey = (pre) => {
return `\${ pre }_\${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
return(
<div key={ generateKey(list.name) }>
<h2>{ list.name }</h2>
<ul>
{ list_data }
</ul>
</div>
)
});
``````

The object 'DF__*' is dependent on column '*' - Changing int to double

Solution :

open database table -> expand table -> expand constraints and see this

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

Subtract a value from every number in a list in Python?

If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:

``````>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])
``````

How do I add a submodule to a sub-directory?

one-liner bash script to help facility Chris's answer above, as I had painted myself in a corner as well using Vundle updates to my .vim scripts. `DEST` is the path to the directory containing your submodules. Do this after doing `git rm -r \$DEST`

``````DEST='path'; for file in `ls \${DEST}`; do git submodule add `grep url \${DEST}/\${file}/.git/config|awk -F= '{print \$2}'` \${DEST}/\${file}; done
``````

cheers

Altering a column: null to not null

As long as the column is not a unique identifier

``````UPDATE table set columnName = 0 where columnName is null
``````

Then

Alter the table and set the field to non null and specify a default value of 0

How to use goto statement correctly

There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.

However this code could be modified a little and using the concept of continue and break we could make the code work.

``````    import java.util.*;

public class Factorial
{
public static void main(String[] args)
{
int x = 1;
int factValue = 1;
Scanner userInput = new Scanner(System.in);
restart: while(true){
System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
int factInput = userInput.nextInt();

while(factInput<=0)
{
System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
factInput = userInput.nextInt();
}

if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
{
System.out.println("The number you entered is not valid. Please try again.");
continue restart;
}
while(x<=factInput)
{
factValue*=x;
x++;
}
System.out.println(factInput+"! = "+factValue);
userInput.close();
break restart;
}
}
}
``````

Calculating width from percent to pixel then minus by pixel in LESS CSS

Try this :

``````width:auto;
margin-right:50px;
``````

Get specific ArrayList item

``````mainList.get(3);
``````

For future reference, you should refer to the Java API for these types of questions:

It's a useful thing!

Python: How do I make a subclass from a superclass?

Subclassing in Python is done as follows:

``````class WindowElement:
def print(self):
pass

class Button(WindowElement):
def print(self):
pass
``````

Here is a tutorial about Python that also contains classes and subclasses.

parse html string with jquery

MarvinS.-

Try:

``````\$.ajax({
url: uri+'?js',
success: function(data) {
var imgAttr = \$("img", data).attr('src');
var htmlCode = \$(data).html();
\$('#imgSrc').html(imgAttr);
\$('#fullHtmlOutput').html(htmlCode);
}
});
``````

This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.

Input and output numpy arrays to h5py

h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:

http://docs.h5py.org/en/latest/quick.html

A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:

``````In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">

In [6]: h5f.close()
``````

You can then load that data back in using: '

``````In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()

In [13]: np.allclose(a,b)
Out[13]: True
``````

Definitely check out the docs:

http://docs.h5py.org

Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as `np.save`, `np.savez` etc:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

`HandlerThread` is better option to normal java Threads in Android .

1. Create a HandlerThread and start it
2. Create a Handler with Looper from HandlerThread :`requestHandler`
3. `post` a `Runnable` task on `requestHandler`

Communication with UI Thread from `HandlerThread`

1. Create a `Handler` with `Looper` for main thread : `responseHandler` and override `handleMessage` method
2. Inside `Runnable` task of other Thread ( `HandlerThread` in this case), call `sendMessage` on `responseHandler`
3. This `sendMessage` result invocation of `handleMessage` in `responseHandler`.
4. Get attributes from the `Message` and process it, update UI

Example: Update `TextView` with data received from a web service. Since web service should be invoked on non-UI thread, created `HandlerThread` for Network Operation. Once you get the content from the web service, send message to your main thread (UI Thread) handler and that `Handler` will handle the message and update UI.

Sample code:

``````HandlerThread handlerThread = new HandlerThread("NetworkOperation");

final Handler responseHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
txtView.setText((String) msg.obj);
}
};

Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
Log.d("Runnable", "Before IO call");
URL page = new URL("http://www.your_web_site.com/fetchData.jsp");
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
String line;
while ((line = buff.readLine()) != null) {
text.append(line + "\n");
}
Log.d("Runnable", "After IO call:"+ text.toString());
Message msg = new Message();
msg.obj = text.toString();
responseHandler.sendMessage(msg);

} catch (Exception err) {
err.printStackTrace();
}
}
};
requestHandler.post(myRunnable);
``````

Useful articles:

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

• 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

• 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

• 12.2

• 12.1

• 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

• 10.3 (Requires macOS 10.14.3 or later)
• 10.2.1 (Requires macOS 10.14.3 or later)
• 10.1 (Last version supporting macOS 10.13.6 High Sierra)
• 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

How to maintain page scroll position after a jquery event is carried out?

``````\$('html,body').animate({
}, 700);
``````

What does ECU units, CPU core and memory mean when I launch a instance

For linuxes I've figured out that ECU could be measured by sysbench:

`sysbench --num-threads=128 --test=cpu --cpu-max-prime=50000 --max-requests=50000 run`

Total time (t) should be calculated by formula:

`ECU=1925/t`

And my example test results:

``````|   instance type   |   time   |   ECU   |
|-------------------|----------|---------|
| m1.small          |  1735,62 |       1 |
| m3.xlarge         |   147,62 |      13 |
| m3.2xlarge        |    74,61 |      26 |
| r3.large          |   295,84 |       7 |
| r3.xlarge         |   148,18 |      13 |
| m4.xlarge         |   146,71 |      13 |
| m4.2xlarge        |    73,69 |      26 |
| c4.xlarge         |   123,59 |      16 |
| c4.2xlarge        |    61,91 |      31 |
| c4.4xlarge        |    31,14 |      62 |
``````

.htaccess File Options -Indexes on Subdirectories

``````Options -Indexes
``````

You must have been thinking of

``````AllowOverride All
``````

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Can I animate absolute positioned element with CSS transition?

try this:

``````.test {
position:absolute;
background:blue;
width:200px;
height:200px;
top:40px;
transition:left 1s linear;
left: 0;
}
``````

int to hex string

Try the following:

``````ToString("X4")
``````

See The `X` format specifier on MSDN.

How to deal with persistent storage (e.g. databases) in Docker

Docker 1.9.0 and above

Use volume API

``````docker volume create --name hello
docker run -d -v hello:/container/path/for/volume container_image my_command
``````

This means that the data-only container pattern must be abandoned in favour of the new volumes.

Actually the volume API is only a better way to achieve what was the data-container pattern.

If you create a container with a `-v volume_name:/container/fs/path` Docker will automatically create a named volume for you that can:

1. Be listed through the `docker volume ls`
2. Be identified through the `docker volume inspect volume_name`
3. Backed up as a normal directory
4. Backed up as before through a `--volumes-from` connection

The new volume API adds a useful command that lets you identify dangling volumes:

``````docker volume ls -f dangling=true
``````

And then remove it through its name:

``````docker volume rm <volume name>
``````

As @mpugach underlines in the comments, you can get rid of all the dangling volumes with a nice one-liner:

``````docker volume rm \$(docker volume ls -f dangling=true -q)
# Or using 1.13.x
docker volume prune
``````

Docker 1.8.x and below

The approach that seems to work best for production is to use a data only container.

The data only container is run on a barebones image and actually does nothing except exposing a data volume.

Then you can run any other container to have access to the data container volumes:

``````docker run --volumes-from data-container some-other-container command-to-execute
``````
• Here you can get a good picture of how to arrange the different containers.
• Here there is a good insight on how volumes work.

In this blog post there is a good description of the so-called container as volume pattern which clarifies the main point of having data only containers.

Docker documentation has now the DEFINITIVE description of the container as volume/s pattern.

Following is the backup/restore procedure for Docker 1.8.x and below.

BACKUP:

``````sudo docker run --rm --volumes-from DATA -v \$(pwd):/backup busybox tar cvf /backup/backup.tar /data
``````
• --rm: remove the container when it exits
• --volumes-from DATA: attach to the volumes shared by the DATA container
• -v \$(pwd):/backup: bind mount the current directory into the container; to write the tar file to
• busybox: a small simpler image - good for quick maintenance
• tar cvf /backup/backup.tar /data: creates an uncompressed tar file of all the files in the /data directory

RESTORE:

``````# Create a new data container
\$ sudo docker run -v /data -name DATA2 busybox true
# untar the backup files into the new container?s data volume
\$ sudo docker run --rm --volumes-from DATA2 -v \$(pwd):/backup busybox tar xvf /backup/backup.tar
data/
data/sven.txt
# Compare to the original container
\$ sudo docker run --rm --volumes-from DATA -v `pwd`:/backup busybox ls /data
sven.txt
``````

Here is a nice article from the excellent Brian Goff explaining why it is good to use the same image for a container and a data container.

How can I check if a user is logged-in in php?

Any page you want to perform session-checks on needs to start with:

``````session_start();
``````

From there, you check your session array for a variable indicating they are logged in:

``````if (!\$_SESSION["loggedIn"]) redirect_to_login();
``````

Logging them in is nothing more than setting that value:

``````\$_SESSION["loggedIn"] = true;
``````

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

``````.PopupPanel
{
border: solid 1px black;
position: fixed;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;

width: 600px;
margin-left: -300px;
}
``````

Reversing a linked list in Java, recursively

``````package com.mypackage;
class list{

node first;
node last;

list(){
first=null;
last=null;
}

/*returns true if first is null*/
public boolean isEmpty(){
return first==null;
}
/*Method for insertion*/

public void insert(int value){

if(isEmpty()){
first=last=new node(value);
last.next=null;
}
else{
node temp=new node(value);
last.next=temp;
last=temp;
last.next=null;
}

}
/*simple traversal from beginning*/
public void traverse(){
node t=first;
while(!isEmpty() && t!=null){
t.printval();
t= t.next;
}
}
/*static method for creating a reversed linked list*/
public static void reverse(node n,list l1){

if(n.next!=null)
reverse(n.next,l1);/*will traverse to the very end*/
l1.insert(n.value);/*every stack frame will do insertion now*/

}
/*private inner class node*/
private class node{
int value;
node next;
node(int value){
this.value=value;
}
void printval(){
System.out.print(value+" ");
}
}

}
``````

Multiple selector chaining in jQuery?

You should be able to use:

``````\$('#Edit.myClass, #Create.myClass').plugin({options here});
``````

jQuery | Multiple Selectors

inserting characters at the start and end of a string

You can also use join:

``````yourstring = ''.join(('L','yourstring','LL'))
``````

Result:

``````>>> yourstring
'LyourstringLL'
``````

Display encoded html with razor

I just got another case to display backslash `\` with Razor and Java Script.

My `@Model.AreaName` looks like Name1\Name2\Name3 so when I display it all backslashes are gone and I see Name1Name2Name3

I found solution to fix it:

``````var areafullName =  JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.AreaName)))");
``````

Don't forget to add `@using Newtonsoft.Json` on top of `chtml` page.

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

``````>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
``````

If you just want to remove spaces instead of all whitespace:

``````>>> s.replace(" ", "")
'\tfoo\nbar'
``````

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

``````\$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
\$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop
``````

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

``````\$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop
``````

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.