w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Count the number of max consecutive "a"'s from a string. Python 3
I've seen a couple of regex answers in the comments and the other question, so I'm gonna take a different road. Just getting the count can be done many different ways. from itertools import groupby inp = 'daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm'; char_groups = groupby(inp, lambda char:char=='a') counts = [len(list(group)) for char, group in char_groups] # We know every other element of 'counts' is an 'a' element. # We just need to know whether to start at zero or one. # If inp starts with 'a', start at 0. Otherwise start at 1. max(counts[not inp.startswith('a')::2]) # 11 I'm pretty sure both of the regex answers I've seen will replace every string of 'aa+' with two 'a's. If you only want to replace the longest string of 'a's with 'aa' and leave the rest alone:

Categories : Python

mysql query count consecutive positive numbers in a column
select GREATEST( sum(if (A <= 0, 0,1)), sum(if (B <= 0, 0,1)), sum(if (C <= 0, 0,1)), sum(if (D <= 0, 0,1)), sum(if (E <= 0, 0,1)), sum(if( F <= 0, 0,1)) ) FROM RESULT

Categories : Mysql

SQL consecutive occurrences count
I think this is exactly what row_number() does: select key1, key2, key3, emailSent_Date, row_number() over (partition by key2, key3 order by key1) as "Count" from "table";

Categories : SQL

Count numbers of consecutive 1s and 0s in a vector
You can do it as follows: dat=[0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1]; str = regexprep(num2str(dat),' ',''); [n1 istart1 iend1] = regexp(str,'[1]+','match','start','end'); [n0 istart0 iend0] = regexp(str(min(istart1):max(iend1)),'[0]+','match','start','end'); % number of strings of `1`s length(n1) % property of intercalated strings of `0`s median([iend0-istart0+1]) mean([iend0-istart0+1])

Categories : Matlab

