javascript date to string
You will need to pad with "0" if its a single digit & note getMonth
returns 0..11 not 1..12
function printDate() {
var temp = new Date();
var dateStr = padStr(temp.getFullYear()) +
padStr(1 + temp.getMonth()) +
padStr(temp.getDate()) +
padStr(temp.getHours()) +
padStr(temp.getMinutes()) +
padStr(temp.getSeconds());
debug (dateStr );
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}
How to get name of dataframe column in pyspark?
I found the answer is very very simple...
// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();
The variable "theNameOftheCol" is "colName"
Internet Explorer 11- issue with security certificate error prompt
This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level
You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property
You can do that by following steps:
- Click on Gear icon at the top of the browser window.
- Select Internet Options.
- Select the Security tab at the top.
- Click the Custom Level... button.
- Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
- Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
- Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
- Close and restart the browser.
Disable browser 'Save Password' functionality
The simplest way to solve this problem is to place INPUT fields outside the FORM tag and add two hidden fields inside the FORM tag. Then in a submit event listener before the form data gets submitted to server copy values from visible input to the invisible ones.
Here's an example (you can't run it here, since the form action is not set to a real login script):
_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Login & Save password test</title>_x000D_
<meta charset="utf-8">_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<!-- the following fields will show on page, but are not part of the form -->_x000D_
<input class="username" type="text" placeholder="Username" />_x000D_
<input class="password" type="password" placeholder="Password" />_x000D_
_x000D_
<form id="loginForm" action="login.aspx" method="post">_x000D_
<!-- thw following two fields are part of the form, but are not visible -->_x000D_
<input name="username" id="username" type="hidden" />_x000D_
<input name="password" id="password" type="hidden" />_x000D_
<!-- standard submit button -->_x000D_
<button type="submit">Login</button>_x000D_
</form>_x000D_
_x000D_
<script>_x000D_
// attache a event listener which will get called just before the form data is sent to server_x000D_
$('form').submit(function(ev) {_x000D_
console.log('xxx');_x000D_
// read the value from the visible INPUT and save it to invisible one_x000D_
// ... so that it gets sent to the server_x000D_
$('#username').val($('.username').val());_x000D_
$('#password').val($('.password').val());_x000D_
});_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
How to get number of entries in a Lua table?
You already have the solution in the question -- the only way is to iterate the whole table with pairs(..)
.
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
Also, notice that the "#" operator's definition is a bit more complicated than that. Let me illustrate that by taking this table:
t = {1,2,3}
t[5] = 1
t[9] = 1
According to the manual, any of 3, 5 and 9 are valid results for #t
. The only sane way to use it is with arrays of one contiguous part without nil values.
Resync git repo with new .gitignore file
The solution mentioned in ".gitignore file not ignoring" is a bit extreme, but should work:
# rm all files
git rm -r --cached .
# add all files as per new .gitignore
git add .
# now, commit for new .gitignore to apply
git commit -m ".gitignore is now working"
(make sure to commit first your changes you want to keep, to avoid any incident as jball037 comments below.
The --cached
option will keep your files untouched on your disk though.)
You also have other more fine-grained solution in the blog post "Making Git ignore already-tracked files":
git rm --cached `git ls-files -i --exclude-standard`
Bassim suggests in his edit:
Files with space in their paths
In case you get an error message like fatal: path spec '...' did not match any files
, there might be files with spaces in their path.
You can remove all other files with option --ignore-unmatch
:
git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`
but unmatched files will remain in your repository and will have to be removed explicitly by enclosing their path with double quotes:
git rm --cached "<path.to.remaining.file>"
Copy tables from one database to another in SQL Server
SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.
If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.
I use this all the time and it works fairly well.
Batch file include external file for variables
Batch uses the less than and greater than brackets as input and output pipes.
>file.ext
Using only one output bracket like above will overwrite all the information in that file.
>>file.ext
Using the double right bracket will add the next line to the file.
(
echo
echo
)<file.ext
This will execute the parameters based on the lines of the file. In this case, we are using two lines that will be typed using "echo". The left bracket touching the right parenthesis bracket means that the information from that file will be piped into those lines.
I have compiled an example-only read/write file. Below is the file broken down into sections to explain what each part does.
@echo off
echo TEST R/W
set SRU=0
SRU can be anything in this example. We're actually setting it to prevent a crash if you press Enter too fast.
set /p SRU=Skip Save? (y):
if %SRU%==y goto read
set input=1
set input2=2
set /p input=INPUT:
set /p input2=INPUT2:
Now, we need to write the variables to a file.
(echo %input%)> settings.cdb
(echo %input2%)>> settings.cdb
pause
I use .cdb as a short form for "Command Database". You can use any extension.
The next section is to test the code from scratch. We don't want to use the set variables that were run at the beginning of the file, we actually want them to load FROM the settings.cdb we just wrote.
:read
(
set /p input=
set /p input2=
)<settings.cdb
So, we just piped the first two lines of information that you wrote at the beginning of the file (which you have the option to skip setting the lines to check to make sure it's working) to set the variables of input and input2.
echo %input%
echo %input2%
pause
if %input%==1 goto newecho
pause
exit
:newecho
echo If you can see this, good job!
pause
exit
This displays the information that was set while settings.cdb was piped into the parenthesis. As an extra good-job motivator, pressing enter and setting the default values which we set earlier as "1" will return a good job message.
Using the bracket pipes goes both ways, and is much easier than setting the "FOR" stuff. :)
Can I configure a subdomain to point to a specific port on my server
I... don't think so. You can redirect the subdomain (such as blah.something.com
) to point to something.com:25566
, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.
Have a fixed position div that needs to scroll if content overflows
Here are both fixes.
First, regarding the fixed sidebar, you need to give it a height for it to overflow:
HTML Code:
<div id="sidebar">Menu</div>
<div id="content">Text</div>
CSS Code:
body {font:76%/150% Arial, Helvetica, sans-serif; color:#666; width:100%; height:100%;}
#sidebar {position:fixed; top:0; left:0; width:20%; height:100%; background:#EEE; overflow:auto;}
#content {width:80%; padding-left:20%;}
@media screen and (max-height:200px){
#sidebar {color:blue; font-size:50%;}
}
Live example:
http://jsfiddle.net/RWxGX/3/
It's impossible NOT to get a scroll bar if your content overflows the height of the div. That's why I've added a media query for screen height. Maybe you can adjust your styles for short screen sizes so the scroll doesn't need to appear.
Cheers,
Ignacio
ReactJS - Call One Component Method From Another Component
You can do something like this
import React from 'react';
class Header extends React.Component {
constructor() {
super();
}
checkClick(e, notyId) {
alert(notyId);
}
render() {
return (
<PopupOver func ={this.checkClick } />
)
}
};
class PopupOver extends React.Component {
constructor(props) {
super(props);
this.props.func(this, 1234);
}
render() {
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default Header;
Using statics
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
MyComponent.customMethod('bar'); // true
Input type "number" won't resize
For <input type=number>
, by the HTML5 CR, the size
attribute is not allowed. However, in Obsolete features it says: “Authors should not, but may despite requirements to the contrary elsewhere in this specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes regardless is to help legacy user agents that do not support input elements with type="number" to still render the text field with a useful width.”
Thus, the size
attribute can be used, but it only affects older browsers that do not support type=number
, so that the element falls back to a simple text control, <input type=text>
.
The rationale behind this is that the browser is expected to provide a user interface that takes the other attributes into account, for good usability. As the implementations may vary, any size imposed by an author might mess things up. (This also applies to setting the width of the control in CSS.)
The conclusion is that you should use <input type=number>
in a more or less fluid setup that does not make any assumptions about the dimensions of the element.
SQL Server FOR EACH Loop
declare @counter as int
set @counter = 0
declare @date as varchar(50)
set @date = cast(1+@counter as varchar)+'/01/2013'
while(@counter < 12)
begin
select cast(1+@counter as varchar)+'/01/2013' as date
set @counter = @counter + 1
end
Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?
Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String filePath) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath = filePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream = fileStream;
}
private void loadFile() throws FileNotFoundException,
NullObjectFoundException {
if (resourceAsStream == null)
throw new FileNotFoundException("Unable to locate give file..");
else {
try {
workbook = new XSSFWorkbook(resourceAsStream);
} catch (IOException ex) {
}
}
}// end loadxlsFile
public String[] getSheetsName() {
int totalsheet = 0;
int i = 0;
String[] sheetName = null;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetName = new String[totalsheet];
while (i < totalsheet) {
sheetName[i] = workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex() {
int totalsheet = 0;
int i = 0;
int[] sheetIndex = null;
String[] sheetname = getSheetsName();
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetIndex = new int[totalsheet];
while (i < totalsheet) {
sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index) {
if (index < getSheetsIndex().length && index >= 0)
return true;
else
return false;
}
public int getNumberOfSheet() {
int totalsheet = 0;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
// logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
// logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex) {
int NO_OF_Column = 0;
@SuppressWarnings("unused")
XSSFCell cell = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = firstRow.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex) {
int NO_OF_ROW = 0;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex) {
int noOfColumns = 0;
XSSFCell cell = null;
int i = 0;
String columns[] = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = Row.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
// logger.error(ex);
}
return columns;
}// end of method
public String[][] getSheetData(int SheetIndex) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int noOfRows = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows = getNumberOfRows(SheetIndex) + 1;
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (rowIter.hasNext()) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
data[i][j] = Boolean.toString(cell
.getBooleanCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
public String[][] getSheetData(int SheetIndex, int noOfRows) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (i < noOfRows) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
}
Created this little testcode:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadXLSXTest {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));
System.out.println(test.getSheetsName());
System.out.println(test.getNumberOfSheet());
}
}
All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.
Cheers,
Wim
How to improve a case statement that uses two columns
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
JQuery - Get select value
val() returns the value of the <select>
element, i.e. the value
attribute of the selected <option>
element.
Since you actually want the inner text of the selected <option>
element, you should match that element and use text() instead:
var nationality = $("#dancerCountry option:selected").text();
Change the "From:" address in Unix "mail"
On Debian 7 I was still unable to correctly set the sender address using answers from this question, (would always be the hostname of the server) but resolved it this way.
Install heirloom-mailx
apt-get install heirloom-mailx
ensure it's the default.
update-alternatives --config mailx
Compose a message.
mail -s "Testing from & replyto" -r "sender <[email protected]>" -S replyto="[email protected]" [email protected] < <(echo "Test message")
Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)
The answer is not efficiency. Non-reentrant mutexes lead to better code.
Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.
Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.
The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.
If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.
How can I throw CHECKED exceptions from inside Java 8 streams?
This answer is similar to 17 but avoiding wrapper exception definition:
List test = new ArrayList();
try {
test.forEach(obj -> {
//let say some functionality throws an exception
try {
throw new IOException("test");
}
catch(Exception e) {
throw new RuntimeException(e);
}
});
}
catch (RuntimeException re) {
if(re.getCause() instanceof IOException) {
//do your logic for catching checked
}
else
throw re; // it might be that there is real runtime exception
}
How do I create and store md5 passwords in mysql
Why don't you use the MySQL built in password hasher:
http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
for comparison you could something like this:
select id from PassworTable where Userid='<userid>' and Password=PASSWORD('<password>')
and if it returns a value then the user is correct.
Convert JS date time to MySQL datetime
Solution built on the basis of other answers, while maintaining the timezone and leading zeros:
var d = new Date;
var date = [
d.getFullYear(),
('00' + d.getMonth() + 1).slice(-2),
('00' + d.getDate() + 1).slice(-2)
].join('-');
var time = [
('00' + d.getHours()).slice(-2),
('00' + d.getMinutes()).slice(-2),
('00' + d.getSeconds()).slice(-2)
].join(':');
var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01
Commit only part of a file in Git
I believe that git add -e myfile
is the easiest way (my preference at least) since it simply opens a text editor and lets you choose which line you want to stage and which line you don't.
Regarding editing commands:
added content:
Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them.
removed content:
Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).
modified content:
Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+"
lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index.
Every details about git add
are available on git --help add
How do I load a file into the python console?
From the man page:
-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.
So this should do what you want:
python -i file.py
Adding options to a <select> using jQuery?
If someone comes here looking for a way to add options with data properties
Using attr
var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);
Using data - version added 1.2.3
var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);
Check if key exists and iterate the JSON array using Python
import json
jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""
def getTargetIds(jsonData):
data = json.loads(jsonData)
if 'to' not in data:
raise ValueError("No target in given data")
if 'data' not in data['to']:
raise ValueError("No data for target")
for dest in data['to']['data']:
if 'id' not in dest:
continue
targetId = dest['id']
print("to_id:", targetId)
Output:
In [9]: getTargetIds(s)
to_id: 1543
Is there a way to make a PowerShell script work by double clicking a .ps1 file?
Or if you want all PS1 files to work the way VBS files do, you can edit the registry like this:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command
Edit the Default value to be something like so...
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"
Then you can just double click all your .PS1 files like you would like to. in my humble opinion, be able to out of the box.
I'm going to call this "The Powershell De-castration Hack". LOL enjoy!
Memory address of variables in Java
That is the output of Object's "toString()" implementation. If your class overrides toString(), it will print something entirely different.
What happened to console.log in IE8?
Here is a version that will log to the console when the developer tools are open and not when they are closed.
(function(window) {
var console = {};
console.log = function() {
if (window.console && (typeof window.console.log === 'function' || typeof window.console.log === 'object')) {
window.console.log.apply(window, arguments);
}
}
// Rest of your application here
})(window)
Export MySQL database using PHP only
You can use this command it works or me 100%
exec('C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -uroot DatabaseName> c:\\database_backup.sql');
note:
C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe
is the path for mysqldump app , check on your pc.
-uroot
is -u{UserName}
If your database is protected with password then add after -uroot this sentense -p{YourPassword}
How to remove components created with Angular-CLI
Try to uninstall angular and then reinstall
npm uninstall --save @angular/(then whatever component you want deleted)
after that, a box with babyblue color border will appear with suggestion to update and install angular back up.
Meaning of "487 Request Terminated"
It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).
Here is a nice CANCEL SIP Call Flow illustration.
How to view file history in Git?
Use git log
to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787
and b410ad4619d296f9d37f0db3d0ff5b9066838b39
). To view the difference between two different commits, use git diff
with the first few characters of the revision specifiers of both commits, like so:
# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b
If you want to get an overview over all the differences that happened from commit to commit, use git log
or git whatchanged
with the patch option:
# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d
Making Enter key on an HTML form submit instead of activating button
You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit"
, and the other buttons mark them with type="button"
. In your example:
<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>
How do you make Git work with IntelliJ?
GitHub for Windows on Windows 7 currently installs Git
in a path similar to this:
C:\Users\{username}\AppData\Local\GitHub\PortableGit_93e8418133eb85e81a81e5e19c272776524496c6\bin\git.exe
The guid after PortableGit_
may well be different on your system.
Stretch background image css?
I think what you are looking for is
.style1 {
background: url('http://localhost/msite/images/12.PNG');
background-repeat: no-repeat;
background-position: center;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
background-size: contain;
}
Can I use multiple "with"?
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
Passing command line arguments to R CMD BATCH
Here's another way to process command line args, using R CMD BATCH
. My approach, which builds on an earlier answer here, lets you specify arguments at the command line and, in your R script, give some or all of them default values.
Here's an R file, which I name test.R:
defaults <- list(a=1, b=c(1,1,1)) ## default values of any arguments we might pass
## parse each command arg, loading it into global environment
for (arg in commandArgs(TRUE))
eval(parse(text=arg))
## if any variable named in defaults doesn't exist, then create it
## with value from defaults
for (nm in names(defaults))
assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]))[[1]])
print(a)
print(b)
At the command line, if I type
R CMD BATCH --no-save --no-restore '--args a=2 b=c(2,5,6)' test.R
then within R we'll have a
= 2
and b
= c(2,5,6)
. But I could, say, omit b
, and add in another argument c
:
R CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.R
Then in R we'll have a
= 2
, b
= c(1,1,1)
(the default), and c
= "hello"
.
Finally, for convenience we can wrap the R code in a function, as long as we're careful about the environment:
## defaults should be either NULL or a named list
parseCommandArgs <- function(defaults=NULL, envir=globalenv()) {
for (arg in commandArgs(TRUE))
eval(parse(text=arg), envir=envir)
for (nm in names(defaults))
assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]), envir=envir)[[1]], pos=envir)
}
## example usage:
parseCommandArgs(list(a=1, b=c(1,1,1)))
SSRS custom number format
am assuming that you want to know how to format numbers in SSRS
Just right click
the TextBox
on which you want to apply formatting, go to its expression
.
suppose its expression is something like below
=Fields!myField.Value
then do this
=Format(Fields!myField.Value,"##.##")
or
=Format(Fields!myFields.Value,"00.00")
difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00
this should give you an idea.
also: you might have to convert your field into a numerical one. i.e.
=Format(CDbl(Fields!myFields.Value),"00.00")
so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present
ie. 45.6567 would be 45.65 for both of them:
UPDATE :
if you want to apply variable formatting on the same column based on row values i.e.
you want myField
to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)
Go to the appropriate textbox and go to its expression and do this:
=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0,
Format(Fields!myField.Value, "##.##"),Fields!myField.Value)
so basically you are using IIF(condition, true,false)
operator of SSRS,
ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.
this should give you an idea, how to handle variable formatting.
HTML5 Audio stop function
From my own javascript function to toggle Play/Pause - since I'm handling a radio stream, I wanted it to clear the buffer so that the listener does not end up coming out of sync with the radio station.
function playStream() {
var player = document.getElementById('player');
(player.paused == true) ? toggle(0) : toggle(1);
}
function toggle(state) {
var player = document.getElementById('player');
var link = document.getElementById('radio-link');
var src = "http://192.81.248.91:8159/;";
switch(state) {
case 0:
player.src = src;
player.load();
player.play();
link.innerHTML = 'Pause';
player_state = 1;
break;
case 1:
player.pause();
player.currentTime = 0;
player.src = '';
link.innerHTML = 'Play';
player_state = 0;
break;
}
}
Turns out, just clearing the currentTime doesn't cut it under Chrome, needed to clear the source too and load it back in. Hope this helps.
How to handle query parameters in angular 2
The simple way to do that in Angular 7+ is to:
Define a path in your ?-routing.module.ts
{ path: '/yourpage', component: component-name }
Import the ActivateRoute and Router module in your component and inject them in the constructor
contructor(private route: ActivateRoute, private router: Router){ ... }
Subscribe the ActivateRoute to the ngOnInit
ngOnInit() {
this.route.queryParams.subscribe(params => {
console.log(params);
// {page: '2' }
})
}
Provide it to a link:
<a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>
Discard all and get clean copy of latest revision?
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
How to return value from function which has Observable subscription inside?
In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await
is the imperative-style programmer's best friend:
(async()=>{
const store = of("someValue");
function getValueFromObservable () {
return store.toPromise();
}
console.log(await getValueFromObservable())
})();
And in case store
is a sequence of multiple values:
const aiFrom = require('ix/asynciterable').from;
(async function() {
const store = from(["someValue","someOtherValue"]);
function getValuesFromObservable () {
return aiFrom(store);
}
for await (let num of getValuesFromObservable()) {
console.log(num);
}
})();
ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?
Here's the exact definition of UsedRange
(MSDN reference) :
Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between.
So basically, what that line does is :
.UsedRange
-> "Draws" a box around the outer-most cells with content inside.
.Columns
-> Selects the entire columns of those cells
.Count
-> Returns an integer corresponding to how many columns there are (in this selection)
- 8
-> Subtracts 8 from the previous integer.
I assume VBA calculates the UsedRange by finding the non-empty cells with lowest and highest index values.
Most likely, you're getting an error because the number of lines in your range is smaller than 3, and therefore the number returned is negative.
Uncaught syntaxerror: unexpected identifier?
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
What is the equivalent of the C++ Pair<L,R> in Java?
As many others have already stated, it really depends on the use case if a Pair class is useful or not.
I think for a private helper function it is totally legitimate to use a Pair class if that makes your code more readable and is not worth the effort of creating yet another value class with all its boiler plate code.
On the other hand, if your abstraction level requires you to clearly document the semantics of the class that contains two objects or values, then you should write a class for it. Usually that's the case if the data is a business object.
As always, it requires skilled judgement.
For your second question I recommend the Pair class from the Apache Commons libraries. Those might be considered as extended standard libraries for Java:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
You might also want to have a look at Apache Commons' EqualsBuilder, HashCodeBuilder and ToStringBuilder which simplify writing value classes for your business objects.
CASE .. WHEN expression in Oracle SQL
Of course...
select case substr(status,1,1) -- you're only interested in the first character.
when 'a' then 'Active'
when 'i' then 'Inactive'
when 't' then 'Terminated'
end as statustext
from stage.tst
However, there's a few worrying things about this schema. Firstly if you have a column that means something, appending a number onto the end it not necessarily the best way to go. Also, depending on the number of status' you have you might want to consider turning this column into a foreign key to a separate table.
Based on your comment you definitely want to turn this into a foreign key. For instance
create table statuses ( -- Not a good table name :-)
status varchar2(10)
, description varchar2(10)
, constraint pk_statuses primary key (status)
)
create table tst (
id number
, status varchar2(10)
, constraint pk_tst primary key (id)
, constraint fk_tst foreign key (status) references statuses (status)
)
Your query then becomes
select a.status, b.description
from tst a
left outer join statuses b
on a.status = b.status
Here's a SQL Fiddle to demonstrate.
More than 1 row in <Input type="textarea" />
As said by Sparky in comments on many answers to this question, there is NOT any textarea
value for the type
attribute of the input
tag.
On other terms, the following markup is not valid :
<input type="textarea" />
And the browser replaces it by the default :
<input type="text" />
To define a multi-lines text input, use :
<textarea></textarea>
See the textarea element documentation for more details.
How do I remove repeated elements from ArrayList?
When you are filling the ArrayList, use a condition for each element. For example:
ArrayList< Integer > al = new ArrayList< Integer >();
// fill 1
for ( int i = 0; i <= 5; i++ )
if ( !al.contains( i ) )
al.add( i );
// fill 2
for (int i = 0; i <= 10; i++ )
if ( !al.contains( i ) )
al.add( i );
for( Integer i: al )
{
System.out.print( i + " ");
}
We will get an array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
How to concatenate two strings to build a complete path
The POSIX standard mandates that multiple /
are treated as a single /
in a file name. Thus
//dir///subdir////file
is the same as /dir/subdir/file
.
As such concatenating a two strings to build a complete path is a simple as:
full_path="$part1/$part2"
Make git automatically remove trailing whitespace before committing
Please try my pre-commit hooks, it can auto detect trailing-whitespace and remove it. Thank you!
it can work under GitBash(windows), Mac OS X and Linux
!
Snapshot:
$ git commit -am "test"
auto remove trailing whitespace in foobar/main.m!
auto remove trailing whitespace in foobar/AppDelegate.m!
[master 80c11fe] test
1 file changed, 2 insertions(+), 2 deletions(-)
Databinding an enum property to a ComboBox in WPF
In the viewmodel you can have:
public MyEnumType SelectedMyEnumType
{
get { return _selectedMyEnumType; }
set {
_selectedMyEnumType = value;
OnPropertyChanged("SelectedMyEnumType");
}
}
public IEnumerable<MyEnumType> MyEnumTypeValues
{
get
{
return Enum.GetValues(typeof(MyEnumType))
.Cast<MyEnumType>();
}
}
In XAML the ItemSource
binds to MyEnumTypeValues
and SelectedItem
binds to SelectedMyEnumType
.
<ComboBox SelectedItem="{Binding SelectedMyEnumType}" ItemsSource="{Binding MyEnumTypeValues}"></ComboBox>
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Return zero if no record is found
You could:
SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;
This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.
Plain queries without aggregate would return no row in such a case. COALESCE
would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:
SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;
Works for your original query as well:
SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;
More about COALESCE()
in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:
How do you plot bar charts in gnuplot?
You can directly use the style histograms provide by gnuplot. This is an example if you have two file in output:
set style data histograms
set style fill solid
set boxwidth 0.5
plot "file1.dat" using 5 title "Total1" lt rgb "#406090",\
"file2.dat" using 5 title "Total2" lt rgb "#40FF00"
Using Vim's tabs like buffers
Contrary to some of the other answers here, I say that you can use tabs however you want. vim was designed to be versatile and customizable, rather than forcing you to work according to predefined parameters. We all know how us programmers love to impose our "ethics" on everyone else, so this achievement is certainly a primary feature.
<C-w>gf
is the tab equivalent of buffers' gf
command. <C-PageUp>
and <C-PageDown>
will switch between tabs. (In Byobu, these two commands never work for me, but they work outside of Byobu/tmux. Alternatives are gt
and gT
.) <C-w>T
will move the current window to a new tab page.
If you'd prefer that vim use an existing tab if possible, rather than creating a duplicate tab, add :set switchbuf=usetab
to your .vimrc file. You can add newtab
to the list (:set switchbuf=usetab,newtab
) to force QuickFix commands that display compile errors to open in separate tabs. I prefer split
instead, which opens the compile errors in a split window.
If you have mouse support enabled with :set mouse=a
, you can interact with the tabs by clicking on them. There's also a +
button by default that will create a new tab.
For the documentation on tabs, type :help tab-page
in normal mode. (After you do that, you can practice moving a window to a tab using <C-w>T
.) There's a long list of commands. Some of the window commands have to do with tabs, so you might want to look at that documentation as well via :help windows
.
Addition: 2013-12-19
To open multiple files in vim with each file in a separate tab, use vim -p file1 file2 ...
. If you're like me and always forget to add -p
, you can add it at the end, as vim follows the normal command line option parsing rules. Alternatively, you can add a bash alias mapping vim
to vim -p
.
Error: Cannot find module 'ejs'
STEP 1
See npm ls | grep ejs
at root level of your project to check if you have already added ejs
dependency
to your project.
If not, add it as dependencies
to your project. (I prefer adding dependency to package.json
instead of npm install
ing the module.)
eg.
{
"name": "musicpedia",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
"jade": "~1.11.0",
"ejs": "^1.0.0",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
}
}
STEP 2 download the dependencies
npm install
STEP 3 check ejs module
$ npm ls | grep ejs
[email protected] /Users/prayagupd/nodejs-fkers/musicpedia
+-- [email protected]
How to select all elements with a particular ID in jQuery?
Your document should not contain two divs with the same id. This is invalid HTML, and as a result, the underlying DOM API does not support it.
From the HTML standard:
id = name [CS] This attribute assigns
a name to an element. This name must
be unique in a document.
You can either assign different ids to each div and select them both using $('#id1, #id2)
. Or assign the same class to both elements (.cls
for example), and use $('.cls')
to select them both.
SVN Commit specific files
Sure. Just list the files:
$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png
I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:
$ svn ci -m "No longer sets printer on fire" printer-driver/*.c
You can also have the svn command read the list of files to commit from a file:
$ svn ci -m "Now works" --targets fix4711.txt
Count characters in textarea
Well, this is not that different from what have been said, but this works very well in all browsers.
The idea is to delete any text which overflows the defined length.
function countTextAreaChar(txtarea, l){
var len = $(txtarea).val().length;
if (len > l) $(txtarea).val($(txtarea).val().slice(0, l));
else $('#charNum').text(l - len);
}
The HTMl code would be:
<div id="charNum"></div>
<textarea onkeyup="countTextAreaChar(this, 10)" class="textareaclass" id="smallword" rows="40" cols="30" name="smallword"></textarea>
How to create a Java / Maven project that works in Visual Studio Code?
This is not a particularly good answer as it explains how to run your java code n VS Code and not necessarily a Maven
project, but it worked for me because I could not get around to doing the manual configuration myself. I decided to use this method instead since it is easier and faster.
Install VSCode (and for windows, set your environment variables), then install vscode:extension/vscjava.vscode-java-pack
as detailed above, and then install the code runner extension pack, which basically sets up the whole process (in the background) as explained in the accepted answer above and then provides a play button to run your java code when you're ready.
This was all explained in this video.
Again, this is not the best solution, but if you want to cut to the chase, you may find this answer useful.
ViewBag, ViewData and TempData
ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:
Similarities between ViewBag & ViewData :
- Helps to maintain data when you move from controller to view.
- Used to pass data from controller to corresponding view.
- Short life means value becomes null when redirection occurs. This is
because their goal is to provide a way to communicate between
controllers and views. It’s a communication mechanism within the
server call.
Difference between ViewBag & ViewData:
- ViewData is a dictionary of objects that is derived from
ViewDataDictionary class and accessible using strings as keys.
- ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0.
- ViewData requires typecasting for complex data type and check for
null values to avoid error.
- ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
In View:
@ViewBag.Name
@ViewData["Name"]
TempData:
TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.
Test if a command outputs an empty string
TL;DR
if [[ $(ls -A | head -c1 | wc -c) -ne 0 ]]; then ...; fi
Thanks to netj
for a suggestion to improve my original:
if [[ $(ls -A | wc -c) -ne 0 ]]; then ...; fi
This is an old question but I see at least two things that need some improvement or at least some clarification.
First problem
First problem I see is that most of the examples provided here simply don't work. They use the ls -al
and ls -Al
commands - both of which output non-empty strings in empty directories. Those examples always report that there are files even when there are none.
For that reason you should use just ls -A
- Why would anyone want to use the -l
switch which means "use a long listing format" when all you want is test if there is any output or not, anyway?
So most of the answers here are simply incorrect.
Second problem
The second problem is that while some answers work fine (those that don't use ls -al
or ls -Al
but ls -A
instead) they all do something like this:
- run a command
- buffer its entire output in RAM
- convert the output into a huge single-line string
- compare that string to an empty string
What I would suggest doing instead would be:
- run a command
- count the characters in its output without storing them
- or even better - count the number of maximally 1 character
using head -c1
(thanks to netj for posting this idea in the comments below)
- compare that number with zero
So for example, instead of:
if [[ $(ls -A) ]]
I would use:
if [[ $(ls -A | wc -c) -ne 0 ]]
# or:
if [[ $(ls -A | head -c1 | wc -c) -ne 0 ]]
Instead of:
if [ -z "$(ls -lA)" ]
I would use:
if [ $(ls -lA | wc -c) -eq 0 ]
# or:
if [ $(ls -lA | head -c1 | wc -c) -eq 0 ]
and so on.
For small outputs it may not be a problem but for larger outputs the difference may be significant:
$ time [ -z "$(seq 1 10000000)" ]
real 0m2.703s
user 0m2.485s
sys 0m0.347s
Compare it with:
$ time [ $(seq 1 10000000 | wc -c) -eq 0 ]
real 0m0.128s
user 0m0.081s
sys 0m0.105s
And even better:
$ time [ $(seq 1 10000000 | head -c1 | wc -c) -eq 0 ]
real 0m0.004s
user 0m0.000s
sys 0m0.007s
Full example
Updated example from the answer by Will Vousden:
if [[ $(ls -A | wc -c) -ne 0 ]]; then
echo "there are files"
else
echo "no files found"
fi
Updated again after suggestions by netj:
if [[ $(ls -A | head -c1 | wc -c) -ne 0 ]]; then
echo "there are files"
else
echo "no files found"
fi
Additional update by jakeonfire:
grep
will exit with a failure if there is no match. We can take advantage of this to simplify the syntax slightly:
if ls -A | head -c1 | grep -E '.'; then
echo "there are files"
fi
if ! ls -A | head -c1 | grep -E '.'; then
echo "no files found"
fi
Discarding whitespace
If the command that you're testing could output some whitespace that you want to treat as an empty string, then instead of:
| wc -c
you could use:
| tr -d ' \n\r\t ' | wc -c
or with head -c1
:
| tr -d ' \n\r\t ' | head -c1 | wc -c
or something like that.
Summary
First, use a command that works.
Second, avoid unnecessary storing in RAM and processing of potentially huge data.
The answer didn't specify that the output is always small so a possibility of large output needs to be considered as well.
Optimal way to DELETE specified rows from Oracle
Store all the to be deleted ID's into a table. Then there are 3 ways.
1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.
2) Use Oracle Bulk Delete
3) Use correlated delete query.
Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.
Compiling and Running Java Code in Sublime Text 2
So this is what i added to the JavaC.sublime-build file
{
"cmd": ["javac", "-Xlint", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",
"variants": [
{ "cmd": ["javac", "-Xlint", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",
"name": "Java Lintter"
},
{ "cmd": ["java", "$file_base_name"],
"name": "Run Java"
}
]
}
What this does is that it creates variants to the regular build command (ctrl+b). With ctrl+b you will still be able to compile your code. If you do shift+ctrl+b the first variant will be executed, which in this case is javac with the -Xlint option. The second and final variant is the java command itself. you can place this as your first variant and shift+ctrl+b will actually execute the java code.
Also, notice that each variant as a "name". This basically allows this specific "build" option to show up in the shift+ctrl+p option. So using this configuration, you can simply do shift+ctrl+p and type "Run Java" and hit enter, and your code will execute.
Hope this helped.
How to get on scroll events?
You could use a @HostListener decorator. Works with Angular 4 and up.
import { HostListener } from '@angular/core';
@HostListener("window:scroll", []) onWindowScroll() {
// do some stuff here when the window is scrolled
const verticalOffset = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop || 0;
}
Fetching data from MySQL database using PHP, Displaying it in a form for editing
<?php
include 'cdb.php';
$show=mysqli_query( $conn,"SELECT *FROM 'reg'");
while($row1= mysqli_fetch_array($show))
{
$id=$row1['id'];
$Name= $row1['name'];
$email = $row1['email'];
$username = $row1['username'];
$password= $row1['password'];
$birthm = $row1['bmonth'];
$birthd= $row1['bday'];
$birthy= $row1['byear'];
$gernder = $row1['gender'];
$phone= $row1['phone'];
$image=$row1['image'];
}
?>
<html>
<head><title>hey</head></title></head>
<body>
<form>
<table border="-2" bgcolor="pink" style="width: 12px; height: 100px;" >
<th>
id<input type="text" name="" style="width: 30px;" value= "<?php echo $row1['id']; ?>" >
</th>
<br>
<br>
<th>
name <input type="text" name="" style="width: 60px;" value= "<?php echo $row1['Name']; ?>" >
</th>
<th>
email<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['email']; ?>" >
</th>
<th>
username<input type="hidden" name="" style="width: 60px;" value= "<?php echo $username['email']; ?>" >
</th>
<th>
password<input type="hidden" name="" style="width: 60px;" value= "<?php echo $row1['password']; ?>">
</ths>
<th>
birthday month<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthm']; ?>">
</th>
<th>
birthday day<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthd']; ?>">
</th>
<th>
birthday year<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthy']; ?>" >
</th>
<th>
gender<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['gender']; ?>">
</th>
<th>
phone number<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['phone']; ?>">
</th>
<th>
<th>
image<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['image']; ?>">
</th>
<th>
<font color="pink"> <a href="update.php">update</a></font>
</th>
</table>
</body>
</form>
</body>
</html>
Read a Csv file with powershell and capture corresponding data
What you should be looking at is Import-Csv
Once you import the CSV you can use the column header as the variable.
Example CSV:
Name | Phone Number | Email
Elvis | 867.5309 | [email protected]
Sammy | 555.1234 | [email protected]
Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:
$Name = @()
$Phone = @()
Import-Csv H:\Programs\scripts\SomeText.csv |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
$inputNumber = Read-Host -Prompt "Phone Number"
if ($Phone -contains $inputNumber)
{
Write-Host "Customer Exists!"
$Where = [array]::IndexOf($Phone, $inputNumber)
Write-Host "Customer Name: " $Name[$Where]
}
And here is the output:
How to encrypt a large file in openssl using public key
To safely encrypt large files (>600MB) with openssl smime
you'll have to split each file into small chunks:
# Splits large file into 500MB pieces
split -b 500M -d -a 4 INPUT_FILE_NAME input.part.
# Encrypts each piece
find -maxdepth 1 -type f -name 'input.part.*' | sort | xargs -I % openssl smime -encrypt -binary -aes-256-cbc -in % -out %.enc -outform DER PUBLIC_PEM_FILE
For the sake of information, here is how to decrypt and put all pieces together:
# Decrypts each piece
find -maxdepth 1 -type f -name 'input.part.*.enc' | sort | xargs -I % openssl smime -decrypt -in % -binary -inform DEM -inkey PRIVATE_PEM_FILE -out %.dec
# Puts all together again
find -maxdepth 1 -type f -name 'input.part.*.dec' | sort | xargs cat > RESTORED_FILE_NAME
How to programmatically get iOS status bar height
Using following single line code you can get status bar height in any orientation and also if it is visible or not
#define STATUS_BAR_HIGHT (
[UIApplicationsharedApplication].statusBarHidden ? 0 : (
[UIApplicationsharedApplication].statusBarFrame.size.height > 100 ?
[UIApplicationsharedApplication].statusBarFrame.size.width :
[UIApplicationsharedApplication].statusBarFrame.size.height
)
)
It just a simple but very useful macro just try this you don't need to write any extra code
Error - Unable to access the IIS metabase
I had the same problem. For me it was that I was using the same my documents as on a previous Windows installation. Simply removing the IISExpress folder from my documents did the trick.
How to convert C# nullable int to int
If you know that v1
has a value, you can use the Value
property:
v2 = v1.Value;
Using the GetValueOrDefault
method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:
v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value
v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value
You can use the HasValue
property to check if v1
has a value:
if (v1.HasValue) {
v2 = v1.Value;
}
There is also language support for the GetValueOrDefault(T)
method:
v2 = v1 ?? -1;
VBA error 1004 - select method of range class failed
assylias and Head of Catering have already given your the reason why the error is occurring.
Now regarding what you are doing, from what I understand, you don't need to use Select
at all
I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as
Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String
filepath = CStr(FileDialog)
'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")
lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)
lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)
Finding Key associated with max Value in a Java Map
For completeness, here is a java-8 way of doing it
countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
or
Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
or
Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
How can I generate a random number in a certain range?
Random Number Generator in Android
If you want to know about random number generator in android then you should read this article till end. Here you can get all information about random number generator in android. Random Number Generator in Android
You should use this code in your java file.
Random r = new Random();
int randomNumber = r.nextInt(100);
tv.setText(String.valueOf(randomNumber));
I hope this answer may helpful for you. If you want to read more about this article then you should read this article. Random Number Generator
Check if a value exists in pandas dataframe index
Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:
df3 = df1[df1.index.isin(df2.index)]
or where df1 index does not exist in df2...
df3 = df1[~df1.index.isin(df2.index)]
How to check if a file is a valid image file?
I have just found the builtin imghdr module. From python documentation:
The imghdr module determines the type
of image contained in a file or byte
stream.
This is how it works:
>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'
Using a module is much better than reimplementing similar functionality
how to inherit Constructor from super class to sub class
Say if you have
/**
*
*/
public KKSSocket(final KKSApp app, final String name) {
this.app = app;
this.name = name;
...
}
then a sub-class named KKSUDPSocket extending KKSSocket could have:
/**
* @param app
* @param path
* @param remoteAddr
*/
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
super(app, path, remoteAddr);
}
and
/**
* @param app
* @param path
*/
public KKSUDPSocket(KKSApp app, String path) {
super(app, path);
}
You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.
Read user input inside a loop
Try to change the loop like this:
for line in $(cat filename); do
read input
echo $input;
done
Unit test:
for line in $(cat /etc/passwd); do
read input
echo $input;
echo "[$line]"
done
How can I generate a 6 digit unique number?
<?php
$file = 'count.txt';
//get the number from the file
$uniq = file_get_contents($file);
//add +1
$id = $uniq + 1 ;
// add that new value to text file again for next use
file_put_contents($file, $id);
// your unique id ready
echo $id;
?>
i hope this will work fine. i use the same technique in my website.
copy from one database to another using oracle sql developer - connection failed
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
- Specify the specific table(s) (e.g. table1).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
Are HTTPS headers encrypted?
HTTP version 1.1 added a special HTTP method, CONNECT - intended to create the SSL tunnel, including the necessary protocol handshake and cryptographic setup.
The regular requests thereafter all get sent wrapped in the SSL tunnel, headers and body inclusive.
BEGIN - END block atomic transactions in PL/SQL
BEGIN
-END
blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN
-END
blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.
If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION
in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.
However, you cannot declare this pragma for nested blocks. You can only declare this for:
- Top-level (not nested) anonymous PL/SQL blocks
- List item
- Local, standalone, and packaged functions and procedures
- Methods of a SQL object type
- Database triggers
Reference: Oracle
Android Activity without ActionBar
Considering everyone is posting older ways of hiding the ActionBar here is the proper way of implementing it within styles for AppCompat support library. Which I highly suggest moving toward if you haven't already.
Simply removing the ActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
If you are using the appcompat support libraries, this is the easiest and recommended way of hiding the ActionBar to make full screen or start implementing to toolbar within your layouts.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Your Toolbar Color-->
<item name="colorPrimary">@color/primary</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/primary_dark</item>
<!-- colorAccent is used as the default value for colorControlActivated,
which is used to tint widgets -->
<item name="colorAccent">@color/accent</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight, and colorSwitchThumbNormal. -->
</style>
Then to change your toolbar color
<android.support.v7.widget.Toolbar
android:id=”@+id/my_awesome_toolbar”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:minHeight=”?attr/actionBarSize”
android:background=”?attr/primary” />
Last note: Your Activity class should extend AppCompatActivity
public class MainActivity extends AppCompatActivity {
<!--Activity Items -->
}
Multiprocessing a for loop?
You can use multiprocessing.Pool
:
from multiprocessing import Pool
class Engine(object):
def __init__(self, parameters):
self.parameters = parameters
def __call__(self, filename):
sci = fits.open(filename + '.fits')
manipulated = manipulate_image(sci, self.parameters)
return manipulated
try:
pool = Pool(8) # on 8 processors
engine = Engine(my_parameters)
data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
pool.close()
pool.join()
What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.
Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.
W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.
Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
Using multiple .cpp files in c++ program?
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h"
to your main.cpp
file.
In second.h
you just declare like this void yourFunction();
In second.cpp
you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h"
also in the beginning of second.cpp
Hope this helps:)
jquery smooth scroll to an anchor?
I hate adding function-named classes to my code, so I put this together instead. If I were to stop using smooth scrolling, I'd feel behooved to go through my code, and delete all the class="scroll" stuff. Using this technique, I can comment out 5 lines of JS, and the entire site updates. :)
<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// Smooth scrolling to element IDs
$('a[href^=#]:not([href=#])').on('click', function () {
var element = $($(this).attr('href'));
$('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
return false;
});
</script>
Requirements:
1. <a>
elements must have an href attribute that begin with #
and be more than just #
2. An element on the page with a matching id
attribute
What it does:
1. The function uses the href value to create the anchorID
object
- In the example, it's $('#contact')
, /about
starts with /
2. HTML
, and BODY
are animated to the top offset of anchorID
- speed = 'normal' ('fast','slow', milliseconds, )
- easing = 'swing' ('linear',etc ... google easing)
3. return false
-- it prevents the browser from showing the hash in the URL
- the script works without it, but it's not as "smooth".
Multiple try codes in one block
Extract (refactor) your statements. And use the magic of and
and or
to decide when to short-circuit.
def a():
try: # a code
except: pass # or raise
else: return True
def b():
try: # b code
except: pass # or raise
else: return True
def c():
try: # c code
except: pass # or raise
else: return True
def d():
try: # d code
except: pass # or raise
else: return True
def main():
try:
a() and b() or c() or d()
except:
pass
js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Update (11/2018):
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
Virtual member call in a constructor
Reasons of the warning are already described, but how would you fix the warning? You have to seal either class or virtual member.
class B
{
protected virtual void Foo() { }
}
class A : B
{
public A()
{
Foo(); // warning here
}
}
You can seal class A:
sealed class A : B
{
public A()
{
Foo(); // no warning
}
}
Or you can seal method Foo:
class A : B
{
public A()
{
Foo(); // no warning
}
protected sealed override void Foo()
{
base.Foo();
}
}
Vim autocomplete for Python
I found a good choice to be coc.nvim with the python language server.
It takes a bit of effort to set up. I got frustrated with jedi-vim, because it would always freeze vim for a bit when completing. coc.nvim doesn't do it because it's asyncronous, meaning that . It also gives you linting for your code. It supports many other languages and is highly configurable.
The python language server uses jedi so you get the same completion as you would get from jedi.
Connection pooling options with JDBC: DBCP vs C3P0
Just got done wasting a day and a half with DBCP. Even though I'm using the latest DBCP release, I ran into exactly the same problems as j pimmel did. I would not recommend DBCP at all, especially it's knack of throwing connections out of the pool when the DB goes away, its inability to reconnect when the DB comes back and its inability to dynamically add connection objects back into the pool (it hangs forever on a post JDBCconnect I/O socket read)
I'm switching over to C3P0 now. I've used that in previous projects and it worked and performed like a charm.
Convert unix time to readable date in pandas dataframe
If you try using:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
and receive an error :
"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"
This means the DATE_FIELD
is not specified in seconds.
In my case, it was milli seconds - EPOCH time
.
The conversion worked using below:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
How can I check if character in a string is a letter? (Python)
I found a good way to do this with using a function and basic code.
This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.
def check(count):
lowercase = 0
uppercase = 0
other = 0
low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
for n in count:
if n in low:
lowercase += 1
elif n in upper:
uppercase += 1
else:
other += 1
print("There are " + str(lowercase) + " lowercase letters.")
print("There are " + str(uppercase) + " uppercase letters.")
print("There are " + str(other) + " other elements to this sentence.")
How to set a Default Route (To an Area) in MVC
Thanks to Aaron for pointing out that it's about locating the views, I misunderstood that.
[UPDATE] I just created a project that sends the user to an Area per default without messing with any of the code or lookup paths:
In global.asax, register as usual:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""} // Parameter defaults,
);
}
in Application_Start()
, make sure to use the following order;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
in you area registration, use
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ShopArea_default",
"{controller}/{action}/{id}",
new { action = "Index", id = "", controller = "MyRoute" },
new { controller = "MyRoute" }
);
}
An example can be found at
http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/
I really hope that this is what you were asking for...
////
I don't think that writing a pseudo ViewEngine
is the best solution in this case. (Lacking reputation, I can't comment). The WebFormsViewEngine
is Area aware and contains AreaViewLocationFormats
which is defined per default as
AreaViewLocationFormats = new[] {
"~/Areas/{2}/Views/{1}/{0}.aspx",
"~/Areas/{2}/Views/{1}/{0}.ascx",
"~/Areas/{2}/Views/Shared/{0}.aspx",
"~/Areas/{2}/Views/Shared/{0}.ascx",
};
I believe you don't adhere to this convention. You posted
public ActionResult ActionY()
{
return View("~/Areas/AreaZ/views/ActionY.aspx");
}
as a working hack, but that should be
return View("~/Areas/AreaZ/views/ControllerX/ActionY.aspx");
IF you don't want to follow the convention, however, you might want to take a short path by either deriving from the WebFormViewEngine
(that is done in MvcContrib, for example) where you can set the lookup paths in the constructor, or -a little hacky- by specifying your convention like this on Application_Start
:
((VirtualPathProviderViewEngine)ViewEngines.Engines[0]).AreaViewLocationFormats = ...;
This should be performed with a little more care, of course, but I think it shows the idea. These fields are public
in VirtualPathProviderViewEngine
in MVC 2 RC.
Is it a good practice to use try-except-else in Python?
What is the reason for the try-except-else to exist?
A try
block allows you to handle an expected error. The except
block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs.
An else
clause will execute if there were no errors, and by not executing that code in the try
block, you avoid catching an unexpected error. Again, catching an unexpected error can hide bugs.
Example
For example:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
else:
return something
The "try, except" suite has two optional clauses, else
and finally
. So it's actually try-except-else-finally
.
else
will evaluate only if there is no exception from the try
block. It allows us to simplify the more complicated code below:
no_error = None
try:
try_this(whatever)
no_error = True
except SomeException as the_exception:
handle(the_exception)
if no_error:
return something
so if we compare an else
to the alternative (which might create bugs) we see that it reduces the lines of code and we can have a more readable, maintainable, and less buggy code-base.
finally
finally
will execute no matter what, even if another line is being evaluated with a return statement.
Broken down with pseudo-code
It might help to break this down, in the smallest possible form that demonstrates all features, with comments. Assume this syntactically correct (but not runnable unless the names are defined) pseudo-code is in a function.
For example:
try:
try_this(whatever)
except SomeException as the_exception:
handle_SomeException(the_exception)
# Handle a instance of SomeException or a subclass of it.
except Exception as the_exception:
generic_handle(the_exception)
# Handle any other exception that inherits from Exception
# - doesn't include GeneratorExit, KeyboardInterrupt, SystemExit
# Avoid bare `except:`
else: # there was no exception whatsoever
return something()
# if no exception, the "something()" gets evaluated,
# but the return will not be executed due to the return in the
# finally block below.
finally:
# this block will execute no matter what, even if no exception,
# after "something" is eval'd but before that value is returned
# but even if there is an exception.
# a return here will hijack the return functionality. e.g.:
return True # hijacks the return in the else clause above
It is true that we could include the code in the else
block in the try
block instead, where it would run if there were no exceptions, but what if that code itself raises an exception of the kind we're catching? Leaving it in the try
block would hide that bug.
We want to minimize lines of code in the try
block to avoid catching exceptions we did not expect, under the principle that if our code fails, we want it to fail loudly. This is a best practice.
It is my understanding that exceptions are not errors
In Python, most exceptions are errors.
We can view the exception hierarchy by using pydoc. For example, in Python 2:
$ python -m pydoc exceptions
or Python 3:
$ python -m pydoc builtins
Will give us the hierarchy. We can see that most kinds of Exception
are errors, although Python uses some of them for things like ending for
loops (StopIteration
). This is Python 3's hierarchy:
BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
ModuleNotFoundError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
RecursionError
StopAsyncIteration
StopIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
A commenter asked:
Say you have a method which pings an external API and you want to handle the exception at a class outside the API wrapper, do you simply return e from the method under the except clause where e is the exception object?
No, you don't return the exception, just reraise it with a bare raise
to preserve the stacktrace.
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
raise
Or, in Python 3, you can raise a new exception and preserve the backtrace with exception chaining:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
raise DifferentException from the_exception
I elaborate in my answer here.
Please add a @Pipe/@Directive/@Component annotation. Error
Another solution is below way and It was my fault that when happened I put HomeService
in declaration section in app.module.ts
whereas I should put HomeService
in Providers section that as you see below HomeService
in declaration:[]
is not in a correct place and HomeService
is in Providers :[]
section in a correct place that should be.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { HomeService } from './components/home/home.service';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
HomeService // You will get error here
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule
],
providers: [
HomeService // Right place to set HomeService
],
bootstrap: [AppComponent]
})
export class AppModule { }
hope this help you.
How to apply filters to *ngFor?
Based on the very elegant callback pipe solution proposed above, it is possible to generalize it a bit further by allowing additional filter parameters to be passed along. We then have :
callback.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'callback',
pure: false
})
export class CallbackPipe implements PipeTransform {
transform(items: any[], callback: (item: any, callbackArgs?: any[]) => boolean, callbackArgs?: any[]): any {
if (!items || !callback) {
return items;
}
return items.filter(item => callback(item, callbackArgs));
}
}
component
filterSomething(something: Something, filterArgs: any[]) {
const firstArg = filterArgs[0];
const secondArg = filterArgs[1];
...
return <some condition based on something, firstArg, secondArg, etc.>;
}
html
<li *ngFor="let s of somethings | callback : filterSomething : [<whatWillBecomeFirstArg>, <whatWillBecomeSecondArg>, ...]">
{{s.aProperty}}
</li>
Open a workbook using FileDialog and manipulate it in Excel VBA
Thankyou Frank.i got the idea.
Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
How to pretty print XML from the command line?
xmllint --format yourxmlfile.xml
xmllint is a command line XML tool and is included in libxml2
(http://xmlsoft.org/).
================================================
Note: If you don't have libxml2
installed you can install it by doing the following:
CentOS
cd /tmp
wget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
tar xzf libxml2-2.8.0.tar.gz
cd libxml2-2.8.0/
./configure
make
sudo make install
cd
Ubuntu
sudo apt-get install libxml2-utils
Cygwin
apt-cyg install libxml2
MacOS
To install this on MacOS with Homebrew just do:
brew install libxml2
Git
Also available on Git if you want the code:
git clone git://git.gnome.org/libxml2
Integrating Dropzone.js into existing HTML form with other fields
Further to what sqram was saying, Dropzone has an additional undocumented option, "hiddenInputContainer". All you have to do is set this option to the selector of the form you want the hidden file field to be appended to. And voila! The ".dz-hidden-input" file field that Dropzone normally adds to the body magically moves into your form. No altering the Dropzone source code.
Now while this works to move the Dropzone file field into your form, the field has no name. So you will need to add:
_this.hiddenFileInput.setAttribute("name", "field_name[]");
to dropzone.js after this line:
_this.hiddenFileInput = document.createElement("input");
around line 547.
How to append to a file in Node?
Your code using createWriteStream creates a file descriptor for every write. log.end is better because it asks node to close immediately after the write.
var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {flags: 'a'});
// use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
logStream.write('Initial line...');
logStream.end('this is the end line');
pyplot scatter plot marker size
You can use markersize to specify the size of the circle in plot method
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(x1, 'bo', markersize=20) # blue circle with size 10
plt.plot(x2, 'ro', ms=10,) # ms is just an alias for markersize
plt.show()
From here
Mergesort with Python
#here is my answer using two function one for merge and another for divide and
#conquer
l=int(input('enter range len'))
c=list(range(l,0,-1))
print('list before sorting is',c)
def mergesort1(c,l,r):
i,j,k=0,0,0
while (i<len(l))&(j<len(r)):
if l[i]<r[j]:
c[k]=l[i]
i +=1
else:
c[k]=r[j]
j +=1
k +=1
while i<len(l):
c[k]=l[i]
i+=1
k+=1
while j<len(r):
c[k]=r[j]
j+=1
k+=1
return c
def mergesort(c):
if len(c)<2:
return c
else:
l=c[0:(len(c)//2)]
r=c[len(c)//2:len(c)]
mergesort(l)
mergesort(r)
return mergesort1(c,l,r)
Play audio file from the assets directory
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
Your version would work if you had only one file in the assets
directory. The asset directory contents are not actually 'real files'
on disk. All of them are put together one after another. So, if you do
not specify where to start and how many bytes to read, the player will
read up to the end (that is, will keep playing all the files in assets
directory)
How to change owner of PostgreSql database?
Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.
IMPORTANT EDIT!
Never use REASSIGN OWNED
when the original role is postgres
, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)
First, connect to admin database and update DB ownership:
psql
postgres=# REASSIGN OWNED BY old_name TO new_name;
This is a global equivalent of ALTER DATABASE
command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.
The next step is to update tables ownership for each database:
psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;
This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.
pandas: find percentile stats of a given column
You can use the pandas.DataFrame.quantile() function, as shown below.
import pandas as pd
import random
A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]
df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
# field_A field_B
# 0 90 72
# 1 63 84
# 2 11 74
# 3 61 66
# 4 78 80
# 5 67 75
# 6 89 47
# 7 12 22
# 8 43 5
# 9 30 64
df.field_A.mean() # Same as df['field_A'].mean()
# 54.399999999999999
df.field_A.median()
# 62.0
# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.
df.field_A.quantile(0.1) # 10th percentile
# 11.9
df.field_A.quantile(0.5) # same as median
# 62.0
df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001
Styling mat-select in Angular Material
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
Demo
Angular Material uses
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style
down through the child component tree into all the child component
views. The /deep/ combinator works to any depth of nested components,
and it applies to both the view children and content children of the
component.
Use /deep/, >>> and ::ng-deep only with emulated view encapsulation.
Emulated is the default and most commonly used view encapsulation. For
more information, see the Controlling view encapsulation section. The
shadow-piercing descendant combinator is deprecated and support is
being removed from major browsers and tools. As such we plan to drop
support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until
then ::ng-deep should be preferred for a broader compatibility with
the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
DEMO
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and
don't affect the rest of the application.
To control how this encapsulation happens on a per component basis,
you can set the view encapsulation mode in the component metadata.
Choose from the following modes:
....
None means that Angular does no view encapsulation. Angular adds the
CSS to the global styles. The scoping rules, isolations, and
protections discussed earlier don't apply. This is essentially the
same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component.
So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
DEMO
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
DEMO
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
DEMO
Golang read request body
Inspecting and mocking request body
When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser
as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.
One option is to read the whole body using ioutil.ReadAll()
, which gives you the body as a byte slice.
You may use bytes.NewBuffer()
to obtain an io.Reader
from a byte slice.
The last missing piece is to make the io.Reader
an io.ReadCloser
, because bytes.Buffer
does not have a Close()
method. For this you may use ioutil.NopCloser()
which wraps an io.Reader
, and returns an io.ReadCloser
, whose added Close()
method will be a no-op (does nothing).
Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.
Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!
Inspecting / modifying response body
If you also want to read the response body, then you have to wrap the http.ResponseWriter
you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).
Here's a simple ResponseWriter
wrapper, which just caches the data, so it'll be available after the subsequent handler returns:
type MyResponseWriter struct {
http.ResponseWriter
buf *bytes.Buffer
}
func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
return mrw.buf.Write(p)
}
Note that MyResponseWriter.Write()
just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write()
method) and write the data immediately to the wrapped / embedded ResponseWriter
. You may even modify the data. You have full control.
Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.
Full example
Putting the pieces together, here's a full working example:
func loginmw(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
// Work / inspect body. You may even modify it!
// And now set a new body, which will simulate the same data we read:
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
// Create a response wrapper:
mrw := &MyResponseWriter{
ResponseWriter: w,
buf: &bytes.Buffer{},
}
// Call next handler, passing the response wrapper:
handler.ServeHTTP(mrw, r)
// Now inspect response, and finally send it out:
// (You can also modify it before sending it out!)
if _, err := io.Copy(w, mrw.buf); err != nil {
log.Printf("Failed to send out response: %v", err)
}
})
}
send Content-Type: application/json post with node.js
As the official documentation says:
body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.
When sending JSON you just have to put it in body of the option.
var options = {
uri: 'https://myurl.com',
method: 'POST',
json: true,
body: {'my_date' : 'json'}
}
request(options, myCallback)
What is the difference between 0.0.0.0, 127.0.0.1 and localhost?
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
Java Command line arguments
public class YourClass {
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("a")){
//...
}
}
}
APT command line interface-like yes/no input?
How about this:
def yes(prompt = 'Please enter Yes/No: '):
while True:
try:
i = raw_input(prompt)
except KeyboardInterrupt:
return False
if i.lower() in ('yes','y'): return True
elif i.lower() in ('no','n'): return False
Using VBA code, how to export Excel worksheets as image in Excel 2003?
Solution without charts
Function SelectionToPicture(nome)
'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"
'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height
With ThisWorkbook.ActiveSheet
.Activate
Dim chtObj As ChartObject
Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
chtObj.Name = "TemporaryPictureChart"
'resize obj to picture size
chtObj.Width = w
chtObj.Height = h
ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
ActiveChart.Paste
ActiveChart.Export FileName:=FName, FilterName:="jpg"
chtObj.Delete
End With
End Function
How to rename a single column in a data.frame?
I find that the most convenient way to rename a single column is using dplyr::rename_at
:
library(dplyr)
cars %>% rename_at("speed",~"new") %>% head
cars %>% rename_at(vars(speed),~"new") %>% head
cars %>% rename_at(1,~"new") %>% head
# new dist
# 1 4 2
# 2 4 10
# 3 7 4
# 4 7 22
# 5 8 16
# 6 9 10
- works well in pipe chaines
- convenient when names are stored in variables
- works with a name or an column index
- clear and compact
Verify a certificate chain using openssl verify
You can easily verify a certificate chain with openssl. The fullchain will include the CA cert so you should see details about the CA and the certificate itself.
openssl x509 -in fullchain.pem -text -noout
Compute row average in pandas
If you are looking to average column wise. Try this,
df.drop('Region', axis=1).apply(lambda x: x.mean())
# it drops the Region column
df.drop('Region', axis=1,inplace=True)
How can I view the source code for a function?
For non-primitive functions, R base includes a function called body()
that returns the body of function. For instance the source of the print.Date()
function can be viewed:
body(print.Date)
will produce this:
{
if (is.null(max))
max <- getOption("max.print", 9999L)
if (max < length(x)) {
print(format(x[seq_len(max)]), max = max, ...)
cat(" [ reached getOption(\"max.print\") -- omitted",
length(x) - max, "entries ]\n")
}
else print(format(x), max = max, ...)
invisible(x)
}
If you are working in a script and want the function code as a character vector, you can get it.
capture.output(print(body(print.Date)))
will get you:
[1] "{"
[2] " if (is.null(max)) "
[3] " max <- getOption(\"max.print\", 9999L)"
[4] " if (max < length(x)) {"
[5] " print(format(x[seq_len(max)]), max = max, ...)"
[6] " cat(\" [ reached getOption(\\\"max.print\\\") -- omitted\", "
[7] " length(x) - max, \"entries ]\\n\")"
[8] " }"
[9] " else print(format(x), max = max, ...)"
[10] " invisible(x)"
[11] "}"
Why would I want to do such a thing? I was creating a custom S3 object (x
, where class(x) = "foo"
) based on a list. One of the list members (named "fun") was a function and I wanted print.foo()
to display the function source code, indented. So I ended up with the following snippet in print.foo()
:
sourceVector = capture.output(print(body(x[["fun"]])))
cat(paste0(" ", sourceVector, "\n"))
which indents and displays the code associated with x[["fun"]]
.
Edit 2020-12-31
A less circuitous way to get the same character
vector of source code is:
sourceVector = deparse(body(x$fun))
How to use a keypress event in AngularJS?
Another simple alternative:
<input ng-model="edItem" type="text"
ng-keypress="($event.which === 13)?foo(edItem):0"/>
And the ng-ui alternative:
<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>
How do I escape only single quotes?
If you want to escape characters with a \
, you have addcslashes()
. For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape '
, "
, \
, and nul
(the byte null), you can use addslashes()
:
echo addslashes($value);
Get text from pressed button
If you're sure that the OnClickListener instance is applied to a Button, then you could just cast the received view to a Button and get the text:
public void onClick(View view){
Button b = (Button)view;
String text = b.getText().toString();
}
How to get my Android device Internal Download Folder path
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
Can git undo a checkout of unstaged files
Unfortunately your changes are lost. Your private modifications are simply overwritten.
Unless you did git stash
prior making checkout...
Take it from the brighter side: you can now implement things even better ;)
How to add a filter class in Spring Boot?
I saw a lot of answers here but I didn't try any of them. I've just created the filter as in the following code.
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/Admin")
@Configuration
public class AdminFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("happened");
}
@Override
public void destroy() {
}
}
And leaved the remaining Spring Boot application as it was.
How to iterate through SparseArray?
The answer is no because SparseArray
doesn't provide it. As pst
put it, this thing doesn't provide any interfaces.
You could loop from 0 - size()
and skip values that return null
, but that is about it.
As I state in my comment, if you need to iterate use a Map
instead of a SparseArray
. For example, use a TreeMap
which iterates in order by the key.
TreeMap<Integer, MyType>
Git command to checkout any branch and overwrite local changes
Couple of points:
- I believe
git stash
+ git stash drop
could be replaced with git reset --hard
... or, even shorter, add -f
to checkout
command:
git checkout -f -b $branch
That will discard any local changes, just as if git reset --hard
was used prior to checkout.
As for the main question:
instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch
, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.
Elegant way to report missing values in a data.frame
I think the Amelia library does a nice job in handling missing data also includes a map for visualizing the missing rows.
install.packages("Amelia")
library(Amelia)
missmap(airquality)
You can also run the following code will return the logic values of na
row.has.na <- apply(training, 1, function(x){any(is.na(x))})
Program "make" not found in PATH
You may try altering toolchain in case if for some reason you can't use gcc. Open Properties for your project (by right clicking on your project name in the Project Explorer), then C/C++ Build > Tool Chain Editor. You can change the current builder there from GNU Make Builder to CDT Internal Builder or whatever compatible you have.
How to print variables in Perl
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
How to get DataGridView cell value in messagebox?
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
Custom Input[type="submit"] style not working with jquerymobile button
I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important
property.
HTML
<a href="#" class="selected_btn" data-role="button">Button name</a>
CSS
.selected_btn
{
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red !important;
background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}
Here is the demo
PHP call Class method / function
To answer your question, the current method would be to create the object then call the method:
$functions = new Functions();
$var = $functions->filter($_GET['params']);
Another way would be to make the method static
since the class has no private data to rely on:
public static function filter($data){
This can then be called like so:
$var = Functions::filter($_GET['params']);
Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions
and the public
in the method. This can then be called like you tried:
$var = filter($_GET['params']);