w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Arranging objects from most matching object to least matching object
Just use OrderByDescending + ThenByDescending: var orderedObjects = objects .OrderByDescending(o => o.Group == keyObj.Group) .ThenByDescending(o => o.Country == keyObj.Country) .ThenByDescending(o => o.Service == keyObj.Service) .ThenByDescending(o => o.Industry == keyObj.Industry) .ThenByDescending(o => o.Technology == keyObj.Technology) .ThenBy(o => o.Group) // now start ordering by the properties itself .ThenBy(o => o.Country) .ThenBy(o => o.Service) .ThenBy(o => o.Industry) .ThenBy(o => o.Technology) .ToArray(); The comparison returns true or false whereas true is "larger" than false, therefore Descending since we want matching properties first.

Categories : C#

ActiveRecordRelation where method matching on unique id returning object slightly diff then when traversing the array and matching on the same id
Regarding your first question about object_ids: The object_id is an internal reference id in Ruby assigned to the actual instance. No two instances can have the same object_id. This is different from calling .id in Rails which should return the id of the record in your datastore. Why your test is probably failing: The moment you called this: contact.contact_campaigns[rand(4)].activate Rails hit your datastore and cached the collection locally. Then you "activated" the item rand(4), which clearly appears to be your intention. Then you called this: contact.assign_campaign(campaign_to_be_assigned.id) which should have deactivated the previously active rand(4). But, in the datastore NOT in memory in contact.contact_campaigns. So remember contact.contact_campaigns is still in memory

Categories : Ruby On Rails

Matching a Pattern in PHP
Try with substr like $needle = 'BA700'; $haystack = 'BA70012345'; if(substr($haystack, 0, 4) == $needle) { echo "Valid"; } else { echo "In Valid"; } You can also check regards with the case by changing both of them in either UPPER or LOWER like if(strtoupper(substr($haystack, 0, 4)) == $needle) { echo "Valid"; } else { echo "In Valid"; }

Categories : PHP

Pattern Matching in R
Here's one approach using term.count (a non exported function) from the qdap package: lst <- list(c('a', 'b', 'c', 'd', 'b', 'c'),c('b', 'c', 'e')) lst2 <- lapply(lst, paste, collapse="") #use lapply to paste the list ## install.packages("qdap") sapply(lst2, qdap:::term.count, "bc") #count occurences ## > sapply(lst2, qdap:::term.count, "bc") ## bc bc ## 2 1 If you don't want to use qdap look at the source for term.count and take what you need.

Categories : R

Pattern Matching on Either
try this one trait Either[+E, +A] { def map[B](f: A => B): Either[E, B] = this match { case Right(y) => Right(f(y)) case left: Left[E] => left } }

Categories : Scala

F# pattern matching oddity
I think F# compiler is being practical in this case. In the end, the second rule can be expressed as a constraint on input list xs: xs = hd :: tl && xs = l F# compiler doesn't seem to explore && constraints. This is reasonable because constraints can be arbitrarily complex and the use of & is quite rare. We have a similar problem with partial active patterns: let (|Empty|_|) = function | [] -> Some() | _ -> None let (|NonEmpty|_|) = function | _ :: _ -> Some() | _ -> None // warning FS0025 let f = function | Empty -> "Empty list" | NonEmpty -> "Not so empty list" To fix this issue, you can: Use as instead of &, which is more appropriate since l is just a binding. Add a wildcard pattern to the end to eliminate th

Categories : F#

Asterisk pattern matching
I think pattern matching can be done with other languages like java,PHP. Asteriks support these languages. Here is a tutorial for asterisk-java http://www.asterisk-java.org/development/tutorial.html I think it can be done with AMI.

Categories : Regex

Having issues in matching pattern
purely based on the example. seems like a termination line problem + SO's 4 spaces quotes.. /<div id="right_song">[ ]+<div style="font-size:15px;"><b>([^<]*)</b></div>[ ]+<div style="clear:both;"></div>[ ]+<div style="float:left;">[ ]+<div style="float:left; height:27px; font-size:13px; padding-top:2px;">[ ]+<div style="float:left;"><a href="([^"]*)" rel="nofollow" target="_blank" style="color:green;">Download</a>/ however there's a shorter/safer way of grep'ing patterns which allows for the 3rd party to change subtle css details /<div[^>]+>[ ]+<div[^>]+><b>([^<]*)</b></div>[ ]+<div[^>]+></div>[ ]+<div[^>]+>[ ]+<div[^>

Categories : Android

pattern matching in arrays
The following regexp checks, whether the string begins with http://www.facebook.com/ or https://www.facebook.com/: '#^https?://www.facebook.com/#i' So, probably, your code should look like this: array('match', true, '#^https?://www.facebook.com/#i'))

Categories : PHP