How to count consecutive number of 10 days
This approach uses correlated subqueries to calculate two values. The first value is the date of the previous record where Present = 1. This allows you to get the number of days in a row where Present = 0 by using datediff(). The second is the Present value of tomorrow, which will be NULL on the last day of the month. When today has Present = 0 and tomorrow is either 1 or NULL, then we can use this record. It is the end of a sequence of 0s. From there is it just a question of adding up the values according to the conditions that you set. The following query assumes that you want to do this for each name: select name, sum(case when datediff(date, lastPresentDate) >= 10 then datediff(date, lastPresentDate) else 0 end) as DaysCounted from (sel

Categories : Mysql

Determine consecutive date count in SQL Server
The way to do this is to subtract a sequence of numbers and take the difference. This is a constant for a sequence of dates. Here is an example to get the length of all sequences for an id: select id, grp, count(*) as NumInSequence, min(date), max(date) from (select t.*, (date - row_number() over (partition by id order by date)) as grp from data t ) t group by id, grp To get the longest one, I would use row_number() again: select t.* from (select id, grp, count(*) as NumInSequence, min(date) as mindate, max(date) as maxdate, row_number() over (partition by id order by count(*) desc) as seqnum from (select t.*, (date - row_number() over (partition by id order by date)) as grp from data t

Categories : Sql Server

Count the number of consecutive days of activity
here is a data.table solution: # convert to data.table library(data.table) DT <- data.table(df) # make sure `date` is in fact a date and not a string DT[, date := as.Date(date)] # re order DT <- setkey(DT[order(date)], id) # compute diffs DT[, diffs := c(0, diff(date)), by=id] ## We will use cumsum. Anything greater than 1, should be reset to 0 DT[diffs > 1, diffs := 0] # add one to each value DT[, diffs := diffs + 1] # fix duplicate dates DT[, diffs := max(diffs), by=list(id, date)] RESULTS DT id date sequential.days diffs 1: 1030 2013-01-01 1 1 2: 1030 2013-01-01 1 1 3: 1030 2013-01-02 2 2 4: 1030 2013-02-04 1 1 5: 2022 2013-01-04 1 1 6: 2022 2013-02-01

Categories : R

SQL - HSQL How to count consecutive occurences of a number
I found the solution by myself only using hsql 1.8 - I'm posting it if somebody else might be interested in it: SELECT "a"."code", ("a"."Seq"-"b"."MaxNum" +1) AS "SeqStart", "a"."Seq" AS "SeqEnd", "b"."MaxNum" AS "Count" FROM (SELECT DISTINCT "x"."code", "x"."Seq", "x"."incr", "x"."Bin", "y"."incr1", CASE WHEN "x"."Bin" = 1 THEN ("x"."incr"-"y"."incr1") ELSE '0' END AS "Num" FROM "MyTable" AS "x" LEFT JOIN (SELECT "code", "incr", MAX("incr1") AS "incr1" FROM (SELECT "a"."code", "a"."incr", "b"."incr" AS "incr1" FROM "MyTable" AS "a", "MyTable" AS "b" WHERE ("b"."incr" BETWEEN '1' AND ("a"."incr" -1)) AND "b"."Bin" = 0) GROUP BY "code", "incr") AS "y" ON "y"."code" = "x"."code" AND "y"."incr" = "x"."incr") AS "a" INNER JOIN

Categories : SQL

Find and count consecutive records in ruby on rails
I refactored my helper...and it works. I decided to rely on the user entering a day as off in their log...and not assuming that a break in entered days could be considered a day off. def consecutive_days_on(user, dutylog) last_day_off = user.dutylogs.where(day_off: true).where("entry_date < ?", dutylog.entry_date).select(:entry_date).last start_date = dutylog.entry_date if last_day_off.present? end_date = last_day_off.entry_date else end_date = dutylog.entry_date end a = user.dutylogs.where("entry_date >= ? AND entry_date <= ?", end_date, start_date).count a-1 end

Categories : Ruby On Rails

@OneToOne or @ManyToOne on x.person references an unknown entity: y.Person - inheritance issue
You have to declare your Superclass as an @Entity instead of @MappedSuperClass and a single table inheritancet strategy, so you can reference it in your ManyToOne relationship @Entity @Table(name="PERSON") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="discriminator",discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue(value="P") public abstract class Person { @Id @GeneratedValue @Column(name = "PERSON_ID") private Long personId; private String firstname; private String lastname; @OneToMany(cascade = {CascadeType.ALL}, mappedBy="customer") @LazyCollection(LazyCollectionOption.FALSE) private List<Address> addresses = null; } @Entity @Table(name="PERSON") @DiscriminatorValue("E") public class Employee

Categories : Java

Query to Return One Row per Person
You can use a common table expression with the ROW_NUMBER window function: WITH cte AS (SELECT [id], [person], [answer], [priority], RN = Row_number() OVER ( partition BY person ORDER BY CASE WHEN priority = 'High' THEN 0 ELSE 1 END ASC) FROM dbo.answers) SELECT [id], [person], [answer], [priority] FROM cte WHERE rn = 1 DEMO ID PERSON ANSWER PRIORITY 4 Amy Italy High 3 Fred England Low 2 Tom Germany High Ranking Functions

Categories : SQL

How to Add Different Custom Boost Factor Query Scores in Elastic Search?
You should take a look at function_score: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html

Categories : Elasticsearch

VBA count consecutive non-empty cells in a column, starting from a given one: must handle special cases
.End(xlDown) has same behavior as pressing Ctrl+Down arrow. When you are in last cell in a non-empty area, cursor will jump to first cell of following non-empty area. You must handle this case: If row > Ncells Then If xlsht.Cells(Row+1, Column).Value = Empty Then CountCells = 1 Exit Function End If End If Note that name Ncells induce in error, it is really a MaxRow.

Categories : Excel

SQL query for fetching attributes of person from different tables
You still haven't made it clear how you want to join the output from this shonky CSV table to whatever other tables you have. So this solution ignores that part of the problem. If you need extra guidance you will need to provide more information regarding your requirements. Hers is one solution. It uses a pipelined function, which isn't necessarily the most performant option, but like I said, your situation is so messed up, you'll have to take "it works" over "it works fast". Pipelined function returns a nested table: create or replace type bp_record as object ( element varchar2(30) , table_name varchar2(30) , value varchar2(30) ); / create or replace type bp_recs as table of bp_record; / The pipelined function itself: create or replace function bp_cannon ( p_id in your_ta

Categories : SQL

Check a string for all or 3 consecutive characters of another string? Regex python NOT case-sensitive
You can create all triplets from string1 and then check if any of these triplets occur in string2: string1 = "Helloworld33" triplets = set([string1[i:i+3] for i in range(len(string1) - 2)]) result = not any(t in string2 for t in triplets)

Categories : Python

How to have window size itself to longest string
To get the Button controls to be the same length, you could add a Grid with the Grid.IsSharedSizeScope property set to true into your DataTemplate. Define one column with the SharedSizeGroup property set: <DataTemplate x:Key="DomainTemplate" DataType="DomainViewModel"> <Grid Grid.IsSharedSizeScope="True"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" SharedSizeGroup="Button" /> </Grid.ColumnDefinitions> <Border BorderBrush="{Binding Converter={StaticResource BrushConverter}, Path=IsSelected}" BorderThickness="2" Margin="5" Name="SelectedBorder"> <Button Click="SelectDomain_Click" Content="{Binding Path=Name}" FontSize="16" FontWeight="Bold" Height="60" IsEnabled="{Binding CurrentSiteIsVa

Categories : Wpf

How can I get the longest increasing subsequence in a string?
In these cases it tends to help to step away from the keyboard and think about the algorithm you're trying to implement. Try to explain it first in words. You are constructing a list of individual characters by appending each of the characters in the input string followed by characters to its right that are in correct alphabetical with their successor. For the input "Welcome" this means the accumulated output will be, showing the outer loop in vertical and inner loop in horizontal: W W e c e e c l c c c o m e In total: WWeceeclccome

Categories : Java

Finding the longest string within an NSArray
Besides all methods that imply iterating over the array, you can easily do this with valueForKeyPath:, using the @max collection operator: NSNumber* maxLength= [array valueForKeyPath: @"@max.length"];

Categories : Objective C

Javascript: find longest word in a string
The index is going up to str.length -1: for (var i = 0; i < str.length - 1; i++) { So the last word is not processed. Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice"). You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA). In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop. for (var i = 0; i < str.length; i++) { Check a demo with both versions (the problematic and the fixed): link here.

Categories : Javascript

Find longest suffix of string in given array
Naive, pseudo-answer: Sort array of suffixes by length (yes, there may be strings of same length, which is a problem with the question you are asking I think) Iterate over array and see if suffix is in given string If it is, exit the loop because you are done! If not, continue. Alternatively, you could skip the sorting and just iterate, assigning the biggestString if the currentString is bigger than the biggestString that has matched. Edit 0: Maybe you could improve this by looking at your array before hand and considering "minimal" elements that need to be checked. For instance, if .com appears in 20 members you could just check .com against the given string to potentially eliminate 20 candidates. Edit 1: On second thought, in order to compare elements in the array you will need

Categories : C

Find longest string in multiple divs (same class)
You could use map(), although under the hood this is still iterating over all matched elements. var lengths = $(".Name span").map(function(i, el) { return $(el).text().length; }).get(); var maxLength = Math.max.apply(this, lengths);

Categories : Jquery

Find first longest word in a string, excluding symbols
Just wrote this little snippet, might help you out: function longestWord(string){ return string.match(/[a-zA-Z]+/g) .reduce(function(a,b){ return a.length>=b.length?a:b; }) } /[a-zA-Z]+/g matches all words in the string, and returns an array of them. Your test string above ("Hello, I am here") will become ["Hello","I","am","here"] when this RegEx is run on it. Once I have this array, it is simply a matter of looping through it to find the longest word. I accomplished this by using .reduce.

Categories : Javascript

mssql query join to work out esclation person based on discounts percentage
While joining the price_escalation_bands you can use one more condition for discount. Check the FIDDLE. Here I have tried with the result in a temp table. You can try the same subquery with your join price_escalation_bands by passing the max(linediscount). Hope this will help you.

Categories : Sql Server

Checking consecutive values at a MySQL query
such alarm ? SELECT ID, Time , count(if(value>%treshold ,1,0)) alert_active FROM mydb.MYTABLE WHERE Value>%s3 AND Time>=%s2 AND Time<=%s1 GROUP BY ID; i don't understand exactly: In this example, only ID 3 should be a valid alarm, since 2 consecutive time values for this ID have their value > threshold. ID 1 has a single, isolated alarm, so it should be filteres. For ID 2 there are 2 alarms, but not consecutive, so it should be also filtered. I guess that You want filter alerts: SELECT ID, Time FROM mydb.MYTABLE WHERE Value>%s3 AND Time>=%s2 AND Time<=%s1 GROUP BY ID having value<%treshold;

Categories : Mysql

SQL query find missing consecutive numbers
This will work, you select all "Dependents" and left join on the prior row. If that row is not there then you show the result: SELECT 'Missing Prior', t1.* FROM employee_members t1 LEFT JOIN employee_members t2 ON t1.employee_number = t2.employee_number AND (t1.familyid-1) = t2.familyid WHERE t2.employee_number is null and t1.relation == 'Dependent' Another version that shows you the missing number: SELECT t1.employee_number, t1.familyid-1 as Missing_Member FROM employee_members t1 LEFT JOIN employee_members t2 ON t1.employee_number = t2.employee_number AND (t1.familyid-1) = t2.familyid WHERE t2.employee_number is null and t1.relation == 'Dependent'

Categories : SQL

Consecutive string input using std::cin
You use the std::ios::clear() in a wrong way. Setting it to not eofbit results in other fail bits being set. Remove the parameter passed to clear() or use std::ios::goodbit, which is the same, to recover the cin from EOF. Reference: ios::clear

Categories : C++

Query with several consecutive LEFT JOIN - unexpected results
This appears to be the classic case where you need to move your where into the join itself so that it doesn't block everything else: SELECT A.*, B.*, C.*, D.*, E.*, F.*, FROM A LEFT JOIN B ON A.id = B.id LEFT JOIN C ON A.id = C.id LEFT JOIN D ON A.id = D.id LEFT JOIN E ON A.id = E.id LEFT JOIN F ON A.id = F.id LEFT JOIN G ON B.myfield = G.myfield and G.anotherfield IN (myvalue1) LEFT JOIN H ON C.myfield = H.myfield;

Categories : Mysql

How to split a string at 2 or more consecutive spaces in PHP
You can use the following: $str = "PALM DESERT SD63376 "; // note that there are two spaces in the regex pattern var_dump(preg_split('~ +~', $str, -1, PREG_SPLIT_NO_EMPTY)); Output: array(2) { [0] => string(11) "PALM DESERT" [1] => string(7) "SD63376" }

Categories : PHP

Max occurrences of consecutive character in a string.(Ruby)
This is crude and likely can be improved, but you're basically looking at a simple state machine, where the current state is the previous character, and the next state is either a reset or an incrementation of a counter. str = "abcccdddeee" state = nil current_count = 0 counts = {} str.each_char do |char| if state == char current_count += 1 counts[char] ||= 0 counts[char] = current_count if current_count > counts[char] else current_count = 0 end state = char end p counts.to_a.sort {|a, b| b[1] <=> a[1] }.map(&:first) Since this only counts and stores counts when the current input causes the FSM to remain in the counting state, you don't get non-repeating characters in your output. However, since this is Ruby, we can cheat and use regexes: "abccdd

Categories : Ruby On Rails

Data retrieval from a string and consecutive writing into DB
Hello and welcome to SO. The problem you are facing has been already solved many times. Probably the best answer you can get is this one. It contains in detail explanation how to split strings in C++. I hope it helps.

Categories : C++

MYSQL: How to write sql query to find minimum value but with count of same value with count of Category
You can do it with a subquery: select c.catid, min(c.value), sum(c.value = cmin.minval), count(c.CatId) from category c join (select catid, min(value) as minval from category group by catid ) cmin on c.catid = cmin.catid group by c.catid; Or with a select within a select: select catid, min(value), (select count(*) from category c2 where c2.value = min(c.value)), count(CatId) from category c group by catid;

Categories : Mysql

Select Query- exclude holidays count from a totaldays count obtain from date range
Try this one - SELECT name , start_date_pj , enddate , No_Days = DATEDIFF(DAY, start_date_pj, enddate) , TotalDay_sundayremoved = (DATEDIFF(dd, start_date_pj, enddate) + 1) - (DATEDIFF(wk, start_date_pj, enddate) * 1) - (CASE WHEN DATENAME(dw, start_date_pj) = 'Sunday' THEN 1 ELSE 0 END) -- - holidays , holidays FROM ( SELECT name , start_date_pj , enddate = ISNULL(ed_date_pj, expectedend_date_pj) FROM dbo.Project_pj ) p OUTER APPLY ( SELECT holidays = COUNT(1) FROM dbo.holiday_hd h WHERE h.date_hd BETWEEN p.start_date_pj AND p.enddate ) t Also you can write sub-query - SELECT name , ... , holidays = ( SELECT holidays = COUNT(1) FROM dbo.holiday_hd h

Categories : Sql Server

Query Failed!Column count doesn't match value count at row 1
You do something like that: INSERT INTO table_name VALUES (value1, value2, value3,...) Which requires for your knowing all columns, and their sequence. You need to use them all. However, if you know which columns you may omit, you can use this method: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) Here, you specify which columns you want to add. If all the rest of columns have defined default values or accept NULL, you will be okay.

Categories : PHP

Parsing a string into parts, only consecutive words, not a power set
First of all, I just want to let you know that if you are going to run ALL these against an SQL database for a search, it's extremely inefficient, and suggest you use the LIKE option. http://www.techonthenet.com/sql/like.php Now, to get all the possible combinations, just break up the words into an array (like you've done with explode), and follow the advice given by @ulvund on this question: PHP: How to get all possible combinations of 1D array? Which is to say <?php $array = explode(" ", "listing of average salaries in germany for 2011"); function depth_picker($arr, $temp_string, &$collect) { if ($temp_string != "") $collect []= $temp_string; for ($i=0; $i<sizeof($arr);$i++) { $arrcopy = $arr; $elem = array_splice($arrcopy, $i, 1); // remo

Categories : PHP

Finding all consecutive occurences of a pattern using preg_match after a specific string
Try this. It's very similar to what you had, but I put a non-capturing grouping around each row, as well as some leading and trailing optional whitespace in each row. For reference, the regex used is /<table[^>]*id="table_id2">((?:s*<tr[^>]*><td>[^>]*</td></tr>s*)+)/

Categories : PHP

PHP/MYSQL - Error Array ( ) string(47) "Column count doesn't match value count at row 1"
Change your query to this: $stmt = $mysqli->prepare("INSERT INTO users VALUES (null,?,?,?,?,?,?)"); $stmt->bind_param('ssssss',$username,$pwd,$lastloggedin,$role,$paswordchangedate,$salt); Note I added the first value to be Null to autoincrement, you were missing the id field. Remember that when you don't specify the field name you have to make sure every field is included. This should work too: $query = "INSERT INTO users (username,password,lastloggedin,role,paswwordchangedate,salt) VALUES (?,?,?,?,?,?) ;";

Categories : PHP

How to compare 2 string arrays and find all consecutive matches and save indices?
This doesn't do exactly what you would like but it's an a really clean and simple way to get a new array with all of the common strings (ie take the intersection of the two arrays). var results = array1.Intersect(array2, StringComparer.OrdinalIgnoreCase); After executing the resutls array will have every string (ignoring case) that occurs in both array1 and array2. If you want a bit of theory the intersect method is based on the intersection operation you do on sets in lambda calculus. The collections in C# implement all the common set operations so it's worth having some familiarity of them. Here's a link to the wiki article; http://en.wikipedia.org/wiki/Intersection_(set_theory)

Categories : C#

Looping the cells and getting the count of a string value in all the sheets and printing the count sequence in another column in respective sheet
Put the following code and add a reference to the "Microsoft Scripting Runtime" (Tools > Reference) so you can use a dictionary structure Sub CountOccurence() ' Reference: Microsoft Scripting Runtime Application.ScreenUpdating = False Set oDict = New Dictionary Dim Shts() As Variant Dim wS As Worksheet Dim r As Integer, rLast As Integer Dim i As Integer Shts = Array("Sheet1", "Sheet2", "Sheet3", "Sheet4") For i = 0 To 3 Step 1 Set wS = Sheets(Shts(i)) rLast = wS.Cells(1, 1).CurrentRegion.Rows.Count For r = 2 To rLast Step 1 If Not (oDict.Exists(wS.Cells(r, 1).Value)) Then oDict.Add wS.Cells(r, 1).Value, 1 Else oDict.Item(wS.Cells(r, 1).Value) = oDict.Item(wS.Cells(r, 1).Value) + 1 End If wS.Cells(r, 2).Value

Categories : Excel

Mysql count and count distinct in same query
COUNT(DISTINCT field) will do the job: SELECT user_id, job.job_id AS job_id, job_link, COUNT(job.click_ip) AS click_ip, COUNT(DISTINCT job.click_ip) AS click_ip_distinct FROM user JOIN job ON user.job_id = job.job_id WHERE user.user_id =7 GROUP BY job_id SQL Fiddle here: http://sqlfiddle.com/#!2/5e03e/2/0

Categories : PHP

Getting the highest count from a monthly count query
You can use - SELECT MAX(`user_id`) FROM `users` From there you can format it. src = http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column.html

Categories : Mysql



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.