I need function whitch from data (always yyyy-mm-dd for example 2010-01-01) cut only month and return me integer not string. But if this month is for example January and first number is 0 function should cut this 0 and return me only 1. I try to do this wuth substr but i always have null. For example from 2014-02-03 fnction return 2. Anyone can help me?
I try to use
date('m', strtotime('$myDate'))
Its work with years but it useless for me becosue it return me first 01, 02 or example but i need need this withot this 0 becouse i transfer this to array where i have 12 numbers without 0.
See this exemple with JAVA :
public Integer getMonth(String date) {
date = date.substring(5,7);
if(date.charAt(1) == 0) {
date.substring(1);
}
return Integer.parseInt(date);
}
The function return 2 for date = "2016-02-10"
This is the same for PHP.
This exemple with PHP :
<?php
public function getMonth($date) {
$date = substr($date, 5, 2);
if(date[0] == 0) {
$date = substr($date,1)
}
return $date;
}
?>
I can't try this because I don't have apache in my computer because I work with JAva and ASP.Net.
Related
I have a 2 "WEEK" vertices on azure cosmosdb graph.
g.V().hasLabel('WEEK').valueMap()
output:
{
"type":["1 week|1 month|1 wk|one month|one week|one wk"]
},
{
"type":["11 weeks|11 months|11 wks|eleven months|eleven weeks|eleven wks"]
}
i am trying to search CONTAINS of a STRING in the "type" property and return the vertices.
STRING = "1 week"
g.V().hasLabel('WEEK').has('type',TextP.containing('1 week')).valueMap()
output:
{
"type":["1 week|1 month|1 wk|one month|one week|one wk"]
},
{
"type":["11 weeks|11 months|11 wks|eleven months|eleven weeks|eleven wks"]
}
i am getting all the vertices because "11 weeks|11 months|11 wks|eleven months|eleven weeks|eleven wks" also have '1 week' in it.
my requirement is that i have to search for the contains operation but only 1st vertex should be present not the second one.
one idea can be changing the data in the "type" property and change the search string as below
g.V().hasLabel('WEEK').valueMap()
output:
{
"type":["(1 week)|(1 month)|(1 wk)|(one month)|(one week)|(one wk)"]
},
{
"type":["(11 weeks)|(11 months)|(11 wks)|(eleven months)|(eleven weeks)|(eleven wks)"]
}
STRING = "(1 week)"
g.V().hasLabel('WEEK').has('type',TextP.containing('(1 week)')).valueMap()
output:
{
"type":["(1 week)|(1 month)|(1 wk)|(one month)|(one week)|(one wk)"]
}
but this way we need to change the entire data in the "type" property and have to change the STRING as well from "1 week" to "(1 week)" (as "1 week" is received from upstream)
Please let me know any other ideas for the above scenario (doing contains is mandatory)
Thanks in advance.
You could place a | at the beginning of the data and then look for
STRING= "|1 week"
You could search for items that contain your search-string + have the same amount of characters?
Your question is kind of confusing, but something like the below should return ONLY LIST[0] being as it's only LIST[2]. It'll only return the string in the first array position which would be LIST[0]
public string[] LIST = { "1 week|1 month|1 wk|one month|one week| one wk","11 weeks|11 months|11 wks|eleven months|eleven weeks|eleven wks"};
public string STRING = "1 Week";
public int LISTLength = LIST.Length;
for(int x = 0; x < LISTLength; x++)
{
if (LIST[x] == STRING)
{
//Your action here
}
}
I want to convert each digit in a number to an int. Here is my code
for (in <- lines) {
for (c <- in) {
val ci = c.toInt
if (ci == 0) {
// do stuff
}
}
}
The result I get is the ascii code, i.e. a 1 gives 49. I'm looking for the value 1.
The answer is trivial, I know. I'm trying to pull myself up with my own bootstraps until my Scala course begins in two weeks. Any assistance gratefully accepted.
One possible solution is:
for(in <- lines) {
in.toString.map(_.asDigit).foreach { i =>
if(i == 1) {
//do stuff
}
}
}
And more compact w/ output:
lines.foreach(in => in.toString.map(_.asDigit).filter(_ == 1).foreach(i => println(s"found $i in $in.")))
If lines is already a collection of Strings, omit the .toString on in.toString.
You can have this:
val number = 123456
//convert Int to String and do transformation for each character to Digit(Int)
val digitsAsList = number.toString.map(_.asDigit)
This will result to digitizing the number. Then with that Collection, you can do anything from filtering, mapping, zipping: you can checkout the the List api on this page: http://www.scala-lang.org/api/2.11.8/#scala.collection.immutable.List
Hope that's help.
I tried to add a column named FTE containing this formula :
=I2/SUMPRODUCT(I:I,(M:M=M2) * (C:C=C2) * (N:N=N2))
This formula worked when applied in Excel, but when added from php, I just get an error:
maximum execution time calculation.php phpexcel
$assembly = $arrayWorksheet->addColValByRow($assembly, 'FTE', ['= I', '/SUMPRODUCT(I:I,(M:M=M', ')*(C:C=C', ')*(N:N=N'], '))');
// Output : =I2/SUMPRODUCT(I:I,(M:M=M2)*(C:C=C2)*(N:N=N2))
Sadly I can't figure out why. My initial formula was SUMIFS that I converted into SUMPRODUCT, because I know that SUMIFS isn't implemented yet.
function addColValByRow($worksheet, $title, $valArray, $finalVal = NULL) {
// Take the last column
$lastCol = key( array_slice( $worksheet[1], -1, 1, TRUE ) );
$newCol = ++$lastCol;
// tke the last cell
$lastCell = key( array_slice( $worksheet, -1, 1, TRUE ) );
$worksheet[1][$newCol] = $title;
for ($i = 2; $i <= $lastCell; $i++) {
$worksheet[$i][$newCol] = "";
foreach (array_keys($valArray) as $key) {
$worksheet[$i][$newCol] .= $valArray[$key] . $i;
}
if ($finalVal != NULL) {
$worksheet[$i][$newCol] .= $finalVal;
}
}
return $worksheet;
}
It's not SUMPRODUCT() that's causing the problem, it's the fact that PHPExcel doesn't support column/row ranges fully, so it's a column range like I:I or M:M or C:C that's causing the problem.
If you can change this to an actual cell range (e.g. I1:I2048), then it shouldn't be an issue.
And (for future reference) SUMIFS() is implemented in the latest code in the develop branch on github
I have the following code, which works, but I'm wondering if there is a "groovier" way of doing this:
/**
* 10 digit - #-######-##-#
* 13 digit - ###-#-######-##-#
* */
private formatISBN(String isbn) {
if (isbn?.length() == 10) {
def part1 = isbn.substring(0, 1)
def part2 = isbn.substring(1, 7)
def part3 = isbn.substring(7, 9)
def part4 = isbn.substring(9, 10)
return "${part1}-${part2}-${part3}-${part4}"
} else if (isbn?.length() == 13) {
def part1 = isbn.substring(0, 3)
def part2 = isbn.substring(3, 4)
def part3 = isbn.substring(4, 10)
def part4 = isbn.substring(10, 12)
def part5 = isbn.substring(12, 13)
return "${part1}-${part2}-${part3}-${part4}-${part5}"
} else {
return isbn
}
}
You could first use the [] string operator to get the substrings instead of substring and drop the intermediate variables. For example in the case for length == 10:
"${isbn[0]}-${isbn[1..6]}-${isbn[7..8]}-${isbn[9]}"
Now, there is a bit of repetition there. You can get instead first get all the isbn segments and then .join them with '-':
[isbn[0], isbn[1..6], isbn[7..8], isbn[9]].join('-')
And, even further, instead of referencing isbn every time, you can make a list of the ranges you want to get and then get them all the same time using collect:
[0, 1..6, 7..8, 9].collect { isbn[it] }.join('-')
If you're going for code golfing, you can also do:
('-'+isbn)[1, 0, 2..7, 0, 8..9, 0, 10]
I'll leave it to you to figure out how that works, but i guess it's probably not a good idea to leave that on production code, unless you want to surprise future maintainers hehe.
Also, notice that the format when length == 13 is the same as for length == 10 but with a different prefix, you can then reuse the same function in that case. The whole function (with a couple of tests) would be:
/**
* 10 digit - #-######-##-#
* 13 digit - ###-#-######-##-#
**/
def formatIsbn(isbn) {
switch (isbn?.length()) {
case 10: return [0, 1..6, 7..8, 9].collect { isbn[it] }.join('-')
case 13: return isbn.take(3) + '-' + formatIsbn(isbn.drop(3))
default: return isbn
}
}
assert formatIsbn('abcdefghij') == 'a-bcdefg-hi-j'
assert formatIsbn('abcdefghijklm') == 'abc-d-efghij-kl-m'
Now, i think there are some bad smells in that code. Can isbn be null? At least to me, this doesn't look like a function that needs to bother about the nullity of its argument, or at least that's not clear by reading its name (it should be called something like formatIsbnOrNull instead if both ISBN strings and null values are accepted). If null values are not valid, then let it blow up with a NullPointerException when accessing isbn.length() so the caller know they have passed a wrong argument, instead of silently returning the same null.
The same goes for the return ISBN at the end. Is it expected for that function to receive a string that's neither 10 nor 13 characters long? If not, better throw new IllegalArgumentException() and let the caller know they have called it wrongly.
Finally, i'm not sure if this is the most "readable" solution. Another possible solution is having a string for the format, like '###-#-######-##-#' and then replace the #s by the isbn characters. I think it might be more self-documenting:
def formatIsbn(isbn) {
def format = [
10: '#-######-##-#',
13: '###-#-######-##-#'
][isbn.length()]
def n = 0
format.replaceAll(/#/) { isbn[n++] }
}
Consider adding the method to the String class, as shown here. Note that this answer is a spin on a clever suggestion in epidemian's answer (re: collect).
Note:
This code augments String with asIsbn().
The range [0..2] does not need the call to asIsbn(), but the symmetry of using collect twice is irresistable.
Groovy returns the last expression in if/else, so 'return' is not necessary
/**
* 10 digit - #-######-##-#
* 13 digit - ###-#-######-##-#
**/
String.metaClass.asIsbn = { ->
if (delegate.length() == 10) {
[0, 1..6, 7..8, 9].collect { delegate[it] }.join('-')
} else if (delegate.length() == 13) {
[0..2, 3..12].collect { delegate[it].asIsbn() }.join('-')
} else {
delegate
}
}
assert "abcdefghij".asIsbn() == 'a-bcdefg-hi-j'
assert "abcdefghijklm".asIsbn() == 'abc-d-efghij-kl-m'
assert "def".asIsbn() == "def"
String s = null
assert s?.asIsbn() == null
I would try using Regex... I think it's pretty much readable if you know how to use regex, and it's javascript inspired syntax in groovy is pretty cool also.
One more thing: it's pretty clear, looking at the capture groups, what your string looks like for the desired formatting.
private formatISBN(String isbn) {
if (isbn?.length() == 10) {
m = isbn =~ /(\d{1})(\d{6})(\d{2})(\d{1})/
return "${m[0][1]}-${m[0][2]}-${m[0][3]}-${m[0][4]}"
} else if (isbn?.length() == 13) {
m = isbn =~ /(\d{3})(\d{1})(\d{6})(\d{2})(\d{1})/
return "${m[0][1]}-${m[0][2]}-${m[0][3]}-${m[0][4]}-${m[0][5]}"
} else {
return isbn
}
}
Btw, #epidemian suggestion using backreferences is great! I think the code would look like:
private formatISBN(String isbn) {
if (isbn?.length() == 10) {
return isbn.replaceAll(/(\d{1})(\d{6})(\d{2})(\d{1})/, '$1-$2-$3-$4')
} else if (isbn?.length() == 13) {
return isbn.replaceAll(/(\d{3})(\d{1})(\d{6})(\d{2})(\d{1})/, '$1-$2-$3-$4-$5')
} else {
return isbn
}
}
Dunno if I like this any better. I'd make the position map a static final, too.
private isbnify(String isbn) {
def dashesAt = [ 10: [[0,1], [1,7], [7,9], [9,10]],
13: [[0,3], [3,4], [4,10], [10,12], [12,13]]]
def dashes = dashesAt[isbn?.length()]
(dashes == null) ? isbn
: dashes.collect { isbn.substring(*it) }.join('-')
}
Ranges make for a bit less clutter, IMO:
private isbnify3(String isbn) {
def dashesAt = [ 10: [0, 1..6, 7..8, 9],
13: [0..2, 3, 4..9, 10..11, 12]]
def dashes = dashesAt[isbn?.length()]
dashes == null ? isbn : dashes.collect { isbn[it] }.join("-")
}
With an inject-with-two-accumulators it should be easy to do a list-of-dash-positions version, too.
This should be a comment to #everton, but I don't have the 50 reputation needed to do that yet. So this answer is really just a suggested variation on #everton's answer.
One less regex by making the first 3 digits optional. The downside is having to remove a leading '-' if the ISBN is 10 characters. (I also prefer \d over \d{1}.)
private formatISBN(String isbn) {
String result = isbn.replaceAll(/^(\d{3})?(\d)(\d{6})(\d{2})(\d)$/,
'$1-$2-$3-$4-$5')
if (result) {
return result.startsWith('-') ? result[1..-1] : result
} else {
return isbn // return value unchanged, pattern didn't match
}
}
println formatISBN('1234567890')
println formatISBN('9991234567890')
println formatISBN('123456789') // test an ISBN that's too short
println formatISBN('12345678901234') // test an ISBN that's too long
I have 2 tables, Imports and Periods.
Imports has the following structure:
AdminID, PeriodID, Some more fields
1, 1
1, 2
1, 6
1, 50
Periods table has the following structure:
PeriodID, PeriodType, StartDate, EndDate, Description
1, 1, 2007-01-01, 2007-12-31, Year 2007
2, 2, 2007-01-01, 2007-03-31, Quarter 1 2007
3, 2, 2007-04-01, 2007-06-30, Quarter 2 2007
4, 2, 2007-07-01, 2007-09-30, Quarter 3 2007
5, 2, 2007-10-01, 2007-12-31, Quarter 4 2007
6, 3, 2007-01-01, 2007-01-31, January 2007
.
.
.
50, 2, 2011-01-01, 2011-03-31, Quarter 1 2011
Now, I need to build a linq query to fetch only the largest period(ignoring the smaller overlapping periods) based on the data in Imports table!
When I query for AdminID = 1, I should only get PeriodID = 1 & 50, ignoring/excluding the PeriodIDs 2 & 6 as they overlap in 1 and 50 as there is no overlapping data yet!
You, can the max help for picking the largest period and while retrieving the values by comparing the PeriodIDs in both tables right.
I'm not sure whether there is a convenient way to do this in the database, but when you pull the data locally, you can do in-memory LINQ queries, if this is appropriate. You need to do this in thee steps.
Step 1: Define a Range class that allows you to do comparisons on periods (see below).
Step 2: Pulling the periods from the database:
var ranges = (
from period in context.Periods
where period.Imports.Any(i => i.AdminID == adminId)
select new Range(period.StartDate, period.EndDate.AddDays(1)))
.ToArray();
Note the .ToArray() to pull everything locally.
Step 3: Aggregating / merging all the periods into a list of non-overlapping periods:
var mergedPeriods = (
from range in ranges
select ranges.Where(p => p.OverlapsWith(range))
.Aggregate((r1, r2) => r1.Merge(r2)))
.Distinct();
For this to work you need a specially designed Range type that contains OverlapsWith, Merge and Equals methods. It might look like this:
public class Range : IEquatable<Range>
{
public Range(DateTime start, DateTime exclusiveEnd)
{
if (exclusiveEnd < start)
throw new ArgumentException();
this.Start = start; this.End = exclusiveEnd;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public TimeSpan Duration { get { return this.End - this.Start; } }
public Range Merge(Range other)
{
if (!this.OverlapsWith(other)) throw new ArgumentException();
var start = this.Start < other.Start ? this.Start : other.Start;
var end = this.End > other.End ? this.End : other.End;
return new Range(start, end);
}
public bool Contains(Range other)
{
return this.Start <= other.Start && this.End > other.End;
}
public bool OverlapsWith(Range other)
{
return this.OverlapsOnStartWith(other) ||
other.OverlapsOnStartWith(this) ||
this.Contains(other) ||
other.Contains(this);
}
private bool OverlapsOnStartWith(Range other)
{
return this.Start >= other.Start && this.Start < other.End;
}
public bool Equals(Range other)
{
return this.Start == other.Start && this.End == other.End;
}
}
I hope this helps.
Well, after a long struggle, I did find an answer! With a single query to database!
And for everyone's benefit posting the same.
var oImportPeriods =
from o in Imports
where o.Administration.AdminID == 143
orderby o.Period.PeriodID
select o.Period;
var oIgnorePeriodList = (
from oPeriod in oImportPeriods
from oSearchPeriod in oImportPeriods
.Where(o => o.PeriodID != oPeriod.PeriodID)
where oPeriod.StartDate >= oSearchPeriod.StartDate
where oPeriod.EndDate <= oSearchPeriod.EndDate
select oPeriod.PeriodID)
.Distinct();
var oDeletablePeriods = oAdministrationPeriods
.Where(o => !oIgnorePeriodList.Contains(o.PeriodID));
foreach(var o in oDeletablePeriods)
Console.WriteLine(o.Name);