Pattern Matching on GADTs
Cast :: (Castable a b) => Expr a -> Expr b So here: instance (Show a) => Show (Expr a) where show (Cast e) = "Cast " ++ show e -- ERROR Cast e is of type Expr a. We have a Show a constraint, and by this very instance that implies Show (Expr a), so we can call show on things of type Expr a. But e is not of type Expr a. Cast takes an argument of any type Expr a1 and gives you an Expr a (renaming the type variables to stay consistent with what we're talking about in the instance), so e is of type Expr a1. We don't have a Show constraint for the type a1, and we require Show a1 to imply Show (Expr a1), so there's no way to show e. And there's no way to add such a constraint in the Show instance, because the type a1 doesn't appear in the type of Cast e. That seems to be the who

Categories : Haskell

Pattern Matching and Replacement
What about replace function? Function replace(string text, from text, to text) Description Replace all occurrences in string of substring from with substring to Sample replace('abcdefabcdef', 'cd', 'XX') abXXefabXXef For your code is a simple update: Update table T set text_col = replace( text_col, 'pear', 'watermelon' ); Updated due Igor Romanchenko suggestion: Update table T set text_col = replace( text_col, 'pear', 'watermelon' ) where text_col like '%pear%';

Categories : SQL

Pattern matching within a string
As alternative, use a for loop and break after first iteration: shopt -s nullglob for f in /tmp/foo-*; do echo "Configure with --with-foo="$f"" break done

Categories : Bash

Matching a Specific URL Pattern with PHP
Replace (.*) with (.*?) - use lazy quantification: preg_match('/<a href="https://docs.google.com/file/d/(.*?)</a>/', $file, $matches);

Categories : PHP

Concatenating and Pattern Matching SQL
Are you after something like this: SELECT `c`.`user_id`, `c`.`zip`, `a`.`city`, CONCAT_WS( ';', `c`.`city`, `aa`.`city-state` ) AS `location` FROM `Accounts` AS `a` LEFT JOIN `Addr` AS `aa` ON `aa`.`zip`, `a`.`id` LEFT JOIN `Customer` AS `c` ON `c`.`user id`, `a`.`id`

Categories : SQL

F# odd pattern matching issues
The match statement doesn't work like you think it does - the correct syntax is match i with | t when t = bs.Length In the second case, you actually create a new variable called bsLength which hides the definition of the earlier bsLength and matches all integers, so you get the rule never matched warning.

Categories : F#

Pattern Matching in perl
Not very nice, but the next: use strict; use warnings; while(<DATA>) { chomp; next if /^s*$/; my @parts = split(/_/); my $b = pop @parts if $parts[$#parts] =~ /d/; $b //= '"original"'; my $a = join('_', @parts); print "$a = $a and $b = $b, "; } __DATA__ Rita_bike_house_Sha9 Rita_bike_house prints: $a = Rita_bike_house and $b = Sha9, $a = Rita_bike_house and $b = "original",

Categories : Perl

Pattern matching in html
You cannot open multiple tabs. There's no concept of tab in standard DOM.Its more of a browser thing I have tried this and there is no way you can do this. However,the nearest you can come is use these properties in the same function window.location.href which opens in the same tab and window.open which opens in a new tab. http://jsfiddle.net/Jx433/

Categories : Javascript

Writing a pattern matching macro
The following seems to work, or at least compile: val cases = subs.toList.map { sub => val pat = Bind(newTermName("x"), Typed(Ident("_"), Ident(sub.asClass))) val body = reify(???).tree // TODO CaseDef(pat, body) }

Categories : Scala

lua pattern matching: delimited captures
&(%d+)(.-)& matches &1 first & Leaving 2 second &4 fourth \ to be matched on Your pattern does not match any further items

Categories : Lua

F# - Pattern Matching on boxed tuples
let coerceColor a = match box a with | :? Color as c -> c | :? (int*int*int) as t -> t |> Color.FromArgb | _ -> failwith "Cannot coerce color" But if I could change the design, I would rather use a DU or alternatively a static member with overloads.

Categories : F#

Regex date pattern matching
d is a predefined character class that is generally equivalent to [0-9] (sometimes it also includes unicode digits, depending on the regex engine). Moreover, {n} is a quantifier, and X{n} matches X exactly n times. Therefore, d{2} matches 2 consecutive digits. Also, [0]{2} is 2 consecutive 0s: 00 (not 0000). You're also slightly off about 0[1-9]: it matches any of 01, 02, ..., 09 (1 can't be at the start). You're correct about 1[012]. Overall, this is what your regex looks like: If you want to read more about them, a great online reference regarding regular expressions is regular-expressions.info. Note that in the above answer I've assumed you mean d by \d, and have used the latter because you're representing the regex in a string format that requires s to be escaped. When represe

Categories : Regex

Erlang variable pattern matching
First of all, let me advise you on never using length(A) =:= 0 for testing whether the list A is empty or not; if A a long list, counting its elements will cost you a lot, although the result will not actually be used. Use A =:= [] instead, simpler and better. I don't understand why you're saying that Conn and BB are the same. This does not follow from the code that you have posted here. If Name is not in the table, you insert an entry {Name, Conn}. Otherwise, if Name exists in the table and is related to a single object BB, you assume that this BB is a module and you call the send function defined therein. It could be that you're reading wrong the semantics of if --- if that's the case, don't let the true guard confuse you, this is how an if-then-else is written in Erlang. Maybe yo

Categories : Sockets

Pattern matching consecutive characters
You need to avoid the implicit comparison with $_, which you can do by writing: unless ($string =~ m/A{4}/ || $string =~ m/G{4}/) This looks for exactly 4 A's or exactly 4 G's in the string; if there are 4, it doesn't matter whether there are any more than 4. You can reduce it to a single regular expression by using: unless ($string =~ m/([AG])1{3}/) which looks for an A or G followed by 3 more of the same character.

Categories : Perl

Extract Nth line after matching pattern
To extract the Nth line after a matching pattern you want: awk 'c&&!--c;/pattern/{c=N}' file e.g. awk 'c&&!--c;/Revision:/{c=5}' file would print the 5th line after the text "Revision:"/. FYI the following idioms describe how to select a range of records given a specific pattern to match: a) Print all records from some pattern: awk '/pattern/{f=1}f' file b) Print all records after some pattern: awk 'f;/pattern/{f=1}' file c) Print the Nth record after some pattern: awk 'c&&!--c;/pattern/{c=N}' file d) Print every record except the Nth record after some pattern: awk 'c&&!--c{next}/pattern/{c=N}1' file e) Print the N records after some pattern: awk 'c&&c--;/pattern/{c=N}' file f) Print every record except the N records after some

