Given a class, see if instance has method (Ruby)
You can use method_defined?
as follows:
String.method_defined? :upcase # => true
Much easier, portable and efficient than the instance_methods.include?
everyone else seems to be suggesting.
Keep in mind that you won't know if a class responds dynamically to some calls with method_missing
, for example by redefining respond_to?
, or since Ruby 1.9.2 by defining respond_to_missing?
.
How to create Toast in Flutter?
It's quite simple,
We just have to install the flutter toast package.
Refer the following documentation:
https://pub.dev/packages/fluttertoast
In the installing tab you will get the dependency which you have to paste it in the pubspec.yaml andthen install.
After this just import the package:
import 'package:fluttertoast/fluttertoast.dart';
Similar to above line.
And then by using FlutterToast class you can use your fluttertoast.
You're Done!!!
Using app.config in .Net Core
It is possible to use your usual System.Configuration
even in .NET Core 2.0 on Linux. Try this test example:
- Created a .NET Standard 2.0 Library (say
MyLib.dll
)
- Added the NuGet package
System.Configuration.ConfigurationManager
v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library
v2.0.0 (I hope that changes)
- All your C# classes derived from
ConfigurationSection
or ConfigurationElement
go into MyLib.dll
. For example MyClass.cs
derives from ConfigurationSection
and MyAccount.cs
derives from ConfigurationElement
. Implementation details are out of scope here but Google is your friend.
- Create a .NET Core 2.0 app (e.g. a console app,
MyApp.dll
). .NET Core apps end with .dll
rather than .exe
in Framework.
- Create an
app.config
in MyApp
with your custom configuration sections. This should obviously match your class designs in #3 above. For example:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
</configSections>
<myCustomConfig>
<myAccount id="007" />
</myCustomConfig>
</configuration>
That's it - you'll find that the app.config is parsed properly within MyApp
and your existing code within MyLib
works just fine. Don't forget to run dotnet restore
if you switch platforms from Windows (dev) to Linux (test).
Additional workaround for test projects
If you're finding that your App.config
is not working in your test projects, you might need this snippet in your test project's .csproj
(e.g. just before the ending </Project>
). It basically copies App.config
into your output folder as testhost.dll.config
so dotnet test
picks it up.
<!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>
<!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
NameError: global name 'xrange' is not defined in Python 3
I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.
Replacing accented characters php
protected $_convertTable = array(
'&' => 'and', '@' => 'at', '©' => 'c', '®' => 'r', 'À' => 'a',
'Á' => 'a', 'Â' => 'a', 'Ä' => 'a', 'Å' => 'a', 'Æ' => 'ae','Ç' => 'c',
'È' => 'e', 'É' => 'e', 'Ë' => 'e', 'Ì' => 'i', 'Í' => 'i', 'Î' => 'i',
'Ï' => 'i', 'Ò' => 'o', 'Ó' => 'o', 'Ô' => 'o', 'Õ' => 'o', 'Ö' => 'o',
'Ø' => 'o', 'Ù' => 'u', 'Ú' => 'u', 'Û' => 'u', 'Ü' => 'u', 'Ý' => 'y',
'ß' => 'ss','à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'å' => 'a',
'æ' => 'ae','ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ò' => 'o', 'ó' => 'o',
'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u',
'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'þ' => 'p', 'ÿ' => 'y', 'A' => 'a',
'a' => 'a', 'A' => 'a', 'a' => 'a', 'A' => 'a', 'a' => 'a', 'C' => 'c',
'c' => 'c', 'C' => 'c', 'c' => 'c', 'C' => 'c', 'c' => 'c', 'C' => 'c',
'c' => 'c', 'D' => 'd', 'd' => 'd', 'Ð' => 'd', 'd' => 'd', 'E' => 'e',
'e' => 'e', 'E' => 'e', 'e' => 'e', 'E' => 'e', 'e' => 'e', 'E' => 'e',
'e' => 'e', 'E' => 'e', 'e' => 'e', 'G' => 'g', 'g' => 'g', 'G' => 'g',
'g' => 'g', 'G' => 'g', 'g' => 'g', 'G' => 'g', 'g' => 'g', 'H' => 'h',
'h' => 'h', 'H' => 'h', 'h' => 'h', 'I' => 'i', 'i' => 'i', 'I' => 'i',
'i' => 'i', 'I' => 'i', 'i' => 'i', 'I' => 'i', 'i' => 'i', 'I' => 'i',
'i' => 'i', '?' => 'ij','?' => 'ij','J' => 'j', 'j' => 'j', 'K' => 'k',
'k' => 'k', '?' => 'k', 'L' => 'l', 'l' => 'l', 'L' => 'l', 'l' => 'l',
'L' => 'l', 'l' => 'l', '?' => 'l', '?' => 'l', 'L' => 'l', 'l' => 'l',
'N' => 'n', 'n' => 'n', 'N' => 'n', 'n' => 'n', 'N' => 'n', 'n' => 'n',
'?' => 'n', '?' => 'n', '?' => 'n', 'O' => 'o', 'o' => 'o', 'O' => 'o',
'o' => 'o', 'O' => 'o', 'o' => 'o', 'Œ' => 'oe','œ' => 'oe','R' => 'r',
'r' => 'r', 'R' => 'r', 'r' => 'r', 'R' => 'r', 'r' => 'r', 'S' => 's',
's' => 's', 'S' => 's', 's' => 's', 'S' => 's', 's' => 's', 'Š' => 's',
'š' => 's', 'T' => 't', 't' => 't', 'T' => 't', 't' => 't', 'T' => 't',
't' => 't', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u',
'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u',
'u' => 'u', 'W' => 'w', 'w' => 'w', 'Y' => 'y', 'y' => 'y', 'Ÿ' => 'y',
'Z' => 'z', 'z' => 'z', 'Z' => 'z', 'z' => 'z', 'Ž' => 'z', 'ž' => 'z',
'?' => 'z', '?' => 'e', 'ƒ' => 'f', 'O' => 'o', 'o' => 'o', 'U' => 'u',
'u' => 'u', 'A' => 'a', 'a' => 'a', 'I' => 'i', 'i' => 'i', 'O' => 'o',
'o' => 'o', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u',
'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', '?' => 'a',
'?' => 'a', '?' => 'ae','?' => 'ae','?' => 'o', '?' => 'o', '?' => 'e',
'?' => 'jo','?' => 'e', '?' => 'i', '?' => 'i', '?' => 'a', '?' => 'b',
'?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'zh','?' => 'z',
'?' => 'i', '?' => 'j', '?' => 'k', '?' => 'l', '?' => 'm', '?' => 'n',
'?' => 'o', '?' => 'p', '?' => 'r', '?' => 's', '?' => 't', '?' => 'u',
'?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch','?' => 'sh','?' => 'sch',
'?' => '-', '?' => 'y', '?' => '-', '?' => 'je','?' => 'ju','?' => 'ja',
'?' => 'a', '?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e',
'?' => 'zh','?' => 'z', '?' => 'i', '?' => 'j', '?' => 'k', '?' => 'l',
'?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
'?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
'?' => 'sh','?' => 'sch','?' => '-','?' => 'y', '?' => '-', '?' => 'je',
'?' => 'ju','?' => 'ja','?' => 'jo','?' => 'e', '?' => 'i', '?' => 'i',
'?' => 'g', '?' => 'g', '?' => 'a', '?' => 'b', '?' => 'g', '?' => 'd',
'?' => 'h', '?' => 'v', '?' => 'z', '?' => 'h', '?' => 't', '?' => 'i',
'?' => 'k', '?' => 'k', '?' => 'l', '?' => 'm', '?' => 'm', '?' => 'n',
'?' => 'n', '?' => 's', '?' => 'e', '?' => 'p', '?' => 'p', '?' => 'C',
'?' => 'c', '?' => 'q', '?' => 'r', '?' => 'w', '?' => 't', '™' => 'tm',
);
From magento, im using it for basically everything
How to define a Sql Server connection string to use in VB.NET?
May it will help for u. U should use (localdb).
LocalDB automatic instance
Server=(localdb)\v11.0;Integrated Security=true;
LocalDB automatic instance with specific data file
Server=(localdb)\v11.0;Integrated Security=true;
AttachDbFileName=C:\MyFolder\MyData.mdf;
The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig
This happens to me every time I add a pod to the podfile.
I constantly try and find the problem but I just go round in circles again and again!
The error messages range, however the way to fix it is the same every time!
Comment out(#) ALL of the pods in the podfile and run pod install in terminal.
Then...
Uncomment out all of the pods in the podfile and run pod install again.
This has worked for me every single time!
How to split a number into individual digits in c#?
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5
How to uninstall jupyter
For Mac OS, you may use the below command in order to remove files manually.
sudo rm -rf /usr/local/bin/jupyter
Javascript call() & apply() vs bind()?
Use .bind()
when you want that function to later be called with a certain context, useful in events. Use .call()
or .apply()
when you want to invoke the function immediately, and modify the context.
Call/apply call the function immediately, whereas bind
returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.
I do this a lot:
function MyObject(element) {
this.elm = element;
element.addEventListener('click', this.onClick.bind(this), false);
};
MyObject.prototype.onClick = function(e) {
var t=this; //do something with [t]...
//without bind the context of this function wouldn't be a MyObject
//instance as you would normally expect.
};
I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.
A simple, naive implementation of bind would be like:
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.
Hope this helps.
Watch multiple $scope attributes
Beginning with AngularJS 1.1.4 you can use $watchCollection
:
$scope.$watchCollection('[item1, item2]', function(newValues, oldValues){
// do stuff here
// newValues and oldValues contain the new and respectively old value
// of the observed collection array
});
Plunker example here
Documentation here
What is the difference between "screen" and "only screen" in media queries?
@media screen and (max-width:480px) { … }
screen
here is to set the screen size of the media query. E.g the maximum width of the display area is 480px. So it is specifying the screen as opposed to the other available media types.
@media only screen and (max-width: 480px;) { … }
only screen
here is used to prevent older browsers that do not support media queries with media features from applying the specified styles.
Search for an item in a Lua list
function valid(data, array)
local valid = {}
for i = 1, #array do
valid[array[i]] = true
end
if valid[data] then
return false
else
return true
end
end
Here's the function I use for checking if data is in an array.
ImportError: No module named 'pygame'
- Install and download pygame .whl file.
- Move .whl file to your python35/Scripts
- Go to cmd
- Change directory to python scripts
Type:
pip install pygame
Here is an example:
C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>pip install pygame
Flask Error: "Method Not Allowed The method is not allowed for the requested URL"
I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.
Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing.
Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other.
Strangely enough they continued running in background after I had killed all my terminals.
Had to kill them manually using fuser -k 8080/tcp
numpy.where() detailed, step-by-step explanation / examples
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
Cron job every three days
* * */3 * * that says, every minute of every hour on every three days.
0 0 */3 * * says at 00:00 (midnight) every three days.
Modifying a subset of rows in a pandas dataframe
Use .loc
for label based indexing:
df.loc[df.A==0, 'B'] = np.nan
The df.A==0
expression creates a boolean series that indexes the rows, 'B'
selects the column. You can also use this to transform a subset of a column, e.g.:
df.loc[df.A==0, 'B'] = df.loc[df.A==0, 'B'] / 2
I don't know enough about pandas internals to know exactly why that works, but the basic issue is that sometimes indexing into a DataFrame returns a copy of the result, and sometimes it returns a view on the original object. According to documentation here, this behavior depends on the underlying numpy behavior. I've found that accessing everything in one operation (rather than [one][two]) is more likely to work for setting.
node: command not found
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?
A crude way would be to call dumpbin with the headers option from the Visual Studio tools on each DLL and look for the appropriate output:
dumpbin /headers my32bit.dll
PE signature found
File Type: DLL
FILE HEADER VALUES
14C machine (x86)
1 number of sections
45499E0A time date stamp Thu Nov 02 03:28:10 2006
0 file pointer to symbol table
0 number of symbols
E0 size of optional header
2102 characteristics
Executable
32 bit word machine
DLL
OPTIONAL HEADER VALUES
10B magic # (PE32)
You can see a couple clues in that output that it is a 32 bit DLL, including the 14C value that Paul mentions. Should be easy to look for in a script.
TypeScript: correct way to do string equality?
The ===
is not for checking string equalit , to do so you can use the Regxp functions for example
if (x.match(y) === null) {
// x and y are not equal
}
there is also the test
function
The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)
It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.
The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.
tl;dr:
There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors>
section from the WCF service's web.config
file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.
EDIT:
Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null
!) or the URL is incorrect.
Floating divs in Bootstrap layout
From all I have read you cannot do exactly what you want without javascript.
If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap :
http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
how to query child objects in mongodb
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
Is it valid to replace http:// with // in a <script src="http://...">?
Here I duplicate the answer in Hidden features of HTML:
Using a protocol-independent absolute
path:
<img src="//domain.com/img/logo.png"/>
If the browser is viewing an page in
SSL through HTTPS, then it'll request
that asset with the https protocol,
otherwise it'll request it with HTTP.
This prevents that awful "This Page
Contains Both Secure and Non-Secure
Items" error message in IE, keeping
all your asset requests within the
same protocol.
Caveat: When used on a <link>
or
@import for a stylesheet, IE7 and IE8
download the file twice. All other
uses, however, are just fine.
Persist javascript variables across pages?
You can use http://rhaboo.org as a wrapper around localStorage. It stores complex objects but doesn't merely stringify and parse the whole thing like most such libraries do. That's really inefficient if you want to store a lot of data and add to it or change it in small chunks. Also, JSON discards a lot of important stuff like non-numerical properties of arrays.
In rhaboo you can write things like this:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
var laststamp = store.stamp ? store.stamp.toString() : "never";
store.write('stamp', new Date());
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
console.log( store.somethingfancy.went[1].mow[1] ); //says lawn
BTW, I wrote rhaboo
Test only if variable is not null in if statement
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
Swap two items in List<T>
There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!
In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!
So... how do we do this?
My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:
static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// Swap the items.
T temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
// Return the items in the new order.
foreach (T item in source)
yield return item;
// Restore the collection.
source[index2] = source[index1];
source[index1] = temp;
}
This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:
- The list could be readonly which will throw an exception.
- If the list is shared by multiple threads, the list will change for the other threads during the duration of this function.
- If an exception occurs during the iteration, the list will not be restored. (This could be resolved to write an try-finally inside the Swap-function, and put the restore-code inside the finally-block).
There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):
static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// If nothing needs to be swapped, just return the original collection.
if (index1 == index2)
return source;
// Make a copy.
List<T> copy = source.ToList();
// Swap the items.
T temp = copy[index1];
copy[index1] = copy[index2];
copy[index2] = temp;
// Return the copy with the swapped items.
return copy;
}
One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.
You might consider the following solution:
static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.
using (IEnumerator<T> e = source.GetEnumerator())
{
// Iterate to the first index.
for (int i = 0; i < index1; i++)
yield return source[i];
// Return the item at the second index.
yield return source[index2];
if (index1 != index2)
{
// Return the items between the first and second index.
for (int i = index1 + 1; i < index2; i++)
yield return source[i];
// Return the item at the first index.
yield return source[index1];
}
// Return the remaining items.
for (int i = index2 + 1; i < source.Count; i++)
yield return source[i];
}
}
And if you want to input parameter to be IEnumerable:
static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.
using(IEnumerator<T> e = source.GetEnumerator())
{
// Iterate to the first index.
for(int i = 0; i < index1; i++)
{
if (!e.MoveNext())
yield break;
yield return e.Current;
}
if (index1 != index2)
{
// Remember the item at the first position.
if (!e.MoveNext())
yield break;
T rememberedItem = e.Current;
// Store the items between the first and second index in a temporary list.
List<T> subset = new List<T>(index2 - index1 - 1);
for (int i = index1 + 1; i < index2; i++)
{
if (!e.MoveNext())
break;
subset.Add(e.Current);
}
// Return the item at the second index.
if (e.MoveNext())
yield return e.Current;
// Return the items in the subset.
foreach (T item in subset)
yield return item;
// Return the first (remembered) item.
yield return rememberedItem;
}
// Return the remaining items in the list.
while (e.MoveNext())
yield return e.Current;
}
}
Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.
jquery: change the URL address without redirecting?
That site makes use of the "fragment" part of a url: the stuff after the "#". This is not sent to the server by the browser as part of the GET request, but can be used to store page state. So yes you can change the fragment without causing a page refresh or reload. When the page loads, your javascript reads this fragment and updates the page content appropriately, fetching data from the server via ajax requests as required. To read the fragment in js:
var fragment = location.hash;
but note that this value will include the "#" character at the beginning. To set the fragment:
location.hash = "your_state_data";
@Scope("prototype") bean scope not creating new bean
Using ApplicationContextAware
is tying you to Spring (which may or may not be an issue). I would recommend passing in a LoginActionFactory
, which you can ask for a new instance of a LoginAction
each time you need one.
How to run test cases in a specified file?
go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
- The TestFunc must be inside a
go
test file in that package
- We can provide a regular expression to match a set of test cases or just the exact test case function to run a single test case. For instance
-run TestCaseFunc
How to parse JSON data with jQuery / JavaScript?
var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ];
var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
json_arr.push(key+' . '+value.name + '<br>');
cand.innerHTML = json_arr;
});
<div id="cand">
</div>
jQuery add text to span within a div
Careful - append()
will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>')
.
Use text()
to replace element content with text, or append(document.createTextNode(x))
to append a text node.
In Python, how do you convert a `datetime` object to seconds?
Starting from Python 3.3 this becomes super easy with the datetime.timestamp()
method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()
The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.
Android SDK manager won't open
Nothing helps me from all this answers, but I found the right steps (Windows 7 64 bit):
1) Open android.bat from your sdk folder for editing;
2) Add exactly this two strings:
set java_exe=c:\Program Files\Java\jdk1.8.0_25\bin\java.exe
rem call lib\find_java.bat
instead of this:
set java_exe=
call lib\find_java.bat
if not defined java_exe goto :EOF
Where c:\Program Files\Java\jdk1.8.0_25
is your jdk folder.
3) Enjoy. SDK Manager will launch from Android studio IDE.
g++ undefined reference to typeinfo
The previous answers are correct, but this error can also be caused by attempting to use typeid on an object of a class that has no virtual functions. C++ RTTI requires a vtable, so classes that you wish to perform type identification on require at least one virtual function.
If you want type information to work on a class for which you don't really want any virtual functions, make the destructor virtual.
SVG Positioning
There is a shorter alternative to the previous answer. SVG Elements can also be grouped by nesting svg elements:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="10">
<rect x="10" y="10" height="100" width="100" style="stroke:#ff0000;fill: #0000ff"/>
</svg>
<svg x="200">
<rect x="10" y="10" height="100" width="100" style="stroke:#009900;fill: #00cc00"/>
</svg>
</svg>
The two rectangles are identical (apart from the colors), but the parent svg elements have different x values.
See http://tutorials.jenkov.com/svg/svg-element.html.
StringBuilder vs String concatenation in toString() in Java
The key is whether you are writing a single concatenation all in one place or accumulating it over time.
For the example you gave, there's no point in explicitly using StringBuilder. (Look at the compiled code for your first case.)
But if you are building a string e.g. inside a loop, use StringBuilder.
To clarify, assuming that hugeArray contains thousands of strings, code like this:
...
String result = "";
for (String s : hugeArray) {
result = result + s;
}
is very time- and memory-wasteful compared with:
...
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
sb.append(s);
}
String result = sb.toString();
Version vs build in Xcode
Apple sort of rearranged/repurposed the fields.
Going forward, if you look on the Info tab for your Application Target, you should use the "Bundle versions string, short" as your Version (e.g., 3.4.0) and "Bundle version" as your Build (e.g., 500 or 1A500). If you don't see them both, you can add them. Those will map to the proper Version and Build textboxes on the Summary tab; they are the same values.
When viewing the Info tab, if you right-click and select Show Raw Keys/Values, you'll see the actual names are CFBundleShortVersionString
(Version) and CFBundleVersion
(Build).
The Version is usually used how you appear to have been using it with Xcode 3. I'm not sure on what level you're asking about the Version/Build difference, so I'll answer it philosophically.
There are all sorts of schemes, but a popular one is:
{MajorVersion}.{MinorVersion}.{Revision}
- Major version - Major changes, redesigns, and functionality
changes
- Minor version - Minor improvements, additions to functionality
- Revision - A patch number for bug-fixes
Then the Build is used separately to indicate the total number of builds for a release or for the entire product lifetime.
Many developers start the Build number at 0, and every time they build they increase the number by one, increasing forever. In my projects, I have a script that automatically increases the build number every time I build. See instructions for that below.
- Release 1.0.0 might be build 542. It took 542 builds to get to a
1.0.0 release.
- Release 1.0.1 might be build 578.
- Release 1.1.0 might be build 694.
- Release 2.0.0 might be build 949.
Other developers, including Apple, have a Build number comprised of a major version + minor version + number of builds for the release. These are the actual software version numbers, as opposed to the values used for marketing.
If you go to Xcode menu > About Xcode, you'll see the Version and Build numbers. If you hit the More Info... button you'll see a bunch of different versions. Since the More Info... button was removed in Xcode 5, this information is also available from the Software > Developer section of the System Information app, available by opening Apple menu > About This Mac > System Report....
For example, Xcode 4.2 (4C139). Marketing version 4.2 is Build major version 4, Build minor version C, and Build number 139. The next release (presumably 4.3) will likely be Build release 4D, and the Build number will start over at 0 and increment from there.
The iPhone Simulator Version/Build numbers are the same way, as are iPhones, Macs, etc.
- 3.2: (7W367a)
- 4.0: (8A400)
- 4.1: (8B117)
- 4.2: (8C134)
- 4.3: (8H7)
Update: By request, here are the steps to create a script that runs each time you build your app in Xcode to read the Build number, increment it, and write it back to the app's {App}-Info.plist
file. There are optional, additional steps if you want to write your version/build numbers to your Settings.bundle/Root*.plist
file(s).
This is extended from the how-to article here.
In Xcode 4.2 - 5.0:
- Load your Xcode project.
- In the left hand pane, click on your project at the very top of the hierarchy. This will load the project settings editor.
- On the left-hand side of the center window pane, click on your app under the TARGETS heading. You will need to configure this setup for each project target.
- Select the Build Phases tab.
- In Xcode 4, at the bottom right, click the Add Build Phase button and select Add Run Script.
- In Xcode 5, select Editor menu > Add Build Phase > Add Run Script Build Phase.
- Drag-and-drop the new Run Script phase to move it to just before the Copy Bundle Resources phase (when the app-info.plist file will be bundled with your app).
- In the new Run Script phase, set Shell:
/bin/bash
.
Copy and paste the following into the script area for integer build numbers:
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
As @Bdebeez pointed out, the Apple Generic Versioning Tool (agvtool
) is also available. If you prefer to use it instead, then there are a couple things to change first:
- Select the Build Settings tab.
- Under the Versioning section, set the Current Project Version to the initial build number you want to use, e.g., 1.
- Back on the Build Phases tab, drag-and-drop your Run Script phase after the Copy Bundle Resources phase to avoid a race condition when trying to both build and update the source file that includes your build number.
Note that with the agvtool
method you may still periodically get failed/canceled builds with no errors. For this reason, I don't recommend using agvtool
with this script.
Nevertheless, in your Run Script phase, you can use the following script:
"${DEVELOPER_BIN_DIR}/agvtool" next-version -all
The next-version
argument increments the build number (bump
is also an alias for the same thing), and -all
updates Info.plist
with the new build number.
And if you have a Settings bundle where you show the Version and Build, you can add the following to the end of the script to update the version and build. Note: Change the PreferenceSpecifiers
values to match your settings. PreferenceSpecifiers:2
means look at the item at index 2 under the PreferenceSpecifiers
array in your plist file, so for a 0-based index, that's the 3rd preference setting in the array.
productVersion=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
If you're using agvtool
instead of reading the Info.plist
directly, you can add the following to your script instead:
buildNumber=$("${DEVELOPER_BIN_DIR}/agvtool" what-version -terse)
productVersion=$("${DEVELOPER_BIN_DIR}/agvtool" what-marketing-version -terse1)
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
And if you have a universal app for iPad & iPhone, then you can also set the settings for the iPhone file:
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root~iphone.plist
/usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root~iphone.plist
Aborting a shell script if any command returns a non-zero value
Add this to the beginning of the script:
set -e
This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.
See the bash(1) man page on the "set" internal command for more details.
I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.
ViewBag, ViewData and TempData
Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.
Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?
Consider Android Development:
IDE: Eclipse etc..
Library: android.app.Activity library (Class with all code)
API: Interface basically all functions with which we call
SDK: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android
(----tools - DDMS,Emulator ----platforms - Android OS versions, ----platform-tools - ADB, ----API docs)
ToolKit: Could be ADT Bundle
Framework: Big library but more of architecture-oriented
Change language of Visual Studio 2017 RC
I didn't find a complete answer here
Firstly
You should install your preferred language
- Open the Visual Studio Installer.
- In installed products click on plus Dropdown menu
- click edit
- then click on language packs
- choose you preferred language and finally click on install
Secondly
Go to Tools -> Options
2.Select International Settings in Environment
3.click on Menu and select you preferred language
4.Click on Ok
5.restart visual studio
What is the preferred Bash shebang?
#!/bin/sh
as most scripts do not need specific bash feature and should be written for sh.
Also, this makes scripts work on the BSDs, which do not have bash per default.
How to change max_allowed_packet size
Following all instructions, this is what I did and worked:
mysql> SELECT CONNECTION_ID();//This is my ID for this session.
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 20 |
+-----------------+
1 row in set (0.00 sec)
mysql> select @max_allowed_packet //Mysql do not found @max_allowed_packet
+---------------------+
| @max_allowed_packet |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet; //That is better... I have max_allowed_packet=32M inside my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 33554432 |
+-----------------------------+
1 row in set (0.00 sec)
mysql> **SET GLOBAL max_allowed_packet=1073741824**; //Now I'm changing the value.
Query OK, 0 rows affected (0.00 sec)
mysql> select @max_allowed_packet; //Mysql not found @max_allowed_packet
+---------------------+
| @max_allowed_packet |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The new value. And I still have max_allowed_packet=32M inisde my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
So, as we can see, the max_allowed_packet has been changed outside from my.ini.
Lets leave the session and check again:
mysql> exit
Bye
C:\Windows\System32>mysql -uroot -pPassword
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.6.26-log MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT CONNECTION_ID();//This is my ID for this session.
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 21 |
+-----------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The new value still here and And I still have max_allowed_packet=32M inisde my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
Now I will stop the server
2016-02-03 10:28:30 - Server is stopped
mysql> SELECT CONNECTION_ID();
ERROR 2013 (HY000): Lost connection to MySQL server during query
Now I will start the server
2016-02-03 10:31:54 - Server is running
C:\Windows\System32>mysql -uroot -pPassword
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.6.26-log MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT CONNECTION_ID();
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 9 |
+-----------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The previous new value has gone. Now I see what I have inside my.ini again.
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 33554432 |
+-----------------------------+
1 row in set (0.00 sec)
Conclusion, after SET GLOBAL max_allowed_packet=1073741824, the server will have the new max_allowed_packet until it is restarted, as someone stated previously.
What algorithms compute directions from point A to point B on a map?
This is pure speculation on my part, but I suppose that they may use an influence map data structure overlaying the directed map in order to narrow the search domain. This would allow the search algorithm to direct the path to major routes when the desired trip is long.
Given that this is a Google app, it's also reasonable to suppose that a lot of the magic is done via extensive caching. :) I wouldn't be surprised if caching the top 5% most common Google Map route requests allowed for a large chunk (20%? 50%?) of requests to be answered by a simple look-up.
Could not instantiate mail function. Why this error occurring
"Could not instantiate mail function" is PHPMailer's way of reporting that the call to mail() (in the Mail extension) failed. (So you're using the 'mail' mailer.)
You could try removing the @s before the calls to mail() in PHPMailer::MailSend and seeing what, if any, errors are being silently discarded.
HTML display result in text (input) field?
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
This should work properly.
1. use .value instead of "innerHTML" when setting the 3rd field (input field)
2. Close the input tags
How to calculate the number of occurrence of a given character in each row of a column of strings?
The stringr package provides the str_count
function which seems to do what you're interested in
# Load your example data
q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = F)
library(stringr)
# Count the number of 'a's in each element of string
q.data$number.of.a <- str_count(q.data$string, "a")
q.data
# number string number.of.a
#1 1 greatgreat 2
#2 2 magic 1
#3 3 not 0
How to clamp an integer to some range?
Whatever happened to my beloved readable Python language? :-)
Seriously, just make it a function:
def addInRange(val, add, minval, maxval):
newval = val + add
if newval < minval: return minval
if newval > maxval: return maxval
return newval
then just call it with something like:
val = addInRange(val, 7, 0, 42)
Or a simpler, more flexible, solution where you do the calculation yourself:
def restrict(val, minval, maxval):
if val < minval: return minval
if val > maxval: return maxval
return val
x = restrict(x+10, 0, 42)
If you wanted to, you could even make the min/max a list so it looks more "mathematically pure":
x = restrict(val+7, [0, 42])
.htaccess deny from all
This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.
2.2 configuration syntax was
Order deny,allow
Deny from all
2.4 configuration now is
Require all denied
Thus, this 2.2 syntax
order deny,allow
deny from all
allow from 127.0.0.1
Would ne now written
Require local
OrderBy descending in Lambda expression?
LastOrDefault()
is usually not working but with the Tolist()
it will work. There is no need to use OrderByDescending
use Tolist()
like this.
GroupBy(p => p.Nws_ID).ToList().LastOrDefault();
Maven: How to rename the war file for the project?
You need to configure the war plugin:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warName>bird.war</warName>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
More info here
How to get the path of running java program
You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()
How to make rpm auto install dependencies
I ran into this and what worked for me was to run yum localinstall enterPkgNameHere.rpm
from inside the directory where the .rpm file is located.
Note: replace the enterPkgNameHere.rpm
with the name of your .rpm file.
Can't access Tomcat using IP address
No solution mentioned above was solved my problem. My problem was different.
First check is your port is disabled in firewall.
Go to Control Panel -> Windows Firewall -> Advance Settings -> Inbound Rules
and see any port is blocked.
A sample image is below:
If so then you can unblock the port by following steps:
Step 1:
Here you can see that the port is blocked.
Step 2: Allow the connection -> Apply -> Ok
.
That's solved my blocked problem. Happy coding :) :)
The type or namespace name 'Objects' does not exist in the namespace 'System.Data'
In my case for EF 6+, when using this:
System.Data.Entity.Core.Objects.ObjectQuery
As part of this command:
var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query).ToTraceString();
I got this error:
Cannot cast 'query' (which has an actual type of 'System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType3<string,string,string,short,string>>') to 'System.Data.Entity.Core.Objects.ObjectQuery'
So I ended up having to use this:
var sql = ((System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType3<string,string,string,short,string>>)query).ToString();
Of course your anonymous type signature might be different.
HTH.
Getting HTTP code in PHP using curl
function getStatusCode()
{
$url = 'example.com/test';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
}
print_r(getStatusCode());
How to disable registration new users in Laravel
Overwriting the getRegister and postRegister is tricky - if you are using git there is a high possibility that .gitignore
is set to ignore framework files which will lead to the outcome that registration will still be possible in your production environment (if laravel is installed via composer for example)
Another possibility is using routes.php and adding this line:
Route::any('/auth/register','HomeController@index');
This way the framework files are left alone and any request will still be redirected away from the Frameworks register module.
Java 8 Lambda function that throws exception?
You can actually extend Consumer
(and Function
etc.) with a new interface that handles exceptions -- using Java 8's default methods!
Consider this interface (extends Consumer
):
@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T> {
@Override
default void accept(final T elem) {
try {
acceptThrows(elem);
} catch (final Exception e) {
// Implement your own exception handling logic here..
// For example:
System.out.println("handling an exception...");
// Or ...
throw new RuntimeException(e);
}
}
void acceptThrows(T elem) throws Exception;
}
Then, for example, if you have a list:
final List<String> list = Arrays.asList("A", "B", "C");
If you want to consume it (eg. with forEach
) with some code that throws exceptions, you would traditionally have set up a try/catch block:
final Consumer<String> consumer = aps -> {
try {
// maybe some other code here...
throw new Exception("asdas");
} catch (final Exception ex) {
System.out.println("handling an exception...");
}
};
list.forEach(consumer);
But with this new interface, you can instantiate it with a lambda expression and the compiler will not complain:
final ThrowingConsumer<String> throwingConsumer = aps -> {
// maybe some other code here...
throw new Exception("asdas");
};
list.forEach(throwingConsumer);
Or even just cast it to be more succinct!:
list.forEach((ThrowingConsumer<String>) aps -> {
// maybe some other code here...
throw new Exception("asda");
});
Update: Looks like there's a very nice utility library part of Durian called Errors which can be used to solve this problem with a lot more flexibility. For example, in my implementation above I've explicitly defined the error handling policy (System.out...
or throw RuntimeException
), whereas Durian's Errors allow you to apply a policy on the fly via a large suite of utility methods. Thanks for sharing it, @NedTwigg!.
Sample usage:
list.forEach(Errors.rethrow().wrap(c -> somethingThatThrows(c)));
Interface extends another interface but implements its methods
ad 1. It does not implement its methods.
ad 4. The purpose of one interface extending, not implementing another, is to build a more specific interface. For example, SortedMap
is an interface that extends Map
. A client not interested in the sorting aspect can code against Map
and handle all the instances of for example TreeMap
, which implements SortedMap
. At the same time, another client interested in the sorted aspect can use those same instances through the SortedMap
interface.
In your example you are repeating the methods from the superinterface. While legal, it's unnecessary and doesn't change anything in the end result. The compiled code will be exactly the same whether these methods are there or not. Whatever Eclipse's hover says is irrelevant to the basic truth that an interface does not implement anything.
Copying data from one SQLite database to another
You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.
INSERT INTO X.TABLE SELECT * FROM Y.TABLE;
Or, if the columns are not matched up in order:
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
How to insert a column in a specific position in oracle without dropping and recreating the table?
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish.
Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ
Jquery change <p> text programmatically
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
Inserting Data Into a MySQL Database using PHP
How can you get the build/version number of your Android application?
private String GetAppVersion() {
try {
PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
return _info.versionName;
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return "";
}
}
private int GetVersionCode() {
try {
PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
return _info.versionCode;
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return -1;
}
}
JRE installation directory in Windows
Not as a command, but this information is in the registry:
- Open the key
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
- Read the
CurrentVersion
REG_SZ
- Open the subkey under
Java Runtime Environment
named with the CurrentVersion
value
- Read the
JavaHome
REG_SZ to get the path
For example on my workstation i have
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
JavaHome = "C:\Program Files\Java\jre6"
So my current JRE is in C:\Program Files\Java\jre6
Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS
You will not be able to capitalize the first word of each sentence with CSS.
CSS offers text-transform
for capitalization, but it only supports capitalize
, uppercase
and lowercase
. None of these will do what you want. You can make use of the selector :first-letter
, which will apply any style to the first letter of an element - but not of the subsequent ones.
p {
text-transform: lowercase;
}
p:first-letter {
text-transform: capitalize;
}
<p>SAMPLE TEXT. SOME SENTENCE. SOMETHING ELSE</p>
<!-- will become this:
Sample text. some sentence. something else. -->
That is not what you want (and :first-letter is not cross-browser compatible... IE again).
The only way to do what you want is with a kind of programming language (serverside or clientside), like Javascript or PHP.
In PHP you have the ucwords
function (documented here), which just like CSS capitalizes each letter of each word, but doing some programming magic (check out the comments of the documentation for references), you are able to achieve capitalization of each first letter of each sentence.
The easier solution and you might not want to do PHP is using Javascript. Check out the following page - Capital Letters - for a full blown Javascript example of doing exactly what you want. The Javascript is pretty short and does the capitalization with some String manipulation - you will have no problem adjusting the capitalize-sentences.js
to your needs.
In any case: Capitalization should usually be done in the content itself not via Javascript or markup languages. Consider cleaning up your content (your texts) with other means. Microsoft Word for example has built in functions to do just what you want.
Is there a way for non-root processes to bind to "privileged" ports on Linux?
Okay, thanks to the people who pointed out the capabilities system and CAP_NET_BIND_SERVICE
capability. If you have a recent kernel, it is indeed possible to use this to start a service as non-root but bind low ports. The short answer is that you do:
setcap 'cap_net_bind_service=+ep' /path/to/program
And then anytime program
is executed thereafter it will have the CAP_NET_BIND_SERVICE
capability. setcap
is in the debian package libcap2-bin
.
Now for the caveats:
- You will need at least a 2.6.24 kernel
- This won't work if your file is a script. (ie, uses a #! line to launch an interpreter). In this case, as far I as understand, you'd have to apply the capability to the interpreter executable itself, which of course is a security nightmare, since any program using that interpreter will have the capability. I wasn't able to find any clean, easy way to work around this problem.
- Linux will disable LD_LIBRARY_PATH on any
program
that has elevated privileges like setcap
or suid
. So if your program
uses its own .../lib/
, you might have to look into another option like port forwarding.
Resources:
Note: RHEL first added this in v6.
Improving bulk insert performance in Entity framework
Use : db.Set<tale>.AddRange(list);
Ref :
TESTEntities db = new TESTEntities();
List<Person> persons = new List<Person> {
new Person{Name="p1",Place="palce"},
new Person{Name="p2",Place="palce"},
new Person{Name="p3",Place="palce"},
new Person{Name="p4",Place="palce"},
new Person{Name="p5",Place="palce"}
};
db.Set<Person>().AddRange(persons);
db.SaveChanges();
JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)
This error occurs when you are sending JSON data to server.
Maybe in your string you are trying to add new line character by using /n.
If you add / before /n, it should work, you need to escape new line character.
"Hello there //n start coding"
The result should be as following
Hello there
start coding
How to Exit a Method without Exiting the Program?
In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
will always return at that point. However:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
}
will only return if it goes into that if
statement.
What characters are allowed in an email address?
As can be found in this Wikipedia link
The local-part of the email address may use any of these ASCII characters:
uppercase and lowercase Latin letters A
to Z
and a
to z
;
digits 0
to 9
;
special characters !#$%&'*+-/=?^_`{|}~
;
dot .
, provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected]
is not allowed but "John..Doe"@example.com
is allowed);
space and "(),:;<>@[\]
characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com
and (comment)[email protected]
are both equivalent to [email protected]
.
In addition to the above ASCII characters, international characters above U+007F, encoded as UTF-8, are permitted by RFC 6531, though mail systems may restrict which characters to use when assigning local-parts.
A quoted string may exist as a dot separated entity within the local-part, or it may exist when the outermost quotes are the outermost characters of the local-part (e.g., abc."defghi"[email protected]
or "abcdefghixyz"@example.com
are allowed. Conversely, abc"defghi"[email protected]
is not; neither is abc\"def\"[email protected]
). Quoted strings and characters however, are not commonly used. RFC 5321 also warns that "a host that expects to receive mail SHOULD avoid defining mailboxes where the Local-part requires (or uses) the Quoted-string form".
The local-part postmaster
is treated specially—it is case-insensitive, and should be forwarded to the domain email administrator. Technically all other local-parts are case-sensitive, therefore [email protected]
and [email protected]
specify different mailboxes; however, many organizations treat uppercase and lowercase letters as equivalent.
Despite the wide range of special characters which are technically valid; organisations, mail services, mail servers and mail clients in practice often do not accept all of them. For example, Windows Live Hotmail only allows creation of email addresses using alphanumerics, dot (.
), underscore (_
) and hyphen (-
). Common advice is to avoid using some special characters to avoid the risk of rejected emails.
Difference Between One-to-Many, Many-to-One and Many-to-Many?
One-to-many
The one-to-many table relationship looks like this:
In a relational database system, a one-to-many table relationship associates two tables based on a Foreign Key
column in the child table referencing the Primary Key
of one record in the parent table.
In the table diagram above, the post_id
column in the post_comment
table has a Foreign Key
relationship with the post
table id Primary Key
column:
ALTER TABLE
post_comment
ADD CONSTRAINT
fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
@ManyToOne annotation
In JPA, the best way to map the one-to-many table relationship is to use the @ManyToOne
annotation.
In our case, the PostComment
child entity maps the post_id
Foreign Key column using the @ManyToOne
annotation:
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
}
Using the JPA @OneToMany
annotation
Just because you have the option of using the @OneToMany
annotation, it doesn't mean it should be the default option for all the one-to-many database relationships.
The problem with JPA collections is that we can only use them when their element count is rather low.
The best way to map a @OneToMany
association is to rely on the @ManyToOne
side to propagate all entity state changes:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
//Constructors, getters and setters removed for brevity
public void addComment(PostComment comment) {
comments.add(comment);
comment.setPost(this);
}
public void removeComment(PostComment comment) {
comments.remove(comment);
comment.setPost(null);
}
}
The parent Post
entity features two utility methods (e.g. addComment
and removeComment
) which are used to synchronize both sides of the bidirectional association.
You should provide these methods whenever you are working with a bidirectional association as, otherwise, you risk very subtle state propagation issues.
The unidirectional @OneToMany
association is to be avoided as it's less efficient than using @ManyToOne
or the bidirectional @OneToMany
association.
One-to-one
The one-to-one table relationship looks as follows:
In a relational database system, a one-to-one table relationship links two tables based on a Primary Key
column in the child which is also a Foreign Key
referencing the Primary Key
of the parent table row.
Therefore, we can say that the child table shares the Primary Key
with the parent table.
In the table diagram above, the id
column in the post_details
table has also a Foreign Key
relationship with the post
table id
Primary Key
column:
ALTER TABLE
post_details
ADD CONSTRAINT
fk_post_details_id
FOREIGN KEY (id) REFERENCES post
Using the JPA @OneToOne
with @MapsId
annotations
The best way to map a @OneToOne
relationship is to use @MapsId
. This way, you don't even need a bidirectional association since you can always fetch the PostDetails
entity by using the Post
entity identifier.
The mapping looks like this:
@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {
@Id
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id")
private Post post;
public PostDetails() {}
public PostDetails(String createdBy) {
createdOn = new Date();
this.createdBy = createdBy;
}
//Getters and setters omitted for brevity
}
This way, the id
property serves as both Primary Key and Foreign Key. You'll notice that the @Id
column no longer uses a @GeneratedValue
annotation since the identifier is populated with the identifier of the post
association.
Many-to-many
The many-to-many table relationship looks as follows:
In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key
columns referencing the Primary Key
columns of the two parent tables.
In the table diagram above, the post_id
column in the post_tag
table has also a Foreign Key
relationship with the post
table id Primary Key
column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post
And, the tag_id
column in the post_tag
table has a Foreign Key
relationship with the tag
table id Primary Key
column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag
Using the JPA @ManyToMany
mapping
This is how you can map the many-to-many
table relationship with JPA and Hibernate:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private Set<Tag> tags = new HashSet<>();
//Getters and setters ommitted for brevity
public void addTag(Tag tag) {
tags.add(tag);
tag.getPosts().add(this);
}
public void removeTag(Tag tag) {
tags.remove(tag);
tag.getPosts().remove(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Post)) return false;
return id != null && id.equals(((Post) o).getId());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
@Entity(name = "Tag")
@Table(name = "tag")
public class Tag {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String name;
@ManyToMany(mappedBy = "tags")
private Set<Post> posts = new HashSet<>();
//Getters and setters ommitted for brevity
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return Objects.equals(name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
- The
tags
association in the Post
entity only defines the PERSIST
and MERGE
cascade types. The REMOVE
entity state transition doesn't make any sense for a @ManyToMany
JPA association since it could trigger a chain deletion that would ultimately wipe both sides of the association.
- The add/remove utility methods are mandatory if you use bidirectional associations so that you can make sure that both sides of the association are in sync.
- The
Post
entity uses the entity identifier for equality since it lacks any unique business key. You can use the entity identifier for equality as long as you make sure that it stays consistent across all entity state transitions.
- The
Tag
entity has a unique business key which is marked with the Hibernate-specific @NaturalId
annotation. When that's the case, the unique business key is the best candidate for equality checks.
- The
mappedBy
attribute of the posts
association in the Tag
entity marks that, in this bidirectional relationship, the Post
entity owns the association. This is needed since only one side can own a relationship, and changes are only propagated to the database from this particular side.
- The
Set
is to be preferred, as using a List
with @ManyToMany
is less efficient.
How to see remote tags?
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
How do format a phone number as a String in Java?
This is how I ended up doing it:
private String printPhone(Long phoneNum) {
StringBuilder sb = new StringBuilder(15);
StringBuilder temp = new StringBuilder(phoneNum.toString());
while (temp.length() < 10)
temp.insert(0, "0");
char[] chars = temp.toString().toCharArray();
sb.append("(");
for (int i = 0; i < chars.length; i++) {
if (i == 3)
sb.append(") ");
else if (i == 6)
sb.append("-");
sb.append(chars[i]);
}
return sb.toString();
}
I understand that this does not support international numbers, but I'm not writing a "real" application so I'm not concerned about that. I only accept a 10 character long as a phone number. I just wanted to print it with some formatting.
Thanks for the responses.
How to expand and compute log(a + b)?
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
Sample database for exercise
Why not download the English Wikipedia? There are compressed SQL files of various sizes, and it should certainly be large enough for you
The main articles are XML, so inserting them into the db is a bit more of a problem, but you might find there are other files there that suit you. For example, the inter-page links SQL file is 2.3GB compressed. Have a look at https://en.wikipedia.org/wiki/Wikipedia:Database_download for more info.
Oskar
overlay a smaller image on a larger image python OpenCv
When attempting to write to the destination image using any of these answers above and you get the following error:
ValueError: assignment destination is read-only
A quick potential fix is to set the WRITEABLE flag to true.
img.setflags(write=1)
Difference in make_shared and normal shared_ptr in C++
The shared pointer manages both the object itself, and a small object containing the reference count and other housekeeping data. make_shared
can allocate a single block of memory to hold both of these; constructing a shared pointer from a pointer to an already-allocated object will need to allocate a second block to store the reference count.
As well as this efficiency, using make_shared
means that you don't need to deal with new
and raw pointers at all, giving better exception safety - there is no possibility of throwing an exception after allocating the object but before assigning it to the smart pointer.
JavaScript: Upload file
Pure JS
You can use fetch optionally with await-try-catch
let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});
_x000D_
_x000D_
async function SavePhoto(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 5000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_
Old school approach - xhr
let photo = document.getElementById("image-file").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("photo", photo);
req.open("POST", '/upload/image');
req.send(formData);
_x000D_
_x000D_
function SavePhoto(e)
{
let user = { name:'john', age:34 };
let xhr = new XMLHttpRequest();
let formData = new FormData();
let photo = e.files[0];
formData.append("user", JSON.stringify(user));
formData.append("photo", photo);
xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
xhr.timeout = 5000;
xhr.open("POST", '/upload/image');
xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_
SUMMARY
- In server side you can read original file name (and other info) which is automatically included to request by browser in
filename
formData parameter.
- You do NOT need to set request header
Content-Type
to multipart/form-data
- this will be set automatically by browser.
- Instead of
/upload/image
you can use full address like http://.../upload/image
.
- If you want to send many files in single request use
multiple
attribute: <input multiple type=... />
, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];
... formData.append("photo2", photo2);
)
- You can include additional data (json) to request e.g.
let user = {name:'john', age:34}
in this way: formData.append("user", JSON.stringify(user));
- You can set timeout: for
fetch
using AbortController
, for old approach by xhr.timeout= milisec
- This solutions should work on all major browsers.
Add floating point value to android resources/values
There is a solution:
<resources>
<item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>
In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:
Format = enclosing data type:
- float
- boolean
- fraction
- integer
- ...
and type stands for:
Type = resource type (referenced with R.XXXXX.name):
- color
- dimen
- string
- style
- etc...
To fetch resource from code, you should use this snippet:
TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();
I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)
), but Android dimensions
have special treatment and pure "float" number is not valid dimension.
Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.
<resources>
<dimen name="text_line_spacing">2.025px</dimen>
</resources>
and from code, you can get that float by
float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);
in this case, value of lineSpacing
is 2.024993896484375
, and not 2.025
as you would expected.
what is the difference between uint16_t and unsigned short int incase of 64 bit processor?
uint16_t
is unsigned 16-bit integer.
unsigned short int
is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX
is 65535
). In practice, it usually is 16-bit, but you can't take that as guaranteed.
Note:
- If you want a portable unsigned 16-bit integer, use
uint16_t
.
inttypes.h
and stdint.h
are both introduced in C99. If you are using C89, define your own type.
uint16_t
may not be provided in certain implementation(See reference below), but unsigned short int
is always available.
Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types
For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).
Passing Objects By Reference or Value in C#
When you pass the the System.Drawing.Image
type object to a method you are actually passing a copy of reference to that object.
So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.
YourMethod(System.Drawing.Image image)
{
//now this image is a new reference
//if you load a new image
image = new Image()..
//you are not changing the original reference you are just changing the copy of original reference
}
How to create a DataTable in C# and how to add rows?
// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));
// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();
How do you get the process ID of a program in Unix or Linux using Python?
For Windows
A Way to get all the pids of programs on your computer without downloading any modules:
import os
pids = []
a = os.popen("tasklist").readlines()
for x in a:
try:
pids.append(int(x[29:34]))
except:
pass
for each in pids:
print(each)
If you just wanted one program or all programs with the same name and you wanted to kill the process or something:
import os, sys, win32api
tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()
print(tasklistr)
def kill(process):
process_exists_forsure = False
gotpid = False
for examine in tasklistrl:
if process == examine[0:len(process)]:
process_exists_forsure = True
if process_exists_forsure:
print("That process exists.")
else:
print("That process does not exist.")
raw_input()
sys.exit()
for getpid in tasklistrl:
if process == getpid[0:len(process)]:
pid = int(getpid[29:34])
gotpid = True
try:
handle = win32api.OpenProcess(1, False, pid)
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
except win32api.error as err:
print(err)
raw_input()
sys.exit()
if not gotpid:
print("Could not get process pid.")
raw_input()
sys.exit()
raw_input()
sys.exit()
prompt = raw_input("Which process would you like to kill? ")
kill(prompt)
That was just a paste of my process kill program I could make it a whole lot better but it is okay.
Enter key press behaves like a Tab in Javascript
Changing this behaviour actually creates a far better user experience than the default behaviour implemented natively. Consider that the behaviour of the enter key is already inconsistent from the user's point of view, because in a single line input, enter tends to submit a form, while in a multi-line textarea, it simply adds a newline to the contents of the field.
I recently did it like this (uses jQuery):
$('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
if (e.keyCode==13) {
var focusable = $('input,a,select,button,textarea').filter(':visible');
focusable.eq(focusable.index(this)+1).focus();
return false;
}
});
This is not terribly efficient, but works well enough and is reliable - just add the 'enterastab' class to any input element that should behave in this way.
For each row return the column name of the largest value
One option from dplyr 1.0.0
could be:
DF %>%
rowwise() %>%
mutate(row_max = names(.)[which.max(c_across(everything()))])
V1 V2 V3 row_max
<dbl> <dbl> <dbl> <chr>
1 2 7 9 V3
2 8 3 6 V1
3 1 5 4 V2
Sample data:
DF <- structure(list(V1 = c(2, 8, 1), V2 = c(7, 3, 5), V3 = c(9, 6,
4)), class = "data.frame", row.names = c(NA, -3L))
how to zip a folder itself using java
I would use Apache Ant, which has an API to call tasks from Java code rather than from an XML build file.
Project p = new Project();
p.init();
Zip zip = new Zip();
zip.setProject(p);
zip.setDestFile(zipFile); // a java.io.File for the zip you want to create
zip.setBasedir(new File("D:\\reports"));
zip.setIncludes("january/**");
zip.perform();
Here I'm telling it to start from the base directory D:\reports
and zip up the january
folder and everything inside it. The paths in the resulting zip file will be the same as the original paths relative to D:\reports
, so they will include the january
prefix.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
URL Encode a string in jQuery for an AJAX request
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
How to stop app that node.js express 'npm start'
If is very simple, just kill the process..
localmacpro$ ps
PID TTY TIME CMD
5014 ttys000 0:00.05 -bash
6906 ttys000 0:00.29 npm
6907 ttys000 0:06.39 node /Users/roger_macpro/my-project/node_modules/.bin/webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
6706 ttys001 0:00.05 -bash
7157 ttys002 0:00.29 -bash
localmacpro$ kill -9 6907 6906
Share data between AngularJS controllers
As pointed out by @MaNn in one of the comments of the accepted answers, the solution wont work if the page is refreshed.
The Solution for this is to use localStorage or sessionStorage for temporary persistence of the data you want to share across controllers.
- Either you make a sessionService whose GET and SET method, encrypts and decrypts the data and reads the data from either localStorage or sessionStorage. So now you use this service directly to read and write the data in the storage via any controller or service you want. This is a open approach and easy one
- Else you make a DataSharing Service and use localStorage inside it - so that if the page is refreshed the service will try and check the storage and reply back via the Getters and Setters you have made public or private in this service file.
How to remove pip package after deleting it manually
I'm sure there's a better way to achieve this and I would like to read about it, but a workaround I can think of is this:
- Install the package on a different machine.
- Copy the
rm
'ed directory to the original machine (ssh, ftp, whatever).
pip uninstall
the package (should work again then).
But, yes, I'd also love to hear about a decent solution for this situation.
SQL variable to hold list of integers
Assuming the variable is something akin to:
CREATE TYPE [dbo].[IntList] AS TABLE(
[Value] [int] NOT NULL
)
And the Stored Procedure is using it in this form:
ALTER Procedure [dbo].[GetFooByIds]
@Ids [IntList] ReadOnly
As
You can create the IntList and call the procedure like so:
Declare @IDs IntList;
Insert Into @IDs Select Id From dbo.{TableThatHasIds}
Where Id In (111, 222, 333, 444)
Exec [dbo].[GetFooByIds] @IDs
Or if you are providing the IntList yourself
DECLARE @listOfIDs dbo.IntList
INSERT INTO @listofIDs VALUES (1),(35),(118);
List of encodings that Node.js supports
The encodings are spelled out in the buffer documentation.
Character Encodings
utf8
: Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.
utf16le
: Multi-byte encoded Unicode characters. Unlike utf8
, each character in the string will be encoded using either 2 or 4 bytes.
latin1
: Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters from U+0000
to U+00FF
.
Binary-to-Text Encodings
base64
: Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5.
hex
: Encode each byte as two hexadecimal characters.
Legacy Character Encodings
ascii
: For 7-bit ASCII data only. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text.
binary
: Alias for 'latin1'.
ucs2
: Alias of 'utf16le'.
Concatenating strings in C, which method is more efficient?
sprintf() is designed to handle far more than just strings, strcat() is specialist. But I suspect that you are sweating the small stuff. C strings are fundamentally inefficient in ways that make the differences between these two proposed methods insignificant. Read "Back to Basics" by Joel Spolsky for the gory details.
This is an instance where C++ generally performs better than C. For heavy weight string handling using std::string is likely to be more efficient and certainly safer.
[edit]
[2nd edit]Corrected code (too many iterations in C string implementation), timings, and conclusion change accordingly
I was surprised at Andrew Bainbridge's comment that std::string was slower, but he did not post complete code for this test case. I modified his (automating the timing) and added a std::string test. The test was on VC++ 2008 (native code) with default "Release" options (i.e. optimised), Athlon dual core, 2.6GHz. Results:
C string handling = 0.023000 seconds
sprintf = 0.313000 seconds
std::string = 0.500000 seconds
So here strcat() is faster by far (your milage may vary depending on compiler and options), despite the inherent inefficiency of the C string convention, and supports my original suggestion that sprintf() carries a lot of baggage not required for this purpose. It remains by far the least readable and safe however, so when performance is not critical, has little merit IMO.
I also tested a std::stringstream implementation, which was far slower again, but for complex string formatting still has merit.
Corrected code follows:
#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>
void a(char *first, char *second, char *both)
{
for (int i = 0; i != 1000000; i++)
{
strcpy(both, first);
strcat(both, " ");
strcat(both, second);
}
}
void b(char *first, char *second, char *both)
{
for (int i = 0; i != 1000000; i++)
sprintf(both, "%s %s", first, second);
}
void c(char *first, char *second, char *both)
{
std::string first_s(first) ;
std::string second_s(second) ;
std::string both_s(second) ;
for (int i = 0; i != 1000000; i++)
both_s = first_s + " " + second_s ;
}
int main(void)
{
char* first= "First";
char* second = "Second";
char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
clock_t start ;
start = clock() ;
a(first, second, both);
printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
start = clock() ;
b(first, second, both);
printf( "sprintf = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
start = clock() ;
c(first, second, both);
printf( "std::string = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
return 0;
}
How to position a DIV in a specific coordinates?
I cribbed this and added the 'px';
Works very well.
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: (el.right + window.scrollX ) +'px',
top: (el.top + window.scrollY ) +'px'
}
}
to call: //Gets it to the right side
el.style.top = getOffset(othis).top ;
el.style.left = getOffset(othis).left ;
Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js
I also encountered this issue. Did the following and it got fixed.
- Open your computer terminal (not VSCode terminal) and type node --version to ensure you have node installed. If not, then install node using nvm.
- Then head to your bash file (eg .bashrc, .bash_profile, .profile) and add the PATH:
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
- If you have multiple bash files, you ensure to add the PATH to all of them.
- Restart your VSCode terminal and it should be fine.
How do I use LINQ Contains(string[]) instead of Contains(string)
So am I assuming correctly that uid is a Unique Identifier (Guid)? Is this just an example of a possible scenario or are you really trying to find a guid that matches an array of strings?
If this is true you may want to really rethink this whole approach, this seems like a really bad idea. You should probably be trying to match a Guid to a Guid
Guid id = new Guid(uid);
var query = from xx in table
where xx.uid == id
select xx;
I honestly can't imagine a scenario where matching a string array using "contains" to the contents of a Guid would be a good idea. For one thing, Contains() will not guarantee the order of numbers in the Guid so you could potentially match multiple items. Not to mention comparing guids this way would be way slower than just doing it directly.
Removing numbers from string
I'd love to use regex to accomplish this, but since you can only use lists, loops, functions, etc..
here's what I came up with:
stringWithNumbers="I have 10 bananas for my 5 monkeys!"
stringWithoutNumbers=''.join(c if c not in map(str,range(0,10)) else "" for c in stringWithNumbers)
print(stringWithoutNumbers) #I have bananas for my monkeys!
Get Base64 encode file-data from Input Form
I used FileReader to display image on click of the file upload button not using any Ajax requests. Following is the code hope it might help some one.
$(document).ready(function($) {
$.extend( true, jQuery.fn, {
imagePreview: function( options ){
var defaults = {};
if( options ){
$.extend( true, defaults, options );
}
$.each( this, function(){
var $this = $( this );
$this.bind( 'change', function( evt ){
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
$('#imageURL').attr('src',e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
});
}
});
$( '#fileinput' ).imagePreview();
});
Matching exact string with JavaScript
Either modify the pattern beforehand so that it only matches the entire string:
var r = /^a$/
or check afterward whether the pattern matched the whole string:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
C pass int array pointer as parameter into a function
Using the really excellent example from Greggo, I got this to work as a bubble sort with passing an array as a pointer and doing a simple -1 manipulation.
#include<stdio.h>
void sub_one(int (*arr)[7])
{
int i;
for(i=0;i<7;i++)
{
(*arr)[i] -= 1 ; // subtract 1 from each point
printf("%i\n", (*arr)[i]);
}
}
int main()
{
int a[]= { 180, 185, 190, 175, 200, 180, 181};
int pos, j, i;
int n=7;
int temp;
for (pos =0; pos < 7; pos ++){
printf("\nPosition=%i Value=%i", pos, a[pos]);
}
for(i=1;i<=n-1;i++){
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0)) // while selected # less than a[j] and not j isn't 0
{
a[j+1]=a[j]; //moves element forward
j=j-1;
}
a[j+1]=temp; //insert element in proper place
}
printf("\nSorted list is as follows:\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
printf("\nmedian = %d\n", a[3]);
sub_one(&a);
return 0;
}
I need to read up on how to encapsulate pointers because that threw me off.
jQuery/JavaScript to replace broken images
I use lazy load and have to do this in order to make it work properly:
lazyload();
var errorURL = "https://example.com/thisimageexist.png";
$(document).ready(function () {
$('[data-src]').on("error", function () {
$(this).attr('src', errorURL);
});
});
How do I make a fixed size formatted string in python?
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point,
right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
Why does Date.parse give incorrect results?
The accepted answer from CMS is correct, I have just added some features :
- trim and clean input spaces
- parse slashes, dashes, colons and spaces
- has default day and time
// parse a date time that can contains spaces, dashes, slashes, colons
function parseDate(input) {
// trimes and remove multiple spaces and split by expected characters
var parts = input.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2] || 1, parts[3] || 0, parts[4] || 0, parts[5] || 0); // Note: months are 0-based
}
Remove columns from DataTable in C#
Aside from limiting the columns selected to reduce bandwidth and memory:
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
Java JTable setting Column Width
This code is worked for me without setAutoResizeModes.
TableColumnModel columnModel = jTable1.getColumnModel();
columnModel.getColumn(1).setPreferredWidth(170);
columnModel.getColumn(1).setMaxWidth(170);
columnModel.getColumn(2).setPreferredWidth(150);
columnModel.getColumn(2).setMaxWidth(150);
columnModel.getColumn(3).setPreferredWidth(40);
columnModel.getColumn(3).setMaxWidth(40);
How to output a comma delimited list in jinja python template?
And using the joiner
from http://jinja.pocoo.org/docs/dev/templates/#joiner
{% set comma = joiner(",") %}
{% for user in userlist %}
{{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}
It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.
A more complex example on why you would use it.
{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
<a href="?action=edit">Edit</a>
{% endif %}
grep --ignore-case --only
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
How to reference a method in javadoc?
you can use @see
to do that:
sample:
interface View {
/**
* @return true: have read contact and call log permissions, else otherwise
* @see #requestReadContactAndCallLogPermissions()
*/
boolean haveReadContactAndCallLogPermissions();
/**
* if not have permissions, request to user for allow
* @see #haveReadContactAndCallLogPermissions()
*/
void requestReadContactAndCallLogPermissions();
}
How to detect the end of loading of UITableView
I am copying Andrew's code and expanding it to account for the case where you just have 1 row in the table. It's working so far for me!
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
// detect when all visible cells have been loaded and displayed
// NOTE: iOS7 workaround used - see: http://stackoverflow.com/questions/4163579/how-to-detect-the-end-of-loading-of-uitableview?lq=1
NSArray *visibleRows = [tableView indexPathsForVisibleRows];
NSIndexPath *lastVisibleCellIndexPath = [visibleRows lastObject];
BOOL isPreviousCallForPreviousCell = self.previousDisplayedIndexPath.row + 1 == lastVisibleCellIndexPath.row;
BOOL isLastCell = [indexPath isEqual:lastVisibleCellIndexPath];
BOOL isFinishedLoadingTableView = isLastCell && ([tableView numberOfRowsInSection:0] == 1 || isPreviousCallForPreviousCell);
self.previousDisplayedIndexPath = indexPath;
if (isFinishedLoadingTableView) {
[self hideSpinner];
}
}
NOTE: I'm just using 1 section from Andrew's code, so keep that in mind..
Downloading a large file using curl
<?php
set_time_limit(0);
//This is the file where we save the information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
Go / golang time.Now().UnixNano() convert to milliseconds?
As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
OneOfOne's answer works because time.Nanosecond
happens to be 1
, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.
See https://en.wikipedia.org/wiki/Dimensional_analysis
Another way of looking at this is that both time.Now().UnixNano()
and time.Millisecond
use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.
JAVA_HOME should point to a JDK not a JRE
I have spent 3 hours for solving the error The JAVA_HOME
environment variable is not defined correctly. This environment variable is needed to run this program NB: JAVA_HOME
should point to a JDK not a JRE
Finally I got the solution. Please set the JAVA_HOME
value by Browse Directory
button/option. Try to find the jdk path. Ex: C:\Program Files\Java\jdk1.8.0_181
It will remove the semicolon issue. :D
More elegant "ps aux | grep -v grep"
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
iPhone UIView Animation Best Practice
Anyway the "Block" method is preffered now-a-days. I will explain the simple block below.
Consider the snipped below. bug2 and bug 3 are imageViews. The below animation describes an animation with 1 second duration after a delay of 1 second. The bug3 is moved from its center to bug2's center. Once the animation is completed it will be logged "Center Animation Done!".
-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;
[UIView animateWithDuration:1
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
bug3.center = bug2Center;
}
completion:^(BOOL finished){
NSLog(@"Center Animation Done!");
}];
}
Hope that's clean!!!
An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4
After trying all these procedures it still didn't work for me. What did work was
- go into File Explorer and delete the .classpath file under the project's root folder
- run Maven update within Eclipse, and check Force update of Snapshots/Releases
Our current work required integrating a number of disparate projects so unfortunately use of SNAPSHOTs in a production environment were required (taboo in Maven circles)!
Make selected block of text uppercase
Without defining keyboard shortcuts
Select the text you want capitalized
Open View->Command Palette (or Shift+Command+P)
Start typing "Transform to uppercase" and select that option
Voila!
Docker compose port mapping
It's important to point out that all of the above solutions map the port to every interface on your machine. This is less than desirable if you have a public IP address, or your machine has an IP on a large network. Your application may be exposed to a much wider audience than you'd hoped.
redis:
build:
context:
dockerfile: Dockerfile-redis
ports:
- "127.0.0.1:3901:3901"
127.0.0.1
is the ip address that maps to the hostname localhost
on your machine. So now your application is only exposed over that interface and since 127.0.0.1
is only accessible via your machine, you're not exposing your containers to the entire world.
The documentation explains this further and can be found here: https://docs.docker.com/compose/compose-file/#ports
Note: If you're using Docker for mac this will make the container listen on 127.0.0.1 on the Docker for Mac VM and will not be accessible from your localhost. If I recall correctly.
How to pretty print nested dictionaries?
One of the most pythonic ways for that is to use the already build pprint module.
The argument that you need for define the print depth is as you may expect depth
import pprint
pp = pprint.PrettyPrinter(depth=4)
pp.pprint(mydict)
That's it !
Python Pylab scatter plot error bars (the error on each point is unique)
This is almost like the other answer but you don't need a scatter
plot at all, you can simply specify a scatter-plot-like format (fmt
-parameter) for errorbar
:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()
Result:
A list of the avaiable fmt
parameters can be found for example in the plot
documentation:
character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
Python: How to create a unique file name?
This can be done using the unique function in ufp.path module.
import ufp.path
ufp.path.unique('./test.ext')
if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.
Tuples( or arrays ) as Dictionary keys in C#
If for some reason you really want to avoid creating your own Tuple class, or using on built into .NET 4.0, there is one other approach possible; you can combine the three key values together into a single value.
For example, if the three values are integer types together not taking more than 64 bits, you could combine them into a ulong
.
Worst-case you can always use a string, as long as you make sure the three components in it are delimited with some character or sequence that does not occur inside the components of the key, for example, with three numbers you could try:
string.Format("{0}#{1}#{2}", key1, key2, key3)
There is obviously some composition overhead in this approach, but depending on what you are using it for this may be trivial enough not to care about it.
How to get the current time in Python
If you need current time as a time
object:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
Accessing @attribute from SimpleXML
You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.
More info at php.net
http://php.net/simplexmlelement.attributes
Example code from that page:
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
C pointer to array/array of pointers disambiguation
I think we can use the simple rule ..
example int * (*ptr)()[];
start from ptr
" ptr
is a pointer to "
go towards right ..its ")" now go left its a "("
come out go right "()" so
" to a function which takes no arguments " go left "and returns a pointer " go right "to
an array" go left " of integers "
Are there any style options for the HTML5 Date picker?
found this on Zurb's github
In case you want to do some more custom styling. Here's all the
default CSS for webkit rendering of the date components.
input[type="date"] {
-webkit-align-items: center;
display: -webkit-inline-flex;
font-family: monospace;
overflow: hidden;
padding: 0;
-webkit-padding-start: 1px;
}
input::-webkit-datetime-edit {
-webkit-flex: 1;
-webkit-user-modify: read-only !important;
display: inline-block;
min-width: 0;
overflow: hidden;
}
input::-webkit-datetime-edit-fields-wrapper {
-webkit-user-modify: read-only !important;
display: inline-block;
padding: 1px 0;
white-space: pre;
}
Import SQL file by command line in Windows 7
Related to importing, if you are having issues importing a file with bulk inserts and you're getting MYSQL GONE AWAY, lost connection or similar error, open your my.cnf / my.ini and temporarily set your max_allowed_packet to something large like 400M
Remember to set it back again after your import!
fopen deprecated warning
Many of Microsoft's secure functions, including fopen_s(), are part of C11, so they should be portable now. You should realize that the secure functions differ in exception behaviors and sometimes in return values. Additionally you need to be aware that while these functions are standardized, it's an optional part of the standard (Annex K) that at least glibc (default on Linux) and FreeBSD's libc don't implement.
However, I fought this problem for a few years. I posted a larger set of conversion macros here., For your immediate problem, put the following code in an include file, and include it in your source code:
#pragma once
#if !defined(FCN_S_MACROS_H)
#define FCN_S_MACROS_H
#include <cstdio>
#include <string> // Need this for _stricmp
using namespace std;
// _MSC_VER = 1400 is MSVC 2005. _MSC_VER = 1600 (MSVC 2010) was the current
// value when I wrote (some of) these macros.
#if (defined(_MSC_VER) && (_MSC_VER >= 1400) )
inline extern
FILE* fcnSMacro_fopen_s(char *fname, char *mode)
{ FILE *fptr;
fopen_s(&fptr, fname, mode);
return fptr;
}
#define fopen(fname, mode) fcnSMacro_fopen_s((fname), (mode))
#else
#define fopen_s(fp, fmt, mode) *(fp)=fopen( (fmt), (mode))
#endif //_MSC_VER
#endif // FCN_S_MACROS_H
Of course this approach does not implement the expected exception behavior.
How to unescape HTML character entities in Java?
In my case i use the replace method by testing every entity in every variable, my code looks like this:
text = text.replace("Ç", "Ç");
text = text.replace("ç", "ç");
text = text.replace("Á", "Á");
text = text.replace("Â", "Â");
text = text.replace("Ã", "Ã");
text = text.replace("É", "É");
text = text.replace("Ê", "Ê");
text = text.replace("Í", "Í");
text = text.replace("Ô", "Ô");
text = text.replace("Õ", "Õ");
text = text.replace("Ó", "Ó");
text = text.replace("Ú", "Ú");
text = text.replace("á", "á");
text = text.replace("â", "â");
text = text.replace("ã", "ã");
text = text.replace("é", "é");
text = text.replace("ê", "ê");
text = text.replace("í", "í");
text = text.replace("ô", "ô");
text = text.replace("õ", "õ");
text = text.replace("ó", "ó");
text = text.replace("ú", "ú");
In my case this worked very well.
How to give spacing between buttons using bootstrap
The original code is mostly there, but you need btn-group
s around each button. In Bootstrap 3 you can use a btn-toolbar and a btn-group to get the job done; I haven't done BS4 but it has similar constructs.
<div class="btn-toolbar" role="toolbar">
<div class="btn-group" role="group">
<button class="btn btn-default">Button 1</button>
</div>
<div class="btn-group" role="group">
<button class="btn btn-default">Button 2</button>
</div>
</div>
from jquery $.ajax to angular $http
The AngularJS way of calling $http would look like:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {"foo":"bar"}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.data = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = response.statusText;
});
or could be written even simpler using shortcut methods:
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);
There are number of things to notice:
- AngularJS version is more concise (especially using .post() method)
- AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
- Callback functions are named
success
and error
respectively (also please note parameters of each callback) - Deprecated in angular v1.5
- use
then
function instead.
- More info of
then
usage can be found here
The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http
Creating a copy of an object in C#
You could do:
class myClass : ICloneable
{
public String test;
public object Clone()
{
return this.MemberwiseClone();
}
}
then you can do
myClass a = new myClass();
myClass b = (myClass)a.Clone();
N.B. MemberwiseClone()
Creates a shallow copy of the current System.Object.
"Could not find a part of the path" error message
There's something wrong. You have written:
string source_dir = @"E:\\Debug\\VipBat\\{0}";
and the error was
Could not find a part of the path E\Debug\VCCSBat
This is not the same directory.
In your code there's a problem, you have to use:
string source_dir = @"E:\Debug\VipBat"; // remove {0} and the \\ if using @
or
string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the @ if using \\
Set colspan dynamically with jquery
Setting colspan="0"
is support only in firefox.
In other browsers we can get around it with:
// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
colCount = 0;
$(this).parents("table").find('tr').eq(0).children().each(function(){
if ($(this).attr('colspan')){
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
$(this).attr("colspan", colCount);
});
http://tinker.io/3d642/4
Converting string to number in javascript/jQuery
For your case, just use:
var votevalue = +$(this).data('votevalue');
There are some ways to convert string to number in javascript.
The best way:
var str = "1";
var num = +str; //simple enough and work with both int and float
You also can:
var str = "1";
var num = Number(str); //without new. work with both int and float
or
var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number
DON'T:
var str = "1";
var num = new Number(str); //num will be an object. typeof num == 'object'
Use parseInt only for special case, for example
var str = "ff";
var num = parseInt(str,16); //255
var str = "0xff";
var num = parseInt(str); //255
What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.
What is RSS and VSZ in Linux memory management
I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up.
As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.
Why Git is not allowing me to commit even after configuration?
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
How to discover number of *logical* cores on Mac OS X?
On a MacBook Pro running Mavericks, sysctl -a | grep hw.cpu
will only return some cryptic details. Much more detailed and accessible information is revealed in the machdep.cpu
section, ie:
sysctl -a | grep machdep.cpu
In particular, for processors with HyperThreading
(HT), you'll see the total enumerated CPU count (logical_per_package
) as double that of the physical core count (cores_per_package
).
sysctl -a | grep machdep.cpu | grep per_package
Purpose of __repr__ method?
This is explained quite well in the Python documentation:
repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()
, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__()
method.
So what you're seeing here is the default implementation of __repr__
, which is useful for serialization and debugging.