Converting a string to a date in a cell
I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5)))
where XX
is the cell in reference.
I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST
and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.
Excel Reference To Current Cell
Full credit to the top answer by @rick-teachey, but you can extend that approach to work with Conditional Formatting. So that this answer is complete, I will duplicate Rick's answer in summary form and then extend it:
- Select cell
A1
in any worksheet.
- Create a Named Range called
THIS
and set the Refers to:
to =!A1
.
Attempting to use THIS
in Conditional Formatting formulas will result in the error:
You may not use references to other workbooks for Conditional Formatting criteria
If you want THIS
to work in Conditional Formatting formulas:
- Create another Named Range called
THIS_CF
and set the Refers to:
to =THIS
.
You can now use THIS_CF
to refer to the current cell in Conditional Formatting formulas.
You can also use this approach to create other relative Named Ranges, such as THIS_COLUMN
, THIS_ROW
, ROW_ABOVE
, COLUMN_LEFT
, etc.
How to import data from one sheet to another
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
![VLOOKUP example](https://i.stack.imgur.com/PidBS.png)
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
Last non-empty cell in a column
I think the response from W5ALIVE is closest to what I use to find the last row of data in a column. Assuming I am looking for the last row with data in Column A, though, I would use the following for the more generic lookup:
=MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0))
The first MATCH will find the last text cell and the second MATCH finds the last numeric cell. The IFERROR function returns zero if the first MATCH finds all numeric cells or if the second match finds all text cells.
Basically this is a slight variation of W5ALIVE's mixed text and number solution.
In testing the timing, this was significantly quicker than the equivalent LOOKUP variations.
To return the actual value of that last cell, I prefer to use indirect cell referencing like this:
=INDIRECT("A"&MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0)))
The method offered by sancho.s is perhaps a cleaner option, but I would modify the portion that finds the row number to this:
=INDEX(MAX((A:A<>"")*(ROW(A:A))),1)
the only difference being that the ",1" returns the first value while the ",0" returns the entire array of values (all but one of which are not needed). I still tend to prefer addressing the cell to the index function there, in other words, returning the cell value with:
=INDIRECT("A"&INDEX(MAX((A:A<>"")*(ROW(A:A))),1))
Great thread!
Excel function to get first word from sentence in other cell
Generic solution extracting the first "n" words of refcell string into a new string of "x" number of characters
=LEFT(SUBSTITUTE(***refcell***&" "," ",REPT(" ",***x***),***n***),***x***)
Assuming A1 has text string to extract, the 1st word extracted to a 15 character result
=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",15),1),15)
This would result in "Toronto" being returned to a 15 character string. 1st 2 words extracted to a 30 character result
=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",30),2),30)
would result in "Toronto is" being returned to a 30 character string
Get values from other sheet using VBA
Try
ThisWorkbook.Sheets("name of sheet 2").Range("A1")
to access a range in sheet 2 independently of where your code is or which sheet is currently active. To make sheet 2 the active sheet, try
ThisWorkbook.Sheets("name of sheet 2").Activate
If you just need the sum of a row in a different sheet, there is no need for using VBA at all. Enter a formula like this in sheet 1:
=SUM([Name-Of-Sheet2]!A1:D1)
I want to compare two lists in different worksheets in Excel to locate any duplicates
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
![Conditional formatting for Excel 2010](https://i.stack.imgur.com/hVmcF.jpg)
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
![Conditional formatting using helper column for rule](https://i.stack.imgur.com/Rtuig.jpg)
Excel formula to get cell color
Color is not data.
The Get.cell technique has flaws.
- It does not update as soon as the cell color changes, but only when
the cell (or the sheet) is recalculated.
- It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.
![enter image description here](https://i.stack.imgur.com/2n8Xt.png)
That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.
Again: Color is not data.
If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.
How to find the first and second maximum number?
OK I found it.
=LARGE($E$4:$E$9;A12)
=large(array, k)
Array Required. The array or range of data for which you want to determine the k-th largest value.
K Required. The position (from the largest) in the array or cell range of data to return.
How to show current user name in a cell?
if you don't want to create a UDF in VBA or you can't, this could be an alternative.
=Cell("Filename",A1)
this will give you the full file name, and from this you could get the user name with something like this:
=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)
This Formula runs only from a workbook saved earlier.
You must start from 4th position because of the first slash from the drive.
`IF` statement with 3 possible answers each based on 3 different ranges
Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0)))
. This simulates the ELSE-IF
operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF
formula is the value to use if the condition evaluates to true
. You can't chain conditions in that manner.
WorksheetFunction.CountA - not working post upgrade to Office 2010
I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:
- It appears you are relying on VBA to determine variable types and modify accordingly. This can get confusing if you are not careful, because VBA may assign a variable type you did not intend. In your code, a type of
Range
should be assigned to myRange
. Since a Range
type is an object in VBA it needs to be Set
, like this: Set myRange = Range("A:A")
- Your use of the worksheet function
CountA()
should be called with .WorksheetFunction
If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim
statements, as I have done below.
The following code works for me in 2010. Hopefully it works for you too:
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
Good Luck.
Self-reference for cell, column and row in worksheet functions
I was looking for a solution to this and used the indirect one found on this page initially, but I found it quite long and clunky for what I was trying to do. After a bit of research, I found a more elegant solution (to my problem) using R1C1 notation - I think you can't mix different notation styles without using VBA though.
Depending on what you're trying to do with the self referenced cell, something like this example should get a cell to reference itself where the cell is F13:
Range("F13").FormulaR1C1 = "RC"
And you can then reference cells in relative positions to that cell such as - where your cell is F13 and you need to reference G12 from it.
Range("F13").FormulaR1C1 = "R[-1]C[1]"
You're essentially telling Excel to find F13 and then move down 1 row and up one column from that.
How this fit into my project was to apply a vlookup across a range where the lookup value was relative to each cell in the range without having to specify each lookup cell separately:
Sub Code()
Dim Range1 As Range
Set Range1 = Range("B18:B23")
Range1.Locked = False
Range1.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],DATABYCODE,2,FALSE),"""")"
Range1.Locked = True
End Sub
My lookup value is the cell to the left of each cell (column -1) in my DIM'd range and DATABYCODE is the named range I'm looking up against.
Hope that makes a little sense? Thought it was worth throwing into the mix as another way to approach the problem.
Case Function Equivalent in Excel
Without reference to the original problem (which I suspect is long since solved), I very recently discovered a neat trick that makes the Choose function work exactly like a select case
statement without any need to modify data. There's only one catch: only one of your choose conditions can be true at any one time.
The syntax is as follows:
CHOOSE(
(1 * (CONDITION_1)) + (2 * (CONDITION_2)) + ... + (N * (CONDITION_N)),
RESULT_1, RESULT_2, ... , RESULT_N
)
On the assumption that only one of the conditions 1 to N will be true, everything else is 0, meaning the numeric value will correspond to the appropriate result.
If you are not 100% certain that all conditions are mutually exclusive, you might prefer something like:
CHOOSE(
(1 * TEST1) + (2 * TEST2) + (4 * TEST3) + (8 * TEST4) ... (2^N * TESTN)
OUT1, OUT2, , OUT3, , , , OUT4 , , <LOTS OF COMMAS> , OUT5
)
That said, if Excel has an upper limit on the number of arguments a function can take, you'd hit it pretty quickly.
Honestly, can't believe it's taken me years to work it out, but I haven't seen it before, so figured I'd leave it here to help others.
EDIT: Per comment below from @aTrusty:
Silly numbers of commas can be eliminated (and as a result, the choose statement would work for up to 254 cases) by using a formula of the following form:
CHOOSE(
1 + LOG(1 + (2*TEST1) + (4*TEST2) + (8*TEST3) + (16*TEST4),2),
OTHERWISE, RESULT1, RESULT2, RESULT3, RESULT4
)
Note the second argument to the LOG
clause, which puts it in base 2 and makes the whole thing work.
Edit: Per David's answer, there's now an actual switch statement if you're lucky enough to be working on office 2016. Aside from difficulty in reading, this also means you get the efficiency of switch, not just the behaviour!
Filter an array using a formula (without VBA)
Today, in Office 365, Excel has so called 'array functions'.
The filter
function does exactly what you want. No need to use CTRL+SHIFT+ENTER
anymore, a simple enter
will suffice.
In Office 365, your problem would be simply solved by using:
=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)
Have Excel formulas that return 0, make the result blank
I noticed this issue recently and it is frustrating that excel changes a blank string into a 0. I do not think that a formula should solve this issue because adding more logic to a complex formula may be cumbersome and might even end up breaking the original formula. I have two non formula options below.
If you want to keep the formulas in the cells and have them return 0 instead of "" use the following Click Path:
- File
- Options
- Advanced
Scroll to "Display options for this worksheet:"
- Deselect "Show a zero in cells that have zero value"
I also want to give a simple manual solution if you want to change a value (as opposed to a formula) from 0 to a blank string. This solution is better than Find and Replace because it will not replace a number like 101 with 11.
- Select all of your data
- On the data tab, click the filter logo
![The Filter Logo itself](https://i.stack.imgur.com/KRtp1.png)
- Click on the pick list of the column with the undesired 0(s) to select only rows with the value "0" (Make sure to only clear the contents of cells containing contents with the exact value 0!)
![enter image description here](https://i.stack.imgur.com/bxR5w.png)
- Select the data (which is only 0s), right click and select clear contents
The other data will remain if you used the filter properly and the back button is always there if something goes wrong. I understand option 2 is very manual and "unelegant" but it does successfully convert a 0 into a blank string and it may relieve a frustrated individual who does not want to use an if statement.
I personally learned something exploring this (very dry) excel issue today and I am personally using these methods moving forward. A quick macro of option 2 could be a good option if this is a frequent task for an intermediate excel user.
Convert date field into text in Excel
You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this
="Today is "&TEXT(A1,"dd-mm-yyyy")
You can change the "dd-mm-yyyy" part as required
Concatenating date with a string in Excel
This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.
You'll have to do:
= A1 & TEXT(A2, "mm/dd/yyyy")
The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.
Now, you could have a user-defined function:
public function AsDisplayed(byval c as range) as string
AsDisplayed = c.Text
end function
and then
= A1 & AsDisplayed(A2)
But then there's a bug (feature?) in Excel because of which the .Text
property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE
instead of what they should.
That is, it's bad either way.
How do I get the last character of a string using an Excel function?
Looks like the answer above was a little incomplete try the following:-
=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))
Obviously, this is for cell A2...
What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.
After the length has been determined and the portion of that which is required - then the Right command will display the information you need.
This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...
=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)
iterating quickly through list of tuples
I wonder whether the below method is what you want.
You can use defaultdict
.
>>> from collections import defaultdict
>>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> sorted(d.items())
[('blue', [2, 4, 4]), ('red', [1, 3, 1])]
How can I install Apache Ant on Mac OS X?
Ant is already installed on some older versions of Mac OS X, so you should run ant -version
to test if it is installed before attempting to install it.
If it is not already installed, then your best bet is to install Homebrew (brew install ant
) or MacPorts (sudo port install apache-ant
), and use those tools to install Apache Ant.
Alternatively, though I would highly advise using Homebrew or MacPorts instead, you can install Apache Ant manually. To do so, you would need to:
- Decompress the .tar.gz file.
- Optionally put it somewhere.
- Put the "bin" subdirectory in your path.
The commands that you would need, assuming apache-ant-1.8.1-bin.tar.gz
(replace 1.8.1 with the actual version) were still in your Downloads directory, would be the following (explanatory comments included):
cd ~/Downloads # Let's get into your downloads folder.
tar -xvzf apache-ant-1.8.1-bin.tar.gz # Extract the folder
sudo mkdir -p /usr/local # Ensure that /usr/local exists
sudo cp -rf apache-ant-1.8.1-bin /usr/local/apache-ant # Copy it into /usr/local
# Add the new version of Ant to current terminal session
export PATH=/usr/local/apache-ant/bin:"$PATH"
# Add the new version of Ant to future terminal sessions
echo 'export PATH=/usr/local/apache-ant/bin:"$PATH"' >> ~/.profile
# Verify new version of ant
ant -version
CROSS JOIN vs INNER JOIN in SQL
Cross join and inner join are the same with the only difference that in inner join we booleanly filter some of the outcomes of the cartesian product
table1
x--------------------------------------x
| fieldA | fieldB | fieldC |
x----------|-------------|-------------x
| A | B | option1 |
| A | B1 | option2 |
x--------------------------------------x
table2
x--------------------------------------x
| fieldA | fieldB | fieldC |
x----------|-------------|-------------x
| A | B | optionB1 |
| A1 | B1 | optionB2 |
x--------------------------------------x
cross join
A,B,option1,A,B,optionB1
A,B,option1,A1,B1,optionB2
A,B1,option2,A,B,optionB1
A,B1,option2,A1,B1,optionB2
inner join on field1 (only with the value is the same in both tables)
A,B,option1,A,B,optionB1
A,B1,option2,A,B,optionB1
inner join on field1
A,B,option1,A,B,optionB1
It is on design of our data where we decide that there is only one case of the field we are using for the join. Join only cross join both tables and get only the lines accomplishing special boolean expression.
Note that if the fields we are doing our Joins on would be null in both tables we would pass the filter. It is up to us or the database manufacturer to add extra rules to avoid or permit nulls. Adhering to the basics it is just a cross join followed by a filter.
What are the differences between 'call-template' and 'apply-templates' in XSL?
<xsl:call-template>
is a close equivalent to calling a function in a traditional programming language.
You can define functions in XSLT, like this simple one that outputs a string.
<xsl:template name="dosomething">
<xsl:text>A function that does something</xsl:text>
</xsl:template>
This function can be called via <xsl:call-template name="dosomething">
.
<xsl:apply-templates>
is a little different and in it is the real power of XSLT: It takes any number of XML nodes (whatever you define in the select
attribute), iterates them (this is important: apply-templates works like a loop!) and finds matching templates for them:
<!-- sample XML snippet -->
<xml>
<foo /><bar /><baz />
</xml>
<!-- sample XSLT snippet -->
<xsl:template match="xml">
<xsl:apply-templates select="*" /> <!-- three nodes selected here -->
</xsl:template>
<xsl:template match="foo"> <!-- will be called once -->
<xsl:text>foo element encountered</xsl:text>
</xsl:template>
<xsl:template match="*"> <!-- will be called twice -->
<xsl:text>other element countered</xsl:text>
</xsl:template>
This way you give up a little control to the XSLT processor - not you decide where the program flow goes, but the processor does by finding the most appropriate match for the node it's currently processing.
If multiple templates can match a node, the one with the more specific match expression wins. If more than one matching template with the same specificity exist, the one declared last wins.
You can concentrate more on developing templates and need less time to do "plumbing". Your programs will become more powerful and modularized, less deeply nested and faster (as XSLT processors are optimized for template matching).
A concept to understand with XSLT is that of the "current node". With <xsl:apply-templates>
the current node moves on with every iteration, whereas <xsl:call-template>
does not change the current node. I.e. the .
within a called template refers to the same node as the .
in the calling template. This is not the case with apply-templates.
This is the basic difference. There are some other aspects of templates that affect their behavior: Their mode
and priority
, the fact that templates can have both a name
and a match
. It also has an impact whether the template has been imported (<xsl:import>
) or not. These are advanced uses and you can deal with them when you get there.
VB.NET Inputbox - How to identify when the Cancel Button is pressed?
I know this is a very old topic, but the correct answer is still not here.
The accepted answer works with a space, but the user can remove this space - so this answer is not reliable.
The answer of Georg works, but is needlessly complex.
To test if the user pressed cancel, just use the following code:
Dim Answer As String = InputBox("Question")
If String.ReferenceEquals(Answer, String.Empty) Then
'User pressed cancel
Else if Answer = "" Then
'User pressed ok with an empty string in the box
Else
'User gave an answer
Plot multiple boxplot in one graph
ggplot version of the lattice plot:
library(reshape2)
library(ggplot2)
df <- read.csv("TestData.csv", header=T)
df.m <- melt(df, id.var = "Label")
ggplot(data = df.m, aes(x=Label, y=value)) +
geom_boxplot() + facet_wrap(~variable,ncol = 4)
Plot:
![enter image description here](https://i.stack.imgur.com/vlwYV.png)
Reading Excel file using node.js
Useful link
https://ciphertrick.com/read-excel-files-convert-json-node-js/
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var xlstojson = require("xls-to-json-lc");
var xlsxtojson = require("xlsx-to-json-lc");
app.use(bodyParser.json());
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage,
fileFilter : function(req, file, callback) { //file filter
if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
}
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
var exceltojson;
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
/** Multer gives us file info in req.file object */
if(!req.file){
res.json({error_code:1,err_desc:"No file passed"});
return;
}
/** Check the extension of the incoming file and
* use the appropriate module
*/
if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson({
input: req.file.path,
output: null, //since we don't need output.json
lowerCaseHeaders:true
}, function(err,result){
if(err) {
return res.json({error_code:1,err_desc:err, data: null});
}
res.json({error_code:0,err_desc:null, data: result});
});
} catch (e){
res.json({error_code:1,err_desc:"Corupted excel file"});
}
})
});
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.listen('3000', function(){
console.log('running on 3000...');
});
How does Git handle symbolic links?
Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
Get first and last date of current month with JavaScript or jQuery
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
EDIT
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
How to display 3 buttons on the same line in css
The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc.
The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.
Splitting a string into chunks of a certain size
This is based on @dove solution but implemented as an extension method.
Benefits:
- Extension method
- Covers corner cases
- Splits string with any chars: numbers, letters, other symbols
Code
public static class EnumerableEx
{
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
}
}
}
Usage
var result = "bobjoecat".SplitBy(3); // bob, joe, cat
Unit tests removed for brevity (see previous revision)
How to check the input is an integer or not in Java?
If you are getting the user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
If you are not, you'll have to convert it to int
and catch a NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}
How to convert string to XML using C#
string test = "<body><head>test header</head></body>";
XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);
XmlNodeList elemlist = xmltest.GetElementsByTagName("head");
string result = elemlist[0].InnerXml;
//result -> "test header"
How do I set a program to launch at startup
You can do this with the win32 class in the Microsoft namespace
using Microsoft.Win32;
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
}
Test if a variable is a list or tuple
Go ahead and use isinstance
if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for str
or unicode
like so:
import types
isinstance(var, types.StringTypes)
N.B. Don't mistake types.StringType
for types.StringTypes
. The latter incorporates str
and unicode
objects.
The types
module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str
and unicode
, like this:
isinstance(var, (str, unicode)):
Edit:
Better still is:
isinstance(var, basestring)
End edit
After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions.
See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo.
Convert Enum to String
Simple: enum names into a List:
List<String> NameList = Enum.GetNames(typeof(YourEnumName)).Cast<string>().ToList()
Two arrays in foreach loop
Your code like this is incorrect as foreach only for single array:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach( $codes as $code and $names as $name ) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Named parameters in JDBC
Vanilla JDBC only supports named parameters in a CallableStatement
(e.g. setString("name", name)
), and even then, I suspect the underlying stored procedure implementation has to support it.
An example of how to use named parameters:
//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
+ "if @id is not null "
+ "select * from sysobjects where id = @id "
+ "else if @name is not null "
+ "select * from sysobjects where name = @name "
+ " end");
stmt.execute();
//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
Counting Chars in EditText Changed Listener
little few change in your code :
TextView tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
tv.setText(String.valueOf(s.toString().length()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
How to plot two histograms together in R?
Plotly's R API might be useful for you. The graph below is here.
library(plotly)
#add username and key
p <- plotly(username="Username", key="API_KEY")
#generate data
x0 = rnorm(500)
x1 = rnorm(500)+1
#arrange your graph
data0 = list(x=x0,
name = "Carrots",
type='histogramx',
opacity = 0.8)
data1 = list(x=x1,
name = "Cukes",
type='histogramx',
opacity = 0.8)
#specify type as 'overlay'
layout <- list(barmode='overlay',
plot_bgcolor = 'rgba(249,249,251,.85)')
#format response, and use 'browseURL' to open graph tab in your browser.
response = p$plotly(data0, data1, kwargs=list(layout=layout))
url = response$url
filename = response$filename
browseURL(response$url)
Full disclosure: I'm on the team.
![Graph](https://i.stack.imgur.com/G1CQZ.png)
When should we use Observer and Observable?
You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.
Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.
The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.
How can I use jQuery to make an input readonly?
Use this example to make text box ReadOnly or Not.
<input type="textbox" class="txt" id="txt"/>
<input type="button" class="Btn_readOnly" value="Readonly" />
<input type="button" class="Btn_notreadOnly" value="Not Readonly" />
<script>
$(document).ready(function(){
('.Btn_readOnly').click(function(){
$("#txt").prop("readonly", true);
});
('.Btn_notreadOnly').click(function(){
$("#txt").prop("readonly", false);
});
});
</script>
SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"
ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused
When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.
The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
Difference Between ViewResult() and ActionResult()
ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
How to check if ZooKeeper is running or up from command prompt?
echo stat | nc localhost 2181 | grep Mode
echo srvr | nc localhost 2181 | grep Mode #(From 3.3.0 onwards)
Above will work in whichever modes Zookeeper is running (standalone or embedded).
Another way
If zookeeper is running in standalone mode, its a JVM process. so -
jps | grep Quorum
will display list of jvm processes; something like this for zookeeper with process ID
HQuorumPeer
How to delete object from array inside foreach loop?
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
Make function wait until element exists
Is better to relay in requestAnimationFrame
than in a setTimeout
. this is my solution in es6 modules and using Promises
.
es6, modules and promises:
// onElementReady.js
const onElementReady = $element => (
new Promise((resolve) => {
const waitForElement = () => {
if ($element) {
resolve($element);
} else {
window.requestAnimationFrame(waitForElement);
}
};
waitForElement();
})
);
export default onElementReady;
// in your app
import onElementReady from './onElementReady';
const $someElement = document.querySelector('.some-className');
onElementReady($someElement)
.then(() => {
// your element is ready
}
plain js and promises
:
var onElementReady = function($element) {
return new Promise((resolve) => {
var waitForElement = function() {
if ($element) {
resolve($element);
} else {
window.requestAnimationFrame(waitForElement);
}
};
waitForElement();
})
};
var $someElement = document.querySelector('.some-className');
onElementReady($someElement)
.then(() => {
// your element is ready
});
c# foreach (property in object)... Is there a simple way of doing this?
I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.
private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
{
List<string> returnValue = new List<string>();
try
{
int index = userPrincipalName.IndexOf("@");
string originatingServer = userPrincipalName.Remove(0, index + 1);
string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
SearchResultCollection properties = objSearcher.FindAll();
ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
foreach (string resProperty in resPropertyCollection)
{
returnValue.Add(resProperty);
}
}
catch (Exception ex)
{
returnValue.Add(ex.Message);
throw;
}
return returnValue;
}
Chrome extension id - how to find it
As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".
However, you must click the Developer Mode checkbox at top of Extensions page to see them.
"std::endl" vs "\n"
If you use Qt and endl
, you could accidentally end up using an incorrect endl
which gives you very surprising results. See the following code snippet:
#include <iostream>
#include <QtCore/QtCore>
#include <QtGui/QtGui>
// notice that there is no "using namespace std;"
int main(int argc, char** argv)
{
QApplication qapp(argc,argv);
QMainWindow mw;
mw.show();
std::cout << "Finished Execution!" << endl;
// This prints something similar to: "Finished Execution!67006AB4"
return qapp.exec();
}
Note that I wrote endl
instead of std::endl
(which would have been correct) and apparently there is a endl
function defined in qtextstream.h (which is part of QtCore).
Using "\n"
instead of endl
completely sidesteps any potential namespace issues.
This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.
Find length (size) of an array in jquery
var array=[];
array.push(array); //insert the array value using push methods.
for (var i = 0; i < array.length; i++) {
nameList += "" + array[i] + ""; //display the array value.
}
$("id/class").html(array.length); //find the array length.
DBMS_OUTPUT.PUT_LINE not printing
All of them are concentrating on the for loop but if we use a normal loop then we had to use of the cursor record variable. The following is the modified code
CREATE OR REPLACE PROCEDURE PRINT_ACTOR_QUOTES (id_actor char)
AS
CURSOR quote_recs IS
SELECT a.firstName,a.lastName, m.title, m.year, r.roleName ,q.quotechar from quote q, role r,
rolequote rq, actor a, movie m
where
rq.quoteID = q.quoteID
AND
rq.roleID = r.roleID
AND
r.actorID = a.actorID
AND
r.movieID = m.movieID
AND
a.actorID = id_actor;
recd quote_recs%rowtype;
BEGIN
open quote_recs;
LOOP
fetch quote_recs into recs;
exit when quote_recs%notfound;
DBMS_OUTPUT.PUT_LINE(recd.firstName||recd.lastName);
end loop;
close quote_recs;
END PRINT_ACTOR_QUOTES;
/
Using grep to help subset a data frame in R
You may also use the stringr
package
library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))
You may not use '^'
(starts with) in this case, to obtain the results you need
html select only one checkbox in a group
The Code snippet below demonstrates a simple approach for selecting only one checkbox in a group.
_x000D_
_x000D_
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<h3>Demonstration of Checkbox Toggle</h3>
<p>
<span><b>Letters:</b></span>
A<input type="checkbox" name="A" >
B<input type="checkbox" name="B" >
C<input type="checkbox" name="C" >
D<input type="checkbox" name="D" >
</p>
<p>
<span><b>Numbers:</b></span>
1<input type="checkbox" name="1" >
2<input type="checkbox" name="2" >
3<input type="checkbox" name="3" >
</p>
<p>
<span><b>Birds:</b></span>
Scarlet Ibis<input type="checkbox" name="Scarlet Ibis" >
Cocrico <input type="checkbox" name="Cocrico" >
hummingbird <input type="checkbox" name="hummingbird" >
</p>
</body>
<script>
$(function()
{
function toggle(choices,name)
{
if(choices.includes(name))
{
for( i=0;i<choices.length;i++)
{
if(name !=choices[i])
$('input[name="' + choices[i] + '"]').not(this).prop('checked', false);
}
}
}
$('input[type="checkbox"]').on('change', function()
{
var letters = ["A","B","C","D"];
var numbers = ["1", "2", "3"];
var birds = ["Scarlet Ibis", "Cocrico", "hummingbird"];
toggle(letters,this.name);
toggle(numbers,this.name);
toggle(birds,this.name);
});
});
</script>
</html>
_x000D_
_x000D_
_x000D_
setTimeout in React Native
Classic javascript mistake.
setTimeout(function(){this.setState({timePassed: true})}, 1000)
When setTimeout
runs this.setState
, this
is no longer CowtanApp
, but window
. If you define the function with the =>
notation, es6 will auto-bind this
.
setTimeout(() => {this.setState({timePassed: true})}, 1000)
Alternatively, you could use a let that = this;
at the top of your render
, then switch your references to use the local variable.
render() {
let that = this;
setTimeout(function(){that.setState({timePassed: true})}, 1000);
If not working, use bind
.
setTimeout(
function() {
this.setState({timePassed: true});
}
.bind(this),
1000
);
How to draw a graph in LaTeX?
In my experience, I always just use an external program to generate the graph (mathematica, gnuplot, matlab, etc.) and export the graph as a pdf or eps file. Then I include it into the document with includegraphics
.
How do I save a stream to a file in C#?
As highlighted by Tilendor in Jon Skeet's answer, streams have a CopyTo
method since .NET 4.
var fileStream = File.Create("C:\\Path\\To\\File");
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
fileStream.Close();
Or with the using
syntax:
using (var fileStream = File.Create("C:\\Path\\To\\File"))
{
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
}
Combining two expressions (Expression<Func<T, bool>>)
Well, you can use Expression.AndAlso
/ OrElse
etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression
in expr1 and expr2? If so, it is easier:
var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);
This also works well to negate a single operation:
static Expression<Func<T, bool>> Not<T>(
this Expression<Func<T, bool>> expr)
{
return Expression.Lambda<Func<T, bool>>(
Expression.Not(expr.Body), expr.Parameters[0]);
}
Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke
:
// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> left,
Expression<Func<T, bool>> right)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.AndAlso(
Expression.Invoke(left, param),
Expression.Invoke(right, param)
);
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return lambda;
}
Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke
, but it is quite lengthy (and I can't remember where I left it...)
Generalized version that picks the simplest route:
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
// need to detect whether they use the same
// parameter instance; if not, they need fixing
ParameterExpression param = expr1.Parameters[0];
if (ReferenceEquals(param, expr2.Parameters[0]))
{
// simple version
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(expr1.Body, expr2.Body), param);
}
// otherwise, keep expr1 "as is" and invoke expr2
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
Expression.Invoke(expr2, param)), param);
}
Starting from .NET 4.0, there is the ExpressionVisitor
class which allows you to build expressions that are EF safe.
public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var parameter = Expression.Parameter(typeof (T));
var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
var left = leftVisitor.Visit(expr1.Body);
var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
var right = rightVisitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(left, right), parameter);
}
private class ReplaceExpressionVisitor
: ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue;
public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}
public override Expression Visit(Expression node)
{
if (node == _oldValue)
return _newValue;
return base.Visit(node);
}
}
How to run different python versions in cmd
I would suggest using the Python Launcher for Windows utility that was introduced into Python 3.3. You can manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.
Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py,
.pyw
, .pyc
, and .pyo
files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX
comments at the beginning of your Python scripts.
Ajax LARAVEL 419 POST error
In laravel you can use view render.
ex.
$returnHTML = view('myview')->render();
myview.blade.php contains your blade code
Call a child class method from a parent class object
Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).
I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.
http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html
The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.
UPDATE: found it here.
Today's Date in Perl in MM/DD/YYYY format
Perl Code for Unix systems:
# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "\n";
extract date only from given timestamp in oracle sql
Convert Timestamp to Date as mentioned below, it will work for sure -
select TO_DATE(TO_CHAR(TO_TIMESTAMP ('2015-04-15 18:00:22.000', 'YYYY-MM-DD HH24:MI:SS.FF'),'MM/DD/YYYY HH24:MI:SS'),'MM/DD/YYYY HH24:MI:SS') dt from dual
PHP order array by date?
He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!
<?php
$data['may_1_2002']=
Array(
'title_id_32'=>'Good morning',
'title_id_21'=>'Blue sky',
'title_id_3'=>'Summer',
'date'=>'1 May 2002'
);
$data['may_2_2002']=
Array(
'title_id_34'=>'Leaves',
'title_id_20'=>'Old times',
'date'=>'2 May 2002 '
);
echo '<pre>';
print_r($data);
?>
How to clear exisiting dropdownlist items when its content changes?
Using ddl.Items.Clear()
will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False"
to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False"
to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))
how to display a javascript var in html body
You cannot add JavaScript variable to HTML code.
For this you need to do in following way.
<html>
<head>
<script type="text/javscript">
var number = 123;
document.addEventListener('DOMContentLoaded', function() {
document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>
casting int to char using C++ style casting
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
long l = reinterpret_cast<long>(i)
static_cast
is the one which has to be used here. See this and this SO questions.
Submit form with Enter key without submit button?
Change #form to your form's ID
$('#form input').keydown(function(e) {
if (e.keyCode == 13) {
$('#form').submit();
}
});
Or alternatively
$('input').keydown(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
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
Can I simultaneously declare and assign a variable in VBA?
There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the :
continuation character if you want it on one line for readability;
Dim clientToTest As String: clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)
Hint (summary of other answers/comments): Works with objects too (Excel 2010):
Dim ws As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"
How to extract the nth word and count word occurrences in a MySQL string?
The following is a proposed solution for the OP's specific problem (extracting the 2nd word of a string), but it should be noted that, as mc0e's answer states, actually extracting regex matches is not supported out-of-the-box in MySQL. If you really need this, then your choices are basically to 1) do it in post-processing on the client, or 2) install a MySQL extension to support it.
BenWells has it very almost correct. Working from his code, here's a slightly adjusted version:
SUBSTRING(
sentence,
LOCATE(' ', sentence) + CHAR_LENGTH(' '),
LOCATE(' ', sentence,
( LOCATE(' ', sentence) + 1 ) - ( LOCATE(' ', sentence) + CHAR_LENGTH(' ') )
)
As a working example, I used:
SELECT SUBSTRING(
sentence,
LOCATE(' ', sentence) + CHAR_LENGTH(' '),
LOCATE(' ', sentence,
( LOCATE(' ', sentence) + 1 ) - ( LOCATE(' ', sentence) + CHAR_LENGTH(' ') )
) as string
FROM (SELECT 'THIS IS A TEST' AS sentence) temp
This successfully extracts the word IS
How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?
I ended up writing a small script that adds the certificates to the keystores, so it is much easier to use.
You can get the latest version from https://github.com/ssbarnea/keytool-trust
#!/bin/bash
# version 1.0
# https://github.com/ssbarnea/keytool-trust
REMHOST=$1
REMPORT=${2:-443}
KEYSTORE_PASS=changeit
KEYTOOL="sudo keytool"
# /etc/java-6-sun/security/cacerts
for CACERTS in /usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts \
/usr/lib/jvm/java-7-oracle/jre/lib/security/cacerts \
"/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/cacerts" \
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/lib/security/cacerts"
do
if [ -e "$CACERTS" ]
then
echo --- Adding certs to $CACERTS
# FYI: the default keystore is located in ~/.keystore
if [ -z "$REMHOST" ]
then
echo "ERROR: Please specify the server name to import the certificatin from, eventually followed by the port number, if other than 443."
exit 1
fi
set -e
rm -f $REMHOST:$REMPORT.pem
if openssl s_client -connect $REMHOST:$REMPORT 1>/tmp/keytool_stdout 2>/tmp/output </dev/null
then
:
else
cat /tmp/keytool_stdout
cat /tmp/output
exit 1
fi
if sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' </tmp/keytool_stdout > /tmp/$REMHOST:$REMPORT.pem
then
:
else
echo "ERROR: Unable to extract the certificate from $REMHOST:$REMPORT ($?)"
cat /tmp/output
fi
if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT >/dev/null
then
echo "Key of $REMHOST already found, skipping it."
else
$KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem
fi
if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -keystore "$CACERTS" >/dev/null
then
echo "Key of $REMHOST already found in cacerts, skipping it."
else
$KEYTOOL -import -trustcacerts -noprompt -keystore "$CACERTS" -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem
fi
fi
done
```
Allowed memory size of X bytes exhausted
1 check current limit:
(in my os)php -i | grep limit => memory_limit => 256M => 256M
2 locate php.ini
php --ini =>
Configuration File (php.ini) Path: /etc
Loaded Configuration File: /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed: /etc/php.d/curl.ini
...
3 change memory_limit in php.ini
vi /etc/php.ini
memory_limit = 512M
4 restart nginx and (php-fpm if being used)
service php-fpm restart
service nginx restart
How can I access Oracle from Python?
You can use any of the following way based on Service Name
or SID
whatever you have.
With SID:
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', 'sid')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
print(row)
conn.close()
OR
With Service Name:
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
print(row)
conn.close()
How to chain scope queries with OR instead of AND?
In case anyone is looking for an updated answer to this one, it looks like there is an existing pull request to get this into Rails: https://github.com/rails/rails/pull/9052.
Thanks to @j-mcnally's monkey patch for ActiveRecord (https://gist.github.com/j-mcnally/250eaaceef234dd8971b) you can do the following:
Person.where(name: 'John').or.where(last_name: 'Smith').all
Even more valuable is the ability to chain scopes with OR
:
scope :first_or_last_name, ->(name) { where(name: name.split(' ').first).or.where(last_name: name.split(' ').last) }
scope :parent_last_name, ->(name) { includes(:parents).where(last_name: name) }
Then you can find all Persons with first or last name or whose parent with last name
Person.first_or_last_name('John Smith').or.parent_last_name('Smith')
Not the best example for the use of this, but just trying to fit it with the question.
jQuery get text as number
var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
// do something
}
Getting the exception value in Python
Use repr() and The difference between using repr and str
Using repr
:
>>> try:
... print(x)
... except Exception as e:
... print(repr(e))
...
NameError("name 'x' is not defined")
Using str
:
>>> try:
... print(x)
... except Exception as e:
... print(str(e))
...
name 'x' is not defined
Echo equivalent in PowerShell for script testing
By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:
$filesizecounter = 8096
"filesizecounter : $filesizecounter"
Of course, you do give up some flexibility when not using the Write-* methods.
Difference between Activity Context and Application Context
This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext
or Activity
directly, instead of using parent class Context.
In the second place, the doc should specify which context to use or not explicitly.
Storing database records into array
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}
<> And Not In VB.NET
Is
is not the same as =
-- Is
compares the references, whilst =
will compare the values.
If you're using v2 of the .Net Framework (or later), there is the IsNot
operator which will do the right thing, and read more naturally.
MySql Error: 1364 Field 'display_name' doesn't have default value
I also faced that problem and there are two ways to solve this in laravel.
first one is you can set the default value as null. I will show you an example:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('gender');
$table->string('slug');
$table->string('pic')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
as the above example, you can set nullable()
for that feature. then when you are inserting data MySQL set the default value as null.
second one is in your model set your input field in protected $fillable
field. as example:
protected $fillable = [
'name', 'email', 'password', 'slug', 'gender','pic'
];
I think the second one is fine than the first one and also you can set nullable feature as well as fillable in the same time without a problem.
Remove an array element and shift the remaining ones
If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):
unsigned int l=0, removed=0;
for( unsigned int i=0; i<count; i++ ) {
if( array[i] != to_remove )
array[l++] = array[i];
else
removed++;
}
count -= removed;
Make selected block of text uppercase
At Sep 19 2018, these lines worked for me:
File-> Preferences -> Keyboard Shortcuts.
An editor will appear with keybindings.json file. Place the following JSON in there and save.
// Place your key bindings in this file to overwrite the defaults
[
{
"key": "ctrl+shift+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
},
]
pip3: command not found but python3-pip is already installed
On Windows 10 install Python from Python.org
Once installed add these two paths to PATH env variable
C:\Users<your user>\AppData\Local\Programs\Python\Python38
C:\Users<your user>\AppData\Local\Programs\Python\Python38\Scripts
Open command prompt and following command should be working
python --version
pip --version
Offline Speech Recognition In Android (JellyBean)
A simple and flexible offline recognition on Android is implemented by CMUSphinx, an open source speech recognition toolkit. It works purely offline, fast and configurable It can listen continuously for keyword, for example.
You can find latest code and tutorial here.
Update in 2019: Time goes fast, CMUSphinx is not that accurate anymore. I recommend to try Kaldi toolkit instead. The demo is here.
Center content in responsive bootstrap navbar
The original post was asking how to center the collapsed navbar. To center elements on the normal navbar, try this:
.navbar-nav {
float:none;
margin:0 auto;
display: block;
text-align: center;
}
.navbar-nav > li {
display: inline-block;
float:none;
}
Is there a way to specify which pytest tests to run from a file?
You can use -k
option to run test cases with different patterns:
py.test tests_directory/foo.py tests_directory/bar.py -k 'test_001 or test_some_other_test'
This will run test cases with name test_001 and test_some_other_test deselecting the rest of the test cases.
Note: This will select any test case starting with test_001 or test_some_other_test. For example, if you have test case test_0012 it will also be selected.
Convert Xml to Table SQL Server
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
How to check if BigDecimal variable == 0 in java?
Just want to share here some helpful extensions for kotlin
fun BigDecimal.isZero() = compareTo(BigDecimal.ZERO) == 0
fun BigDecimal.isOne() = compareTo(BigDecimal.ONE) == 0
fun BigDecimal.isTen() = compareTo(BigDecimal.TEN) == 0
not None test in Python
From, Programming Recommendations, PEP 8:
Comparisons to singletons like None should always be done with is
or is not
, never the equality operators.
Also, beware of writing if x
when you really mean if x is not None
— e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
PEP 8 is essential reading for any Python programmer.
Difference between `npm start` & `node app.js`, when starting app?
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "start
"
property of its "scripts
" object. If no "start
" property is specified
on the "scripts
" object, it will run node server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)
npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)
- I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no
package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
wait until all threads finish their work in java
I had similar situation , where i had to wait till all child threads complete its execution then only i could get the status result for each of them .. hence i needed to wait till all child thread completed.
below is my code where i did multi-threading using
public static void main(String[] args) {
List<RunnerPojo> testList = ExcelObject.getTestStepsList();//.parallelStream().collect(Collectors.toList());
int threadCount = ConfigFileReader.getInstance().readConfig().getParallelThreadCount();
System.out.println("Thread count is : ========= " + threadCount); // 5
ExecutorService threadExecutor = new DriverScript().threadExecutor(testList, threadCount);
boolean isProcessCompleted = waitUntilCondition(() -> threadExecutor.isTerminated()); // Here i used waitUntil condition
if (isProcessCompleted) {
testList.forEach(x -> {
System.out.println("Test Name: " + x.getTestCaseId());
System.out.println("Test Status : " + x.getStatus());
System.out.println("======= Test Steps ===== ");
x.getTestStepsList().forEach(y -> {
System.out.println("Step Name: " + y.getDescription());
System.out.println("Test caseId : " + y.getTestCaseId());
System.out.println("Step Status: " + y.getResult());
System.out.println("\n ============ ==========");
});
});
}
Below method is for distribution of list with parallel proccessing
// This method will split my list and run in a parallel process with mutliple threads
private ExecutorService threadExecutor(List<RunnerPojo> testList, int threadSize) {
ExecutorService exec = Executors.newFixedThreadPool(threadSize);
testList.forEach(tests -> {
exec.submit(() -> {
driverScript(tests);
});
});
exec.shutdown();
return exec;
}
This is my wait until method: here you can wait till your condition satisfies within do while loop . in my case i waited for some max timeout .
this will keep checking until your threadExecutor.isTerminated()
is true
with polling period of 5 sec.
static boolean waitUntilCondition(Supplier<Boolean> function) {
Double timer = 0.0;
Double maxTimeOut = 20.0;
boolean isFound;
do {
isFound = function.get();
if (isFound) {
break;
} else {
try {
Thread.sleep(5000); // Sleeping for 5 sec (main thread will sleep for 5 sec)
} catch (InterruptedException e) {
e.printStackTrace();
}
timer++;
System.out.println("Waiting for condition to be true .. waited .." + timer * 5 + " sec.");
}
} while (timer < maxTimeOut + 1.0);
return isFound;
}
How to set a bitmap from resource
Using this function you can get Image Bitmap. Just pass image url
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
CSS image resize percentage of itself?
Try zoom
property
<img src="..." style="zoom: 0.5" />
Edit: Apparently, FireFox doesn't support zoom
property. You should use;
-moz-transform: scale(0.5);
for FireFox.
How to center links in HTML
p
is not how you put text in a
. That is the problem. The only solution is to put the text between <a>
and </a>
. For example:
<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>
Using Service to run background and create notification
Your error is in UpdaterServiceManager in onCreate and showNotification method.
You are trying to show notification
from Service using Activity Context
. Whereas Every Service has its own Context,
just use the that. You don't need to pass a Service an Activity's Context.
I don't see why you need a specific Activity's Context to show Notification.
Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.
You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference
Pandas: Appending a row to a dataframe and specify its index label
There is another solution. The next code is bad (although I think pandas needs this feature):
import pandas as pd
# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}
But the next code runs fine:
import pandas as pd
# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))
Which are more performant, CTE or temporary tables?
I'd say they are different concepts but not too different to say "chalk and cheese".
A temp table is good for re-use or to perform multiple processing passes on a set of data.
A CTE can be used either to recurse or to simply improved readability.
And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query
A temp table is another table with some rules around scope
I have stored procs where I use both (and table variables too)
Appending the same string to a list of strings in Python
The simplest way to do this is with a list comprehension:
[s + mystring for s in mylist]
Notice that I avoided using builtin names like list
because that shadows or hides the builtin names, which is very much not good.
Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):
(s + mystring for s in mylist)
These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.
MetadataException: Unable to load the specified metadata resource
I also had this problem and it was because the connectionstring in my web.config was slightly different than the one in the app.config of the assembly where my EDMX is located. No idea why it changed, but here are the two different versions.
App.config:
<add name="SCMSEntities" connectionString="metadata=res://*/Model.SMCSModel.csdl|res://*/Model.SMCSModel.ssdl|res://*/Model.SMCSModel.msl;provider=System.Data.SqlClient;provider connection string="data source=SANDIEGO\sql2008;initial catalog=SCMS;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Web.config:
<add name="SCMSEntities" connectionString="metadata=res://*/Model.SCMSModel.csdl|res://*/Model.SCMSModel.ssdl|res://*/Model.SCMSModel.msl;provider=System.Data.SqlClient;provider connection string="data source=SANDIEGO\sql2008;initial catalog=SCMS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
What fixed it was simply copying the app.config string (notice the small difference at the end - instead of "App=EntityFramework
" it wanted "application name=EntityFramework
") into the web.config and problem was solved. :)
Difference between 'cls' and 'self' in Python classes?
The distinction between "self"
and "cls"
is defined in PEP 8
. As Adrien said, this is not a mandatory. It's a coding style. PEP 8
says:
Function and method arguments:
Always use self
for the first argument to instance methods.
Always use cls
for the first argument to class methods.
Login failed for user 'IIS APPPOOL\ASP.NET v4.0'
Looks like it's failing trying to open a connection to SQL Server.
You need to add a login to SQL Server for IIS APPPOOL\ASP.NET v4.0
and grant permissions to the database.
In SSMS, under the server, expand Security, then right click Logins and select "New Login...".
In the New Login dialog, enter the app pool as the login name and click "OK".
![enter image description here](https://i.stack.imgur.com/6sfIM.png)
You can then right click the login for the app pool, select Properties and select "User Mapping". Check the appropriate database, and the appropriate roles. I think you could just select db_datareader
and db_datawriter
, but I think you would still need to grant permissions to execute stored procedures if you do that through EF. You can check the details for the roles here.
What is Domain Driven Design?
DDD(domain driven design) is a useful concept for analyse of requirements of a project and handling the complexity of these requirements.Before that people were analysing these requirements with considering the relationships between classes and tables and in fact their design were based on database tables relationships it is not old but it has some problems:
In big projects with complex requirements it is not useful although this is a great way of design for small projects.
when you are dealing with none technical persons that they don,t have technical concept, this conflict may cause some huge problems in our project.
So DDD handle the first problem with considering the main project as a Domain and splitting each part of this project to small pieces which we are famous to Bounded Context and each of them do not have any influence on other pieces.
And the second problem has been solved with a ubiquitous language which is a common language between technical team members and Product owners which are not technical but have enough knowledge about their requirements
Generally the simple definition for Domain is the main project that makes money for the owners and other teams.
What is the maximum length of a table name in Oracle?
Teach a man to fish
Notice the data-type and size
>describe all_tab_columns
VIEW all_tab_columns
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
Laravel 4 with Sentry 2 add user to a group on Registration
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
How do I write JSON data to a file?
All previous answers are correct here is a very simple example:
#! /usr/bin/env python
import json
def write_json():
# create a dictionary
student_data = {"students":[]}
#create a list
data_holder = student_data["students"]
# just a counter
counter = 0
#loop through if you have multiple items..
while counter < 3:
data_holder.append({'id':counter})
data_holder.append({'room':counter})
counter += 1
#write the file
file_path='/tmp/student_data.json'
with open(file_path, 'w') as outfile:
print("writing file to: ",file_path)
# HERE IS WHERE THE MAGIC HAPPENS
json.dump(student_data, outfile)
outfile.close()
print("done")
write_json()
![enter image description here](https://i.stack.imgur.com/1CNhG.png)
C# ListView Column Width Auto
Use this:
yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
from here
Is there a Google Chrome-only CSS hack?
Sure is:
@media screen and (-webkit-min-device-pixel-ratio:0)
{
#element { properties:value; }
}
And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/
Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.
Also, these hacks may not be future proof.
Find Java classes implementing an interface
The code you are talking about sounds like ServiceLoader
, which was introduced in Java 6 to support a feature that has been defined since Java 1.3 or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find my implementation helpful.
There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.
pretty-print JSON using JavaScript
Here's user123444555621's awesome HTML one adapted for terminals. Handy for debugging Node scripts:
function prettyJ(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, undefined, 2);
}
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
let cls = "\x1b[36m";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "\x1b[34m";
} else {
cls = "\x1b[32m";
}
} else if (/true|false/.test(match)) {
cls = "\x1b[35m";
} else if (/null/.test(match)) {
cls = "\x1b[31m";
}
return cls + match + "\x1b[0m";
}
);
}
Usage:
// thing = any json OR string of json
prettyJ(thing);
Create a new workspace in Eclipse
In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.
Then close eclipse and reopen.
Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.
Or File->Switch Workspace->Other...
how to pass parameters to query in SQL (Excel)
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?
, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.
ListView item background via custom selector
I'm not sure how to achieve your desired effect through the selector itself -- after all, by definition, there is one selector for the whole list.
However, you can get control on selection changes and draw whatever you want. In this sample project, I make the selector transparent and draw a bar on the selected item.
How to convert milliseconds into a readable date?
You can do it with just a few lines of pure js codes.
var date = new Date(1324339200000);
var dateToStr = date.toUTCString().split(' ');
var cleanDate = dateToStr[2] + ' ' + dateToStr[1] ;
console.log(cleanDate);
returns Dec 20.
Hope it helps.
Load CSV file with Spark
If you want to load csv as a dataframe then you can do the following:
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
df = sqlContext.read.format('com.databricks.spark.csv') \
.options(header='true', inferschema='true') \
.load('sampleFile.csv') # this is your csv file
It worked fine for me.
Find (and kill) process locking port 3000 on Mac
A one-liner to extract the PID of the process using port 3000 and kill it.
lsof -ti:3000 | xargs kill
The -t flag removes everything but the PID from the lsof output, making it easy to kill it.
How do I perform a JAVA callback between classes?
In this particular case, the following should work:
serverConnectionHandler = new ServerConnections(_address) {
public void newConnection(Socket _socket) {
System.out.println("A function of my child class was called.");
}
};
It's an anonymous subclass.
How to convert a file into a dictionary?
I had a requirement to take values from text file and use as key value pair. i have content in text file as key = value, so i have used split method with separator as "=" and
wrote below code
d = {}
file = open("filename.txt")
for x in file:
f = x.split("=")
d.update({f[0].strip(): f[1].strip()})
By using strip method any spaces before or after the "=" separator are removed and you will have the expected data in dictionary format
Easy way to export multiple data.frame to multiple Excel worksheets
There's a new library in town, from rOpenSci: writexl
Portable, light-weight data frame to xlsx exporter based on
libxlsxwriter. No Java or Excel required
I found it better and faster than the above suggestions (working with the dev version):
library(writexl)
sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frames
write_xlsx(sheets, "path/to/location")
Remove ALL styling/formatting from hyperlinks
You can simply define a style for links, which would override a:hover
, a:visited
etc.:
a {
color: blue;
text-decoration: none; /* no underline */
}
You can also use the inherit
value if you want to use attributes from parent styles instead:
body {
color: blue;
}
a {
color: inherit; /* blue colors for links too */
text-decoration: inherit; /* no underline */
}
Getting date format m-d-Y H:i:s.u from milliseconds
php.net says:
Microseconds (added in PHP 5.2.2). Note that date()
will always generate 000000
since it takes an integer parameter, whereas DateTime::format()
does support microseconds if DateTime
was created with microseconds.
So use as simple:
$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";
Recommended and use dateTime()
class from referenced:
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
print $d->format("Y-m-d H:i:s.u"); // note at point on "u"
Note u
is microseconds (1 seconds = 1000000 µs).
Another example from php.net:
$d2=new DateTime("2012-07-08 11:14:15.889342");
Reference of dateTime()
on php.net
I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds
Calculate the number of business days between two dates?
Here's a quick sample code. It's a class method, so will only work inside of your class. If you want it to be static
, change the signature to private static
(or public static
).
private IEnumerable<DateTime> GetWorkingDays(DateTime sd, DateTime ed)
{
for (var d = sd; d <= ed; d = d.AddDays(1))
if (d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)
yield return d;
}
This method creates a loop variable d
, initializes it to the start day, sd
, then increments by one day each iteration (d = d.AddDays(1)
).
It returns the desired values using yield
, which creates an iterator
. The cool thing about iterators is that they don't hold all of the values of the IEnumerable
in memory, only calling each one sequentially. This means that you can call this method from the dawn of time to now without having to worry about running out of memory.
How do I import material design library to Android Studio?
If you are using Android Studio:
You can import the project as a module and change the following in the build.gradle
file of the imported module.
Change apply plugin: com.android.application
to apply plugin: com.android.library
remove applicationId
and set minSdkVersion
to match your project minSdkVersion.
And in your project build.gradle
file compile project(':MaterialDesignLibrary')
, where MaterialDesignLibrary
is the name of your library project or you can import the module by File -> Project Structure -> Select your project under Modules -> Dependencies -> Click on + to add a module.
Module is not available, misspelled or forgot to load (but I didn't)
I got this error when my service declaration was inside a non-invoked function (IIFE). The last line below did NOT have the extra () to run and define the service.
(function() {
"use strict";
angular.module("reviewService", [])
.service("reviewService", reviewService);
function reviewService($http, $q, $log) {
//
}
}());
Get child Node of another Node, given node name
Check if the Node
is a Dom Element
, cast, and call getElementsByTagName()
Node doc = docs.item(i);
if(doc instanceof Element) {
Element docElement = (Element)doc;
...
cell = doc.getElementsByTagName("aoo").item(0);
}
Arraylist swap elements
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Read The official Docs of collection
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
How to set the "Content-Type ... charset" in the request header using a HTML link
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
![alt text](https://i.stack.imgur.com/diSbx.png)
Modifying Objects within stream in Java8 while iterating
The functional way would imho be:
import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateTestRun {
public static void main(String[] args) {
List<String> lines = Arrays.asList("a", "b", "c");
System.out.println(lines); // [a, b, c]
Predicate<? super String> predicate = value -> "b".equals(value);
lines = lines.stream().filter(predicate.negate()).collect(toList());
System.out.println(lines); // [a, c]
}
}
In this solution the original list is not modified, but should contain your expected result in a new list that is accessible under the same variable as the old one
Call function with setInterval in jQuery?
First of all: Yes you can mix jQuery with common JS :)
Best way to build up an intervall call of a function is to use setTimeout methode:
For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:
function test(){
console.log('test called');
setTimeout(test, 5000);
}
Finally you have to trigger the function once:
$(document).ready(function(){
test();
});
This document ready function is called automatically, after all html is loaded.
GET URL parameter in PHP
$_GET
is not a function or language construct—it's just a variable (an array). Try:
<?php
echo $_GET['link'];
In particular, it's a superglobal: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the global keyword).
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['link'])) {
echo $_GET['link'];
} else {
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);
Last but not least, you can use the null coalescing operator (available since PHP/7.0) to handle missing parameters:
echo $_GET['link'] ?? 'Fallback value';
ASP.NET MVC 5 - Identity. How to get current ApplicationUser
Right now the asp.mvc project template creates an account controller that gets the usermanager this way:
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()
The following works for me:
ApplicationUser user = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());
How SQL query result insert in temp table?
You can use select ... into ...
to create and populate a temp table and then query the temp table to return the result.
select *
into #TempTable
from YourTable
select *
from #TempTable
Set a form's action attribute when submitting?
<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />
Or you can modify it from outside the form, with javascript the normal way:
document.getElementById('form_id').action = 'somethingelse';
MySQL FULL JOIN?
![Various types of joins, for illustration](https://i.stack.imgur.com/hMKKt.jpg)
There are a couple of methods for full mysql FULL [OUTER] JOIN.
UNION a left join and right join.
UNION will remove duplicates by performing an ORDER BY operation.
So depending on your data, it may not be performant.
SELECT * FROM A
LEFT JOIN B ON A.key = B.key
UNION
SELECT * FROM A
RIGHT JOIN B ON A.key = B.key
UNION ALL a left join and right EXCLUDING join (that's the lower right figure in the diagram). UNION ALL will not remove duplicates. Sometimes this might be the behaviour that you want. You also want to use RIGHT EXCLUDING to avoid duplicating common records from selection A and selection B - i.e Left join has already included common records from selection B, lets not repeat that again with the right join.
SELECT * FROM A
LEFT JOIN B ON A.key = B.key
UNION ALL
SELECT * FROM A
RIGHT JOIN B ON A.key = B.key
WHERE A.key IS NULL
how to setup ssh keys for jenkins to publish via ssh
You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.
Generating the SSH Key Pair
On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:
On the Target Server
On the target server, you will need to place the content of the public key (id_rsa.pub
per the above article) into the .ssh/authorized_keys
file under the home directory of the user which Jenkins will be using for deployment.
In Jenkins
Using "Publish over SSH" Plugin
Ref: https://plugins.jenkins.io/publish-over-ssh/
Visit: Jenkins
> Manage Jenkins
> Configure System
> Publish over SSH
- If the private key is encrypted, then you will need to enter the passphrase for the key into the "Passphrase" field, otherwise leave it alone.
- Leave the "Path to key" field empty as this will be ignored anyway when you use a pasted key (next step)
- Copy and paste the contents of the private key (
id_rsa
per the above article) into the "Key" field
- Under "SSH Servers", "Add" a new server configuration for your target server.
Using Stored Global Credentials
Visit: Jenkins
> Credentials
> System
> Global credentials (unrestricted)
> Add Credentials
- Kind: "SSH Username with private key"
- Scope: "Global"
- ID: [CREAT A UNIQUE ID FOR THIS KEY]
- Description: [optionally, enter a decription]
- Username: [USERNAME JENKINS WILL USE TO CONNECT TO REMOTE SERVER]
- Private Key: [select "Enter directly"]
- Key: [paste the contents of the private key (
id_rsa
per the above article)]
- Passphrase: [enter the passphrase for the key, or leave it blank if the key is not encrypted]
Compress files while reading data from STDIN
Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.
cat test.csv | gzip > test.csv.gz
cat test.csv
will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.
How do we use runOnUiThread in Android?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gifImageView = (GifImageView) findViewById(R.id.GifImageView);
gifImageView.setGifImageResource(R.drawable.success1);
new Thread(new Runnable() {
@Override
public void run() {
try {
//dummy delay for 2 second
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//update ui on UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
gifImageView.setGifImageResource(R.drawable.success);
}
});
}
}).start();
}
How to convert comma-separated String to List?
There is no built-in method for this but you can simply use split() method in this.
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items =
new ArrayList<String>(Arrays.asList(commaSeparated.split(",")));
How to convert CSV to JSON in Node.js
Using ES6
const toJSON = csv => {
const lines = csv.split('\n')
const result = []
const headers = lines[0].split(',')
lines.map(l => {
const obj = {}
const line = l.split(',')
headers.map((h, i) => {
obj[h] = line[i]
})
result.push(obj)
})
return JSON.stringify(result)
}
const csv = `name,email,age
francis,[email protected],33
matty,[email protected],29`
const data = toJSON(csv)
console.log(data)
Output
// [{"name":"name","email":"email","age":"age"},{"name":"francis","email":"[email protected]","age":"33"},{"name":"matty","email":"[email protected]","age":"29"}]
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
![https://bugs.eclipse.org/bugs/attachment.cgi?id=238285](https://i.stack.imgur.com/4YNL4.png)
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
For Loop on Lua
By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:
Way1
names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end
Way2
names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end
Way1 uses the table index/key
, on your table names
each element has a key starting from 1, for example:
names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John
So you just make i
go from 1 to 3.
On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:
names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end
prints the following:
1 John
2 Joe
myKey myValue
Hiding the address bar of a browser (popup)
What is the truth?
Microsoft's documentation describing the behaviour of their browser is correct.
Is there any solution to hide the addressbar?
No. If you could hide it, then you could use HTML/CSS to make something that looked like a common address bar. You could then put a different address in it. You could then trick people into thinking they were on a different site and entering their password for it.
It is impossible to conceal the user's location from them because it is essential for security that they know what their location is.
Vertically align text to top within a UILabel
I took a while to read the code, as well as the code in the introduced page, and found that they all try to modify the frame size of label, so that the default center vertical alignment would not appear.
However, in some cases we do want the label to occupy all those spaces, even if the label does have so much text (e.g. multiple rows with equal height).
Here, I used an alternative way to solve it, by simply pad newlines to the end of label (pls note that I actually inherited the UILabel
, but it is not necessary):
CGSize fontSize = [self.text sizeWithFont:self.font];
finalHeight = fontSize.height * self.numberOfLines;
finalWidth = size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i = 0; i < newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:@"\n "];
}
How do I format currencies in a Vue component?
There is issues with the precision of the accepted answer.
the round(value, decimals) function in this test works.
unlike the simple toFixed example.
this is a test of the toFixed vs round method.
http://www.jacklmoore.com/notes/rounding-in-javascript/
_x000D_
_x000D_
Number.prototype.format = function(n) {_x000D_
return this.toFixed(Math.max(0, ~~n));_x000D_
};_x000D_
function round(value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);_x000D_
}_x000D_
_x000D_
// can anyone tell me why these are equivalent for 50.005, and 1050.005 through 8150.005 (increments of 50)_x000D_
_x000D_
var round_to = 2;_x000D_
var maxInt = 1500000;_x000D_
var equalRound = '<h1>BEGIN HERE</h1><div class="matches">';_x000D_
var increment = 50;_x000D_
var round_from = 0.005;_x000D_
var expected = 0.01;_x000D_
var lastWasMatch = true;_x000D_
_x000D_
for( var n = 0; n < maxInt; n=n+increment){_x000D_
var data = {};_x000D_
var numberCheck = parseFloat(n + round_from);_x000D_
data.original = numberCheck * 1;_x000D_
data.expected = Number(n + expected) * 1;_x000D_
data.formatIt = Number(numberCheck).format(round_to) * 1;_x000D_
data.roundIt = round(numberCheck, round_to).toFixed(round_to) * 1;_x000D_
data.numberIt = Number(numberCheck).toFixed(round_to) * 1;_x000D_
//console.log(data);_x000D_
_x000D_
if( data.roundIt !== data.formatIt || data.formatIt !== data.numberIt ||_x000D_
data.roundIt !== data.numberIt || data.roundIt != data.expected_x000D_
){_x000D_
if(lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="errors"> <hr/> Did Not Round UP <hr/>' ;_x000D_
document.write(' <h3>EXAMPLE: Did Not Round UP: ' + numberCheck + '</h3><br /><hr/> ');_x000D_
document.write('expected: '+data.expected + ' :: ' + (typeof data.expected) + '<br />');_x000D_
document.write('format: '+data.formatIt + ' :: ' + (typeof data.formatIt) + '<br />');_x000D_
document.write('round : '+data.roundIt + ' :: ' + (typeof data.roundIt) + '<br />');_x000D_
document.write('number: '+data.numberIt + ' :: ' + (typeof data.numberIt) + '<br />');_x000D_
lastWasMatch=false;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
} else {_x000D_
if(!lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="matches"> <hr/> All Rounded UP! <hr/>' ;_x000D_
} {_x000D_
lastWasMatch=true;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
}_x000D_
}_x000D_
document.write('equalRound: '+equalRound + '</div><br />');
_x000D_
_x000D_
_x000D_
mixin example
_x000D_
_x000D_
export default {_x000D_
methods: {_x000D_
roundFormat: function (value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(decimals);_x000D_
},_x000D_
currencyFormat: function (value, decimals, symbol='$') {_x000D_
return symbol + this.roundFormat(value,2);_x000D_
}_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_
reStructuredText tool support
Salvaging (and extending) the list from an old version of the Wikipedia page:
Documentation
Implementations
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
Python - Docutils
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
- rst2html - from reStructuredText to HTML
- rst2xml - from reStructuredText to XML
- rst2latex - from reStructuredText to LaTeX
- rst2odt - from reStructuredText to ODF Text (word processor) document.
- rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
- rst2man - from reStructuredText to Man page
Haskell - Pandoc
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
- POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
- POT output lacks the helpful error messages displayed by the ROR (and generated by
docutils
)
Java - JRst
JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Scala - Laika
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
Perl
PHP
C#/.NET
Nim/C
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
- rst - implements a reStructuredText parser
- rstast - implements an AST for the reStructuredText parser
- rstgen - implements a generator of HTML/Latex from reStructuredText
Other 3rd party converters
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
From reStructuredText
- restview - This
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
- starts a small web server
- calls
docutils
to render your document(s) to HTML
- calls your device's browser to display the output HTML.
- rst2pdf - from reStructuredText to PDF
- rst2odp - from reStructuredText to ODF Presentation
- rst2beamer - from reStructuredText to LaTeX beamer Presentation class
- Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
- rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file
To reStructuredText
- xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
- Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
- db2rst is a simple and limited DocBook to reStructuredText translator
- pod2rst - convert .pod files to reStructuredText files
Extensions
Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
Sphinx
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
Free Editors
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
Emacs
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
Vim
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
Jed
There is a rst mode for the Jed programmers editor.
gedit
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
FTE
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers.
FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
Eclipse
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Dedicated reStructuredText Editors
Proprietary editors
Sublime Text
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit / TextWrangler
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E Text Editor
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).
)
Wiki
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac
Trac is an enhanced wiki and issue tracking system for software development projects.
There is a reStructuredText Support in Trac.
This Wiki
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
ikiwiki
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
Web Services
Sandbox
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
Blogging frameworks
WordPress
WordPreSt reStructuredText plugin for WordPress. (PHP)
Zine
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
pelican
Pelican is a static blog generator that supports writing articles in ReST. (Python)
hyde
Hyde is a static website generator that supports ReST. (Python)
Acrylamid
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
ipsum genera
Ipsum genera is a static blog generator written in Nim.
Yozuch
Yozuch is a static blog generator written in Python.
More
Excel VBA - select multiple columns not in sequential order
Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.
First I declared all my variables as Public
Then I defined/set each variable
Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges
Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range
With Sheet8
c = pvt.DataBodyRange.Columns.Count + 1
d = 3
r = .Cells(.Rows.Count, 1).End(xlUp).Row
Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
FormulaRange3.NumberFormat = "0"
Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
FormulaRange4.NumberFormat = "0"
Set SelectRanges = Union(FormulaRange3, FormulaRange4)
Shell equality operators (=, ==, -eq)
==
is a bash-specific alias for =
and it performs a string (lexical) comparison instead of a numeric comparison. eq
being a numeric comparison of course.
Finally, I usually prefer to use the form if [ "$a" == "$b" ]
How to convert a boolean array to an int array
I know you asked for non-looping solutions, but the only solutions I can come up with probably loop internally anyway:
map(int,y)
or:
[i*1 for i in y]
or:
import numpy
y=numpy.array(y)
y*1
How to loop through a dataset in powershell?
The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()
for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}
Additionally foreach
allows you to iterate through a collection or array without needing to figure out the length.
Rewritten (and edited for compile) -
foreach ($Row in $ds.Tables[1].Rows)
{
write-host "value is : $($Row[0])"
}
How to restart adb from root to user mode?
This is a very common issue.
One solution is to kill adb server and restart it through command prompt. Sometimes this may not help out.
Just go to Window Task Manager to kill adb process and restart Eclipse.
Will work perfect :)
How do I use itertools.groupby()?
A neato trick with groupby is to run length encoding in one line:
[(c,len(list(cgen))) for c,cgen in groupby(some_string)]
will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.
Edit: Note that this is what separates itertools.groupby
from the SQL GROUP BY
semantics: itertools doesn't (and in general can't) sort the iterator in advance, so groups with the same "key" aren't merged.
Login to remote site with PHP cURL
This is how I solved this in ImpressPages:
//initial request with login data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
//another request preserving the session
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}