Categories : Regex

pattern matching an array without redundancies
In your case I'd just double up the match (though one could also write a custom extractor) and to avoid duplication return a function that does the work: def badLine() = throw new IllegalArgumentException("unable to identify line format") lineSplit match { case Array(cls @ TaggedString(), prop @ TaggedString(), x, ".") => val processValue = x match { case value: Literal() => () => processLiteral(value) case value: LiteralwithSchema() ... ... case _ => badLine() } processProperty(prop) processValue() case _ => badLine() }

Categories : Scala

How to extract the words through pattern matching?
#!/usr/bin/perl use strict; use warnings; my $string = "praveen is a good boy"; my @try = split(/s/,$string); for(@try) { # if(/[a,e,i,o,u]{2}/) { if(/[aeiou]{2}/) { # edited after Birei's comment print "$_ "; }; }; First argumant of "split" is a delimiter. Split splits (-8

Categories : Perl

How to delete the matching pattern from given occurrence
Taken from : unix.com Using awk '!x[$0]++' will remove duplicate lines. x is a array and it's initialized to 0.the index of x is $0,if $0 is first time meet,then plus 1 to the value of x[$0],x[$0] now is 1.As ++ here is "suffix ++",0 is returned and then be added.So !x[$0] is true,the $0 is printed by default.if $0 appears more than once,! x[$0] will be false so won't print $0.

Categories : Linux

Haskell unicode pattern matching
As far as I can tell, pattern matching on Unicode characters works out of the box. Try this: f ('薬':rest) = rest f _ = "Your string doesn't begin with 薬" main = do putStrLn (f "薬は絶対飲まへん!") putStrLn (f "なぜ?死にたいのか?") Regarding libraries, you definitely want Text rather than ByteString, the reason being that Text is actually meant for working with text, counting the length of strings by character rather than by byte and so on, whereas ByteString is just an immutable array of bytes with a few extra frills, more suitable for storing and transmitting binary data. As for pattern matching on ByteString, Text, etc., it's simply not possible without extensions since they are opaque types with deliberately hidden implementations. You can, h

Categories : Haskell

pattern matching of the form: Option{..} <-
This is a GHC syntactic extension called record wildcards. Quoting documentation: Record wildcard syntax permits a ".." in a record pattern, where each elided field f is replaced by the pattern f = f. So this code is equivalent to Option { cabal = cabal, noStylish = noStylish } <- cmdArgs defOption effectively binding name x to the value of record field named x for every field in the record type. <- part is irrelevant here, you can as well write let Option { .. } = some expression

Categories : Haskell

White space pattern matching using sed
If I understand correctly, you have name="blah" value="blah" on seperate lines, and want to just remove the sed ':a;N;$!ba;s/ / /g' would do what you want taken from SED: How can I replace a newline ( )?

Categories : Bash

