How to create threads in nodejs
The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.
You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using --experimental-worker when invoking Node.js.
Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1
//package.json
"scripts": {
"start": "node --experimental-modules --experimental- worker index.mjs"
},
Now, you need to import Worker from worker_threads.
Note: You need to declare you js files with '.mjs' extension for ES6 support.
//index.mjs
import { Worker } from 'worker_threads';
const spawnWorker = workerData => {
return new Promise((resolve, reject) => {
const worker = new Worker('./workerService.mjs', { workerData });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with
exit code ${code}`)));
})
}
const spawnWorkers = () => {
for (let t = 1; t <= 5; t++)
spawnWorker('Hello').then(data => console.log(data));
}
spawnWorkers();
Finally, we create a workerService.mjs
//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';
// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);
Output:
npm run start
Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5
Parse a URI String into Name-Value Collection
If you are using servlet doGet try this
request.getParameterMap()
Returns a java.util.Map of the parameters of this request.
Returns:
an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.
(Java doc)
JQuery addclass to selected div, remove class if another div is selected
**This can be achived easily using two different ways:**
1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery
**1)First Way**
$(documnet.ready(function(){
$('#dvId').click(function(){
$('#dvId').removeClass('active class or your class name which you want to remove').addClass('active class or your class name which you want to add');
});
});
**2) Second Way**
i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)
<div id="dvId" class="ActiveClassname ">
</div
$(documnet.ready(function(){
$('#dvId').click(function(){
$('#dvId').toggleClass('ActiveClassname InActiveClassName');
});
});
Enjoy.....:)
If you any doubt free to ask any time...
A python class that acts like dict
Don’t inherit from Python built-in dict, ever! for example update
method woldn't use __setitem__
, they do a lot for optimization. Use UserDict.
from collections import UserDict
class MyDict(UserDict):
def __delitem__(self, key):
pass
def __setitem__(self, key, value):
pass
Oracle database: How to read a BLOB?
If the content is not too large, you can also use
SELECT CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) FROM <table>;
or
SELECT DUMP ( CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) ) FROM <table>;
This will show you the HEX values.
Sending email with PHP from an SMTP server
When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).
For example, I usually use PHPMailer with similar settings to this ones:
$mail = new PHPMailer();
// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer
iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot
I found the same issue and tried everything. I have two different apps, one in objective-C and one in swift - both have the same problem. The error message comes in the debugger and the screen goes black after the first photo. This only happens in iOS >= 8.0, obviously it is a bug.
I found a difficult workaround. Shut off the camera controls with imagePicker.showsCameraControls = false and create your own overlayView that has the missing buttons. There are various tutorials around how to do this.
The strange error message stays, but at least the screen doesn't go black and you have a working app.
What is the difference between __dirname and ./ in node.js?
The gist
In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
For example...
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
Using .
inside require
...
If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
Open links in new window using AngularJS
@m59 Directives will work for ng-bind-html you just need to wait for $viewContentLoaded
to finish
app.directive('targetBlank', function($timeout) {
return function($scope, element) {
$scope.initializeTarget = function() {
return $scope.$on('$viewContentLoaded', $timeout(function() {
var elems;
elems = element.prop('tagName') === 'A' ? element : element.find('a');
elems.attr('target', '_blank');
}));
};
return $scope.initializeTarget();
};
});
Creating for loop until list.length
You could learn about Python loops here:
http://en.wikibooks.org/wiki/Python_Programming/Loops
You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.
So you can do loop inside loop with double tab (indent)
An example of double loop is like this:
onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
for count2 in tentotwenty
print(count2)
Recursively add the entire folder to a repository
If you want to add a directory and all the files which are located inside it recursively, Go to the directory where the directory you want to add is located.
$ cd directory
$ git add directoryname
asp.net: Invalid postback or callback argument
I had this same problem with a datalist I"m dynamically binding, adding EnableViewState="false" quieted the error message. I figure if I'm binding programmatically, then the control is being populated on each post back, the view state doesn't have to be maintained if it may or may not change on each call back, that's why I'm dynamically binding it, lol.
How to display errors on laravel 4?
I had a problem with the white screen after installing a new laravel instance. I couldn't find anything in the logs because (eventually I found out) that the reason for the white screen was that app/storage wasn't writable.
In order to get an error message on the screen I added the following to the public/index.php
try {
$app->run();
} catch(\Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
After that it was easy to solve the problem.
set the iframe height automatically
If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>
Is there a simple, elegant way to define singletons?
OK, singleton could be good or evil, I know. This is my implementation, and I simply extend a classic approach to introduce a cache inside and produce many instances of a different type or, many instances of same type, but with different arguments.
I called it Singleton_group, because it groups similar instances together and prevent that an object of the same class, with same arguments, could be created:
# Peppelinux's cached singleton
class Singleton_group(object):
__instances_args_dict = {}
def __new__(cls, *args, **kwargs):
if not cls.__instances_args_dict.get((cls.__name__, args, str(kwargs))):
cls.__instances_args_dict[(cls.__name__, args, str(kwargs))] = super(Singleton_group, cls).__new__(cls, *args, **kwargs)
return cls.__instances_args_dict.get((cls.__name__, args, str(kwargs)))
# It's a dummy real world use example:
class test(Singleton_group):
def __init__(self, salute):
self.salute = salute
a = test('bye')
b = test('hi')
c = test('bye')
d = test('hi')
e = test('goodbye')
f = test('goodbye')
id(a)
3070148780L
id(b)
3070148908L
id(c)
3070148780L
b == d
True
b._Singleton_group__instances_args_dict
{('test', ('bye',), '{}'): <__main__.test object at 0xb6fec0ac>,
('test', ('goodbye',), '{}'): <__main__.test object at 0xb6fec32c>,
('test', ('hi',), '{}'): <__main__.test object at 0xb6fec12c>}
Every object carries the singleton cache... This could be evil, but it works great for some :)
Find the least number of coins required that can make any change from 1 to 99 cents
A vb version
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
For saleAMT As Decimal = 0.01D To 0.99D Step 0.01D
Dim foo As New CashDrawer(0, 0, 0)
Dim chg As List(Of Money) = foo.MakeChange(saleAMT, 1D)
Dim t As Decimal = 1 - saleAMT
Debug.WriteLine(t.ToString("C2"))
For Each c As Money In chg
Debug.WriteLine(String.Format("{0} of {1}", c.Count.ToString("N0"), c.moneyValue.ToString("C2")))
Next
Next
End Sub
Class CashDrawer
Private _drawer As List(Of Money)
Public Sub New(Optional ByVal QTYtwoD As Integer = -1, _
Optional ByVal QTYoneD As Integer = -1, _
Optional ByVal QTYfifty As Integer = -1, _
Optional ByVal QTYquarters As Integer = -1, _
Optional ByVal QTYdimes As Integer = -1, _
Optional ByVal QTYnickels As Integer = -1, _
Optional ByVal QTYpennies As Integer = -1)
_drawer = New List(Of Money)
_drawer.Add(New Money(2D, QTYtwoD))
_drawer.Add(New Money(1D, QTYoneD))
_drawer.Add(New Money(0.5D, QTYfifty))
_drawer.Add(New Money(0.25D, QTYquarters))
_drawer.Add(New Money(0.1D, QTYdimes))
_drawer.Add(New Money(0.05D, QTYnickels))
_drawer.Add(New Money(0.01D, QTYpennies))
End Sub
Public Function MakeChange(ByVal SaleAmt As Decimal, _
ByVal amountTendered As Decimal) As List(Of Money)
Dim change As Decimal = amountTendered - SaleAmt
Dim rv As New List(Of Money)
For Each c As Money In Me._drawer
change -= (c.NumberOf(change) * c.moneyValue)
If c.Count > 0 Then
rv.Add(c)
End If
Next
If change <> 0D Then Throw New ArithmeticException
Return rv
End Function
End Class
Class Money
'-1 equals unlimited qty
Private _qty As Decimal 'quantity in drawer
Private _value As Decimal 'value money
Private _count As Decimal = 0D
Public Sub New(ByVal theValue As Decimal, _
ByVal theQTY As Decimal)
Me._value = theValue
Me._qty = theQTY
End Sub
ReadOnly Property moneyValue As Decimal
Get
Return Me._value
End Get
End Property
Public Function NumberOf(ByVal theAmount As Decimal) As Decimal
If (Me._qty > 0 OrElse Me._qty = -1) AndAlso Me._value <= theAmount Then
Dim ct As Decimal = Math.Floor(theAmount / Me._value)
If Me._qty <> -1D Then 'qty?
'limited qty
If ct > Me._qty Then 'enough
'no
Me._count = Me._qty
Me._qty = 0D
Else
'yes
Me._count = ct
Me._qty -= ct
End If
Else
'unlimited qty
Me._count = ct
End If
End If
Return Me._count
End Function
ReadOnly Property Count As Decimal
Get
Return Me._count
End Get
End Property
End Class
End Class
"The semaphore timeout period has expired" error for USB connection
I had this problem as well on two different Windows computers when communicating with a Arduino Leonardo. The reliable solution was:
- Find the COM port in device manager and open the device properties.
- Open the "Port Settings" tab, and click the advanced button.
- There, uncheck the box "Use FIFO buffers (required 16550 compatible UART), and press OK.
Unfortunately, I don't know what this feature does, or how it affects this issue. After several PC restarts and a dozen device connection cycles, this is the only thing that reliably fixed the issue.
on change event for file input element
Give unique class and different id for file input
$("#tab-content").on('change',class,function()
{
var id=$(this).attr('id');
$("#"+id).trigger(your function);
//for name of file input $("#"+id).attr("name");
});
How do relative file paths work in Eclipse?
This is really similar to another question.
How should I load files into my Java application?
How should I load my files into my Java Application?
You do not want to load your files in by:
C:\your\project\file.txt
this is bad!
You should use getResourceAsStream.
InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.
Parsing string as JSON with single quotes?
Something like this:
_x000D_
_x000D_
var div = document.getElementById("result");_x000D_
_x000D_
var str = "{'a':1}";_x000D_
str = str.replace(/\'/g, '"');_x000D_
var parsed = JSON.parse(str);_x000D_
console.log(parsed);_x000D_
div.innerText = parsed.a;
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_
xlrd.biffh.XLRDError: Excel xlsx file; not supported
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
- make sure you are on a recent version of Pandas, at least 1.0.1,
and preferably the latest release. 1.2 will make his
even clearer.
- install
openpyxl
: https://openpyxl.readthedocs.io/en/stable/
- change your Pandas code to be:
df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file
The practical way is setting font-family
to a value that is the specific name of the semibold version, such as
font-family: "Myriad pro Semibold"
if that’s the name. (Personally I use my own font listing tool, which runs on Internet Explorer only to see the fonts in my system by names as usable in CSS.)
In this approach, font-weight
is not needed (and probably better not set).
Web browsers have been poor at implementing font weights by the book: they largely cannot find the specific weight version, except bold. The workaround is to include the information in the font family name, even though this is not how things are supposed to work.
Testing with Segoe UI, which often exists in different font weight versions on Windows systems, I was able to make Internet Explorer 9 select the proper version when using the logical approach (of using the font family name Segoe UI and different font-weight
values), but it failed on Firefox 9 and Chrome 16 (only normal and bold work). On all of these browsers, for example, setting font-family: Segoe UI Light
works OK.
Replace all occurrences of a String using StringBuilder?
How about create a method and let String.replaceAll
do it for you:
public static void replaceAll(StringBuilder sb, String regex, String replacement)
{
String aux = sb.toString();
aux = aux.replaceAll(regex, replacement);
sb.setLength(0);
sb.append(aux);
}
Android SharedPreferences in Fragment
As a note of caution this answer provided by the user above me is correct.
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.
in iPhone App How to detect the screen resolution of the device
Use it in App Delegate: I am using storyboard
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;
//----------------HERE WE SETUP FOR IPHONE 4/4s/iPod----------------------
if(iOSDeviceScreenSize.height == 480){
UIStoryboard *iPhone35Storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
// Instantiate the initial view controller object from the storyboard
UIViewController *initialViewController = [iPhone35Storyboard instantiateInitialViewController];
// Instantiate a UIWindow object and initialize it with the screen size of the iOS device
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Set the initial view controller to be the root view controller of the window object
self.window.rootViewController = initialViewController;
// Set the window object to be the key window and show it
[self.window makeKeyAndVisible];
iphone=@"4";
NSLog(@"iPhone 4: %f", iOSDeviceScreenSize.height);
}
//----------------HERE WE SETUP FOR IPHONE 5----------------------
if(iOSDeviceScreenSize.height == 568){
// Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4
UIStoryboard *iPhone4Storyboard = [UIStoryboard storyboardWithName:@"iPhone5" bundle:nil];
// Instantiate the initial view controller object from the storyboard
UIViewController *initialViewController = [iPhone4Storyboard instantiateInitialViewController];
// Instantiate a UIWindow object and initialize it with the screen size of the iOS device
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Set the initial view controller to be the root view controller of the window object
self.window.rootViewController = initialViewController;
// Set the window object to be the key window and show it
[self.window makeKeyAndVisible];
NSLog(@"iPhone 5: %f", iOSDeviceScreenSize.height);
iphone=@"5";
}
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// NSLog(@"wqweqe");
storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];
}
return YES;
}
Check if a string isn't nil or empty in Lua
Can this code be simplified in one if test instead two?
nil
and ''
are different values. If you need to test that s
is neither, IMO you should just compare against both, because it makes your intent the most clear.
That and a few alternatives, with their generated bytecode:
if not foo or foo == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 0
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
if foo == nil or foo == '' then end
GETGLOBAL 0 -1 ; foo
EQ 1 0 -2 ; - nil
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -3 ; - ""
JMP 0 ; to 7
if (foo or '') == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 1
JMP 1 ; to 5
LOADK 0 -2 ; ""
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.
How to replace all occurrences of a string in Javascript?
This is the fastest version that doesn't use regular expressions.
Revised jsperf
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
It is almost twice as fast as the split and join method.
As pointed out in a comment here, this will not work if your omit
variable contains place
, as in: replaceAll("string", "s", "ss")
, because it will always be able to replace another occurrence of the word.
There is another jsperf with variants on my recursive replace that go even faster (http://jsperf.com/replace-all-vs-split-join/12)!
- Update July 27th 2017: It looks like RegExp now has the fastest performance in the recently released Chrome 59.
Handling the null value from a resultset in JAVA
The description of the getString() method says the following:
the column value; if the value is SQL NULL, the value returned is null
That means your problem is not that the String value is null, rather some other
object is, perhaps your ResultSet or maybe you closed the connection or something
like this. Provide the stack trace, that would help.
get dictionary key by value
maybe something like this:
foreach (var keyvaluepair in dict)
{
if(Object.ReferenceEquals(keyvaluepair.Value, searchedObject))
{
//dict.Remove(keyvaluepair.Key);
break;
}
}
Switch to another branch without changing the workspace files
Edit: I just noticed that you said you had already created some commits. In that case, use git merge --squash
to make a single commit:
git checkout cleanchanges
git merge --squash master
git commit -m "nice commit comment for all my changes"
(Edit: The following answer applies if you have uncommitted changes.)
Just switch branches with git checkout cleanchanges
. If the branches refer to the same ref, then all your uncommitted changes will be preserved in your working directory when you switch.
The only time you would have a conflict is if some file in the repository is different between origin/master
and cleanchanges
. If you just created the branch, then no problem.
As always, if you're at all concerned about losing work, make a backup copy first. Git is designed to not throw away work without asking you first.
Bootstrap with jQuery Validation Plugin
Try using this sample code. Using the Jquery validation plugin and additional methods.
This is the working code for my project. Hope this helps you
_x000D_
_x000D_
//jquery validation booking page_x000D_
_x000D_
// Wait for the DOM to be ready_x000D_
$(function() {_x000D_
// Initialize form validation on the registration form._x000D_
// It has the name attribute "registration"_x000D_
$("form[name='book']").validate({_x000D_
//on key up validation_x000D_
onkeyup: function(element) {_x000D_
$(element).valid(); _x000D_
}, _x000D_
// Specify validation rules_x000D_
rules: {_x000D_
// The key name on the left side is the name attribute_x000D_
// of an input field. Validation rules are defined_x000D_
// on the right side_x000D_
fname: {_x000D_
required: true,_x000D_
lettersonly: true_x000D_
},_x000D_
lname:{_x000D_
required: true,_x000D_
lettersonly: true_x000D_
},_x000D_
email: {_x000D_
required: true,_x000D_
// Specify that email should be validated_x000D_
// by the built-in "email" rule_x000D_
email: true_x000D_
},_x000D_
password: {_x000D_
required: true,_x000D_
minlength: 5_x000D_
}_x000D_
},_x000D_
// Specify validation error messages_x000D_
messages: {_x000D_
fname: {_x000D_
required:"Please enter your firstname",_x000D_
lettersonly:"Letters allowed only"_x000D_
},_x000D_
lname: {_x000D_
required:"Please enter your lastname",_x000D_
lettersonly:"Letters allowed only"_x000D_
},_x000D_
email: "Please enter a valid email address"_x000D_
},_x000D_
// Make sure the form is submitted to the destination defined_x000D_
// in the "action" attribute of the form when valid_x000D_
submitHandler: function(form) {_x000D_
form.submit();_x000D_
}_x000D_
});_x000D_
});
_x000D_
.error {_x000D_
color: red;_x000D_
margin-left: 5px;_x000D_
font-size:15px;_x000D_
}
_x000D_
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>_x000D_
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>_x000D_
_x000D_
<form name="book" id="book" action="" method="post">_x000D_
_x000D_
<div class="row form-group">_x000D_
<div class="col-md-6 ">_x000D_
<label class="" for="fname">First Name</label>_x000D_
<input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<label class="" for="lname">Last Name</label>_x000D_
<input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row form-group">_x000D_
<div class="col-md-6 ">_x000D_
<label class="" for="date">Date</label>_x000D_
<input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<label class="" for="email">Email</label>_x000D_
<input type="email" name="email" id="email" class="form-control" placeholder="Email">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row form-group">_x000D_
<div class="col-md-12">_x000D_
<label class="" for="treatment">Service You Want</label>_x000D_
<select name="treatment" id="treatment" class="form-control">_x000D_
<option value="">Hair Cut</option>_x000D_
<option value="">Hair Coloring</option>_x000D_
<option value="">Perms and Curls</option>_x000D_
<option value="">Hair Conditioning</option>_x000D_
<option value="">Manicure</option>_x000D_
<option value="">Pedicure</option>_x000D_
<option value="">Nails Extension</option>_x000D_
<option value="">Nail Design</option>_x000D_
<option value="">Waxing Eyebrows</option>_x000D_
<option value="">Waxing Hands/Legs</option>_x000D_
<option value="">Full Face Waxing</option>_x000D_
<option value="">Full Body/Body Parts Wax</option>_x000D_
</select>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row form-group">_x000D_
<div class="col-md-12">_x000D_
<label class="" for="note">Notes</label>_x000D_
<textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row form-group">_x000D_
<div class="col-md-12">_x000D_
<center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_
Group by with union mysql select query
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
Best practices for copying files with Maven
I can only assume that your ${project.server.config} property is something custom defined and is outside of the standard directory layout.
If so, then I'd use the copy task.
Quicksort with Python
This algorithm doesn't use recursive functions.
Let N
be any list of numbers with len(N) > 0
. Set K = [N]
and execute the following program.
Note: This is a stable sorting algorithm.
def BinaryRip2Singletons(K, S):
K_L = []
K_P = [ [K[0][0]] ]
K_R = []
for i in range(1, len(K[0])):
if K[0][i] < K[0][0]:
K_L.append(K[0][i])
elif K[0][i] > K[0][0]:
K_R.append(K[0][i])
else:
K_P.append( [K[0][i]] )
K_new = [K_L]*bool(len(K_L)) + K_P + [K_R]*bool(len(K_R)) + K[1:]
while len(K_new) > 0:
if len(K_new[0]) == 1:
S.append(K_new[0][0])
K_new = K_new[1:]
else:
break
return K_new, S
N = [16, 19, 11, 15, 16, 10, 12, 14, 4, 10, 5, 2, 3, 4, 7, 1]
K = [ N ]
S = []
print('K =', K, 'S =', S)
while len(K) > 0:
K, S = BinaryRip2Singletons(K, S)
print('K =', K, 'S =', S)
PROGRAM OUTPUT:
K = [[16, 19, 11, 15, 16, 10, 12, 14, 4, 10, 5, 2, 3, 4, 7, 1]] S = []
K = [[11, 15, 10, 12, 14, 4, 10, 5, 2, 3, 4, 7, 1], [16], [16], [19]] S = []
K = [[10, 4, 10, 5, 2, 3, 4, 7, 1], [11], [15, 12, 14], [16], [16], [19]] S = []
K = [[4, 5, 2, 3, 4, 7, 1], [10], [10], [11], [15, 12, 14], [16], [16], [19]] S = []
K = [[2, 3, 1], [4], [4], [5, 7], [10], [10], [11], [15, 12, 14], [16], [16], [19]] S = []
K = [[5, 7], [10], [10], [11], [15, 12, 14], [16], [16], [19]] S = [1, 2, 3, 4, 4]
K = [[15, 12, 14], [16], [16], [19]] S = [1, 2, 3, 4, 4, 5, 7, 10, 10, 11]
K = [[12, 14], [15], [16], [16], [19]] S = [1, 2, 3, 4, 4, 5, 7, 10, 10, 11]
K = [] S = [1, 2, 3, 4, 4, 5, 7, 10, 10, 11, 12, 14, 15, 16, 16, 19]
Component based game engine design
I am currently researching this exact topic in the many (MANY) threads at GameDev.net and found the following two solutions to be good candidates on what I will develop for my game:
Changing the child element's CSS when the parent is hovered
If you're using Twitter Bootstrap styling and base JS for a drop down menu:
.child{ display:none; }
.parent:hover .child{ display:block; }
This is the missing piece to create sticky-dropdowns (that aren't annoying)
- The behavior is to:
- Stay open when clicked, close when clicking again anywhere else on the page
- Close automatically when the mouse scrolls out of the menu's elements.
How to find locked rows in Oracle
The below PL/SQL block finds all locked rows in a table. The other answers only find the blocking session, finding the actual locked rows requires reading and testing each row.
(However, you probably do not need to run this code. If you're having a locking problem, it's usually easier to find the culprit using GV$SESSION.BLOCKING_SESSION
and other related data dictionary views. Please try another approach before you run this abysmally slow code.)
First, let's create a sample table and some data. Run this in session #1.
--Sample schema.
create table test_locking(a number);
insert into test_locking values(1);
insert into test_locking values(2);
commit;
update test_locking set a = a+1 where a = 1;
In session #2, create a table to hold the locked ROWIDs.
--Create table to hold locked ROWIDs.
create table locked_rowids(the_rowid rowid);
--Remove old rows if table is already created:
--delete from locked_rowids;
--commit;
In session #2, run this PL/SQL block to read the entire table, probe each row, and store the locked ROWIDs. Be warned, this may be ridiculously slow. In your real version of this query, change both references to TEST_LOCKING to your own table.
--Save all locked ROWIDs from a table.
--WARNING: This PL/SQL block will be slow and will temporarily lock rows.
--You probably don't need this information - it's usually good enough to know
--what other sessions are locking a statement, which you can find in
--GV$SESSION.BLOCKING_SESSION.
declare
v_resource_busy exception;
pragma exception_init(v_resource_busy, -00054);
v_throwaway number;
type rowid_nt is table of rowid;
v_rowids rowid_nt := rowid_nt();
begin
--Loop through all the rows in the table.
for all_rows in
(
select rowid
from test_locking
) loop
--Try to look each row.
begin
select 1
into v_throwaway
from test_locking
where rowid = all_rows.rowid
for update nowait;
--If it doesn't lock, then record the ROWID.
exception when v_resource_busy then
v_rowids.extend;
v_rowids(v_rowids.count) := all_rows.rowid;
end;
rollback;
end loop;
--Display count:
dbms_output.put_line('Rows locked: '||v_rowids.count);
--Save all the ROWIDs.
--(Row-by-row because ROWID type is weird and doesn't work in types.)
for i in 1 .. v_rowids.count loop
insert into locked_rowids values(v_rowids(i));
end loop;
commit;
end;
/
Finally, we can view the locked rows by joining to the LOCKED_ROWIDS table.
--Display locked rows.
select *
from test_locking
where rowid in (select the_rowid from locked_rowids);
A
-
1
Code line wrapping - how to handle long lines
In general, I break lines before operators, and indent the subsequent lines:
Map<long parameterization> longMap
= new HashMap<ditto>();
String longString = "some long text"
+ " some more long text";
To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.
how to create a logfile in php?
Use below function
// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');
$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");
Above function will create a log in file php_error with proper description and email will be sent.
How to change values in a tuple?
I've found the best way to edit tuples is to recreate the tuple using the previous version as the base.
Here's an example I used for making a lighter version of a colour (I had it open already at the time):
colour = tuple([c+50 for c in colour])
What it does, is it goes through the tuple 'colour' and reads each item, does something to it, and finally adds it to the new tuple.
So what you'd want would be something like:
values = ('275', '54000', '0.0', '5000.0', '0.0')
values = (tuple(for i in values: if i = 0: i = 200 else i = values[i])
That specific one doesn't work, but the concept is what you need.
tuple = (0, 1, 2)
tuple = iterate through tuple, alter each item as needed
that's the concept.
Request Permission for Camera and Library in iOS 10 - Info.plist
Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:
Swift 4.0 and 4.1
func proceedWithCameraAccess(identifier: String){
// handler in .requestAccess is needed to process user's answer to our request
AVCaptureDevice.requestAccess(for: .video) { success in
if success { // if request is granted (success is true)
DispatchQueue.main.async {
self.performSegue(withIdentifier: identifier, sender: nil)
}
} else { // if request is denied (success is false)
// Create Alert
let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)
// Add "OK" Button to alert, pressing it will bring you to the settings app
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
}))
// Show the alert with animation
self.present(alert, animated: true)
}
}
}
How do I use Ruby for shell scripting?
Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.
So, if you had a script called my_shell_script:
#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
puts value
end
...make it executable (as others have mentioned):
chmod u+x my_shell_script
And call it like so:
> ./my_shell_script one two three four five
You'd get this:
I was passed:
one
two
three
four
five
The arguments work nicely with filename expansion:
./my_shell_script *
I was passed:
a_file_in_the_current_directory
another_file
my_shell_script
the_last_file
Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.
Converting HTML to PDF using PHP?
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
String Concatenation using '+' operator
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
Inserting HTML into a div
And many lines may look like this. The html here is sample only.
var div = document.createElement("div");
div.innerHTML =
'<div class="slideshow-container">\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">1 / 3</div>\n' +
'<img src="image1.jpg" style="width:100%">\n' +
'<div class="text">Caption Text</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">2 / 3</div>\n' +
'<img src="image2.jpg" style="width:100%">\n' +
'<div class="text">Caption Two</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">3 / 3</div>\n' +
'<img src="image3.jpg" style="width:100%">\n' +
'<div class="text">Caption Three</div>\n' +
'</div>\n' +
'<a class="prev" onclick="plusSlides(-1)">❮</a>\n' +
'<a class="next" onclick="plusSlides(1)">❯</a>\n' +
'</div>\n' +
'<br>\n' +
'<div style="text-align:center">\n' +
'<span class="dot" onclick="currentSlide(1)"></span> \n' +
'<span class="dot" onclick="currentSlide(2)"></span> \n' +
'<span class="dot" onclick="currentSlide(3)"></span> \n' +
'</div>\n';
document.body.appendChild(div);
Print directly from browser without print popup window
this.print(false);
I tried this in Chrome, Firefox and IE. It works only in Firefox and IE, it uses the default printer (with default print settings) and only works when I render a PDF (I use Foxit Reader with Safe Reading Mode disabled). Chrome shows the print dialog, also the other browsers when I render an HTML page.
bootstrap multiselect get selected values
the solution what I found to work in my case
$('#multiselect1').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
maxHeight: '300',
buttonWidth: '235',
onChange: function(element, checked) {
var brands = $('#multiselect1 option:selected');
var selected = [];
$(brands).each(function(index, brand){
selected.push([$(this).val()]);
});
console.log(selected);
}
});
@font-face src: local - How to use the local font if the user already has it?
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
How do I wrap text in a pre tag?
The answer, from this page in CSS:
pre {
white-space: pre-wrap; /* Since CSS 2.1 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
Submit form and stay on same page?
Use XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
ASP.Net MVC: Calling a method from a view
Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.
If you need to call controller from View - you are doing something wrong. Time for refactoring.
Default passwords of Oracle 11g?
actually during the installation process.it will prompt u to enter the password..At the last step of installation, a window will appear showing cloning database files..After copying,there will be a option..like password managament..there we hav to set our password..and user name will be default..
Groovy write to file (newline)
As @Steven points out, a better way would be:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}
As this handles the line separator for you, and handles closing the writer as well
(and doesn't open and close the file each time you write a line, which could be slow in your original version)
Create a BufferedImage from file and make it TYPE_INT_ARGB
try {
File img = new File("somefile.png");
BufferedImage image = ImageIO.read(img );
System.out.println(image);
} catch (IOException e) {
e.printStackTrace();
}
Example output for my image file:
BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24
numComponents = 3 color
space = java.awt.color.ICC_ColorSpace@50a649
transparency = 1
has alpha = false
isAlphaPre = false
ByteInterleavedRaster:
width = 800
height = 600
#numDataElements 3
dataOff[0] = 2
You can run System.out.println(object); on just about any object and get some information about it.
Checking if any elements in one list are in another
I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.
def reachedGoal(a,b):
if(len(a)!=len(b)):
raise ValueError("Wrong lists provided")
for val1 in range(0,len(a)):
temp1=a[val1]
temp2=b[val1]
for val2 in range(0,len(b)):
if(temp1[val2]!=temp2[val2]):
return False
return True
How do you debug MySQL stored procedures?
I do something very similar to you.
I'll usually include a DEBUG param that defaults to false and I can set to true at run time. Then wrap the debug statements into an "If DEBUG" block.
I also use a logging table with many of my jobs so that I can review processes and timing. My Debug code gets output there as well. I include the calling param name, a brief description, row counts affected (if appropriate), a comments field and a time stamp.
Good debugging tools is one of the sad failings of all SQL platforms.
JavaScript Promises - reject vs. throw
The difference is ternary operator
return condition ? someData : Promise.reject(new Error('not OK'))
return condition ? someData : throw new Error('not OK')
When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?
This error can sometimes be misleading. 2 things you might want to check:
Is there an actual JAR for the dependency in the repo? Your error message contains a URL of where it is searching, so go there, and then browse to the folder that matches your dependency. Is there a jar? If not, you need to change your dependency. (for example, you could be pointing at a top level parent dependency, when you should be pointing at a sub project)
If the jar exists on the remote repo, then just delete your local copy. It will be in your home directory (unless you configured differently) under .m2/repository (ls -a to show hidden if on Linux).
How to change string into QString?
Do you mean a C string, as in a char*
string, or a C++ std::string
object?
Either way, you use the same constructor, as documented in the QT reference:
For a regular C string, just use the main constructor:
char name[] = "Stack Overflow";
QString qname(name);
For a std::string
, you obtain the char*
to the buffer and pass that to the QString
constructor:
std::string name2("Stack Overflow");
QString qname2(name2.c_str());
Error while sending QUERY packet
You cannot have the WHERE
clause in an INSERT
statement.
insert into table1(data) VALUES(:data) where sno ='45830'
Should be
insert into table1(data) VALUES(:data)
Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:
SET GLOBAL max_allowed_packet=32M
Change the 32M
(32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.
How to include a child object's child object in Entity Framework 5
A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.
public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)
{
foreach (var include in includeProperties)
{
query = query.Include(include);
}
return query.ToList();
}
PL/SQL block problem: No data found error
Your SELECT
statement isn't finding the data you're looking for. That is, there is no record in the ENROLLMENT
table with the given STUDENT_ID
and SECTION_ID
. You may want to try putting some DBMS_OUTPUT.PUT_LINE
statements before you run the query, printing the values of v_student_id
and v_section_id
. They may not be containing what you expect them to contain.
Get Current date & time with [NSDate date]
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
Function pointer to member function
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:
class A {
public:
int f();
int (A::*x)(); // <- declare by saying what class it is a pointer to
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f; // use the :: syntax
printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}
a.x
does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a
. Prepending a
another time as the left operand to the .*
operator will tell the compiler on what object to call the function on.
Target a css class inside another css class
I use div instead of tables and am able to target classes within the main class, as below:
CSS
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
HTML
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
Get connection status on Socket.io client
You can check the socket.connected
property:
var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
console.log('check 2', socket.connected);
});
It's updated dynamically, if the connection is lost it'll be set to false
until the client picks up the connection again. So easy to check for with setInterval
or something like that.
Another solution would be to catch disconnect
events and track the status yourself.
moment.js, how to get day of week number
You can get this in 2 way using moment and also using Javascript
_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const usingMoment_1 = date.day();_x000D_
const usingMoment_2 = date.isoWeekday();_x000D_
_x000D_
console.log('usingMoment: date.day() ==> ',usingMoment_1);_x000D_
console.log('usingMoment: date.isoWeekday() ==> ',usingMoment_2);_x000D_
_x000D_
_x000D_
const usingJS= new Date("2015-07-02").getDay();_x000D_
console.log('usingJavaSript: new Date("2015-07-02").getDay() ===> ',usingJS);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_
File.Move Does Not Work - File Already Exists
What you need is:
if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Delete(@"c:\test\Test\SomeFile.txt");
}
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
This will either:
- If the file doesn't exist at the destination location, successfully move the file, or;
- If the file does exist at the destination location, delete it, then move the file.
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt
.
PHP unable to load php_curl.dll extension
libeay32.dll
and ssleay32.dll
have to be path-accessible for php_curl.dll
loading to succeed.
But copying them into Apache's ServerRoot
, Apache's \bin\
, Window's \System32\
, or even worse into the Windows main directory is a bad hack and may not even work with newer PHP versions.
The right way to do it is to add the PHP path to the Windows Path
variable.
- In
Control Panel -> System
click on Advanced System Settings or press WIN+R and type SystemPropertiesAdvanced
- Click the button Environment Variables.
- Under System Variables you will find the
Path
variable. Edit it and prepend C:\PHP;
to it - or whatever the path to your PHP folder is.
(Hint: If your PHP folder contains spaces like C:\Program Files\PHP
you may need to use the short filename form here, i.e. C:\Progra~1\PHP
.)
- Then fully stop Apache and start it again (a simple restart might not be enough).
Update 2017-05:
I changed the instructions above to prepend the Path variable with the PHP path instead of appending to it. This makes sure that the DLLs in the PHP path are used and not any other (outdated) versions in other paths of the system.
Update 2018-04:
If you have already chosen the wrong way and copied any of the PHP DLLs to Apache or Windows paths, then I strongly recommend that you remove them again! If you don't, you might get into trouble when you later try to update PHP. If a new PHP version brings new versions of these DLLs, but your old DLLs still linger around in system or webserver paths, these old DLLs might be found first. This will most certainly prevent the PHP interpreter from starting. Such errors can be very hard to understand and resolve. So better clean up now and remove any of the mentioned DLLs from Windows and Apache paths, if you copied them there.
(Thanks to @EdmundTam and @WasimA. for pointing out this problem in the comments!)
Update 2019-10:
Tip: To find all copies of these DLLs and check whether you might have placed them in the wrong folders, you can use the following commands in a Windows Command Prompt window:
dir c:\libeay32.dll /s
dir c:\ssleay32.dll /s
Be warned that these commands may take some time to complete as they search through the entire directory structure of your system drive C:.
Update 2020-08:
If your PHP folder contains spaces (i.e. C:\Program Files\PHP
) you may need to use the short filename form in the Path
variable at step 3 (i.e. C:\Progra~1\PHP
). Thanks to @onee for this tip!
How do I activate a specific workbook and a specific sheet?
You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:
Sub Test()
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")
wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54
End Sub
addClass and removeClass in jQuery - not removing class
why not simplify it?
jquery
$('.clickable').on('click', function() {//on parent click
$(this).removeClass('spot').addClass('grown');//use remove/add Class here because it needs to perform the same action every time, you don't want a toggle
}).children('.close_button').on('click', function(e) {//on close click
e.stopPropagation();//stops click from triggering on parent
$(this).parent().toggleClass('spot grown');//since this only appears when .grown is present, toggling will work great instead of add/remove Class and save some space
});
This way it's much easier to maintain.
made a fiddle: http://jsfiddle.net/filever10/3SmaV/
How are software license keys generated?
You can use and implement Secure Licensing API from very easily in your Software Projects using it,(you need to download the desktop application for creating secure license from https://www.systemsoulsoftwares.com/)
- Creates unique UID for client software based on System Hardware(CPU,Motherboard,Hard-drive)
(UID acts as Private Key for that unique system)
- Allows to send Encrypted license string very easily to client system, It verifies license string and works on only that particular system
- This method allows software developers or company to store more information about software/developer/distributor services/features/client
- It gives control for locking and unlocked the client software features, saving time of developers for making more version for same software with changing features
- It take cares about trial version too for any number of days
- It secures the License timeline by Checking DateTime online during registration
- It unlocks all hardware information to developers
- It has all pre-build and custom function that developer can access at every process of licensing for making more complex secure code
Enter key pressed event handler
In WPF, TextBox element will not get opportunity to use "Enter" button for creating KeyUp Event until you will not set property: AcceptsReturn="True".
But, it would`t solve the problem with handling KeyUp Event in TextBox element. After pressing "ENTER" you will get a new text line in TextBox.
I had solved problem of using KeyUp Event of TextBox element by using Bubble event strategy. It's short and easy. You have to attach a KeyUp Event handler in some (any) parent element:
XAML:
<Window x:Class="TextBox_EnterButtomEvent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TextBox_EnterButtomEvent"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height ="0.3*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
Input text end press ENTER:
</TextBlock>
<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
You have entered:
</TextBlock>
<TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid></Window>
C# logical part (KeyUp Event handler is attached to a grid element):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Grid_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
TextBox txtBox = e.Source as TextBox;
if(txtBox != null)
{
this.txtBlock.Text = txtBox.Text;
this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
}
}
}
}
Result:
How to iterate over the file in python
This is probably because an empty line at the end of your input file.
Try this:
for x in f:
try:
print int(x.strip(),16)
except ValueError:
print "Invalid input:", x
Angular ng-click with call to a controller function not working
Use alias when defining Controller in your angular configuration. For example:
NOTE: I'm using TypeScript here
Just take note of the Controller, it has an alias of homeCtrl.
module MongoAngular {
var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);
app.config([
'$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
$routeProvider
.when('/Home', {
templateUrl: '/PartialViews/Home/home.html',
controller: 'HomeController as homeCtrl'
})
.otherwise({ redirectTo: '/Home' });
}])
.config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
restangularProvider.setBaseUrl('/api');
}]);
}
And here's the way to use it...
ng-click="homeCtrl.addCustomer(customer)"
Try it.. It might work for you as it worked for me... ;)
How can I generate a self-signed certificate with SubjectAltName using OpenSSL?
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
Angular 5 Scroll to top on every Route click
None of the above worked for me for some reason :/, so I added an element ref to a top element in app.component.html
, and (activate)=onNavigate($event)
to the router-outlet
.
<!--app.component.html-->
<div #topScrollAnchor></div>
<app-navbar></app-navbar>
<router-outlet (activate)="onNavigate($event)"></router-outlet>
Then I added the child to the app.component.ts file to the type of ElementRef
, and had it scroll to it on activation of the router-outlet.
export class AppComponent {
@ViewChild('topScrollAnchor') topScroll: ElementRef;
onNavigate(event): any {
this.topScroll.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
Here's the code in stackblitz
HTTP GET with request body
Elasticsearch accepts GET requests with a body. It even seems that this is the preferred way: Elasticsearch guide
Some client libraries (like the Ruby driver) can log the cry command to stdout in development mode and it is using this syntax extensively.
Program "make" not found in PATH
Additional hint: If you have multiple projects with different toolchains open, check the build console header for the failing project's path.
I've just spent half an hour trying to fix a build that showed this error because another project with hopelessly outdated toolchain settings was open in the same workbench. Closing the other project re-enabled the build.
Stop a youtube video with jquery?
This works for me on both YouTube and Vimeo players.
I'm basically just resetting the src attribute, so be aware that the video will go back to the beginning.
var $theSource = $theArticleDiv.find('.views-field-field-video-1 iframe').attr('src');
$theArticleDiv.find('.views-field-field-video-1 iframe').attr('src', $theSource); //reset the video so it stops playing
$theArticleDiv is my current video's container - since I have multiple videos on the page, and they're being exposed via a Drupal view at runtime, I have no idea what their ids are going to be. So I've bound muy click event to a currently visible element, found its parent, and decided that's $theArticleDiv.
('.views-field-field-video-1 iframe') finds the current video's iframe for me - in particular the one that's visible right now.
That iframe has a src attribute. I just pick that up and reset it right back to what it already was, and automagically the video stops and goes back to the start.
If my users want to pause and resume, they can do it without closing the video, of course - but frankly if they do close the video, I feel they can live with the fact that it's reset to the start.
HTH
WARNING: Can't verify CSRF token authenticity rails
I'm using Rails 4.2.4 and couldn't work out why I was getting:
Can't verify CSRF token authenticity
I have in the layout:
<%= csrf_meta_tags %>
In the controller:
protect_from_forgery with: :exception
Invoking tcpdump -A -s 999 -i lo port 3000
was showing the header being set ( despite not needing to set the headers with ajaxSetup
- it was done already):
X-CSRF-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
DNT: 1
Content-Length: 125
authenticity_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
In the end it was failing because I had cookies switched off. CSRF doesn't work without cookies being enabled, so this is another possible cause if you're seeing this error.
Connect to Active Directory via LDAP
ldapConnection is the server adres: ldap.example.com
Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.
OU=Your_OU,OU=other_ou,dc=example,dc=com
You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain
Now i miss a parameter to authenticate, this works the same as the path for the username
CN=username,OU=users,DC=example,DC=com
Introduction to LDAP
IOCTL Linux device driver
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
Any way to write a Windows .bat file to kill processes?
I'm assuming as a developer, you have some degree of administrative control over your machine. If so, from the command line, run msconfig.exe. You can remove many processes from even starting, thereby eliminating the need to kill them with the above mentioned solutions.
How to convert base64 string to image?
Return converted image without saving:
from PIL import Image
import cv2
# Take in base64 string and return cv image
def stringToRGB(base64_string):
imgdata = base64.b64decode(str(base64_string))
image = Image.open(io.BytesIO(imgdata))
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
Python For loop get index
Do you want to iterate over characters or words?
For words, you'll have to split the words first, such as
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
This prints the index of the word.
For the absolute character position you'd need something like
chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1
Border around tr element doesn't show?
Add this to the stylesheet:
table {
border-collapse: collapse;
}
JSFiddle.
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in
CSS. One is most suitable for so-called separated borders around
individual cells, the other is suitable for borders that are
continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that
surround all or part of a cell, row, row group, column, and column
group.
Create a batch file to run an .exe with an additional parameter
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution.
Note: if your path folder name consists of spaces, then do not forget to add "".
How to markdown nested list items in Bitbucket?
4 spaces do the trick even inside definition list:
Endpoint
: `/listAgencies`
Method
: `GET`
Arguments
: * `level` - bla-bla.
* `withDisabled` - should we include disabled `AGENT`s.
* `userId` - bla-bla.
I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).
What are naming conventions for MongoDB?
Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.
I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...
MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.
MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id
(but this may be be to indicate that _id
is intended to be private, internal, never displayed or edited.
Is calculating an MD5 hash less CPU intensive than SHA family functions?
On my 2012 MacBook Air (Intel Core i5-3427U, 2x 1.8 GHz, 2.8 GHz Turbo), SHA-1 is slightly faster than MD5 (using OpenSSL in 64-bit mode):
$ openssl speed md5 sha1
OpenSSL 0.9.8r 8 Feb 2011
The 'numbers' are in 1000s of bytes per second processed.
type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
md5 30055.02k 94158.96k 219602.97k 329008.21k 384150.47k
sha1 31261.12k 95676.48k 224357.36k 332756.21k 396864.62k
Update: 10 months later with OS X 10.9, SHA-1 got slower on the same machine:
$ openssl speed md5 sha1
OpenSSL 0.9.8y 5 Feb 2013
The 'numbers' are in 1000s of bytes per second processed.
type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
md5 36277.35k 106558.04k 234680.17k 334469.33k 381756.70k
sha1 35453.52k 99530.85k 206635.24k 281695.48k 313881.86k
Second update: On OS X 10.10, SHA-1 speed is back to the 10.8 level:
$ openssl speed md5 sha1
OpenSSL 0.9.8zc 15 Oct 2014
The 'numbers' are in 1000s of bytes per second processed.
type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
md5 35391.50k 104905.27k 229872.93k 330506.91k 382791.75k
sha1 38054.09k 110332.44k 238198.72k 340007.12k 387137.77k
Third update: OS X 10.14 with LibreSSL is a lot faster (still on the same machine). SHA-1 still comes out on top:
$ openssl speed md5 sha1
LibreSSL 2.6.5
The 'numbers' are in 1000s of bytes per second processed.
type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
md5 43128.00k 131797.91k 304661.16k 453120.00k 526789.29k
sha1 55598.35k 157916.03k 343214.08k 489092.34k 570668.37k
Converting HTML to XML
I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.
function tryToXml($dom,$content) {
if(!$content) return false;
// xml well formed content can be loaded as xml node tree
$fragment = $dom->createDocumentFragment();
// wonderfull appendXML to add an XML string directly into the node tree!
// aappendxml will fail on a xml declaration so manually skip this when occurred
if( substr( $content,0, 5) == '<?xml' ) {
$content = substr($content,strpos($content,'>')+1);
if( strpos($content,'<') ) {
$content = substr($content,strpos($content,'<'));
}
}
// if appendXML is not working then use below htmlToXml() for nasty html correction
if(!@$fragment->appendXML( $content )) {
return $this->htmlToXml($dom,$content);
}
return $fragment;
}
// convert content into xml
// dom is only needed to prepare the xml which will be returned
function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {
// no xml when html is empty
if(!$content) return false;
// real content and possibly it needs encoding
if( $needEncoding ) {
// no need to convert character encoding as loadHTML will respect the content-type (only)
$content = '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
}
// return a dom from the content
$domInject = new DOMDocument("1.0", "UTF-8");
$domInject->preserveWhiteSpace = false;
$domInject->formatOutput = true;
// html type
try {
@$domInject->loadHTML( $content );
} catch(Exception $e){
// do nothing and continue as it's normal that warnings will occur on nasty HTML content
}
// to check encoding: echo $dom->encoding
$this->reworkDom( $domInject );
if( $bodyOnly ) {
$fragment = $dom->createDocumentFragment();
// retrieve nodes within /html/body
foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
foreach( $elementLevel1->childNodes as $elementInject ) {
$fragment->insertBefore( $dom->importNode($elementInject, true) );
}
}
}
} else {
$fragment = $dom->importNode($domInject->documentElement, true);
}
return $fragment;
}
protected function reworkDom( $node, $level = 0 ) {
// start with the first child node to iterate
$nodeChild = $node->firstChild;
while ( $nodeChild ) {
$nodeNextChild = $nodeChild->nextSibling;
switch ( $nodeChild->nodeType ) {
case XML_ELEMENT_NODE:
// iterate through children element nodes
$this->reworkDom( $nodeChild, $level + 1);
break;
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
// do nothing with text, cdata
break;
case XML_COMMENT_NODE:
// ensure comments to remove - sign also follows the w3c guideline
$nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
break;
case XML_DOCUMENT_TYPE_NODE: // 10: needs to be removed
case XML_PI_NODE: // 7: remove PI
$node->removeChild( $nodeChild );
$nodeChild = null; // make null to test later
break;
case XML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
case XML_HTML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
default:
throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
}
$nodeChild = $nodeNextChild;
} ;
}
Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:
$c='<p>test<font>two</p>';
$dom=new DOMDocument('1.0', 'UTF-8');
$n=$dom->appendChild($dom->createElement('info')); // make a root element
if( $valueXml=tryToXml($dom,$c) ) {
$n->appendChild($valueXml);
}
echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';
In this example '<p>test<font>two</p>'
will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>
'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>
' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info>
tag can be skipped.
With this I'm getting real nice XML out of unstructured and even corrupted HTML!
I hope it's a bit clear and might contribute to other people to use it.
Delete all Duplicate Rows except for One in MySQL?
Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.
NB - You need to do this first on a test copy of your table!
When I did it, I found that unless I also included AND n1.id <> n2.id
, it deleted every row in the table.
If you want to keep the row with the lowest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
If you want to keep the row with the highest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
I used this method in MySQL 5.1
Not sure about other versions.
Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE
, please be advised that using INSERT
and DISTINCT
is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE
, it took more than 2 hours and yet didn't complete.
INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
SELECT DISTINCT cellId,attributeId,entityRowId,value
FROM tableName;
How to set a header in an HTTP response?
Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).
Reading JSON from a file?
This works for me.
json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Suppose JSON file is like this:
{
"emp_details":[
{
"emp_name":"John",
"emp_emailId":"[email protected]"
},
{
"emp_name":"Aditya",
"emp_emailId":"[email protected]"
}
]
}
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
#Output:
{'emp_name':'John','emp_emailId':'[email protected]'}
{'emp_name':'Aditya','emp_emailId':'[email protected]'}
Read SQL Table into C# DataTable
var table = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{
da.Fill(table);
}
git - Server host key not cached
Just open Putty and try to establish connection to remote server you want to push your code.
when the dialog appears press Yes(you trust remote) then everything would be OK.
Compare two folders which has many files inside contents
Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.
-b Ignores trailing blanks (spaces and tabs)
and treats other strings of blanks as
equivalent.
-i Ignores the case of letters. For example,
`A' will compare equal to `a'.
-t Expands <TAB> characters in output lines.
Normal or -c output adds character(s) to the
front of each line that may adversely affect
the indentation of the original source lines
and make the output lines difficult to
interpret. This option will preserve the
original source's indentation.
-w Ignores all blanks (<SPACE> and <TAB> char-
acters) and treats all other strings of
blanks as equivalent. For example,
`if ( a == b )' will compare equal to
`if(a==b)'.
and there are many more.
how to read certain columns from Excel using Pandas - Python
"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.)
below are the examples
- Selected Columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
- Range of Columns and selected column
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
- Multiple Ranges
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
- Range of columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")
How to Call Controller Actions using JQuery in ASP.NET MVC
You can easily call any controller's action using jQuery AJAX method like this:
Note in this example my controller name is Student
Controller Action
public ActionResult Test()
{
return View();
}
In Any View of this above controller you can call the Test() action like this:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "@Url.Action("Test", "Student")",
success: function (result, status, xhr) {
alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
</script>
lodash multi-column sortBy descending
As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):
var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);
Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):
var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);
In version 4 of lodash this method has been renamed orderBy:
var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);
How do I resize a Google Map with JavaScript after it has loaded?
for Google Maps v3, you need to trigger the resize event differently:
google.maps.event.trigger(map, "resize");
See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event
Update
This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.
_x000D_
_x000D_
$(function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map($("#map-canvas")[0], mapOptions);
// listen for the window resize event & trigger Google Maps to update too
$(window).resize(function() {
// (the 'map' here is the result of the created 'var map = ...' above)
google.maps.event.trigger(map, "resize");
});
});
_x000D_
html,
body {
height: 100%;
}
#map-canvas {
min-width: 200px;
width: 50%;
min-height: 200px;
height: 80%;
border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_
UPDATE 2018-05-22
With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map
class.
The documentation states
When the map is resized, the map center is fixed
source: https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize");
doesn't have any effect starting from version 3.32
How can I get Android Wifi Scan Results into a list?
Try this code
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
}
WiFiDemo.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/textStatus"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Status" />
<Button
android:id="@+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Scan" />
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"></ListView>
</LinearLayout>
For ListView- row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/list_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp" />
</LinearLayout>
Add these permission in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
python numpy/scipy curve fitting
You'll first need to separate your numpy array into two separate arrays containing x and y values.
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
Here's an example for a linear fit with the data you provided.
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
Mapping a JDBC ResultSet to an object
Complete solution using @TEH-EMPRAH ideas and Generic casting from Cast Object to Generic Type for returning
import annotations.Column;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.*;
public class ObjectMapper<T> {
private Class clazz;
private Map<String, Field> fields = new HashMap<>();
Map<String, String> errors = new HashMap<>();
public DataMapper(Class clazz) {
this.clazz = clazz;
List<Field> fieldList = Arrays.asList(clazz.getDeclaredFields());
for (Field field : fieldList) {
Column col = field.getAnnotation(Column.class);
if (col != null) {
field.setAccessible(true);
fields.put(col.name(), field);
}
}
}
public T map(Map<String, Object> row) throws SQLException {
try {
T dto = (T) clazz.getConstructor().newInstance();
for (Map.Entry<String, Object> entity : row.entrySet()) {
if (entity.getValue() == null) {
continue; // Don't set DBNULL
}
String column = entity.getKey();
Field field = fields.get(column);
if (field != null) {
field.set(dto, convertInstanceOfObject(entity.getValue()));
}
}
return dto;
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
throw new SQLException("Problem with data Mapping. See logs.");
}
}
public List<T> map(List<Map<String, Object>> rows) throws SQLException {
List<T> list = new LinkedList<>();
for (Map<String, Object> row : rows) {
list.add(map(row));
}
return list;
}
private T convertInstanceOfObject(Object o) {
try {
return (T) o;
} catch (ClassCastException e) {
return null;
}
}
}
and then in terms of how it ties in with the database, I have the following:
// connect to database (autocloses)
try (DataConnection conn = ds1.getConnection()) {
// fetch rows
List<Map<String, Object>> rows = conn.nativeSelect("SELECT * FROM products");
// map rows to class
ObjectMapper<Product> objectMapper = new ObjectMapper<>(Product.class);
List<Product> products = objectMapper.map(rows);
// display the rows
System.out.println(rows);
// display it as products
for (Product prod : products) {
System.out.println(prod);
}
} catch (Exception e) {
e.printStackTrace();
}
Save array in mysql database
The way things like that are done is with serializing the array, which means "making a string out of it". To better understand this, have a look on this:
$array = array("my", "litte", "array", 2);
$serialized_array = serialize($array);
$unserialized_array = unserialize($serialized_array);
var_dump($serialized_array); // gives back a string, perfectly for db saving!
var_dump($unserialized_array); // gives back the array again
Adding a y-axis label to secondary y-axis in matplotlib
For everyone stumbling upon this post because pandas gets mentioned,
you now have the very elegant and straighforward option of directly accessing the
secondary_y axis in pandas with ax.right_ax
So paraphrasing the example initially posted, you would write:
table = sql.read_frame(query,connection)
ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.set_ylabel('$')
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')
(this is already mentioned in these posts as well: 1 2)
Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
mysql server port number
If your MySQL server runs on default settings, you don't need to specify that.
Default MySQL port is 3306.
[updated to show mysql_error() usage]
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Error connecting to mysql: '.mysql_error());
How can I read a text file in Android?
Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file
Round up value to nearest whole number in SQL UPDATE
Ceiling is the command you want to use.
Unlike Round, Ceiling only takes one parameter (the value you wish to round up), therefore if you want to round to a decimal place, you will need to multiply the number by that many decimal places first and divide afterwards.
Example.
I want to round up 1.2345 to 2 decimal places.
CEILING(1.2345*100)/100 AS Cost
Error: Uncaught (in promise): Error: Cannot match any routes Angular 2
I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem
export class AppRoutingModule {
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
}
}
}
Hope this will help you.
How to get the value from the GET parameters?
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
- Convert document.location to a string (it's an object)
- Feed that string to URI.js's URI class construtor
- Invoke the search() function to get the search (query) portion of the url
(passing true tells it to output an object)
- Access the foo property on the resulting object to get the value
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
Eclipse Bug: Unhandled event loop exception No more handles
The 'bug' is discussed here https://bugs.eclipse.org/bugs/show_bug.cgi?id=402983. A lot of discussion around 'multiple monitor' set-ups. I experienced the problem today(click in Eclipse (off-the-shelf ADT v22.3.0-887826) Package Explorer then click in java editor, and the "no more handles" error appears). It makes Eclipse unuseable.
Got me thinking that it is a monitor/graphics card problem on my win7 64bit PC, rather than a problem with Eclipse. I re-installed the graphics card (nVidia GTX480) and updated the drivers. Noticed multiple error dialog boxes(samsung monitor not found) relating to my monitor(in fact a single BX2440 monitor set-up) as i closed the system down for reboot. So, on re-boot I upgraded the monitor driver. Then booted again, and the problem has gone(at least for now).
BTW, I don't have Win 7 SP1 installed, so i don't think the 'full Windows update' solution discussed elsewhere on SO necessarily works for everyone.
How to disable and then enable onclick event on <div> with javascript
I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:
$("#id").on('click', function(){ //enables click event
//do your thing here
});
$("#id").off('click'); //disables click event
If you want to disable a div, use the following code:
$("#id").attr('disabled','disabled');
Hope this helps.
edit:
oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()
Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources
cracked it after 2 hours...
- download this usb driver:
http://dlcdnet.asus.com/pub/ASUS/EeePAD/nexus7/usb_driver_r06_windows.zip
2.go to the device manager , right click the nexus device and choose properties,
choose "hardware" and then choose update your driver , choose manualy and pick the folder
you opend the zip file to and press apply.
3.open your setting in nexus . go to : "about the device" , at to the bottom of the page and press it strong text7 times .
4.open the developers menu and enable debug with usb.
5.finally press storage from the setting menu and click the menu that apears at the top left corner.
press the connect usb to the computer, choose the second option (PTP).
one more thing: if that doesn't work restart your computer
that should do the trick , they couldn't make it more simple than that...
SSH SCP Local file to Remote in Terminal Mac Os X
At first, you need to add :
after the IP address to indicate the path is following:
scp magento.tar.gz [email protected]:/var/www
I don't think you need to sudo
the scp
. In this case it doesn't affect the remote machine, only the local command.
Then if your user
@xx.x.x.xx doesn't have write access to /var/www
then you need to do it in 2 times:
Copy to remote server in your home folder (:
represents your remote home folder, use :subfolder/
if needed, or :/home/user/
for full path):
scp magento.tar.gz [email protected]:
Then SSH and move the file:
ssh [email protected]
sudo mv magento.tar.gz /var/www
php mysqli_connect: authentication method unknown to the client [caching_sha2_password]
If you're on Windows and it's not possible to use caching_sha2_password
at all, you can do the following:
- rerun the MySQL Installer
- select "Reconfigure" next to MySQL Server (the top item)
- click "Next" until you get to "Authentication Method"
- change "Use Strong Password Encryption for Authentication (RECOMMENDED)" to "Use Legacy Authentication Method (Retain MySQL 5.X Compatibility)
- click "Next"
- enter your Root Account Password in Accounts and Roles, and click "Check"
- click "Next"
- keep clicking "Next" until you get to "Apply Configuration"
- click "Execute"
The Installer will make all the configuration changes needed for you.
Can't get value of input type="file"?
You can get it by using document.getElementById();
var fileVal=document.getElementById("some Id");
alert(fileVal.value);
will give the value of file,but it gives with fakepath as follows
c:\fakepath\filename
What is a practical use for a closure in JavaScript?
I'm trying to learn closures and I think the example that I have created is a practical use case. You can run a snippet and see the result in the console.
We have two separate users who have separate data. Each of them can see the actual state and update it.
_x000D_
_x000D_
function createUserWarningData(user) {
const data = {
name: user,
numberOfWarnings: 0,
};
function addWarning() {
data.numberOfWarnings = data.numberOfWarnings + 1;
}
function getUserData() {
console.log(data);
return data;
}
return {
getUserData: getUserData,
addWarning: addWarning,
};
}
const user1 = createUserWarningData("Thomas");
const user2 = createUserWarningData("Alex");
//USER 1
user1.getUserData(); // Returning data user object
user1.addWarning(); // Add one warning to specific user
user1.getUserData(); // Returning data user object
//USER2
user2.getUserData(); // Returning data user object
user2.addWarning(); // Add one warning to specific user
user2.addWarning(); // Add one warning to specific user
user2.getUserData(); // Returning data user object
_x000D_
_x000D_
_x000D_
Could not find method compile() for arguments Gradle
compile
is a configuration
that is usually introduced by a plugin (most likely the java plugin) Have a look at the gradle userguide for details about configurations. For now adding the java plugin on top of your build script should do the trick:
apply plugin:'java'
Python check if list items are integers?
The usual way to check whether something can be converted to an int
is to try
it and see, following the EAFP principle:
try:
int_value = int(string_value)
except ValueError:
# it wasn't an int, do something appropriate
else:
# it was an int, do something appropriate
So, in your case:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
In most cases, a loop around some trivial code that ends with mynewlist.append(item)
can be turned into a list comprehension, generator expression, or call to map
or filter
. But here, you can't, because there's no way to put a try
/except
into an expression.
But if you wrap it up in a function, you can:
def raises(func, *args, **kw):
try:
func(*args, **kw)
except:
return True
else:
return False
mynewlist = [item for item in mylist if not raises(int, item)]
… or, if you prefer:
mynewlist = filter(partial(raises, int), item)
It's cleaner to use it this way:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True
, but if any unexpected exceptions are raised, they'll propagate out. So:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
… will do what you want, but:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
… will raise a TypeError
, as it should.
Getting files by creation date in .NET
DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
ArrayList files = new ArrayList();
foreach (string ext in exts)
files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());
How to connect to mysql with laravel?
In Laravel 5, there is a .env
file,
It looks like
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY
DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Edit that .env There is .env.sample is there , try to create from that if no such .env file found.
How to select a range of the second row to the last row
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
Strip HTML from Text JavaScript
Another, admittedly less elegant solution than nickf's or Shog9's, would be to recursively walk the DOM starting at the <body> tag and append each text node.
var bodyContent = document.getElementsByTagName('body')[0];
var result = appendTextNodes(bodyContent);
function appendTextNodes(element) {
var text = '';
// Loop through the childNodes of the passed in element
for (var i = 0, len = element.childNodes.length; i < len; i++) {
// Get a reference to the current child
var node = element.childNodes[i];
// Append the node's value if it's a text node
if (node.nodeType == 3) {
text += node.nodeValue;
}
// Recurse through the node's children, if there are any
if (node.childNodes.length > 0) {
appendTextNodes(node);
}
}
// Return the final result
return text;
}
How to pass parameter to a promise function
You can use .bind() to pass the param(this) to the function.
var someFunction =function(resolve, reject) {
/* get username, password*/
var username=this.username;
var password=this.password;
if ( /* everything turned out fine */ ) {
resolve("Stuff worked!");
} else {
reject(Error("It broke"));
}
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));
Detect if the app was launched/opened from a push notification
// shanegao's code in Swift 2.0
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
if ( application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background ){
print("opened from a push notification when the app was on background")
}else{
print("opened from a push notification when the app was on foreground")
}
}
Python Create unix timestamp five minutes in the future
You can use datetime.strftime
to get the time in Epoch form, using the %s
format string:
def expires():
future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
return int(future.strftime("%s"))
Note:
This only works under linux, and this method doesn't work with timezones.
Is there any difference between a GUID and a UUID?
The simple answer is: **no difference, they are the same thing.
2020-08-20 Update: While GUIDs (as used by Microsoft) and UUIDs (as defined by RFC4122) look similar and serve similar purposes, there are subtle-but-occasionally-important differences. Specifically, some Microsoft GUID docs allow GUIDs to contain any hex digit in any position, while RFC4122 requires certain values for the version
and variant
fields. Also, [per that same link], GUIDs should be all-upper case, whereas UUIDs should be "output as lower case characters and are case insensitive on input". This can lead to incompatibilities between code libraries (such as this).
(Original answer follows)
Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak.
Even the authors of the UUID specification and Microsoft claim they are synonyms:
From the introduction to IETF RFC 4122 "A Universally Unique IDentifier (UUID) URN Namespace": "a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier)."
From the ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard: "UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation."
And Microsoft even claims a GUID is specified by the UUID RFC: "In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID."
But the correct answer depends on what the question means when it says "UUID"...
The first part depends on what the asker is thinking when they are saying "UUID".
Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set?
Looking at the details of the RFC 4122, there are four different "variants" of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of RFC 4122, the four variants of UUID are:
- Reserved, Network Computing System backward compatibility
- The variant specified in RFC 4122 (of which there are five sub-variants, which are called "versions")
- Reserved, Microsoft Corporation backward compatibility
- Reserved for future definition.
According to RFC 4122, all UUID variants are "real UUIDs", then all GUIDs are real UUIDs. To the literal question "is there any difference between GUID and UUID" the answer is definitely no for RFC 4122 UUIDs: no difference (but subject to the second part below).
But not all GUIDs are variant 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was "is there any difference between GUID and variant 2 UUIDs", then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about variants and they might be only thinking of variant 2 UUIDs when they say the word "UUID" (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both versions of variant 2). In which case, the answer is yes different.
So the answer, in part, depends on what the person asking is thinking when they say the word "UUID". Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs?
The second part depends on which specification being used as the definition of UUID.
If you think that was confusing, read the ITU-T X.667 ISO/IEC 9834-8:2004 which is supposed to be aligned and fully technically compatible with RFC 4122. It has an extra sentence in Clause 11.2 that says, "All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0". Which means that only variant 2 UUID conform to that Standard (those two bit values mean variant 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be variant 2 values.
Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is no difference between GUID and IETF's UUIDs, but yes difference between GUID and conforming ITU-T/ISO/IEC's UUIDs!
Binary encodings could differ
When encoded in binary (as opposed to the human-readable text format), the GUID may be stored in a structure with four different fields as follows. This format differs from the [UUID standard] 8 only in the byte order of the first 3 fields.
Bits Bytes Name Endianness Endianness
(GUID) RFC 4122
32 4 Data1 Native Big
16 2 Data2 Native Big
16 2 Data3 Native Big
64 8 Data4 Big Big
Sending emails in Node.js?
campaign is a comprehensive solution for sending emails in Node, and it comes with a very simple API.
You instance it like this.
var client = require('campaign')({
from: '[email protected]'
});
To send emails, you can use Mandrill, which is free and awesome. Just set your API key, like this:
process.env.MANDRILL_APIKEY = '<your api key>';
(if you want to send emails using another provider, check the docs)
Then, when you want to send an email, you can do it like this:
client.sendString('<p>{{something}}</p>', {
to: ['[email protected]', '[email protected]'],
subject: 'Some Subject',
preview': 'The first line',
something: 'this is what replaces that thing in the template'
}, done);
The GitHub repo has pretty extensive documentation.
Output Django queryset as JSON
To return the queryset you retrieved with queryset = Users.objects.all(),
you first need to serialize them.
Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.
from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View
class JSONListView(View):
def get(self, request, *args, **kwargs):
qs = User.objects.all()
data = serialize("json", qs)
return JsonResponse(data)
This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.
__FILE__, __LINE__, and __FUNCTION__ usage in C++
FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.
PS:
static string getScopedClassMethod( string thePrettyFunction )
{
size_t index = thePrettyFunction . find( "(" );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( index );
index = thePrettyFunction . rfind( " " );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( 0, index + 1 );
return thePrettyFunction; /* The scoped class name. */
}
Insert some string into given string at given index in Python
An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't ever modify them in place.
You need to retrain yourself when working with strings in Python so that instead of thinking, "How can I modify this string?" instead you're thinking "how can I create a new string that has some pieces from this one I've already gotten?"
How to get method parameter names?
Here is something I think will work for what you want, using a decorator.
class LogWrappedFunction(object):
def __init__(self, function):
self.function = function
def logAndCall(self, *arguments, **namedArguments):
print "Calling %s with arguments %s and named arguments %s" %\
(self.function.func_name, arguments, namedArguments)
self.function.__call__(*arguments, **namedArguments)
def logwrap(function):
return LogWrappedFunction(function).logAndCall
@logwrap
def doSomething(spam, eggs, foo, bar):
print "Doing something totally awesome with %s and %s." % (spam, eggs)
doSomething("beans","rice", foo="wiggity", bar="wack")
Run it, it will yield the following output:
C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.
PHP __get and __set magic methods
I'd recommend to use an array for storing all values via __set()
.
class foo {
protected $values = array();
public function __get( $key )
{
return $this->values[ $key ];
}
public function __set( $key, $value )
{
$this->values[ $key ] = $value;
}
}
This way you make sure, that you can't access the variables in another way (note that $values
is protected), to avoid collisions.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
LaTeX Optional Arguments
Example from the guide:
\newcommand{\example}[2][YYY]{Mandatory arg: #2;
Optional arg: #1.}
This defines \example to be a command with two arguments,
referred to as #1 and #2 in the {<definition>}--nothing new so far.
But by adding a second optional argument to this \newcommand
(the [YYY]) the first argument (#1) of the newly defined
command \example is made optional with its default value being YYY.
Thus the usage of \example is either:
\example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
\example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.
Custom Authentication in ASP.Net-Core
From what I learned after several days of research,
Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication
In Startup.cs
:
Add below lines to ConfigureServices
method :
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(
CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
});
services.AddMvc();
// authentication
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddTransient(
m => new UserManager(
Configuration
.GetValue<string>(
DEFAULT_CONNECTIONSTRING //this is a string constant
)
)
);
services.AddDistributedMemoryCache();
}
keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize]
, they well force redirect to /Account/Login
url.
Add below lines to Configure
method :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler(ERROR_URL);
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: DEFAULT_ROUTING);
});
}
Create your UserManager
class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):
public class UserManager
{
string _connectionString;
public UserManager(string connectionString)
{
_connectionString = connectionString;
}
public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
{
using (var con = new SqlConnection(_connectionString))
{
var queryString = "sp_user_login";
var dbUserData = con.Query<UserDbModel>(
queryString,
new
{
UserEmail = user.UserEmail,
UserPassword = user.UserPassword,
UserCellphone = user.UserCellphone
},
commandType: CommandType.StoredProcedure
).FirstOrDefault();
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
}
}
public async void SignOut(HttpContext httpContext)
{
await httpContext.SignOutAsync();
}
private IEnumerable<Claim> GetUserClaims(UserDbModel user)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
claims.AddRange(this.GetUserRoleClaims(user));
return claims;
}
private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
return claims;
}
}
Then maybe you have an AccountController
which has a Login
Action that should look like below :
public class AccountController : Controller
{
UserManager _userManager;
public AccountController(UserManager userManager)
{
_userManager = userManager;
}
[HttpPost]
public IActionResult LogIn(LogInViewModel form)
{
if (!ModelState.IsValid)
return View(form);
try
{
//authenticate
var user = new UserDbModel()
{
UserEmail = form.Email,
UserCellphone = form.Cellphone,
UserPassword = form.Password
};
_userManager.SignIn(this.HttpContext, user);
return RedirectToAction("Search", "Home", null);
}
catch (Exception ex)
{
ModelState.AddModelError("summary", ex.Message);
return View(form);
}
}
}
Now you are able to use [Authorize]
annotation on any Action
or Controller
.
Feel free to comment any questions or bug's.