SQLAlchemy: What's the difference between flush() and commit()?
commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.
Excel VBA Run-time error '13' Type mismatch
Diogo
Justin has given you some very fine tips :)
You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.
For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code
Sheets("Sheet1").Range("A1").Value - 1
I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim x As Integer, i As Integer, a As Integer, y As Integer
Dim name As String
Dim lastRow As Long
10 On Error GoTo Whoa
20 Application.ScreenUpdating = False
30 name = InputBox("Please insert the name of the sheet")
40 If Len(Trim(name)) = 0 Then Exit Sub
50 Set ws = Sheets(name)
60 With ws
70 If Not IsError(.Range("BE4").Value) Then
80 x = Val(.Range("BE4").Value)
90 Else
100 MsgBox "Please check the value of cell BE4. It seems to have an error"
110 GoTo LetsContinue
120 End If
130 .Range("BF4").Value = x
140 lastRow = .Range("BE" & Rows.Count).End(xlUp).Row
150 For i = 5 To lastRow
160 If IsError(.Range("BE" & i)) Then
170 MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180 GoTo LetsContinue
190 End If
200 a = 0: y = Val(.Range("BE" & i))
210 If y <> x Then
220 If y <> 0 Then
230 If y = 3 Then
240 a = x
250 .Range("BF" & i) = Val(.Range("BE" & i)) - x
260 x = Val(.Range("BE" & i)) - x
270 End If
280 .Range("BF" & i) = Val(.Range("BE" & i)) - a
290 x = Val(.Range("BE" & i)) - a
300 Else
310 .Range("BF" & i).ClearContents
320 End If
330 Else
340 .Range("BF" & i).ClearContents
350 End If
360 Next i
370 End With
LetsContinue:
380 Application.ScreenUpdating = True
390 Exit Sub
Whoa:
400 MsgBox "Error Description :" & Err.Description & vbNewLine & _
"Error at line : " & Erl
410 Resume LetsContinue
End Sub
Java executors: how to be notified, without blocking, when a task completes?
You may use a implementation of Callable such that
public class MyAsyncCallable<V> implements Callable<V> {
CallbackInterface ci;
public MyAsyncCallable(CallbackInterface ci) {
this.ci = ci;
}
public V call() throws Exception {
System.out.println("Call of MyCallable invoked");
System.out.println("Result = " + this.ci.doSomething(10, 20));
return (V) "Good job";
}
}
where CallbackInterface is something very basic like
public interface CallbackInterface {
public int doSomething(int a, int b);
}
and now the main class will look like this
ExecutorService ex = Executors.newFixedThreadPool(2);
MyAsyncCallable<String> mac = new MyAsyncCallable<String>((a, b) -> a + b);
ex.submit(mac);
Why doesn't file_get_contents work?
Check file_get_contents
PHP Manual return value. If the value is FALSE
then it could not read the file. If the value is NULL
then the function itself is disabled.
To learn more what might gone wrong with the file_get_contents
operation you must enable error reporting and the display of errors to actually read them.
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents
function is allow_url_fopen
. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
$jsonData = file_get_contents($url);
print '<p>', var_dump($jsonData), '</p>';
# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}
# Decide what to do based on return value:
if ($jsonData === FALSE) {
echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
echo "Function is disabled.";
} else {
echo $jsonData;
}
?>
</body>
</html>
If all of this fails, it might be due to the use of short open tags, <?
. The example code in this answer has been therefore changed to make use of <?php
to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <?
or <?php
.
How to pause a vbscript execution?
Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.
Pause("Press Enter to continue")
Sub Pause(strPause)
WScript.Echo (strPause)
z = WScript.StdIn.Read(1)
End Sub
How to create a delay in Swift?
I agree with Palle that using dispatch_after
is a good choice here. But you probably don't like the GCD calls as they are quite annoying to write. Instead you can add this handy helper:
public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
let dispatchTime = DispatchTime.now() + seconds
dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}
public enum DispatchLevel {
case main, userInteractive, userInitiated, utility, background
var dispatchQueue: DispatchQueue {
switch self {
case .main: return DispatchQueue.main
case .userInteractive: return DispatchQueue.global(qos: .userInteractive)
case .userInitiated: return DispatchQueue.global(qos: .userInitiated)
case .utility: return DispatchQueue.global(qos: .utility)
case .background: return DispatchQueue.global(qos: .background)
}
}
}
Now you simply delay your code on a background thread like this:
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
Delaying code on the main thread is even simpler:
delay(bySeconds: 1.5) {
// delayed code, by default run in main thread
}
If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via SwiftPM then use it exactly like in the examples above:
import HandySwift
delay(by: .seconds(1.5)) {
// delayed code
}
'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?
and
tests whether both expressions are logically True
while &
(when used with True
/False
values) tests if both are True
.
In Python, empty built-in objects are typically treated as logically False
while non-empty built-ins are logically True
. This facilitates the common use case where you want to do something if a list is empty and something else if the list is not. Note that this means that the list [False] is logically True
:
>>> if [False]:
... print 'True'
...
True
So in Example 1, the first list is non-empty and therefore logically True
, so the truth value of the and
is the same as that of the second list. (In our case, the second list is non-empty and therefore logically True
, but identifying that would require an unnecessary step of calculation.)
For example 2, lists cannot meaningfully be combined in a bitwise fashion because they can contain arbitrary unlike elements. Things that can be combined bitwise include: Trues and Falses, integers.
NumPy objects, by contrast, support vectorized calculations. That is, they let you perform the same operations on multiple pieces of data.
Example 3 fails because NumPy arrays (of length > 1) have no truth value as this prevents vector-based logic confusion.
Example 4 is simply a vectorized bit and
operation.
Bottom Line
If you are not dealing with arrays and are not performing math manipulations of integers, you probably want and
.
If you have vectors of truth values that you wish to combine, use numpy
with &
.
Use String.split() with multiple delimiters
If you know the sting will always be in the same format, first split the string based on .
and store the string at the first index in a variable. Then split the string in the second index based on -
and store indexes 0, 1 and 2. Finally, split index 2 of the previous array based on .
and you should have obtained all of the relevant fields.
Refer to the following snippet:
String[] tmp = pdfName.split(".");
String val1 = tmp[0];
tmp = tmp[1].split("-");
String val2 = tmp[0];
...
How do you convert Html to plain text?
If you have data that has HTML tags and you want to display it so that a person can SEE the tags, use HttpServerUtility::HtmlEncode.
If you have data that has HTML tags in it and you want the user to see the tags rendered, then display the text as is. If the text represents an entire web page, use an IFRAME for it.
If you have data that has HTML tags and you want to strip out the tags and just display the unformatted text, use a regular expression.
PHP and MySQL Select a Single Value
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
Reporting Services export to Excel with Multiple Worksheets
Here are screenshots for SQL Server 2008 R2, using SSRS Report Designer in Visual Studio 2010.
I have done screenshots as some of the dialogs are not easy to find.
1: Add the group
2: Specify the field you want to group on
3: Now click on the group in the 'Row Groups' selector, directly below the report designer
4: F4 to select property pane; expand 'Group' and set Group > PageBreak > BreakLocation = 'Between', then enter the expression you want for Group > PageName
5: Here is an example expression
Here is the result of the report exported to Excel, with tabs named according to the PageName expression
Warning: mysqli_query() expects at least 2 parameters, 1 given. What?
the mysqli_query
excepts 2 parameters , first variable is mysqli_connect
equivalent variable , second one is the query you have provided
$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);
$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");
How to delete a module in Android Studio
In Android studio v1.0.2
Method 1
Go to project structure, File -> Project Structure...
, as the following picture show, click -
icon to remove the module.
Method 2
Edit the file settings.gradle
and remove the entry you are going to delete. e.g. edit the file from include ':app', ':apple'
to include ':app'
.
That will work in most of the situation, however finally you have to delete the module from disk manually if you don't need it anymore.
Using BeautifulSoup to search HTML for string
The following line is looking for the exact NavigableString 'Python':
>>> soup.body.findAll(text='Python')
[]
Note that the following NavigableString is found:
>>> soup.body.findAll(text='Python Jobs')
[u'Python Jobs']
Note this behaviour:
>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]
So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.
Retrieving the output of subprocess.call()
In Ipython
shell:
In [8]: import subprocess
In [9]: s=subprocess.check_output(["echo", "Hello World!"])
In [10]: s
Out[10]: 'Hello World!\n'
Based on sargue's answer. Credit to sargue.
Laravel 5 - How to access image uploaded in storage within View?
If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/
), then you can use my little dirty hack below :p)
public static function hackoutFileFromStorageFolder($fullfilePath) {
if (strpos($fullfilePath, 'storage/app/public/')) {
$fileParts = explode('storage/app/public/', $fullfilePath);
if( count($fileParts) > 1){
return $fileParts[1];
}
}
return '';
}
How can I add shadow to the widget in flutter?
The given answers do the trick for outer shadow i.e. around the widget. I wanted a shadow on the widget which is inside the boundaries and according to the github issue there is no inset attribute in ShadowBox yet.
My workaround was to add a layer of widget with a gradient using the stack widget so that it looks like the widget itself has the shadows. You must use the mediaQuery for dimensions otherwise the layout will be messed up on different devices.
Here's a sample of code for better understanding:
Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage("assets/sampleFaces/makeup.jpeg"),
// fit: BoxFit.cover,
),
),
height: 350.0,
),
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: FractionalOffset.topCenter,
end: FractionalOffset.bottomCenter,
colors: [
Colors.black.withOpacity(0.0),
Colors.black54,
],
stops: [0.95, 5.0],
),
),
)
],
),
Are vectors passed to functions by value or by reference in C++
A vector
is functionally same as an array. But, to the language vector
is a type, and int
is also a type. To a function argument, an array of any type (including vector[]
) is treated as pointer. A vector<int>
is not same as int[]
(to the compiler). vector<int>
is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.
So, you must use vector<int>&
(preferably with const
, if function isn't modifying it) to pass it as a reference.
How to run travis-ci locally
I'm not sure what was your original reason for running Travis locally, if you just wanted to play with it, then stop reading here as it's irrelevant for you.
If you already have experience with hosted Travis and you want to get the same experience in your own datacenter, read on.
Since Dec 2014 Travis CI offers an Enterprise on-premises version.
http://blog.travis-ci.com/2014-12-19-introducing-travis-ci-enterprise/
The pricing is part of the article as well:
The licensing is done per seats, where every license includes 20 users. Pricing starts at $6,000 per license, which includes 20 users and 5 concurrent builds. There's a premium option with unlimited builds for $8,500.
What is the best way to seed a database in Rails?
Updating since these answers are slightly outdated (although some still apply).
Simple feature added in rails 2.3.4, db/seeds.rb
Provides a new rake task
rake db:seed
Good for populating common static records like states, countries, etc...
http://railscasts.com/episodes/179-seed-data
*Note that you can use fixtures if you had already created them to also populate with the db:seed task by putting the following in your seeds.rb file (from the railscast episode):
require 'active_record/fixtures'
Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "operating_systems")
For Rails 3.x use 'ActiveRecord::Fixtures' instead of 'Fixtures' constant
require 'active_record/fixtures'
ActiveRecord::Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "fixtures_file_name")
Rails 4 Authenticity Token
I don't think it's good to generally turn off CSRF protection as long as you don't exclusively implement an API.
When looking at the Rails 4 API documentation for ActionController I found that you can turn off forgery protection on a per controller or per method base.
For example to turn off CSRF protection for methods you can use
class FooController < ApplicationController
protect_from_forgery except: :index
How do I block comment in Jupyter notebook?
I tried this on Mac OSX with Chrome 42.0.2311.90 (64-bit) and this works by using CMD + /
The version of the notebook server is 3.1.0-cbccb68 and is running on:
Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34)
[GCC 4.2.1 (Apple Inc. build 5577)]
Could it be a browser related problem? Did you try Firefox or IE?
Running Selenium WebDriver python bindings in chrome
You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.
see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up.
Edit:
Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.
import os
from selenium import webdriver
chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()
Android: how to refresh ListView contents?
I think refilling the same adapter with different data would be more or most better technique.
Put this method in your Adapter class with right argument (the data list you want to display as names in my case)
Call this where u update the data of list with updated list (names in my case)
public void refill(ArrayList<BeanDatabase> names) {
list.clear();
list.addAll(names);
list.notifyDataSetChanged();
}
If you change the adapter or set the adapter again and again on when the list updates, then force close error would surely cause problems at some point. (Error:List data been updated but adapter doesn't notify the List View)
Declaration of Methods should be Compatible with Parent Methods in PHP
This message means that there are certain possible method calls which may fail at run-time. Suppose you have
class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}
The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.
This however can never fail and does not trigger the error
class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}
So no method may have more required parameters than its parent method.
The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:
class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}
as does this:
class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}
That seems more restrictive than it needs to be and I assume is due to internals.
Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.
Best XML Parser for PHP
Hi I think the SimpleXml is very useful .
And with it I am using xpath;
$xml = simplexml_load_file("som_xml.xml");
$blocks = $xml->xpath('//block'); //gets all <block/> tags
$blocks2 = $xml->xpath('//layout/block'); //gets all <block/> which parent are <layout/> tags
I use many xml configs and this helps me to parse them really fast.
SimpleXml
is written on C
so it's very fast.
Select where count of one field is greater than one
I give an example up on Group By between two table in Sql:
Select cn.name,ct.name,count(ct.id) totalcity
from city ct left join country cn on ct.countryid = cn.id
Group By cn.name,ct.name
Having totalcity > 2
Accessing attributes from an AngularJS directive
Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
Directive:
myApp.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '=tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass('tooltip-title');
}
},
}
});
Fiddle.
With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.
What is the difference between vmalloc and kmalloc?
What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?
From Google's "I'm Feeling Lucky" on vmalloc
:
kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before
memory gets fragmented.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
What is the use of "object sender" and "EventArgs e" parameters?
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the event
e
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.
In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
C# Call a method in a new thread
Does it really have to be a thread, or can it be a task too?
if so, the easiest way is:
Task.Factory.StartNew(() => SecondFoo())
How to delete node from XML file using C#
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
How do I escape double and single quotes in sed?
Aside: sed expressions containing BASH variables need to be double ("
)-quoted for the variable to be interpreted correctly.
If you also double-quote your $BASH variable (recommended practice)
... then you can escape the variable double quotes as shown:
sed -i "s/foo/bar ""$VARIABLE""/g" <file>
I.e., replace the $VARIABLE-associated "
with ""
.
(Simply -escaping "$VAR"
as \"$VAR\"
results in a "
-quoted output string.)
Examples
$ VAR='apples and bananas'
$ echo $VAR
apples and bananas
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' $VAR
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' "$VAR"
I like apples and bananas!
Here, $VAR is "
-quoted before piping to sed (sed is either '
- or "
-quoted):
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/"$VAR"/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/""$VAR""/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed "s/$VAR/cherries/g"
I like cherries!
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!
Compare that to:
$ printf 'I like %s!\n' $VAR | sed "s/$VAR/cherries/g"
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' $VAR | sed "s/""$VAR""/cherries/g"
I like apples!
I like and!
I like bananas!
... and so on ...
Conclusion
My recommendation, as standard practice, is to
"
-quote BASH variables ("$VAR"
)
"
-quote, again, those variables (""$VAR""
) if they are used in a sed expression (which itself must be "
-quoted, not '
-quoted)
$ VAR='apples and bananas'
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!
Internet Access in Ubuntu on VirtualBox
How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.
Remove Identity from a column in a table
This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:
First, create a duplicate column with a temporary name:
alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;
Next, get the name of your primary key constraint:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';
Now try drop the primary key constraint for your column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..
Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
commit;
Finally, add the FK constraints back in:
alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..
El Fin!
How to wrap text using CSS?
If you type "AAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRGGGGGGGGGGGGGGGGGGGGG"
this will produce:
AARRRRRRRRRRRRRRRRRRRR
RRGGGGGGGGGGGGGGGGGGGG
G
I have taken my example from a couple different websites on google. I have tested this on ff 5.0, IE 8.0, and Chrome 10. It works on all of them.
.wrapword {
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: pre-wrap; /* css-3 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
white-space: -webkit-pre-wrap; /* Newer versions of Chrome/Safari*/
word-break: break-all;
white-space: normal;
}
<table style="table-layout:fixed; width:400px">
<tr>
<td class="wrapword"></td>
</tr>
</table>
How do I convert NSMutableArray to NSArray?
I like both of the 2 main solutions:
NSArray *array = [NSArray arrayWithArray:mutableArray];
Or
NSArray *array = [mutableArray copy];
The primary difference I see in them is how they behave when mutableArray is nil:
NSMutableArray *mutableArray = nil;
NSArray *array = [NSArray arrayWithArray:mutableArray];
// array == @[] (empty array)
NSMutableArray *mutableArray = nil;
NSArray *array = [mutableArray copy];
// array == nil
regex error - nothing to repeat
regular expression normally uses * and + in theory of language.
I encounter the same bug while executing the line code
re.split("*",text)
to solve it, it needs to include \ before * and +
re.split("\*",text)
Change Screen Orientation programmatically using a Button
A working code:
private void changeScreenOrientation() {
int orientation = yourActivityName.this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
showMediaDescription();
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
hideMediaDescription();
}
if (Settings.System.getInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0) == 1) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}, 4000);
}
}
call this method in your button click
How do I save a stream to a file in C#?
You must not use StreamReader
for binary files (like gifs or jpgs). StreamReader
is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)
Why do you need to use a StreamReader
at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?
EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:
/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
To use it to dump a stream to a file, for example:
using (Stream file = File.Create(filename))
{
CopyStream(input, file);
}
Note that Stream.CopyTo
was introduced in .NET 4, serving basically the same purpose.
ASP.NET Web API session or something?
You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.
Request and response HTTP headers can also be used to pass information between service calls.
How to calculate DATE Difference in PostgreSQL?
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
Algorithm to return all combinations of k elements from n
Another one solution with C#:
static List<List<T>> GetCombinations<T>(List<T> originalItems, int combinationLength)
{
if (combinationLength < 1)
{
return null;
}
return CreateCombinations<T>(new List<T>(), 0, combinationLength, originalItems);
}
static List<List<T>> CreateCombinations<T>(List<T> initialCombination, int startIndex, int length, List<T> originalItems)
{
List<List<T>> combinations = new List<List<T>>();
for (int i = startIndex; i < originalItems.Count - length + 1; i++)
{
List<T> newCombination = new List<T>(initialCombination);
newCombination.Add(originalItems[i]);
if (length > 1)
{
List<List<T>> newCombinations = CreateCombinations(newCombination, i + 1, length - 1, originalItems);
combinations.AddRange(newCombinations);
}
else
{
combinations.Add(newCombination);
}
}
return combinations;
}
Example of usage:
List<char> initialArray = new List<char>() { 'a','b','c','d'};
int combinationLength = 3;
List<List<char>> combinations = GetCombinations(initialArray, combinationLength);
How to use group by with union in t-sql
Identifying the column is easy:
SELECT *
FROM ( SELECT id,
time
FROM dbo.a
UNION
SELECT id,
time
FROM dbo.b
)
GROUP BY id
But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION
rather than UNION ALL
, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).
So, for example, change the first line to SELECT id, MAX(time)
or the like!
Get and Set Screen Resolution
If you want to collect screen resolution you can run the following code within a WPF window (the window is what the this
would refer to):
System.Windows.Media.Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
Double dpiX = m.M11 * 96;
Double dpiY = m.M22 * 96;
Getting the last n elements of a vector. Is there a better way than using the length() function?
Here is a function to do it and seems reasonably fast.
endv<-function(vec,val)
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}
USAGE:
test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)
BENCHMARK:
test replications elapsed relative
1 expression(tail(x, 5)) 100000 5.24 6.469
2 expression(x[seq.int(to = length(x), length.out = 5)]) 100000 0.98 1.210
3 expression(x[length(x) - (4:0)]) 100000 0.81 1.000
4 expression(endv(x, 5)) 100000 1.37 1.691
Oracle: Call stored procedure inside the package
To those that are incline to use GUI:
Click Right mouse button on procecdure name then select Test
Then in new window you will see script generated just add the parameters and click on Start Debugger
or F9
Hope this saves you some time.
Float vs Decimal in ActiveRecord
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change
change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
end
Android - Dynamically Add Views into View
It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged()
you have full control of the Views generation and rendering.
Take a look at these tutorials
How to filter for multiple criteria in Excel?
Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.
The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.
=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")
Like I said, not as elegant as the advanced filters but options are always good.
How to set placeholder value using CSS?
From what I understand using,
::-webkit-input-placeholder::before
or ::-webkit-input-placeholder::after
,
to add more placeholder content doesn't work anymore.
Think its a new Chrome update.
Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder.
eg:
<input type="text" value="" id="email1" placeholder="I am on one line. I am on a second line etc etc..." />
Syntax for an If statement using a boolean
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
React Native add bold or italics to single words in <Text> field
You could just nest the Text components with the required style. The style will be applied along with already defined style in the first Text component.
Example:
<Text style={styles.paragraph}>
Trouble singing in. <Text style={{fontWeight: "bold"}}> Resolve</Text>
</Text>
How can I use different certificates on specific connections?
I read through LOTS of places online to solve this thing.
This is the code I wrote to make it work:
ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
app.certificateString is a String that contains the Certificate, for example:
static public String certificateString=
"-----BEGIN CERTIFICATE-----\n" +
"MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
"BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
... a bunch of characters...
"5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
"-----END CERTIFICATE-----";
I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.
CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift
CGRect
Can be simply created using an instance of a CGPoint
or CGSize
, thats given below.
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
// Or
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
Or if we want to specify each value in CGFloat
or Double
or Int
, we can use this method.
let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // CGFloat, Double, Int
CGPoint
Can be created like this.
let point = CGPoint(x: 0,y :0) // CGFloat, Double, Int
CGSize
Can be created like this.
let size = CGSize(width: 100, height: 100) // CGFloat, Double, Int
Also size and point with 0 as the values, it can be done like this.
let size = CGSize.zero // width = 0, height = 0
let point = CGPoint.zero // x = 0, y = 0, equal to CGPointZero
let rect = CGRect.zero // equal to CGRectZero
CGRectZero
& CGPointZero
replaced with CGRect.zero
& CGPoint.zero
in Swift 3.0
.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1
That happened to me too, because I was trying to get an IEnumerable
but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:
HttpResponseMessage response = await client.GetAsync("api/yourUrl");
if (response.IsSuccessStatusCode)
{
IEnumerable<RootObject> rootObjects =
awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();
foreach (var rootObject in rootObjects)
{
Console.WriteLine(
"{0}\t${1}\t{2}",
rootObject.Data1, rootObject.Data2, rootObject.Data3);
}
Console.ReadLine();
}
Hope It helps.
How to display pdf in php
if(isset($_GET['content'])){
$content = $_GET['content'];
$dir = $_GET['dir'];
header("Content-type:".$content);
@readfile($dir);
}
$directory = (file_exists("mydir/"))?"mydir/":die("file/directory doesn't exists");// checks directory if existing.
//the line above is just a one-line if statement (syntax: (conditon)?code here if true : code if false; )
if($handle = opendir($directory)){ //opens directory if existing.
while ($file = readdir($handle)) { //assign each file with link <a> tag with GET params
echo '<a target="_blank" href="?content=application/pdf&dir='.$directory.'">'.$file.'</a>';
}
}
if you click the link a new window will appear with the pdf file
How do you set autocommit in an SQL Server session?
With SQLServer 2005 Express, what I found was that even with autocommit off, insertions into a Db table were committed without my actually issuing a commit command from the Management Studio session. The only difference was, when autocommit was off, I could roll back all the insertions; with *autocommit on, I could not.*
Actually, I was wrong. With autocommit mode off, I see the changes only in the QA (Query Analyzer) window from which the commands were issued. If I popped a new QA (Query Analyzer) window, I do not see the changes made by the first window (session), i.e. they are NOT committed! I had to issue explicit commit or rollback commands to make changes visible to other sessions(QA windows) -- my bad! Things are working correctly.
Running sites on "localhost" is extremely slow
After building your project the website needs some time to walk through the new dll :).
It's normal that loading a webpage after rebuilding takes some time. This shouldn't happen when only changing something in for example javascript.
How to get an HTML element's style values in javascript?
In jQuery, you can do alert($("#theid").css("width"))
.
-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.
Update
for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.
Split large string in n-size chunks in JavaScript
I have written an extended function, so the chunk length can also be an array of numbers, like [1,3]
String.prototype.chunkString = function(len) {
var _ret;
if (this.length < 1) {
return [];
}
if (typeof len === 'number' && len > 0) {
var _size = Math.ceil(this.length / len), _offset = 0;
_ret = new Array(_size);
for (var _i = 0; _i < _size; _i++) {
_ret[_i] = this.substring(_offset, _offset = _offset + len);
}
}
else if (typeof len === 'object' && len.length) {
var n = 0, l = this.length, chunk, that = this;
_ret = [];
do {
len.forEach(function(o) {
chunk = that.substring(n, n + o);
if (chunk !== '') {
_ret.push(chunk);
n += chunk.length;
}
});
if (n === 0) {
return undefined; // prevent an endless loop when len = [0]
}
} while (n < l);
}
return _ret;
};
The code
"1234567890123".chunkString([1,3])
will return:
[ '1', '234', '5', '678', '9', '012', '3' ]
Excel date to Unix timestamp
I had an old Excel database with "human-readable" dates, like 2010.03.28 20:12:30
Theese dates were in UTC+1 (CET) and needed to convert it to epoch time.
I used the =(A4-DATE(1970;1;1))*86400-3600 formula to convert the dates to epoch time from the A column to B column values.
Check your timezone offset and make a math with it. 1 hour is 3600 seconds.
The only thing why i write here an anwser, you can see that this topic is more than 5 years old is that i use the new Excel versions and also red posts in this topic, but they're incorrect. The DATE(1970;1;1). Here the 1970 and the January needs to be separated with ; and not with ,
If you're also experiencing this issue, hope it helps you.
Have a nice day :)
Easy way to pull latest of all git submodules
I think you'll have to write a script to do this. To be honest, I might install python to do it so that you can use os.walk
to cd
to each directory and issue the appropriate commands. Using python or some other scripting language, other than batch, would allow you to easily add/remove subprojects with out having to modify the script.
JavaScript Infinitely Looping slideshow with delays?
Here:
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num==10;) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
That makes it keep looping alright! That's why it isn't runnable here.
How to send email from MySQL 5.1
If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.
Otherwise, you will need to create a UDF.
Here's a sample trigger solution:
CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
/* START THE WRITING OF THE EMAIL FILE HERE*/
SELECT concat("To: ",NEW.To),
concat("From: ",NEW.From),
concat("Subject: ",NEW.Subject),
NEW.Body
INTO OUTFILE
"C:\\inetpub\\mailroot\\pickup\\mail.txt"
FIELDS TERMINATED by '\r\n' ESCAPED BY '';
END;
To markup the message body you will need something like this...
CREATE FUNCTION `HTMLBody`(Msg varchar(8192))
RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
declare tmpMsg varchar(17408);
set tmpMsg = cast(concat(
'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
'MIME-Version: 1.0','\r\n',
'Content-Type: multipart/alternative;','\r\n',
' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
'Content-Class: urn:content-classes:message','\r\n',
'Importance: normal','\r\n',
'Priority: normal','\r\n','','\r\n','','\r\n',
'This is a multi-part message in MIME format.','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/plain;','\r\n',
' charset=\"iso-8859-1\"','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
Msg,
'\r\n','','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/html','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
Msg,
'\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
) as char);
RETURN tmpMsg;
END ;
MySQL Query to select data from last week?
I often do a quick "last week" check as well and the following tends to work well for me and includes today.
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = Getdate() - 7 /* Seven Days Earlier */
SET @EndDate = Getdate() /* Now */
SELECT id
FROM mytable
WHERE date BETWEEN @StartDate AND @Enddate
If you want this to NOT include today just subtract an extra day from the @EndDate. If I select these two variables today get
@StartDate 2015-11-16 16:34:05.347 /* Last Monday */
@EndDate 2015-11-23 16:34:05.347 /* This Monday */
If I wanted Sunday to Sunday I would have the following.
SET @StartDate = Getdate() - 8 /* Eight Days Earlier */
SET @EndDate = Getdate() - 1 /* Yesterday */
@StartDate 2015-11-15 16:34:05.347 /* Previous Sunday */
@EndDate 2015-11-22 16:34:05.347 /* Last Sunday */
how does array[100] = {0} set the entire array to 0?
Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.
How to check if a file exists from inside a batch file
if exist <insert file name here> (
rem file exists
) else (
rem file doesn't exist
)
Or on a single line (if only a single action needs to occur):
if exist <insert file name here> <action>
for example, this opens notepad on autoexec.bat, if the file exists:
if exist c:\autoexec.bat notepad c:\autoexec.bat
Iterating on a file doesn't work the second time
The file object is a buffer. When you read from the buffer, that portion that you read is consumed (the read position is shifted forward). When you read through the entire file, the read position is at the end of the file (EOF), so it returns nothing because there is nothing left to read.
If you have to reset the read position on a file object for some reason, you can do:
f.seek(0)
Is java.sql.Timestamp timezone specific?
I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos.
In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal)
Calendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT.
API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.
run main class of Maven project
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
What is an application binary interface (ABI)?
Summary
There are various interpretation and strong opinions of the exact layer that define an ABI (application binary interface).
In my view an ABI is a subjective convention of what is considered a given/platform for a specific API. The ABI is the "rest" of conventions that "will not change" for a specific API or that will be addressed by the runtime environment: executors, tools, linkers, compilers, jvm, and OS.
Defining an Interface: ABI, API
If you want to use a library like joda-time you must declare a dependency on joda-time-<major>.<minor>.<patch>.jar
. The library follows best practices and use Semantic Versioning. This defines the API compatibility at three levels:
- Patch - You don't need to change at all your code. The library just fixes some bugs.
- Minor - You don't need to change your code since the additions
- Major - The interface (API) is changed and you might need to change your code.
In order for you to use a new major release of the same library a lot of other conventions are still to be respected:
- The binary language used for the libraries (in Java cases the JVM target version that defines the Java bytecode)
- Calling conventions
- JVM conventions
- Linking conventions
- Runtime conventions
All these are defined and managed by the tools we use.
Examples
Java case study
For example, Java standardized all these conventions, not in a tool, but in a formal JVM specification. The specification allowed other vendors to provide a different set of tools that can output compatible libraries.
Java provides two other interesting case studies for ABI: Scala versions and Dalvik virtual machine.
Dalvik virtual machine broke the ABI
The Dalvik VM needs a different type of bytecode than the Java bytecode. The Dalvik libraries are obtained by converting the Java bytecode (with same API) for Dalvik. In this way you can get two versions of the same API: defined by the original joda-time-1.7.2.jar
. We could call it joda-time-1.7.2.jar
and joda-time-1.7.2-dalvik.jar
. They use a different ABI one is for the stack-oriented standard Java vms: Oracle's one, IBM's one, open Java or any other; and the second ABI is the one around Dalvik.
Scala successive releases are incompatible
Scala doesn't have binary compatibility between minor Scala versions: 2.X . For this reason the same API "io.reactivex" %% "rxscala" % "0.26.5" has three versions (in the future more): for Scala 2.10, 2.11 and 2.12. What is changed? I don't know for now, but the binaries are not compatible. Probably the latest versions adds things that make the libraries unusable on the old virtual machines, probably things related to linking/naming/parameter conventions.
Java successive releases are incompatible
Java has problems with the major releases of the JVM too: 4,5,6,7,8,9. They offer only backward compatibility. Jvm9 knows how to run code compiled/targeted (javac's -target
option) for all other versions, while JVM 4 doesn't know how to run code targeted for JVM 5. All these while you have one joda-library. This incompatibility flies bellow the radar thanks to different solutions:
- Semantic versioning: when libraries target higher JVM they usually change the major version.
- Use JVM 4 as the ABI, and you're safe.
- Java 9 adds a specification on how you can include bytecode for specific targeted JVM in the same library.
Why did I start with the API definition?
API and ABI are just conventions on how you define compatibility. The lower layers are generic in respect of a plethora of high level semantics. That's why it's easy to make some conventions. The first kind of conventions are about memory alignment, byte encoding, calling conventions, big and little endian encodings, etc. On top of them you get the executable conventions like others described, linking conventions, intermediate byte code like the one used by Java or LLVM IR used by GCC. Third you get conventions on how to find libraries, how to load them (see Java classloaders). As you go higher and higher in concepts you have new conventions that you consider as a given. That's why they didn't made it to the semantic versioning. They are implicit or collapsed in the major version. We could amend semantic versioning with <major>-<minor>-<patch>-<platform/ABI>
. This is what is actually happening already: platform is already a rpm
, dll
, jar
(JVM bytecode), war
(jvm+web server), apk
, 2.11
(specific Scala version) and so on. When you say APK you already talk about a specific ABI part of your API.
API can be ported to different ABI
The top level of an abstraction (the sources written against the highest API can be recompiled/ported to any other lower level abstraction.
Let's say I have some sources for rxscala. If the Scala tools are changed I can recompile them to that. If the JVM changes I could have automatic conversions from the old machine to the new one without bothering with the high level concepts. While porting might be difficult will help any other client. If a new operating system is created using a totally different assembler code a translator can be created.
APIs ported across languages
There are APIs that are ported in multiple languages like reactive streams. In general they define mappings to specific languages/platforms. I would argue that the API is the master specification formally defined in human language or even a specific programming language. All the other "mappings" are ABI in a sense, else more API than the usual ABI. The same is happening with the REST interfaces.
Export database schema into SQL file
In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want.
This is the option you should choose to export a schema and data
How to delete shared preferences data from App in Android
Just did this this morning. From a command prompt:
adb shell
cd /data/data/YOUR_PACKAGE_NAME/shared_prefs
rm * // to remove all shared preference files
rm YOUR_PREFS_NAME.xml // to remove a specific shared preference file
NOTE: This requires a rooted device such as the stock Android virtual devices, a Genymotion device, or an actual rooted handset/tablet, etc.
A warning - comparison between signed and unsigned integer expressions
At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).
Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.
Generate table relationship diagram from existing schema (SQL Server)
Visio Professional has a database reverse-engineering feature if yiu create a database diagram. It's not free but is fairly ubiquitous in most companies and should be fairly easy to get.
Note that Visio 2003 does not play nicely with SQL2005 or SQL2008 for reverse engineering - you will need to get 2007.
Running Python code in Vim
How about adding an autocmd
to your ~/.vimrc
-file, creating a mapping:
autocmd FileType python map <buffer> <F9> :w<CR>:exec '!python3' shellescape(@%, 1)<CR>
autocmd FileType python imap <buffer> <F9> <esc>:w<CR>:exec '!python3' shellescape(@%, 1)<CR>
then you could press <F9>
to execute the current buffer with python
Explanation:
autocmd
: command that Vim will execute automatically on {event}
(here: if you open a python file)
[i]map
: creates a keyboard shortcut to <F9>
in insert/normal mode
<buffer>
: If multiple buffers/files are open: just use the active one
<esc>
: leaving insert mode
:w<CR>
: saves your file
!
: runs the following command in your shell (try :!ls
)
%
: is replaced by the filename of your active buffer. But since it can contain things like whitespace and other "bad" stuff it is better practise not to write :python %
, but use:
shellescape
: escape the special characters. The 1
means with a backslash
TL;DR: The first line will work in normal mode and once you press <F9>
it first saves your file and then run the file with python.
The second does the same thing, but leaves insert mode first
Actionbar notification count icon (badge) like Google has
Ok, for @AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="@drawable/shape_notification" />
</menu>
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
Pointers in C: when to use the ampersand and the asterisk?
I was looking through all the wordy explanations so instead turned to a video from University of New South Wales for rescue.Here is the simple explanation: if we have a cell that has address x
and value 7
, the indirect way to ask for address of value 7
is &7
and the indirect way to ask for value at address x
is *x
.So (cell: x , value: 7) == (cell: &7 , value: *x)
.Another way to look into it: John
sits at 7th seat
.The *7th seat
will point to John
and &John
will give address
/location of the 7th seat
. This simple explanation helped me and hope it will help others as well. Here is the link for the excellent video: click here.
Here is another example:
#include <stdio.h>
int main()
{
int x; /* A normal integer*/
int *p; /* A pointer to an integer ("*p" is an integer, so p
must be a pointer to an integer) */
p = &x; /* Read it, "assign the address of x to p" */
scanf( "%d", &x ); /* Put a value in x, we could also use p here */
printf( "%d\n", *p ); /* Note the use of the * to get the value */
getchar();
}
Add-on: Always initialize pointer before using them.If not, the pointer will point to anything, which might result in crashing the program because the operating system will prevent you from accessing the memory it knows you don't own.But simply putting p = &x;
, we are assigning the pointer a specific location.
Redraw datatables after using ajax to refresh the table content?
In the initialization use:
"fnServerData": function ( sSource, aoData, fnCallback ) {
//* Add some extra data to the sender *
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
$.getJSON( sSource, newData, function (json) {
//* Do whatever additional processing you want on the callback, then tell DataTables *
fnCallback(json);
} );
},
And then just use:
$("#table_id").dataTable().fnDraw();
The important thing in the fnServerData is:
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.
Jquery bind double click and single click separately
Look at the following code
$("#clickMe").click(function (e) {
var $this = $(this);
if ($this.hasClass('clicked')){
alert("Double click");
//here is your code for double click
return;
}else{
$this.addClass('clicked');
//your code for single click
setTimeout(function() {
$this.removeClass('clicked'); },500);
}//end of else
});
Demo goes here http://jsfiddle.net/cB484/
What does $_ mean in PowerShell?
I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_
is similar to x
in x => Console.WriteLine(x)
anonymous function in C#. Consider following examples:
PowerShell:
1,2,3 | ForEach-Object {Write-Host $_}
Prints:
1
2
3
or
1,2,3 | Where-Object {$_ -gt 1}
Prints:
2
3
And compare this with C# syntax using LINQ:
var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));
Prints:
1
2
3
or
list.Where( _ => _ > 1)
.ToList()
.ForEach(s => Console.WriteLine(s));
Prints:
2
3
Creating an IFRAME using JavaScript
You can use:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
Hiding the scroll bar on an HTML page
I wrote a WebKit version with some options like auto hide, little version, scroll only-y, or only-x:
._scrollable{
@size: 15px;
@little_version_ratio: 2;
@scrollbar-bg-color: rgba(0,0,0,0.15);
@scrollbar-handler-color: rgba(0,0,0,0.15);
@scrollbar-handler-color-hover: rgba(0,0,0,0.3);
@scrollbar-coner-color: rgba(0,0,0,0);
overflow-y: scroll;
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
width: 100%;
height: 100%;
&::-webkit-scrollbar {
background: none;
width: @size;
height: @size;
}
&::-webkit-scrollbar-track {
background-color:@scrollbar-bg-color;
border-radius: @size;
}
&::-webkit-scrollbar-thumb {
border-radius: @size;
background-color:@scrollbar-handler-color;
&:hover{
background-color:@scrollbar-handler-color-hover;
}
}
&::-webkit-scrollbar-corner {
background-color: @scrollbar-coner-color;
}
&.little{
&::-webkit-scrollbar {
background: none;
width: @size / @little_version_ratio;
height: @size / @little_version_ratio;
}
&::-webkit-scrollbar-track {
border-radius: @size / @little_version_ratio;
}
&::-webkit-scrollbar-thumb {
border-radius: @size / @little_version_ratio;
}
}
&.autoHideScrollbar{
overflow-x: hidden;
overflow-y: hidden;
&:hover{
overflow-y: scroll;
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
&.only-y{
overflow-y: scroll !important;
overflow-x: hidden !important;
}
&.only-x{
overflow-x: scroll !important;
overflow-y: hidden !important;
}
}
}
&.only-y:not(.autoHideScrollbar){
overflow-y: scroll !important;
overflow-x: hidden !important;
}
&.only-x:not(.autoHideScrollbar){
overflow-x: scroll !important;
overflow-y: hidden !important;
}
}
http://codepen.io/hicTech/pen/KmKrjb
How do you tell if a checkbox is selected in Selenium for Java?
For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):
NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the !
sign at the beginning of the statement.
if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected())
{
driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}
Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?
Check this fully functional directive for MEAN.JS (Angular.js, bootstrap, Express.js and MongoDb)
Based on @Blackhole ´s response, we just finished it to be used with mongodb and express.
It will allow you to save and load dates from a mongoose connector
Hope it Helps!!
angular.module('myApp')
.directive(
'dateInput',
function(dateFilter) {
return {
require: 'ngModel',
template: '<input type="date" class="form-control"></input>',
replace: true,
link: function(scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
});
ngModelCtrl.$parsers.push(function(modelValue){
return angular.toJson(modelValue,true)
.substring(1,angular.toJson(modelValue).length-1);
})
}
};
});
The JADE/HTML:
div(date-input, ng-model="modelDate")
How to output oracle sql result into a file in windows?
Having the same chore on windows 10, and windows server 2012.
I found the following solution:
echo quit |sqlplus schemaName/schemaPassword@sid @plsqlScript.sql > outputFile.log
Explanation
echo quit |
send the quit command to exit sqlplus
after the script completes
sqlplus schemaName/schemaPassword@sid @plsqlScript.sql
execute plssql script plsqlScript.sql
in schema schemaName
with password schemaPassword
connecting to SID sid
> outputFile.log
redirect sqlplus output to log file outputFile.log
Get bottom and right position of an element
Vanilla Javascript Answer
var c = document.getElementById("myElement").getBoundingClientRect();
var bot = c.bottom;
var rgt = c.right;
To be clear the element can be anything so long as you have allocated an id to it <img>
<div>
<p>
etc.
for example
<img
id='myElement'
src='/img/logout.png'
className='logoutImg img-button'
alt='Logout'
/>
Full examples of using pySerial package
Blog post Serial RS232 connections in Python
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB1',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
How to read the post request parameters using JavaScript
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
How to sum up an array of integers in C#
Try this code:
using System;
namespace Array
{
class Program
{
static void Main()
{
int[] number = new int[] {5, 5, 6, 7};
int sum = 0;
for (int i = 0; i <number.Length; i++)
{
sum += number[i];
}
Console.WriteLine(sum);
}
}
}
The result is:
23
How can I use querySelector on to pick an input element by name?
1- you need to close the block of the function with '}', which is missing.
2- the argument of querySelector may not be an empty string '' or ' '... Use '*' for all.
3- those arguments will return the needed value:
querySelector('*')
querySelector('input')
querySelector('input[name="pwd"]')
querySelector('[name="pwd"]')
How to execute XPath one-liners from shell?
I wasn't happy with Python one-liners for HTML XPath queries, so I wrote my own. Assumes that you installed python-lxml
package or ran pip install --user lxml
:
function htmlxpath() { python -c 'for x in __import__("lxml.html").html.fromstring(__import__("sys").stdin.read()).xpath(__import__("sys").argv[1]): print(x)' $1 }
Once you have it, you can use it like in this example:
> curl -s https://slashdot.org | htmlxpath '//title/text()'
Slashdot: News for nerds, stuff that matters
Creating a JSON array in C#
You're close. This should do the trick:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
LINQ equivalent of foreach for IEnumerable<T>
This "functional approach" abstraction leaks big time. Nothing on the language level prevents side effects. As long as you can make it call your lambda/delegate for every element in the container - you will get the "ForEach" behavior.
Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites)
this is a hack, and should not be used in any production code.
var b = srcDictionary.Select(
x=>
{
destDictionary[x.Key] = x.Value;
return true;
}
).Count();
Get the string within brackets in Python
You could use str.split
to do this.
s = "<alpha.Customer[cus_Y4o9qMEZAugtnW] active_card=<alpha.AlphaObject[card]\
...>, created=1324336085, description='Customer for My Test App',\
livemode=False>"
val = s.split('[', 1)[1].split(']')[0]
Then we have:
>>> val
'cus_Y4o9qMEZAugtnW'
How can I change an element's class with JavaScript?
There is a property className in javascript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How to change class of an HTML element in Javascript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class=document.getElementById("change-class");
change_class.onclick=function()
{
var icon=document.getElementById("icon");
icon.className="fa fa-gear";
}
</script>
</body>
</html>
Credit - https://jaischool.com/javascript-lang/how-to-change-class-name-of-an-html-element-in-javascript.html
MVC4 input field placeholder
You can easily add Css class, placeholder , etc. as shown below:
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder="Name" })
Hope this helps
How to delete a file or folder?
To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:
def remove_file_or_dir(path: str) -> None:
""" Remove a file or directory """
try:
shutil.rmtree(path)
except NotADirectoryError:
os.remove(path)
Since shutil.rmtree()
will only remove directories and os.remove()
or os.unlink()
will only remove files.
VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory
Taking Shiraz's idea and running with it...
In your application, are you explicitly defining a domain User Account and Password to access AD?
When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.
A VBScript example would be as follows:
Dim objConnection As ADODB.Connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = "MyDomain\MyAccount"
objConnection.Properties("Password") = "MyPassword"
objConnection.Open "Active Directory Provider"
If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.
How to define a List bean in Spring?
And this is how to inject set in some property in Spring:
<bean id="process"
class="biz.bsoft.processing">
<property name="stages">
<set value-type="biz.bsoft.AbstractStage">
<ref bean="stageReady"/>
<ref bean="stageSteady"/>
<ref bean="stageGo"/>
</set>
</property>
</bean>
SQL GROUP BY CASE statement with aggregate function
My guess is that you don't really want to GROUP BY
some_product.
The answer to: "Is there a way to GROUP BY
a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY
a column alias.
The SELECT
clause, where column aliases are assigned, is not processed until after the GROUP BY
clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.
Inline view:
select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... ) T
group by some_product ...
CTE:
with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... )
select ...
from T
group by some_product ...
Force IE9 to emulate IE8. Possible?
The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.
How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?
Given that both strings — argv[1]
and "--foo"
— are C strings, @FelixDombek's answer is hands-down the best solution.
Seeing the other answers, however, I thought it worth noting that, if your text is already available as a std::string
, then a simple, zero-copy, maximally efficient solution exists that hasn't been mentioned so far:
const char * foo = "--foo";
if (text.rfind(foo, 0) == 0)
foo_value = text.substr(strlen(foo));
And if foo is already a string:
std::string foo("--foo");
if (text.rfind(foo, 0) == 0)
foo_value = text.substr(foo.length());
How to change the scrollbar color using css
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
Debugging iframes with Chrome developer tools
Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.
Update: This is no longer true. See Metagrapher's answer.
Start redis-server with config file
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
Curl and PHP - how can I pass a json through curl by PUT,POST,GET
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See @Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
Angularjs ng-model doesn't work inside ng-if
The ng-if
directive, like other directives creates a child scope. See the script below (or this jsfiddle)
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
function main($scope) {_x000D_
$scope.testa = false;_x000D_
$scope.testb = false;_x000D_
$scope.testc = false;_x000D_
$scope.obj = {test: false};_x000D_
}_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
<div ng-controller="main">_x000D_
_x000D_
Test A: {{testa}}<br />_x000D_
Test B: {{testb}}<br />_x000D_
Test C: {{testc}}<br />_x000D_
{{obj.test}}_x000D_
_x000D_
<div>_x000D_
testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
</div>_x000D_
<div ng-if="!testa">_x000D_
testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
</div>_x000D_
<div ng-if="!someothervar">_x000D_
testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
</div>_x000D_
<div ng-if="!someothervar">_x000D_
object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
So, your checkbox changes the testb
inside of the child scope, but not the outer parent scope.
Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.
How to verify static void method has been called with power mockito
Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
Here, I dont understand why we are calling InternalUtils.sendEmail ourself.
I will explain in my code why we don't need to do that.
mockStatic(Internalutils.class);
So, we have mocked the class which is fine.
Now, lets have a look how we need to verify the sendEmail(/..../) method.
@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {
@Mock
private InternalService.Order order;
private InternalService internalService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
internalService = new InternalService();
}
@Test
public void processOrder() throws Exception {
Mockito.when(order.isSuccessful()).thenReturn(true);
PowerMockito.mockStatic(InternalService.InternalUtils.class);
internalService.processOrder(order);
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
}
}
These two lines is where the magic is,
First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ??
Second line tells which method it needs to verify.
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
This is code of my class, sendEmail api twice.
public class InternalService {
public void processOrder(Order order) {
if (order.isSuccessful()) {
InternalUtils.sendEmail("", new String[1], "", "");
InternalUtils.sendEmail("", new String[1], "", "");
}
}
public static class InternalUtils{
public static void sendEmail(String from, String[] to, String msg, String body){
}
}
public class Order{
public boolean isSuccessful(){
return true;
}
}
}
As it is calling twice you just need to change the verify(times(2))... that's all.
paint() and repaint() in Java
The paint()
method supports painting via a Graphics object.
The repaint()
method is used to cause paint()
to be invoked by the AWT painting thread.
What's the difference between MyISAM and InnoDB?
MYISAM:
- MYISAM supports Table-level Locking
- MyISAM designed for need of speed
- MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
- MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
- MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
- MYISAM supports fulltext search
- You can use MyISAM, if the table is more static with lots of select and less update and delete.
INNODB:
- InnoDB supports Row-level Locking
- InnoDB designed for maximum performance when processing high volume of data
- InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
- InnoDB stores its tables and indexes in a tablespace
- InnoDB supports transaction. You can commit and rollback with InnoDB
inline conditionals in angular.js
Thousands of ways to skin this cat. I realize you're asking about between {{}} speifically, but for others that come here, I think it's worth showing some of the other options.
function on your $scope (IMO, this is your best bet in most scenarios):
app.controller('MyCtrl', function($scope) {
$scope.foo = 1;
$scope.showSomething = function(input) {
return input == 1 ? 'Foo' : 'Bar';
};
});
<span>{{showSomething(foo)}}</span>
ng-show and ng-hide of course:
<span ng-show="foo == 1">Foo</span><span ng-hide="foo == 1">Bar</span>
ngSwitch
<div ng-switch on="foo">
<span ng-switch-when="1">Foo</span>
<span ng-switch-when="2">Bar</span>
<span ng-switch-default>What?</span>
</div>
A custom filter as Bertrand suggested. (this is your best choice if you have to do the same thing over and over)
app.filter('myFilter', function() {
return function(input) {
return input == 1 ? 'Foo' : 'Bar';
}
}
{{foo | myFilter}}
Or A custom directive:
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
link: function(scope, elem, attrs) {
scope.$watch(attrs.value, function(v) {
elem.text(v == 1 ? 'Foo': 'Bar');
});
}
};
});
<my-directive value="foo"></my-directive>
Personally, in most cases I'd go with a function on my scope, it keeps the markup pretty clean, and it's quick and easy to implement. Unless, that is, you're going to be doing the same exact thing over and over again, in which case I'd go with Bertrand's suggestion and create a filter or possibly a directive, depending on the circumstances.
As always, the most important thing is that your solution is easy to maintain, and is hopefully testable. And that is going to depend completely on your specific situation.
phpmyadmin.pma_table_uiprefs doesn't exist
A really simple solution is to edit /etc/phpmyadmin/config.inc.php and put
$cfg['Servers'][$i]['table_uiprefs'] = '';
It just manages the UI and who needs the UI if its interfering with display of actual data.
cheers
Calling a phone number in swift
If your phone number contains spaces, remove them first! Then you can use the accepted answer's solution.
let numbersOnly = busPhone.replacingOccurrences(of: " ", with: "")
if let url = URL(string: "tel://\(numbersOnly)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
Setting a JPA timestamp column to be generated by the database?
I'm posting this for people searching for an answer when using MySQL and Java Spring Boot JPA, like @immanuelRocha says, only have too @CreationTimeStamp to the @Column in Spring, and in MySQL set the default value to "CURRENT_TIMESTAMP".
In Spring add just the line :
_x000D_
_x000D_
@Column(name = "insert_date")_x000D_
@CreationTimestamp_x000D_
private Timestamp insert_date;
_x000D_
_x000D_
_x000D_
CSS to select/style first word
Here's a bit of JavaScript and jQuery I threw together to wrap the first word of each paragraph with a <span>
tag.
$(function() {
$('#content p').each(function() {
var text = this.innerHTML;
var firstSpaceIndex = text.indexOf(" ");
if (firstSpaceIndex > 0) {
var substrBefore = text.substring(0,firstSpaceIndex);
var substrAfter = text.substring(firstSpaceIndex, text.length)
var newText = '<span class="firstWord">' + substrBefore + '</span>' + substrAfter;
this.innerHTML = newText;
} else {
this.innerHTML = '<span class="firstWord">' + text + '</span>';
}
});
});
You can then use CSS to create a style for .firstWord
.
It's not perfect, as it doesn't account for every type of whitespace; however, I'm sure it could accomplish what you're after with a few tweaks.
Keep in mind that this code will only execute after page load, so it may take a split second to see the effect.
how to set mongod --dbpath
mongod --port portnumber --dbpath /path_to_your_folder
By default portnumber is 27017 and path is /var/lib/mongodb
You can set your own port number and path where you want to keep all your database.
Check if specific input file is empty
<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}
How do you declare string constants in C?
One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:
#define HELLO "hello"
#define WORLD "world"
puts( HELLO WORLD );
Not sure that's really an advantage, but it is a technique that cannot be used with const char *
's.
python requests file upload
(2018) the new python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text
Excel SUMIF between dates
You haven't got your SUMIF
in the correct order - it needs to be range, criteria, sum range. Try:
=SUMIF(A:A,">="&DATE(2012,1,1),B:B)
Java - Change int to ascii
You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.
char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));
Output:
Character: 1
Character: 49
TCPDF output without saving file
Print the PDF header (using header() function) like:
header("Content-type: application/pdf");
and then just echo the content of the PDF file you created (instead of writing it to disk).
How to quit a java app from within the program
You can use System.exit()
for this purpose.
According to oracle's Java 8 documentation:
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
What's the difference between "app.render" and "res.render" in express.js?
Here are some differences:
You can call app.render
on root level and res.render
only inside a route/middleware.
app.render
always returns the html
in the callback function, whereas res.render
does so only when you've specified the callback function as your third parameter. If you call res.render
without the third parameter/callback function the rendered html is sent to the client with a status code of 200
.
Take a look at the following examples.
app.render
app.render('index', {title: 'res vs app render'}, function(err, html) {
console.log(html)
});
// logs the following string (from default index.jade)
<!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
res.render
without third parameter
app.get('/render', function(req, res) {
res.render('index', {title: 'res vs app render'})
})
// also renders index.jade but sends it to the client
// with status 200 and content-type text/html on GET /render
res.render
with third parameter
app.get('/render', function(req, res) {
res.render('index', {title: 'res vs app render'}, function(err, html) {
console.log(html);
res.send('done');
})
})
// logs the same as app.render and sends "done" to the client instead
// of the content of index.jade
res.render
uses app.render
internally to render template files.
You can use the render
functions to create html emails. Depending on your structure of your app, you might not always have acces to the app
object.
For example inside an external route:
app.js
var routes = require('routes');
app.get('/mail', function(req, res) {
// app object is available -> app.render
})
app.get('/sendmail', routes.sendmail);
routes.js
exports.sendmail = function(req, res) {
// can't use app.render -> therefore res.render
}
Count specific character occurrences in a string
Another possibility is to use a regular expression:
string a = "this is test";
string pattern = "t";
System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection m = ex.Matches(a);
MessageBox.Show(m.Count.ToString());
Please convert this into VB.NET.
Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'
In my case the error was due to incorrect port number (the error is definitely due to incorrect credentials i.e. host/port/dbname/username/password
).
Solution:
- right click on WAMP tray;
- click (drag your cursor) on MySQL;
- see the port number used by MySQL;
- add same in your Laravel configuration:
.env
file;
config/database.php
.
Clear cache
php artisan config:cache
Run migration
php artisan migrate
Removing duplicates from a String in Java
import java.util.Scanner;
public class dublicate {
public static void main(String... a) {
System.out.print("Enter the String");
Scanner Sc = new Scanner(System.in);
String st=Sc.nextLine();
StringBuilder sb=new StringBuilder();
boolean [] bc=new boolean[256];
for(int i=0;i<st.length();i++)
{
int index=st.charAt(i);
if(bc[index]==false)
{
sb.append(st.charAt(i));
bc[index]=true;
}
}
System.out.print(sb.toString());
}
}
Column/Vertical selection with Keyboard in SublimeText 3
Alright, here's the best solution I've found that meets all the requirements:
- Download the Sublime-Text-Advanced-CSV Sublime plugin and install.
- Specify a delimiter for your column (default is ","), via the "CSV: Set Delimiter" command.
- Hit "ctrl + , s" (or select from Command Palette) and your column will be selected.
No need for mouse interaction whatsoever.
What's NSLocalizedString equivalent in Swift?
In addition to great extension written here if you are lazy to find and replace old NSLocalizedString
you can open find & replace in Xcode and in the find section you can write NSLocalizedString\(\(".*"\), comment: ""\)
then in the replace section you need to write $1.localized
to change all NSLocalizedString
with "blabla".localized
in your project.
Add row to query result using select
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
TypeError: $(...).modal is not a function with bootstrap Modal
I guess you should use in your button
<a data-toggle="modal" href="#form-content"
instead of href there should be data-target
<a data-toggle="modal" data-target="#form-content"
just be sure, that modal content is already loaded
I think problem is, that showing modal is called twice, one in ajax call, that works fine, you said modal is shown correctly, but error probably comes with init action on that button, that should handle modal, this action cant be executed, because modal is not loaded at that time.