Is this "string pattern matching" algorithm? Or something else?
I don't have a direct answer to your question, but after thinking about it there's several ways in which I could frame the problem: Document retrieval (such as used in search engines -- how do they rank disjunctive queries so quickly?) Non-metric nearest neighbor (link is for the common metric version) 0-1 linear programming As such, I don't think there's one term for this problem -- it's too interesting to too many fields. There's certainly plenty of studies between the three fields (e.g. Google): Document retrieval Non-metric nearest neighbor 0-1 linear programming

Categories : String

Simulating ML-style pattern matching in C++
There was a paper in the C++ committee recently which describe a library that allow to do just that: Open and Efficient Type Switch for C++ by Stroustup, Dos Reis and Solodkyy http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf A link to a page with source code : https://parasol.tamu.edu/~yuriys/pm/ Disclaimer : I didn't try to compile or use this library, but it seem to fit your question. Here is one of the sample provided by the library : #include <utility> #include "match.hpp" // Support for Match statement //------------------------------------------------------------------------------ typedef std::pair<double,double> loc; // An Algebraic Data Type implemented through inheritance struct Shape { virtual ~Shape() {} }; struct Circ

Categories : C++

How to Adjust Angular's URL matching pattern
See Mozilla Regular Expressions doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions What @shaunhusain already explained in a comment is mostly correct, except for the following: w matches a single alphanumeric character or underscore + matches 1 or more (not 0 or 1) of the previous character Therefore, w+ matches a word of length 1 or more characters. You do need to modify the regex to only have one slash after the colon if you want to match something like app:/.

Categories : Regex

Pattern matching against Scala Map entries
Maybe you are looking for solution that you don't really need? Can't imagine extractors here. You can use PF if you want to match key-value pairs: val map = Map[String, String]("a" -> "b") def matchTuple[A,B,C](map: Map[A,B])(pf: PartialFunction[(A,B), C]) = map.collectFirst(pf) matchTuple(map) { case ("a", b) => println("value for a is " + b) } Return type is Option[Unit] because we use collectFirst and println

Categories : Scala

How to apply pattern matching in this case
Not a pattern matching, but should do the trick: checkTop(clickedIndex) orElse checkBottom(clickedIndex) orElse checkLeft(clickedIndex) orElse checkRight(clickedIndex) orElse is a method defined for Option. When option is defined, it returns an option itself, otherwise it tries an alternative.

Categories : Scala

Java Pattern Matching of Tuples
I would do the following: First, use a regular expression to geht the actual String, representing ONE tupel. (<[^>]+>) Create a Tuppel class, that takes that in a constructor, implement the equals and hashcode method as required, and add all results to a set while iterating. Class: Class MyTupel{ private int a; private int b; private int c; private double d; public MyTupel(String tupel){ //Regex to match a,b,c,d over here: ^<(d+),(d+),(d+),([^>]+)>$ } public boolean equals(MyTupel another){ return (a == another.getA() && b == another.getB() && c = another.getC() && d == another.getD()) } @Override public int hashCode(){ return a+b+c+ (int)Math.floor(d); } //getter and setter } and finally u can use it

Categories : Java

How can I employ the "use" declaration within a matching pattern?
let createAndUseStreamIfAny = let streamOpt = getSteamOpt match streamOpt with | Some(s) -> use stream = s printf "stream has to be disposed after this" | None -> printf "blah"

Categories : F#

PHP preg_replace is not matching entire pattern
You should use this regex /(?<=||)[a-zA-Z]{4,8}$/ You need to escape | since it represents OR in regex $ marks the end of string (?<=||) is a zero width lookbehind

Categories : Regex

Using REGEXP_REPLACE for a pattern of string matching
regexp_replace('ABC1111|~@SERIAL_NUM_ONE@~|~@SERIAL_NUM_TWO@~|~@SERIAL_NUM_THREE@~', '~@.+?@~', '~@') .+? is non-greedy expression and returns, ABC1111|~@|~@|~@ .+ is greedy expression, tried to mach as much as possible and returns ABC1111|~@ Demo at sqlfiddle.

Categories : Regex

boost mpl sequence pattern matching
Wow, I find the root of the problem. Look at the error message(you could see it if you comment typedef get_first<SEQ_C> type; line): error: ‘type’ in ‘struct get_first<boost::mpl::vector_c<int, 1l, 2l, 3l> >’ does not name a type // ^ ^ ^ As you can see, g++ interprets passed arguments as long, not as int. So, if you change your specification to: template<template<class T, long... S> class SEQ_C, class T, long x, long... xs> struct get_first<SEQ_C<T, x, xs...>> { enum { value = x }; typedef get_first<SEQ_C<T, x, xs...>> type; }; It would work. Of course, it is not a solution, I just show, how it would work. I think, it's bug in g++, since clang++ prod

Categories : C++



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